From 9596bc0b1bb30d4c3a9497707ccbe384ddc47a69 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 11 Nov 2026 05:18:00 +0000 Subject: [PATCH] GEN-2877 initialize browser unlock key --- packages/api-client/src/schema.d.ts | 107 ++++++++++++++ .../0034_unlock_key_verifications.sql | 6 + packages/api/src/api-contract.ts | 4 + packages/api/src/flow-service.ts | 14 ++ packages/api/test/api-boundary.test.ts | 8 ++ packages/api/test/api-contract.test.ts | 8 ++ ...encrypted-integration-api.postgres.test.ts | 19 +++ .../src/features/settings/integrations.tsx | 3 +- .../features/settings/unlock-key-setup.tsx | 45 ++++++ packages/app/src/lib/unlock-crypto.ts | 22 +++ packages/app/src/lib/unlock-key.ts | 18 +++ packages/app/test/settings.browser.test.mjs | 45 ++++++ packages/app/test/unlock-crypto.test.mjs | 14 +- packages/docs/openapi.yaml | 130 ++++++++++++++++++ 14 files changed, 441 insertions(+), 2 deletions(-) create mode 100644 packages/api/migrations/0034_unlock_key_verifications.sql create mode 100644 packages/app/src/features/settings/unlock-key-setup.tsx create mode 100644 packages/app/src/lib/unlock-key.ts diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 65f0c0a9..3a6e82f7 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1,5 +1,37 @@ // Generated from packages/docs/openapi.yaml. Do not edit. export interface paths { + "/api/v1/unlock-key/verification": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get the current encrypted unlock-key verification record + * @description Requires an interactive owner browser session. Returns user-encrypted verification ciphertext and its key generation; the unlock key is never accepted or returned. + * + * Requires the integrations:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_unlock_key_verification"]; + put?: never; + /** + * Create the encrypted unlock-key verification record + * @description Requires an interactive owner browser session. Stores only browser-encrypted verification ciphertext and permits one setup per account. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_unlock_key_verification"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/integrations/bearer": { parameters: { query?: never; @@ -2515,6 +2547,81 @@ export interface components { } export type $defs = Record; export interface operations { + get_api_v1_unlock_key_verification: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Encrypted verification record or empty setup state */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ownerId: string; + verification: { + /** Format: uuid */ + generationId: string; + encryptedVerification: string; + } | null; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_unlock_key_verification: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** Format: uuid */ + generationId: string; + encryptedVerification: string; + }; + }; + }; + responses: { + /** @description Created verification record */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + generationId: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_integrations_bearer: { parameters: { query?: never; diff --git a/packages/api/migrations/0034_unlock_key_verifications.sql b/packages/api/migrations/0034_unlock_key_verifications.sql new file mode 100644 index 00000000..346b492c --- /dev/null +++ b/packages/api/migrations/0034_unlock_key_verifications.sql @@ -0,0 +1,6 @@ +CREATE TABLE app.unlock_key_verifications ( + tenant_id uuid PRIMARY KEY REFERENCES app.tenants(id) ON DELETE CASCADE, + generation_id uuid NOT NULL, + encrypted_verification text NOT NULL CHECK (length(encrypted_verification) BETWEEN 1 AND 4096), + created_at timestamptz NOT NULL DEFAULT now() +); diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index cd92fd90..c2b3c356 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -131,6 +131,8 @@ const bearerIntegrationDelete = z.object({ expectedRevision: z.number().int().no const bearerIntegrationList = z.object({ revision: z.number().int().nonnegative(), integrations: z.array(bearerIntegrationMetadata) }); const bearerIntegrationWriteResult = z.object({ revision: z.number().int().nonnegative(), duplicate: z.boolean() }); const bearerIntegrationDeleteResult = z.object({ id: z.uuid(), deleted: z.literal(true), revision: z.number().int().nonnegative(), duplicate: z.boolean() }); +const unlockKeyVerification = z.object({ ownerId: z.string(), verification: z.object({ generationId: z.uuid(), encryptedVerification: z.string() }).strict().nullable() }).strict(); +const unlockKeyVerificationInput = z.object({ generationId: z.uuid(), encryptedVerification: z.string().min(1).max(4096) }).strict(); function route( method: string, @@ -209,6 +211,8 @@ function authRoute(method: string, path: string, action: AuthAction, summary: st } export const API_ROUTES: RouteContract[] = [ + route("GET", "/api/v1/unlock-key/verification", "integrations:read", { summary: "Get the current encrypted unlock-key verification record", description: "Requires an interactive owner browser session. Returns user-encrypted verification ciphertext and its key generation; the unlock key is never accepted or returned.", responses: { "200": { description: "Encrypted verification record or empty setup state", content: { "application/json": { schema: jsonSchema(unlockKeyVerification, "output") } } } } }, service => service.getUnlockKeyVerification(), { ownerSession: true }), + route("POST", "/api/v1/unlock-key/verification", "integrations:write", { summary: "Create the encrypted unlock-key verification record", description: "Requires an interactive owner browser session. Stores only browser-encrypted verification ciphertext and permits one setup per account.", responses: { "200": { description: "Created verification record", content: { "application/json": { schema: jsonSchema(z.object({ generationId: z.uuid() }), "output") } } } } }, (service, { body }) => service.createUnlockKeyVerification(body), { body: unlockKeyVerificationInput, maxBodyBytes: 8192, ownerSession: true }), route("GET", "/api/v1/integrations/bearer", "flows:read", { summary: "List encrypted bearer integrations", description: "Requires an interactive owner browser session. Returns safe metadata and user-encrypted ciphertext; credentials are never decrypted or revealed.", diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index b7be1eec..6d9b3e15 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -495,6 +495,20 @@ export class ApiService { const result = await this.bearerWrite({ id, name: existing.name, origin: existing.origin!, description: existing.description, ...input, operation: "delete" }); return { id, deleted: true as const, ...result }; } + async getUnlockKeyVerification() { + await this.authorizeOwnerSession("integrations:read"); + const { rows } = await databaseFor(this.env).pool.query<{ generation_id: string; encrypted_verification: string }>("SELECT generation_id,encrypted_verification FROM app.unlock_key_verifications WHERE tenant_id=$1", [this.auth.tenantId]); + return { ownerId: this.auth.userId, verification: rows[0] ? { generationId: rows[0].generation_id, encryptedVerification: rows[0].encrypted_verification } : null }; + } + async createUnlockKeyVerification(input: { generationId: string; encryptedVerification: string }) { + await this.authorizeOwnerSession("integrations:write"); + let envelope: any; + try { envelope = JSON.parse(input.encryptedVerification); } catch { throw new ServiceError(400, "invalid_request", "Verification ciphertext is malformed."); } + if (!envelope || typeof envelope !== "object" || Array.isArray(envelope) || envelope.version !== 1 || envelope.algorithm !== "A256GCM" || Object.keys(envelope).sort().join(",") !== "algorithm,ciphertext,nonce,version" || typeof envelope.nonce !== "string" || !/^[A-Za-z0-9_-]{16}$/u.test(envelope.nonce) || typeof envelope.ciphertext !== "string" || !/^[A-Za-z0-9_-]{22,}$/u.test(envelope.ciphertext)) throw new ServiceError(400, "invalid_request", "Verification ciphertext is malformed."); + const { rows } = await databaseFor(this.env).pool.query("INSERT INTO app.unlock_key_verifications(tenant_id,generation_id,encrypted_verification) VALUES ($1,$2,$3) ON CONFLICT (tenant_id) DO NOTHING RETURNING generation_id", [this.auth.tenantId, input.generationId, input.encryptedVerification]); + if (!rows.length) throw new ServiceError(409, "conflict", "An unlock key is already set up for this account."); + return { generationId: input.generationId }; + } async removeTailIntegration(id: string) { await this.authorize("integrations:write"); if (!await this.connections().delete(`cloudflare-tail:${id}`)) throw new ServiceError(404, "not_found", "Integration not found"); return { id, deleted: true }; } async linearProjects() { await this.authorize("integrations:read"); return publicValue(z.array(namedOption), await this.providers().linearProjects()); } async linearOptions() { await this.authorize("integrations:read"); return publicValue(providerOptions, await this.providers().linearOptions()); } diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index be466e0e..5a9f32a2 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -94,6 +94,14 @@ const jobInput = { }; describe("Worker OpenAPI request/response boundaries", () => { + it("accepts only browser-encrypted unlock verification and rejects plaintext key fields", async () => { + const payload = { generationId: "00000000-0000-4000-8000-000000000001", encryptedVerification: JSON.stringify({ version: 1, algorithm: "A256GCM", nonce: "AAAAAAAAAAAAAAAA", ciphertext: "AAAAAAAAAAAAAAAAAAAAAA" }) }; + const create = vi.spyOn(ApiService.prototype, "createUnlockKeyVerification").mockResolvedValue({ generationId: payload.generationId }); + await assertResponse(await request("POST", "/api/v1/unlock-key/verification", payload), "POST", "/api/v1/unlock-key/verification", 200); + expect(create).toHaveBeenCalledWith(payload); + await assertResponse(await request("POST", "/api/v1/unlock-key/verification", { ...payload, key: "fzk1.never-send-me" }), "POST", "/api/v1/unlock-key/verification", 400); + expect(create).toHaveBeenCalledTimes(1); + }); it("returns a documented JSON array for a read", async () => { vi.spyOn(ApiService.prototype, "listJobs").mockResolvedValue([]); expect( diff --git a/packages/api/test/api-contract.test.ts b/packages/api/test/api-contract.test.ts index 460028f3..688d7528 100644 --- a/packages/api/test/api-contract.test.ts +++ b/packages/api/test/api-contract.test.ts @@ -56,6 +56,14 @@ describe("versioned API contract", () => { expect(operation?.parameters.shape.projectId).toBeDefined(); expect(openapi.paths["/api/v1/projects/{projectId}/graph"].get["x-required-scope"]).toBe("projects:read"); }); + it("publishes owner-session unlock verification operations and strict ciphertext-only input", () => { + const get = API_ROUTES.find(route => route.method === "GET" && route.path === "/api/v1/unlock-key/verification"); + const post = API_ROUTES.find(route => route.method === "POST" && route.path === "/api/v1/unlock-key/verification"); + expect(get?.scope).toBe("integrations:read"); expect(get?.ownerSession).toBe(true); + expect(post?.scope).toBe("integrations:write"); expect(post?.ownerSession).toBe(true); + expect(post?.body?.safeParse({ generationId: "00000000-0000-4000-8000-000000000001", encryptedVerification: "ciphertext", key: "plain" }).success).toBe(false); + expect(openapi.paths["/api/v1/unlock-key/verification"].post.requestBody).toBeDefined(); + }); it("accepts code jobs without agent prompts or models and rejects missing scripts", () => { const code = { name: "Export", slug: "export", executionType: "code", script: "#!/bin/sh\nprintf '{\"status\":\"succeeded\"}' > \"$FACTORIZE_RESULT_PATH\"", executionConfigId: "exe", triggers: [] }; expect(jobInputSchema.safeParse(code).success).toBe(true); diff --git a/packages/api/test/encrypted-integration-api.postgres.test.ts b/packages/api/test/encrypted-integration-api.postgres.test.ts index e4b59dc2..7aa42ad5 100644 --- a/packages/api/test/encrypted-integration-api.postgres.test.ts +++ b/packages/api/test/encrypted-integration-api.postgres.test.ts @@ -18,6 +18,25 @@ async function userEncrypt(plaintext: string): Promise { } describe.skipIf(!databaseUrl)("browser-only encrypted bearer integration API (PostgreSQL)", { timeout: 60_000 }, () => { + it("stores one ciphertext-only unlock verification per owner and never accepts a plaintext key", async () => { + const f = await loadingFixture(databaseUrl!); + try { + const request = (method = "GET", body?: unknown, cookie = f.cookie) => worker.fetch(new Request(f.env.APP_ORIGIN + "/api/v1/unlock-key/verification", { + method, headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }), f.env, { waitUntil() {} } as any); + expect(await (await request()).json()).toEqual({ ownerId: f.userId, verification: null }); + const generationId = crypto.randomUUID(); + const encryptedVerification = JSON.stringify({ version: 1, algorithm: "A256GCM", nonce: "AAAAAAAAAAAAAAAA", ciphertext: "AAAAAAAAAAAAAAAAAAAAAA" }); + const body = { generationId, encryptedVerification }; + expect((await request("POST", body)).status).toBe(200); + expect(await (await request()).json()).toEqual({ ownerId: f.userId, verification: body }); + const stored = await f.db.pool.query("SELECT generation_id,encrypted_verification FROM app.unlock_key_verifications WHERE tenant_id=$1", [f.tenantId]); + expect(stored.rows).toEqual([{ generation_id: generationId, encrypted_verification: encryptedVerification }]); + expect(JSON.stringify(stored.rows)).not.toContain("fzk1."); + expect((await request("POST", body)).status).toBe(409); + expect((await request("POST", { ...body, unlockKey: "fzk1.must-not-be-accepted" })).status).toBe(400); + } finally { await f.cleanup(); } + }); it("supports safe create, list, update, delete and rejects malformed and stale writes", async () => { const f = await loadingFixture(databaseUrl!); try { diff --git a/packages/app/src/features/settings/integrations.tsx b/packages/app/src/features/settings/integrations.tsx index 110ad828..3535247a 100644 --- a/packages/app/src/features/settings/integrations.tsx +++ b/packages/app/src/features/settings/integrations.tsx @@ -8,6 +8,7 @@ import { installationsQuery } from "../jobs/provider-queries"; import { SettingsLayout } from "./navigation"; import { IntegrationForm } from "./integration-form"; import { messageOf } from "../auth/session"; +import { UnlockKeySetup } from "./unlock-key-setup"; 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"; @@ -38,7 +39,7 @@ export function Integrations() { const buttons = (kind: "exe" | "amp" | "cloudflareTail" | "github", id: string) => { const key = `${kind}:${id}`, current = feedback?.key === key ? feedback : null; return
{kind !== "github" && }{current &&

{current.error ? current.message : `✓ ${current.message}`}

}
; }; const manage = (key: string, form: ReactNode) => openSetup === key &&
{form}
; const hasConnections = Boolean(status.data?.linear || status.data?.clickup || status.data?.exeConnections.length || status.data?.ampConnections.length || status.data?.cloudflareTail.installations.length || github.data?.length); - return + return {status.isPending &&

Loading integrations…

}{[status.error, github.error].filter(Boolean).map((error, i) =>

{error?.message}

)}

