Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -2515,6 +2547,81 @@ export interface components {
}
export type $defs = Record<string, never>;
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;
Expand Down
6 changes: 6 additions & 0 deletions packages/api/migrations/0034_unlock_key_verifications.sql
Original file line number Diff line number Diff line change
@@ -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()
);
4 changes: 4 additions & 0 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.",
Expand Down
14 changes: 14 additions & 0 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()); }
Expand Down
8 changes: 8 additions & 0 deletions packages/api/test/api-boundary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
8 changes: 8 additions & 0 deletions packages/api/test/api-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
19 changes: 19 additions & 0 deletions packages/api/test/encrypted-integration-api.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,25 @@ async function userEncrypt(plaintext: string): Promise<string> {
}

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 {
Expand Down
3 changes: 2 additions & 1 deletion packages/app/src/features/settings/integrations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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 <div className="flex flex-wrap items-center gap-2">{kind !== "github" && <Button disabled={action.isPending} onClick={() => { setFeedback(null); action.mutate({ kind, id, test: true }); }}>Test connection</Button>}<Button variant="destructive" disabled={action.isPending} onClick={() => { if (window.confirm("Disconnect this integration? Jobs that still reference it must be updated first.")) { setFeedback(null); action.mutate({ kind, id }); } }}>Disconnect</Button>{current && <p role={current.error ? "alert" : "status"} aria-live="polite" className={current.error ? "text-red-700 dark:text-red-400" : "text-green-700 dark:text-green-400"}>{current.error ? current.message : `✓ ${current.message}`}</p>}</div>; };
const manage = (key: string, form: ReactNode) => openSetup === key && <div className="mt-3 border-t border-stone-200 pt-3 dark:border-slate-700">{form}</div>;
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 <SettingsLayout title="Integrations">
return <SettingsLayout title="Integrations"><UnlockKeySetup />
{status.isPending && <p role="status">Loading integrations…</p>}{[status.error, github.error].filter(Boolean).map((error, i) => <p role="alert" key={i}>{error?.message}</p>)}
<section aria-labelledby="your-integrations-heading"><div className="mb-4"><h2 id="your-integrations-heading" className="text-2xl font-bold">Your integrations</h2><p className="mt-1 text-sm text-slate-600 dark:text-slate-400">Manage the connections already available to your workspace.</p></div>
{!hasConnections && !status.isPending && <Card className="border-dashed"><p className="font-semibold">No integrations added yet</p><p className="mt-1 text-sm text-slate-600 dark:text-slate-400">Choose a provider from the available integrations below to get started.</p></Card>}
Expand Down
Loading
Loading