From 5bc153c5adaaeb129d8905e784038eef302080fc Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 11 Nov 2026 06:57:04 +0000 Subject: [PATCH] GEN-2850 add encrypted bearer integration UI --- .../features/settings/bearer-integrations.tsx | 95 +++++++++++++++ .../src/features/settings/integrations.tsx | 2 + packages/app/test/settings.browser.test.mjs | 112 +++++++++++++++++- 3 files changed, 205 insertions(+), 4 deletions(-) create mode 100644 packages/app/src/features/settings/bearer-integrations.tsx diff --git a/packages/app/src/features/settings/bearer-integrations.tsx b/packages/app/src/features/settings/bearer-integrations.tsx new file mode 100644 index 00000000..a8d9ad4d --- /dev/null +++ b/packages/app/src/features/settings/bearer-integrations.tsx @@ -0,0 +1,95 @@ +import { useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { api } from "factorize-api-client"; +import { Button, Card, Input, Label } from "../../shared/ui"; +import { encryptRecord, verifyUnlockKey } from "../../lib/unlock-crypto"; +import { getUnlockVerification } from "../../lib/unlock-key"; +import { messageOf } from "../auth/session"; + +type BearerRecord = { id: string; name: string; origin: string; description: string | null; revision: number; encryptedPayload: string }; +const recordsQuery = { queryKey: ["settings", "bearer-integrations"], queryFn: async ({ signal }: { signal: AbortSignal }) => { + const { data, error } = await api.GET("/api/v1/integrations/bearer", { signal }); + if (!data || error) throw new Error(messageOf(error)); + return data; +} }; +const verificationQuery = { queryKey: ["unlock-key-verification"], queryFn: ({ signal }: { signal: AbortSignal }) => getUnlockVerification(signal), retry: false as const }; +const bytesToBase64 = (bytes: Uint8Array) => { + let value = ""; + for (const byte of bytes) value += String.fromCharCode(byte); + return btoa(value); +}; +const base64UrlToBytes = (value: string) => Uint8Array.from(atob(value.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - value.length % 4) % 4)), char => char.charCodeAt(0)); + +function validOrigin(value: string): boolean { + try { + const parsed = new URL(value); + if (parsed.protocol !== "https:" || parsed.origin !== value || parsed.username || parsed.password) return false; + const host = parsed.hostname.toLowerCase(); + if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host === "0.0.0.0") return false; + const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u); + if (ipv4) { + const octets = ipv4.slice(1).map(Number); + if (octets.some(part => part > 255) || octets[0] === 10 || octets[0] === 127 || octets[0] === 0 || + (octets[0] === 169 && octets[1] === 254) || (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) || + (octets[0] === 192 && octets[1] === 168) || (octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127)) return false; + } + return true; + } catch { return false; } +} + +export function BearerIntegrations() { + const cache = useQueryClient(), records = useQuery(recordsQuery), verification = useQuery(verificationQuery); + const [editing, setEditing] = useState(null), [name, setName] = useState(""), [origin, setOrigin] = useState(""), [description, setDescription] = useState(""), [token, setToken] = useState(""), [key, setKey] = useState(""); + const [notice, setNotice] = useState(""); + const clearFields = () => { setToken(""); setKey(""); }; + const save = useMutation({ retry: false, mutationFn: async () => { + const cleanName = name.trim(), cleanOrigin = origin.trim(), cleanDescription = description.trim(); + if (!cleanName || cleanName.length > 120) throw new Error("Enter a name up to 120 characters."); + if (!validOrigin(cleanOrigin)) throw new Error("Enter a public HTTPS origin without a path, query, fragment, or credentials."); + if (cleanDescription.length > 500) throw new Error("Description must be at most 500 characters."); + if (!token) throw new Error("Enter a bearer token to create or replace this credential."); + const setup = verification.data?.verification; + if (!setup || !verification.data) throw new Error("Set up an unlock key before managing bearer integrations."); + try { await verifyUnlockKey(key, verification.data.ownerId, setup.generationId, JSON.parse(setup.encryptedVerification)); } + catch (error) { + if (error instanceof TypeError && error.message === "Malformed unlock key") throw error; + throw new Error("Unlock key could not be verified for this account and generation."); + } + const id = editing ?? crypto.randomUUID(), expectedRevision = records.data?.revision ?? 0; + const encrypted = await encryptRecord(new TextEncoder().encode(token), key, { ownerId: verification.data.ownerId, recordId: id, recordType: "bearer", destination: cleanOrigin, revision: expectedRevision + 1 }); + const encryptedPayload = `${bytesToBase64(base64UrlToBytes(encrypted.nonce))}.${bytesToBase64(base64UrlToBytes(encrypted.ciphertext))}`; + const body = { expectedRevision, idempotencyKey: crypto.randomUUID(), name: cleanName, origin: cleanOrigin, description: cleanDescription || null, encryptedPayload }; + if (editing) { + const { data, error } = await api.PUT("/api/v1/integrations/bearer/{integrationId}", { params: { path: { integrationId: editing } }, body }); + if (!data || error) throw new Error(messageOf(error)); + return data; + } + const { data, error } = await api.POST("/api/v1/integrations/bearer", { body: { ...body, id } }); + if (!data || error) throw new Error(messageOf(error)); + return data; + }, onSuccess: async () => { clearFields(); setNotice("Saved encrypted integration. Changes remain pending until the proxy is unlocked."); setEditing(null); setName(""); setOrigin(""); setDescription(""); await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); }, onError: async error => { clearFields(); setNotice(error.message); if (error.message.includes("changed") || error.message.includes("revision")) await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); } }); + const remove = useMutation({ retry: false, mutationFn: async (record: BearerRecord) => { + const { data, error } = await api.DELETE("/api/v1/integrations/bearer/{integrationId}", { params: { path: { integrationId: record.id } }, body: { expectedRevision: records.data?.revision ?? 0, idempotencyKey: crypto.randomUUID() } }); + if (!data || error) throw new Error(messageOf(error)); + return data; + }, onSuccess: async () => { setNotice("Integration deleted."); await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); }, onError: async error => { setNotice(error.message); await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); } }); + const beginEdit = (record: BearerRecord) => { clearFields(); setNotice(""); setEditing(record.id); setName(record.name); setOrigin(record.origin); setDescription(record.description ?? ""); }; + const reset = () => { clearFields(); setEditing(null); setName(""); setOrigin(""); setDescription(""); setNotice(""); }; + return
+