Your integrations

Manage the connections already available to your workspace.

{!hasConnections && !status.isPending &&

No integrations added yet

Choose a provider from the available integrations below to get started.

} diff --git a/packages/app/src/features/settings/unlock-key-setup.tsx b/packages/app/src/features/settings/unlock-key-setup.tsx new file mode 100644 index 00000000..60dbdec2 --- /dev/null +++ b/packages/app/src/features/settings/unlock-key-setup.tsx @@ -0,0 +1,45 @@ +import { useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Button, Card, Input, Label } from "../../shared/ui"; +import { createUnlockSetup, generateUnlockKey, getUnlockVerification, verifyUnlockKey } from "../../lib/unlock-key"; + +export function UnlockKeySetup() { + const cache = useQueryClient(); + const verification = useQuery({ queryKey: ["unlock-key-verification"], queryFn: ({ signal }) => getUnlockVerification(signal), retry: false }); + const [pendingKey, setPendingKey] = useState(""); + const [acknowledged, setAcknowledged] = useState(false); + const [enteredKey, setEnteredKey] = useState(""); + const [verified, setVerified] = useState(false); + const setup = useMutation({ retry: false, mutationFn: async () => { + if (!verification.data || verification.data.verification || !pendingKey || !acknowledged) throw new Error("Save and acknowledge your unlock key before setup."); + return createUnlockSetup(verification.data.ownerId, pendingKey, crypto.randomUUID()); + }, onSuccess: async () => { setPendingKey(""); setAcknowledged(false); await cache.invalidateQueries({ queryKey: ["unlock-key-verification"] }); } }); + const check = useMutation({ retry: false, mutationFn: async () => { + const current = verification.data?.verification; + if (!current || !verification.data) throw new Error("Set up an unlock key before verifying it."); + await verifyUnlockKey(enteredKey, verification.data.ownerId, current.generationId, JSON.parse(current.encryptedVerification)); + }, onSuccess: () => setVerified(true), onError: () => setVerified(false) }); + const resetPending = () => { setPendingKey(""); setAcknowledged(false); }; + return +

Unlock key

+ {verification.isPending &&

Checking unlock key setup…

} + {verification.error &&

{verification.error.message}

} + {verification.data && !verification.data.verification && <> +

Generate a key and save it somewhere safe. Factorize cannot recover it. The key is shown once and is never saved in this browser.

+ {!pendingKey ? : <> + + + + + } + } + {verification.data?.verification && <> +

Unlock key verification is set up. Enter your saved key to verify it before encrypting changes. The key is kept only in memory while this page is open.

+ + + {verified &&

Unlock key verified for this account and generation.

} + {check.error &&

Unlock key could not be verified for this account and generation.

} + } + {setup.error &&

{setup.error.message}

} +
; +} diff --git a/packages/app/src/lib/unlock-crypto.ts b/packages/app/src/lib/unlock-crypto.ts index 17921973..900aabcf 100644 --- a/packages/app/src/lib/unlock-crypto.ts +++ b/packages/app/src/lib/unlock-crypto.ts @@ -4,6 +4,7 @@ const VERSION = 1 as const; const KEY_PREFIX = "fzk1."; const SALT = new TextEncoder().encode("factorize.unlock-key.v1"); const INFO = new TextEncoder().encode("factorize.record.aes-256-gcm.v1"); +export const UNLOCK_VERIFICATION_TEXT = "factorize-unlock-key-verification-v1"; export type RecordBinding = { ownerId: string; @@ -106,3 +107,24 @@ export async function decryptRecord(envelope: unknown, key: string, binding: Rec const plaintext = await crypto.subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer(nonce), additionalData: toArrayBuffer(aad), tagLength: 128 }, aesKey, toArrayBuffer(ciphertext)); return new Uint8Array(plaintext); } + +export async function createUnlockVerification(key: string, ownerId: string, generationId: string): Promise { + return encryptRecord(encoder.encode(UNLOCK_VERIFICATION_TEXT), key, { ownerId, recordId: generationId, recordType: "unlock-verification", destination: "factorize", revision: 0 }); +} + +export async function verifyUnlockKey(key: string, ownerId: string, generationId: string, encryptedVerification: unknown): Promise { + const plain = await decryptRecord(encryptedVerification, key, { ownerId, recordId: generationId, recordType: "unlock-verification", destination: "factorize", revision: 0 }); + try { + if (new TextDecoder().decode(plain) !== UNLOCK_VERIFICATION_TEXT) throw new TypeError("Unlock key does not match this account and key generation"); + } finally { plain.fill(0); } +} + +export async function encryptAfterUnlockVerification(key: string, ownerId: string, generationId: string, encryptedVerification: unknown, plaintext: Uint8Array, binding: RecordBinding) { + await verifyUnlockKey(key, ownerId, generationId, encryptedVerification); + return encryptRecord(plaintext, key, binding); +} + +export async function decryptAfterUnlockVerification(key: string, ownerId: string, generationId: string, encryptedVerification: unknown, envelope: unknown, binding: RecordBinding) { + await verifyUnlockKey(key, ownerId, generationId, encryptedVerification); + return decryptRecord(envelope, key, binding); +} diff --git a/packages/app/src/lib/unlock-key.ts b/packages/app/src/lib/unlock-key.ts new file mode 100644 index 00000000..3af6b34d --- /dev/null +++ b/packages/app/src/lib/unlock-key.ts @@ -0,0 +1,18 @@ +import { api } from "factorize-api-client"; +import { createUnlockVerification, generateUnlockKey, verifyUnlockKey } from "./unlock-crypto"; +import { messageOf } from "../features/auth/session"; + +export async function getUnlockVerification(signal?: AbortSignal) { + const { data, error } = await api.GET("/api/v1/unlock-key/verification", { signal }); + if (!data || error) throw new Error(messageOf(error)); + return data; +} + +export async function createUnlockSetup(ownerId: string, key: string, generationId: string) { + const encryptedVerification = JSON.stringify(await createUnlockVerification(key, ownerId, generationId)); + const { data, error } = await api.POST("/api/v1/unlock-key/verification", { body: { generationId, encryptedVerification } }); + if (!data || error) throw new Error(messageOf(error)); + return data; +} + +export { generateUnlockKey, verifyUnlockKey }; diff --git a/packages/app/test/settings.browser.test.mjs b/packages/app/test/settings.browser.test.mjs index 6db26c6d..15a9d2cd 100644 --- a/packages/app/test/settings.browser.test.mjs +++ b/packages/app/test/settings.browser.test.mjs @@ -18,6 +18,51 @@ test("integration setup tests credentials, submits typed fields, clears secrets await form.getByLabel("exe.dev account token").fill("private-input"); await form.getByRole("button", { name: "Test credentials" }).click(); await form.getByText("✓ Credentials verified.", { exact: true }).waitFor(); await form.getByLabel("VM tags").selectOption(["dev"]); await form.getByRole("button", { name: "Save integration", exact: true }).click(); await form.getByText("Integration saved", { exact: true }).waitFor(); assert.deepEqual(body.tags, ["dev"]); assert.equal(body.agentKind, "codex"); assert.equal(await form.getByLabel("exe.dev account token").inputValue(), ""); assert.equal(await page.evaluate(() => JSON.stringify(localStorage).includes("private-input")), false); await page.getByText("dev", { exact: true }).waitFor(); await context.close(); }); +test("unlock-key setup requires acknowledgement, stores ciphertext only, verifies entered keys and survives refresh without a saved key", 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 saved = null, writes = 0; + await page.route("**/api/v1/unlock-key/verification", async route => { + if (route.request().method() === "GET") return route.fulfill({ json: { ownerId: "owner", verification: saved } }); + writes++; + const body = route.request().postDataJSON(); + assert.deepEqual(Object.keys(body).sort(), ["encryptedVerification", "generationId"]); + assert.equal(typeof body.encryptedVerification, "string"); + assert.equal(body.encryptedVerification.includes("fzk1."), false); + saved = { generationId: body.generationId, encryptedVerification: body.encryptedVerification }; + return route.fulfill({ json: { generationId: body.generationId } }); + }); + await page.goto(origin + "/settings/integrations"); + await page.getByRole("button", { name: "Generate unlock key" }).click(); + const key = await page.getByLabel("New unlock key").inputValue(); + assert.match(key, /^fzk1\.[A-Za-z0-9_-]{43}$/u); + await page.getByRole("button", { name: "Cancel setup" }).click(); + assert.equal(writes, 0); + assert.equal(await page.evaluate(() => localStorage.length), 0); + await page.getByRole("button", { name: "Generate unlock key" }).click(); + const savedKey = await page.getByLabel("New unlock key").inputValue(); + await page.getByRole("button", { name: "I saved my key" }).waitFor(); + assert.equal(await page.getByRole("button", { name: "I saved my key" }).isDisabled(), true); + 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(); + 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"); + 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 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(), ""); + assert.equal(await page.getByText(savedKey, { exact: true }).count(), 0); + assert.equal(await page.evaluate(() => localStorage.length), 0); + 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: [] })); diff --git a/packages/app/test/unlock-crypto.test.mjs b/packages/app/test/unlock-crypto.test.mjs index bed77ff1..2ac54691 100644 --- a/packages/app/test/unlock-crypto.test.mjs +++ b/packages/app/test/unlock-crypto.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { decryptRecord, encryptRecord, generateUnlockKey } from "../src/lib/unlock-crypto.ts"; +import { createUnlockVerification, decryptRecord, encryptAfterUnlockVerification, encryptRecord, generateUnlockKey, verifyUnlockKey } from "../src/lib/unlock-crypto.ts"; const key = "fzk1.AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"; const binding = { ownerId: "owner-vector", recordId: "record-vector", recordType: "integration", destination: "https://api.example.test", revision: 7 }; @@ -42,3 +42,15 @@ test("malformed keys and envelopes and unsupported versions are rejected", async } await assert.rejects(decryptRecord({ ...vector, version: 2 }, key, binding), /Unsupported/u); }); + +test("verification records bind the account and generation, and edits verify before encryption", async () => { + const generation = "00000000-0000-4000-8000-000000000001"; + const record = await createUnlockVerification(key, "owner-1", generation); + await verifyUnlockKey(key, "owner-1", generation, record); + await assert.rejects(verifyUnlockKey(key, "owner-2", generation, record)); + await assert.rejects(verifyUnlockKey(key, "owner-1", "00000000-0000-4000-8000-000000000002", record)); + await assert.rejects(verifyUnlockKey("malformed", "owner-1", generation, record)); + const binding = { ownerId: "owner-1", recordId: "record-1", recordType: "integration", destination: "https://api.example.test", revision: 1 }; + await assert.rejects(encryptAfterUnlockVerification("fzk1.AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "owner-1", generation, record, new TextEncoder().encode("edit"), binding)); + assert.ok(await encryptAfterUnlockVerification(key, "owner-1", generation, record, new TextEncoder().encode("edit"), binding)); +}); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 14652096..01ebe83e 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1787,6 +1787,136 @@ components: schema: $ref: "#/components/schemas/Error" paths: + /api/v1/unlock-key/verification: + get: + summary: Get the current encrypted unlock-key verification record + description: |- + Requires an interactive owner browser session. Returns user-encrypted verification ciphertext and its key generation; the unlock key is never accepted or returned. + + Requires the integrations:read scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Encrypted verification record or empty setup state + content: + application/json: + schema: + type: object + properties: + ownerId: + type: string + verification: + anyOf: + - type: object + properties: + generationId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + encryptedVerification: + type: string + required: + - generationId + - encryptedVerification + additionalProperties: false + - type: "null" + required: + - ownerId + - verification + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: get_api_v1_unlock_key_verification + tags: + - unlock-key + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: integrations:read + x-owner-session-required: true + post: + summary: Create the encrypted unlock-key verification record + description: |- + Requires an interactive owner browser session. Stores only browser-encrypted verification ciphertext and permits one setup per account. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Created verification record + content: + application/json: + schema: + type: object + properties: + generationId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + required: + - generationId + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_unlock_key_verification + tags: + - unlock-key + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + generationId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + encryptedVerification: + type: string + minLength: 1 + maxLength: 4096 + required: + - generationId + - encryptedVerification + additionalProperties: false /api/v1/integrations/bearer: get: summary: List encrypted bearer integrations