Bearer integrations

Credentials are encrypted in this browser. Stored tokens cannot be viewed; edit to replace one.

+ {records.isPending &&

Loading bearer integrations…

}{records.error &&

{records.error.message}

} + {records.data?.integrations.map(record =>

{record.name}

{record.origin}

{record.description &&

{record.description}

}

Bearer token stored encrypted

)} +

{editing ? "Edit bearer integration" : "Add bearer integration"}

+ {!verification.data?.verification && verification.data &&

Set up your unlock key above before adding bearer integrations.

} +
{ event.preventDefault(); setNotice(""); save.mutate(); }}> + + + + + +
{editing && }
+
+
+ {notice &&

{notice}

} +
; +} diff --git a/packages/app/src/features/settings/integrations.tsx b/packages/app/src/features/settings/integrations.tsx index 3535247a..dfa08fbc 100644 --- a/packages/app/src/features/settings/integrations.tsx +++ b/packages/app/src/features/settings/integrations.tsx @@ -9,6 +9,7 @@ import { SettingsLayout } from "./navigation"; import { IntegrationForm } from "./integration-form"; import { messageOf } from "../auth/session"; import { UnlockKeySetup } from "./unlock-key-setup"; +import { BearerIntegrations } from "./bearer-integrations"; const linkClass = "inline-flex min-h-10 items-center rounded-lg border border-stone-200 px-3 py-2 text-sm font-semibold hover:bg-stone-100 dark:border-slate-700 dark:hover:bg-slate-800"; @@ -52,6 +53,7 @@ export function Integrations() { {status.data?.cloudflareTail.installations.map(c =>

Cloudflare Tail · {c.name}

Referenced by {c.referencedJobCount} {c.referencedJobCount === 1 ? "job" : "jobs"}

Connected{buttons("cloudflareTail", c.integrationId)}
{manage(`tail:${c.integrationId}`, )}
)} } +

Available integrations

Connect a provider to add it to your workspace. Connected providers remain available for additional connections.

setOpenSetup(open ? "linear-new" : null)}>{status.data?.linear ? "Add another Linear account" : "Connect Linear"} setOpenSetup(open ? "clickup-new" : null)}>{status.data?.clickup ? "Add another ClickUp workspace" : "Connect ClickUp"} diff --git a/packages/app/test/settings.browser.test.mjs b/packages/app/test/settings.browser.test.mjs index 15a9d2cd..bc3368e5 100644 --- a/packages/app/test/settings.browser.test.mjs +++ b/packages/app/test/settings.browser.test.mjs @@ -50,19 +50,123 @@ test("unlock-key setup requires acknowledgement, stores ciphertext only, verifie assert.equal(writes, 1); assert.equal(saved.encryptedVerification.includes(savedKey), false); assert.equal(await page.evaluate(() => localStorage.length), 0); - await page.getByRole("textbox", { name: "Unlock key" }).fill("malformed"); + const keySetup = page.getByRole("region", { name: "Unlock key" }); + await keySetup.getByRole("textbox", { name: "Unlock key" }).fill("malformed"); await page.getByRole("button", { name: "Verify unlock key" }).click(); await page.getByRole("alert").filter({ hasText: "Unlock key could not be verified" }).waitFor(); - await page.getByRole("textbox", { name: "Unlock key" }).fill(savedKey); + await keySetup.getByRole("textbox", { name: "Unlock key" }).fill(savedKey); await page.getByRole("button", { name: "Verify unlock key" }).click(); await page.getByRole("status").filter({ hasText: "Unlock key verified for this account and generation." }).waitFor(); await page.reload(); - await page.getByRole("textbox", { name: "Unlock key" }).waitFor(); - assert.equal(await page.getByRole("textbox", { name: "Unlock key" }).inputValue(), ""); + await keySetup.getByRole("textbox", { name: "Unlock key" }).waitFor(); + assert.equal(await keySetup.getByRole("textbox", { name: "Unlock key" }).inputValue(), ""); assert.equal(await page.getByText(savedKey, { exact: true }).count(), 0); assert.equal(await page.evaluate(() => localStorage.length), 0); await context.close(); }); +test("bearer integrations encrypt in the browser, clear secrets, handle conflicts and delete conditionally", async () => { + const { context, page } = await setup(); + await page.route("**/api/v1/providers/github/installations", route => route.fulfill({ json: [] })); + await page.route("**/api/v1/integrations", route => route.fulfill({ json: { linear: null, clickup: null, exe: null, exeConnections: [], ampConnections: [], cloudflareTail: { count: 0, installations: [] } } })); + let verification = null, revision = 0, writeBody = null, updateBody = null, deleteBody = null, conflict = true, deleted = false; + await page.route("**/api/v1/unlock-key/verification", async route => { + if (route.request().method() === "GET") return route.fulfill({ json: { ownerId: "owner", verification } }); + const body = route.request().postDataJSON(); verification = { generationId: body.generationId, encryptedVerification: body.encryptedVerification }; + return route.fulfill({ json: { generationId: body.generationId } }); + }); + await page.route("**/api/v1/integrations/bearer", async route => { + if (route.request().method() === "GET") return route.fulfill({ json: { revision, integrations: deleted ? [] : writeBody ? [{ id: writeBody.id, name: writeBody.name, origin: writeBody.origin, description: writeBody.description, revision, encryptedPayload: writeBody.encryptedPayload }] : [] } }); + writeBody = route.request().postDataJSON(); + assert.deepEqual(Object.keys(writeBody).sort(), ["description", "encryptedPayload", "expectedRevision", "id", "idempotencyKey", "name", "origin"]); + assert.equal(writeBody.encryptedPayload.includes("plain-bearer-value"), false); + assert.match(writeBody.encryptedPayload, /^[A-Za-z0-9+/]+=*\.[A-Za-z0-9+/]+=*$/u); + if (conflict) { conflict = false; revision = 1; return route.fulfill({ status: 409, json: { error: { code: "stale_revision", message: "The integration collection changed. Current revision is 1." } } }); } + revision++; + return route.fulfill({ status: 201, json: { revision, duplicate: false } }); + }); + await page.route("**/api/v1/integrations/bearer/*", async route => { + if (route.request().method() === "PUT") { + updateBody = route.request().postDataJSON(); + assert.deepEqual(Object.keys(updateBody).sort(), ["description", "encryptedPayload", "expectedRevision", "idempotencyKey", "name", "origin"]); + assert.equal(updateBody.encryptedPayload.includes("replacement-bearer-value"), false); + revision++; writeBody = { ...writeBody, ...updateBody }; + return route.fulfill({ json: { revision, duplicate: false } }); + } + assert.equal(route.request().method(), "DELETE"); deleteBody = route.request().postDataJSON(); + assert.deepEqual(Object.keys(deleteBody).sort(), ["expectedRevision", "idempotencyKey"]); + deleted = true; revision++; + return route.fulfill({ json: { id: writeBody.id, deleted: true, revision, duplicate: false } }); + }); + await page.goto(origin + "/settings/integrations"); + await page.getByRole("button", { name: "Generate unlock key" }).click(); + const key = await page.getByLabel("New unlock key").inputValue(); + await page.getByRole("checkbox", { name: "I saved this key somewhere safe." }).check(); + await page.getByRole("button", { name: "I saved my key" }).click(); + await page.getByText("Unlock key verification is set up.", { exact: false }).waitFor(); + + const bearer = page.getByRole("region", { name: "Bearer integrations" }); + await bearer.getByLabel("Name").fill("Test bearer"); + await bearer.getByLabel("HTTPS origin").fill("https://api.example.test"); + await bearer.getByLabel("Description or help (optional)").fill("fixture help"); + await bearer.getByLabel("Bearer token").fill("plain-bearer-value"); + await bearer.getByLabel("Unlock key").fill("malformed-key"); + await bearer.getByRole("button", { name: "Add integration" }).click(); + await bearer.getByRole("alert").filter({ hasText: "Malformed unlock key" }).waitFor(); + assert.equal(writeBody, null); + assert.equal(await bearer.getByLabel("Bearer token").inputValue(), ""); + assert.equal(await bearer.getByLabel("Unlock key").inputValue(), ""); + + const wrongKey = `${key.slice(0, -1)}${key.endsWith("A") ? "B" : "A"}`; + await bearer.getByLabel("HTTPS origin").fill("https://api.example.test"); + await bearer.getByLabel("Bearer token").fill("plain-bearer-value"); + await bearer.getByLabel("Unlock key").fill(wrongKey); + await bearer.getByRole("button", { name: "Add integration" }).click(); + await bearer.getByRole("alert").waitFor(); + assert.equal((await bearer.getByRole("alert").innerText()).includes("plain-bearer-value"), false); + assert.equal(writeBody, null); + assert.equal(await bearer.getByLabel("Bearer token").inputValue(), ""); + assert.equal(await bearer.getByLabel("Unlock key").inputValue(), ""); + + await bearer.getByLabel("HTTPS origin").fill("https://127.0.0.1"); + await bearer.getByLabel("Bearer token").fill("plain-bearer-value"); + await bearer.getByLabel("Unlock key").fill(key); + await bearer.getByRole("button", { name: "Add integration" }).click(); + await bearer.getByRole("alert").filter({ hasText: "public HTTPS origin" }).waitFor(); + assert.equal(writeBody, null, "private origins are rejected before any request"); + + await bearer.getByLabel("HTTPS origin").fill("https://api.example.test"); + await bearer.getByLabel("Bearer token").fill("plain-bearer-value"); + await bearer.getByLabel("Unlock key").fill(key); + await bearer.getByRole("button", { name: "Add integration" }).click(); + await bearer.getByRole("alert").filter({ hasText: "collection changed" }).waitFor(); + assert.equal(await bearer.getByLabel("Bearer token").inputValue(), ""); + assert.equal(await bearer.getByLabel("Unlock key").inputValue(), ""); + await bearer.getByLabel("Bearer token").fill("plain-bearer-value"); + await bearer.getByLabel("Unlock key").fill(key); + await bearer.getByRole("button", { name: "Add integration" }).click(); + await bearer.getByRole("status").filter({ hasText: "pending until the proxy is unlocked" }).waitFor(); + assert.equal(writeBody.encryptedPayload.includes("plain-bearer-value"), false); + assert.equal(await page.evaluate(() => JSON.stringify(localStorage) + JSON.stringify(sessionStorage)), "{}{}"); + assert.equal(page.url().includes("plain-bearer-value"), false); + assert.equal(await bearer.getByText("plain-bearer-value", { exact: true }).count(), 0); + assert.equal(await bearer.getByLabel("Bearer token").inputValue(), ""); + assert.equal(await bearer.getByLabel("Unlock key").inputValue(), ""); + + await bearer.getByRole("button", { name: "Replace or edit" }).click(); + await bearer.getByLabel("Replacement bearer token").fill("replacement-bearer-value"); + await bearer.getByLabel("Unlock key").fill(key); + await bearer.getByRole("button", { name: "Save replacement" }).click(); + await bearer.getByRole("status").filter({ hasText: "pending until the proxy is unlocked" }).waitFor(); + assert.equal(updateBody.expectedRevision, 2); + assert.equal(await bearer.getByLabel("Bearer token").inputValue(), ""); + assert.equal(await bearer.getByLabel("Unlock key").inputValue(), ""); + + page.once("dialog", dialog => dialog.accept()); + await bearer.getByRole("button", { name: "Delete" }).click(); + await bearer.getByText("Integration deleted.", { exact: true }).waitFor(); + assert.equal(deleteBody.expectedRevision, revision - 1); + await context.close(); +}); test("integration settings tolerates legacy exe connections without tags", async () => { const { context, page } = await setup(); await page.route("**/api/v1/providers/github/installations", route => route.fulfill({ json: [] }));