An open-source, faster Devin alternative
TypeScript
api-edge: computer session API mount, key claims, key sync (work 084)
Igor Zalutski via Computerc75424e8a7e0
diff --git a/cloudflare-workers/api-edge/src/api_keys.ts b/cloudflare-workers/api-edge/src/api_keys.tsindex 8659aa9c..75606a5a 100644--- a/cloudflare-workers/api-edge/src/api_keys.ts+++ b/cloudflare-workers/api-edge/src/api_keys.ts@@ -25,8 +25,28 @@ export async function hashAPIKey(key: string): Promise<string> {*/export async function createAPIKey(env: APIKeyEnv,- input: { orgID: string; userID: string; name: string; expiresAt?: number; sessionKey?: string },+ input: CreateAPIKeyInput,): Promise<CreatedAPIKey> {+ return (await createAPIKeyWithHash(env, input)).created;+}++export interface CreateAPIKeyInput {+ orgID: string;+ userID: string;+ name: string;+ expiresAt?: number;+ sessionKey?: string;+}++/**+ * createAPIKey plus the stored SHA-256 hex, for callers that tell the+ * computer API about the new key (work 084). The hash never goes in the+ * one-time response.+ */+export async function createAPIKeyWithHash(+ env: APIKeyEnv,+ input: CreateAPIKeyInput,+): Promise<{ created: CreatedAPIKey; hash: string }> {const bytes = new Uint8Array(32);crypto.getRandomValues(bytes);const plainKey = "osb_" + [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");@@ -42,7 +62,7 @@ export async function createAPIKey(.bind(id, input.orgID, input.userID, hash, prefix, input.name, now, input.expiresAt ?? null, input.sessionKey ?? null).run();- return {+ const created: CreatedAPIKey = {id,orgId: input.orgID,name: input.name,@@ -54,4 +74,5 @@ export async function createAPIKey(? { expiresAt: new Date(input.expiresAt * 1000).toISOString() }: {}),};+ return { created, hash };}diff --git a/cloudflare-workers/api-edge/src/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.tsindex 456ec3dc..afb8e756 100644--- a/cloudflare-workers/api-edge/src/cli_auth.test.ts+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts@@ -472,6 +472,50 @@ describe("CLI device authorization edge contract", () => {expect(logs).not.toContain("[email protected]");});+ it("tells the computer API about the new key by hash (work 084)", async () => {+ const db = new FakeDB();+ const fetchMock = vi.fn(async (url: string, _init?: RequestInit) =>+ String(url).startsWith("https://managedagents.test")+ ? new Response(null, { status: 204 })+ : Response.json({ user: { id: "workos-user", email: "[email protected]", first_name: "Igor" } }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const pending: Promise<unknown>[] = [];+ const syncCtx = {+ waitUntil: (p: Promise<unknown>) => pending.push(p),+ passThroughOnException: vi.fn(),+ } as unknown as ExecutionContext;+ const env = {+ ...testEnv(db),+ MANAGED_AGENTS_API_URL: "https://managedagents.test",+ OC_MANAGED_AGENTS_SECRET: "assert-secret",+ } as Env;++ const resp = await worker.fetch(request("/auth/cli/device/exchange", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ device_code: "opaque", credential_name: "oc CLI on test" }),+ }), env, syncCtx);+ expect(resp.status).toBe(200);+ const body = await resp.json<{ credential: { id: string; key: string } }>();+ await Promise.all(pending);++ const sync = fetchMock.mock.calls.find(([url]) => String(url).endsWith("/v1/computer/keys/sync"));+ expect(sync).toBeDefined();+ const sent = JSON.parse(String(sync?.[1]?.body)) as { key: Record<string, unknown> };+ const insert = db.executed.find((entry) => entry.sql.includes("INSERT INTO api_keys"));+ expect(sent.key).toMatchObject({+ id: body.credential.id,+ hash: insert?.args[3],+ name: "oc CLI on test",+ kind: "user",+ scopes: ["sandbox:*"],+ expiresAt: null,+ userId: userID,+ });+ expect(String(sync?.[1]?.body)).not.toContain(body.credential.key);+ });+it("owns the empty CLI credential-name fallback at the edge", async () => {const db = new FakeDB();vi.stubGlobal("fetch", vi.fn(async () => Response.json({diff --git a/cloudflare-workers/api-edge/src/computer_api.test.ts b/cloudflare-workers/api-edge/src/computer_api.test.tsnew file mode 100644index 00000000..e4190db5--- /dev/null+++ b/cloudflare-workers/api-edge/src/computer_api.test.ts@@ -0,0 +1,761 @@+// The computer's session API at the edge (work 084): which routes are open,+// what the assertion says about the key, the wire Worker for workspace files,+// CORS, and telling blue about created and revoked keys.+import { afterEach, describe, expect, it, vi } from "vitest";++import worker, { type Env } from "./index";+import { hashAPIKey } from "./api_keys";+import { computerApiFamily, isComputerApiRoute } from "./computer_api";++const ORG = "22222222-2222-4222-8222-222222222222";+const USER = "11111111-1111-4111-8111-111111111111";+const ORIGIN = "https://app.opencomputer.dev";+const BLUE = "https://managedagents.test";+const WIRE = "https://wire.test";++interface KeyRow {+ id: string;+ name: string;+ scopes: string;+ created_at: number;+ expires_at: number | null;+}++class FakeStatement {+ private args: unknown[] = [];+ constructor(+ private readonly db: FakeDB,+ private readonly sql: string,+ ) {}+ bind(...args: unknown[]): this {+ this.args = args;+ return this;+ }+ async first<T>(): Promise<T | null> {+ this.db.reads.push({ sql: this.sql, args: this.args });+ if (this.sql.includes("FROM api_keys k")) {+ const row = this.db.keys.get(String(this.args[0]));+ if (!row) return null;+ return {+ org_id: ORG,+ created_by: USER,+ expires_at: row.expires_at,+ session_key: null,+ key_id: row.id,+ key_hash: this.args[0],+ key_name: row.name,+ key_scopes: row.scopes,+ key_created_at: row.created_at,+ user_name: "Igor",+ user_email: "[email protected]",+ role: "admin",+ } as T;+ }+ if (this.sql.includes("SELECT role FROM org_memberships")) {+ return { role: "owner" } as T;+ }+ if (this.sql.includes("SELECT id FROM api_keys WHERE key_hash")) {+ const row = this.db.keys.get(String(this.args[0]));+ return (row ? { id: row.id } : null) as T | null;+ }+ return null;+ }+ async all<T>(): Promise<{ results: T[] }> {+ return { results: [] };+ }+ async run(): Promise<{ meta: { changes: number } }> {+ this.db.executed.push({ sql: this.sql, args: this.args });+ return { meta: { changes: 1 } };+ }+}++class FakeDB {+ keys = new Map<string, KeyRow>();+ reads: { sql: string; args: unknown[] }[] = [];+ executed: { sql: string; args: unknown[] }[] = [];+ prepare(sql: string): FakeStatement {+ return new FakeStatement(this, sql);+ }+ async batch(stmts: FakeStatement[]) {+ return Promise.all(stmts.map((s) => s.run()));+ }+}++function testEnv(db: FakeDB, extra: Partial<Record<string, unknown>> = {}): Env {+ return {+ OPENCOMPUTER_DB: db,+ SESSIONS_KV: {},+ CREDIT_ACCOUNT: {},+ SESSION_JWT_SECRET: "test-session-secret",+ WORKOS_API_KEY: "sk_test",+ WORKOS_CLIENT_ID: "client_test",+ STRIPE_API_KEY: "",+ WORKER_ENV: "test",+ CF_ADMIN_SECRET: "",+ STRIPE_WEBHOOK_SECRET: "",+ EVENT_SECRET: "",+ SECRET_ENCRYPTION_KEY: "",+ MANAGED_AGENTS_API_URL: BLUE,+ OC_MANAGED_AGENTS_SECRET: "assert-secret",+ WIRE_HTTP_URL: WIRE,+ COMPUTER_ENABLED_FOR_ALL: "true",+ ...extra,+ } as unknown as Env;+}++function testCtx() {+ const pending: Promise<unknown>[] = [];+ const ctx = {+ waitUntil: vi.fn((p: Promise<unknown>) => pending.push(p)),+ passThroughOnException: vi.fn(),+ } as unknown as ExecutionContext;+ return { ctx, settle: () => Promise.all(pending) };+}++let keySeq = 0;+// The isolate's auth cache outlives a test, so every test gets its own key.+async function addKey(db: FakeDB, overrides: Partial<KeyRow> = {}): Promise<string> {+ keySeq += 1;+ const key = `osb_test_${keySeq}_${crypto.randomUUID().replace(/-/g, "")}`;+ db.keys.set(await hashAPIKey(key), {+ id: `key-${keySeq}`,+ name: "laptop",+ scopes: "sandbox:*,computer:read",+ created_at: 1_790_000_000,+ expires_at: null,+ ...overrides,+ });+ return key;+}++function b64url(bytes: Uint8Array | ArrayBuffer): string {+ let s = "";+ for (const b of new Uint8Array(bytes)) s += String.fromCharCode(b);+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+}++async function sessionCookie(secret = "test-session-secret"): Promise<string> {+ const enc = new TextEncoder();+ const now = Math.floor(Date.now() / 1000);+ const input =+ b64url(enc.encode(JSON.stringify({ alg: "HS256", typ: "JWT" }))) ++ "." ++ b64url(+ enc.encode(+ JSON.stringify({+ iss: "opensandbox-session",+ sub: USER,+ iat: now,+ exp: now + 3600,+ org_id: ORG,+ user_id: USER,+ plan: "free",+ }),+ ),+ );+ const key = await crypto.subtle.importKey(+ "raw",+ enc.encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(input));+ return `oc_session=${input}.${b64url(sig)}`;+}++function claims(token: string): Record<string, unknown> {+ return JSON.parse(+ atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")),+ ) as Record<string, unknown>;+}++function api(path: string, init?: RequestInit): Request {+ return new Request(`${ORIGIN}/api/managed-agents/computer${path}`, init);+}++function sent(fetchMock: ReturnType<typeof vi.fn>, call = 0) {+ const [url, init] = fetchMock.mock.calls[call] as [string | URL, RequestInit];+ return { url: String(url), init, headers: new Headers(init.headers) };+}++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe("computer API allowlist", () => {+ it.each([+ ["GET", "/computer/me"],+ ["POST", "/computer/tickets"],+ ["GET", "/computer/sessions"],+ ["POST", "/computer/sessions"],+ ["GET", "/computer/sessions/cs_01h"],+ ["PATCH", "/computer/sessions/cs_01h"],+ ["GET", "/computer/sessions/cs_01h/capabilities"],+ ["POST", "/computer/sessions/cs_01h/interrupt"],+ ["POST", "/computer/sessions/cs_01h/compact"],+ ["POST", "/computer/sessions/cs_01h/suspend"],+ ["POST", "/computer/sessions/cs_01h/resume"],+ ["GET", "/computer/sessions/cs_01h/turns"],+ ["POST", "/computer/sessions/cs_01h/turns"],+ ["GET", "/computer/sessions/cs_01h/turns/tn_1"],+ ["POST", "/computer/sessions/cs_01h/turns/tn_1/cancel"],+ ["GET", "/computer/sessions/cs_01h/events"],+ ["GET", "/computer/sessions/cs_01h/asks"],+ ["GET", "/computer/sessions/cs_01h/asks/toolu_1"],+ ["POST", "/computer/sessions/cs_01h/asks/toolu_1/answer"],+ ["POST", "/computer/sessions/cs_01h/asks/toolu_1/dismiss"],+ ["GET", "/computer/secrets"],+ ["PUT", "/computer/sessions/cs_01h/secrets/API_KEY"],+ ["DELETE", "/computer/me/secrets/API_KEY"],+ ["PUT", "/computer/organization/secrets/API_KEY"],+ ["GET", "/computer/sessions/cs_01h/workspace/archive"],+ ["PUT", "/computer/sessions/cs_01h/workspace/archive"],+ ["GET", "/computer/sessions/cs_01h/workspace/file"],+ ["GET", "/computer/sessions/cs_01h/workspace/files"],+ ])("allows %s %s", (method, suffix) => {+ expect(isComputerApiRoute(method, suffix)).toBe(true);+ });++ it.each([+ // Blue's internal key sync is the edge's to call, never a client's.+ ["POST", "/computer/keys/sync"],+ ["POST", "/computer/keys/revoke"],+ ["DELETE", "/computer/sessions/cs_01h"],+ ["PUT", "/computer/sessions/cs_01h/workspace/file"],+ ["POST", "/computer/sessions/cs_01h/turns/tn_1"],+ ["GET", "/computer/sessions/../me"],+ ["GET", "/computer/sessions/.hidden"],+ ["GET", "/computer/sessions/a%2Fb"],+ ["GET", "/computer/sessions/cs_01h/unknown"],+ ["POST", "/computer/slack/install"],+ ])("refuses %s %s", (method, suffix) => {+ expect(isComputerApiRoute(method, suffix)).toBe(false);+ });++ it("serves the API mount only", () => {+ expect(computerApiFamily.apiOnly).toBe(true);+ expect(computerApiFamily.dashboardOnly).toBe(false);+ });++ it("answers 404 in the documented shape and never calls blue for an unlisted route", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/keys/sync", { method: "POST", headers: { "x-api-key": key }, body: "{}" }),+ testEnv(db),+ testCtx().ctx,+ );+ expect(res.status).toBe(404);+ const body = (await res.json()) as { error: Record<string, unknown> };+ expect(body.error).toMatchObject({ code: "not_found", retryable: false });+ expect(String(body.error.requestId)).toMatch(/^req_[0-9a-z]{16}$/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("answers 401 unauthenticated without a credential", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(api("/me"), testEnv(new FakeDB()), testCtx().ctx);+ expect(res.status).toBe(401);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("unauthenticated");+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("answers 401 when x-api-key and Bearer name different keys", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const res = await worker.fetch(+ api("/me", { headers: { "x-api-key": key, authorization: "Bearer osb_other" } }),+ testEnv(db),+ testCtx().ctx,+ );+ expect(res.status).toBe(401);+ });++ it("answers 404 to an organization the computer is not rolled out to", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/me", { headers: { "x-api-key": key } }),+ testEnv(db, { COMPUTER_ENABLED_FOR_ALL: undefined, COMPUTER_ENABLED_ORGS: "org_other" }),+ testCtx().ctx,+ );+ expect(res.status).toBe(404);+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe("computer API proxy to blue", () => {+ it("forwards a key's call to /v1/computer with key claims, headers both ways", async () => {+ const db = new FakeDB();+ const key = await addKey(db, { expires_at: 1_800_000_000 });+ const fetchMock = vi.fn().mockResolvedValue(+ new Response('{"sessions":[],"nextCursor":null}', {+ status: 200,+ headers: {+ "content-type": "application/json",+ "server-timing": "blue;dur=3",+ "x-request-id": "req_0123456789abcdef",+ "x-opc-latest": "0.9.0",+ etag: '"v1"',+ "retry-after": "1",+ "set-cookie": "nope=1",+ },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/sessions?limit=5", {+ headers: {+ authorization: `Bearer ${key}`,+ "idempotency-key": "idem-1",+ "user-agent": "opc/0.9.0",+ "x-request-id": "client-req-1",+ "if-none-match": '"v0"',+ "x-opencomputer-surface": "dashboard",+ "x-opencomputer-agent-token": "forged",+ },+ }),+ testEnv(db),+ testCtx().ctx,+ );+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ sessions: [], nextCursor: null });+ for (const [name, value] of [+ ["server-timing", "blue;dur=3"],+ ["x-request-id", "req_0123456789abcdef"],+ ["x-opc-latest", "0.9.0"],+ ["etag", '"v1"'],+ ["retry-after", "1"],+ ]) {+ expect(res.headers.get(name)).toBe(value);+ }+ expect(res.headers.get("set-cookie")).toBeNull();++ const { url, headers } = sent(fetchMock);+ expect(url).toBe(`${BLUE}/v1/computer/sessions?limit=5`);+ expect(headers.get("idempotency-key")).toBe("idem-1");+ expect(headers.get("user-agent")).toBe("opc/0.9.0");+ expect(headers.get("x-request-id")).toBe("client-req-1");+ expect(headers.get("if-none-match")).toBe('"v0"');+ // The edge says which contract; a client's own value never passes.+ expect(headers.get("x-opencomputer-surface")).toBe("api");+ expect(headers.get("authorization")).toBeNull();+ expect(headers.get("x-api-key")).toBeNull();++ const payload = claims(headers.get("x-opencomputer-agent-token") ?? "");+ expect(payload).toMatchObject({+ iss: "opencomputer-edge",+ aud: "managedagents",+ org_id: ORG,+ user_id: USER,+ role: "admin",+ key_id: `key-${keySeq}`,+ key_hash: await hashAPIKey(key),+ key_name: "laptop",+ key_kind: "user",+ key_scopes: ["sandbox:*", "computer:read"],+ key_expires_at: new Date(1_800_000_000 * 1000).toISOString(),+ key_created_at: new Date(1_790_000_000 * 1000).toISOString(),+ user_name: "Igor",+ user_email: "[email protected]",+ });+ expect(JSON.stringify(payload)).not.toContain(key);+ });++ it("puts key_expires_at null on a key that never expires", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const fetchMock = vi.fn().mockResolvedValue(Response.json({}));+ vi.stubGlobal("fetch", fetchMock);+ await worker.fetch(api("/me", { headers: { "x-api-key": key } }), testEnv(db), testCtx().ctx);+ const payload = claims(sent(fetchMock).headers.get("x-opencomputer-agent-token") ?? "");+ expect(payload.key_expires_at).toBeNull();+ expect(Object.hasOwn(payload, "key_expires_at")).toBe(true);+ });++ it("lets blue mint the request id when the client sent none", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const fetchMock = vi.fn().mockResolvedValue(Response.json({}));+ vi.stubGlobal("fetch", fetchMock);+ await worker.fetch(api("/me", { headers: { "x-api-key": key } }), testEnv(db), testCtx().ctx);+ expect(sent(fetchMock).headers.get("x-request-id")).toBeNull();+ });++ it("asserts a dashboard session with no key claims", async () => {+ const fetchMock = vi.fn().mockResolvedValue(Response.json({ sessions: [], nextCursor: null }));+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/sessions", { headers: { cookie: await sessionCookie() } }),+ testEnv(new FakeDB()),+ testCtx().ctx,+ );+ expect(res.status).toBe(200);+ const { url, headers } = sent(fetchMock);+ expect(url).toBe(`${BLUE}/v1/computer/sessions`);+ expect(headers.get("x-opencomputer-surface")).toBe("api");+ const payload = claims(headers.get("x-opencomputer-agent-token") ?? "");+ expect(payload).toMatchObject({ org_id: ORG, user_id: USER, role: "admin" });+ for (const claim of Object.keys(payload)) {+ expect(claim.startsWith("key_")).toBe(false);+ }+ expect(payload.user_name).toBeUndefined();+ expect(payload.user_email).toBeUndefined();+ });++ it("refuses a cookie's unsafe call from another origin", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/sessions", {+ method: "POST",+ headers: { cookie: await sessionCookie(), origin: "https://evil.sb.opencomputer.dev" },+ body: "{}",+ }),+ testEnv(new FakeDB()),+ testCtx().ctx,+ );+ expect(res.status).toBe(403);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("streams a long-poll body both ways", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const encoder = new TextEncoder();+ let pushLater!: () => void;+ const upstreamBody = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(encoder.encode('{"type":"turn.started"}\n'));+ pushLater = () => {+ controller.enqueue(encoder.encode('{"type":"turn.completed"}\n'));+ controller.close();+ };+ },+ });+ const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {+ expect(init.body).toBeInstanceOf(ReadableStream);+ return new Response(upstreamBody, { headers: { "content-type": "application/x-ndjson" } });+ });+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/sessions/cs_1/turns", {+ method: "POST",+ headers: { "x-api-key": key, "content-type": "application/json" },+ body: new ReadableStream({+ start(c) {+ c.enqueue(encoder.encode('{"input":"hi"}'));+ c.close();+ },+ }),+ duplex: "half",+ } as RequestInit),+ testEnv(db),+ testCtx().ctx,+ );+ const reader = res.body!.getReader();+ // The first event arrives before upstream has finished.+ const first = await reader.read();+ expect(new TextDecoder().decode(first.value)).toBe('{"type":"turn.started"}\n');+ pushLater();+ const second = await reader.read();+ expect(new TextDecoder().decode(second.value)).toBe('{"type":"turn.completed"}\n');+ });++ it("returns a 304 with no body", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 304, headers: { etag: '"v1"' } })));+ const res = await worker.fetch(+ api("/sessions/cs_1", { headers: { "x-api-key": key, "if-none-match": '"v1"' } }),+ testEnv(db),+ testCtx().ctx,+ );+ expect(res.status).toBe(304);+ expect(res.headers.get("etag")).toBe('"v1"');+ });++ it("keeps the dashboard mount's computer list on the dashboard family", async () => {+ const fetchMock = vi.fn().mockResolvedValue(Response.json({ sessions: [] }));+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ new Request(`${ORIGIN}/api/dashboard/managed-agents/computer/sessions`, {+ headers: { cookie: await sessionCookie(), "x-opencomputer-surface": "api" },+ }),+ testEnv(new FakeDB()),+ testCtx().ctx,+ );+ expect(res.status).toBe(200);+ const { url, headers } = sent(fetchMock);+ expect(url).toBe(`${BLUE}/v1/computer/sessions`);+ expect(headers.get("x-opencomputer-surface")).toBeNull();+ });+});++describe("workspace files go to the wire Worker", () => {+ it("forwards the caller's own Authorization and streams the archive up and down", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {+ expect(init.body).toBeInstanceOf(ReadableStream);+ return new Response(+ new ReadableStream({+ start(c) {+ c.enqueue(new Uint8Array([1, 2, 3]));+ c.close();+ },+ }),+ { status: 200, headers: { "content-type": "application/x-tar", etag: '"a"', "x-request-id": "req_x" } },+ );+ });+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/sessions/cs_1/workspace/archive?path=src", {+ method: "PUT",+ headers: {+ authorization: `Bearer ${key}`,+ "content-type": "application/x-tar",+ "content-encoding": "gzip",+ "idempotency-key": "idem-2",+ "x-request-id": "client-2",+ },+ body: new ReadableStream({+ start(c) {+ c.enqueue(new Uint8Array([9, 9]));+ c.close();+ },+ }),+ duplex: "half",+ } as RequestInit),+ testEnv(db),+ testCtx().ctx,+ );+ expect(res.status).toBe(200);+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3]));+ expect(res.headers.get("etag")).toBe('"a"');+ const { url, init, headers } = sent(fetchMock);+ expect(url).toBe(`${WIRE}/v1/sessions/cs_1/workspace/archive?path=src`);+ expect(init.method).toBe("PUT");+ expect(headers.get("authorization")).toBe(`Bearer ${key}`);+ expect(headers.get("content-type")).toBe("application/x-tar");+ expect(headers.get("content-encoding")).toBe("gzip");+ expect(headers.get("idempotency-key")).toBe("idem-2");+ expect(headers.get("x-request-id")).toBe("client-2");+ expect(headers.get("x-opencomputer-agent-token")).toBeNull();+ });++ it("forwards x-api-key as sent and defaults to wire.opencomputer.dev", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const fetchMock = vi.fn().mockResolvedValue(new Response("hello"));+ vi.stubGlobal("fetch", fetchMock);+ await worker.fetch(+ api("/sessions/cs_1/workspace/file?path=README.md", { headers: { "x-api-key": key } }),+ testEnv(db, { WIRE_HTTP_URL: undefined }),+ testCtx().ctx,+ );+ const { url, headers } = sent(fetchMock);+ expect(url).toBe("https://wire.opencomputer.dev/v1/sessions/cs_1/workspace/file?path=README.md");+ expect(headers.get("x-api-key")).toBe(key);+ });++ it("refuses a dashboard session with key_required", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/sessions/cs_1/workspace/files", { headers: { cookie: await sessionCookie() } }),+ testEnv(new FakeDB()),+ testCtx().ctx,+ );+ expect(res.status).toBe(403);+ const body = (await res.json()) as { error: Record<string, unknown> };+ expect(body.error).toMatchObject({ code: "forbidden", reason: "key_required", retryable: false });+ expect(body.error.requestId).toMatch(/^req_/);+ expect(body.error.message).toEqual(expect.any(String));+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("refuses an unknown key before reaching the wire Worker", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/sessions/cs_1/workspace/files", { headers: { "x-api-key": "osb_unknown" } }),+ testEnv(new FakeDB()),+ testCtx().ctx,+ );+ expect(res.status).toBe(401);+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe("computer API CORS", () => {+ it("answers a dashboard preflight", async () => {+ const res = await worker.fetch(+ api("/sessions", {+ method: "OPTIONS",+ headers: { origin: ORIGIN, "access-control-request-method": "POST" },+ }),+ testEnv(new FakeDB()),+ testCtx().ctx,+ );+ expect(res.status).toBe(204);+ expect(res.headers.get("access-control-allow-origin")).toBe(ORIGIN);+ expect(res.headers.get("access-control-allow-headers")).toBe(+ "authorization, content-type, idempotency-key, x-request-id, if-none-match",+ );+ expect(res.headers.get("access-control-allow-methods")).toBe("GET, POST, PATCH, PUT, DELETE");+ expect(res.headers.get("access-control-max-age")).toBe("600");+ });++ it("allows a configured extra origin and ignores others", async () => {+ const env = testEnv(new FakeDB(), { COMPUTER_API_CORS_ORIGINS: "https://dash.example.com" });+ const ok = await worker.fetch(+ api("/me", { method: "OPTIONS", headers: { origin: "https://dash.example.com" } }),+ env,+ testCtx().ctx,+ );+ expect(ok.headers.get("access-control-allow-origin")).toBe("https://dash.example.com");+ const no = await worker.fetch(+ api("/me", { method: "OPTIONS", headers: { origin: "https://evil.example.com" } }),+ env,+ testCtx().ctx,+ );+ expect(no.status).toBe(204);+ expect(no.headers.get("access-control-allow-origin")).toBeNull();+ });++ it("exposes the API's headers on responses", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({}, { headers: { "server-timing": "x;dur=1" } })));+ const res = await worker.fetch(+ api("/me", { headers: { "x-api-key": key, origin: ORIGIN } }),+ testEnv(db),+ testCtx().ctx,+ );+ expect(res.headers.get("access-control-allow-origin")).toBe(ORIGIN);+ expect(res.headers.get("access-control-expose-headers")).toBe(+ "server-timing, x-request-id, x-opc-latest, retry-after, etag",+ );+ expect(res.headers.get("server-timing")).toBe("x;dur=1");+ });+});++describe("key create and revoke tell blue", () => {+ it("syncs a dashboard-created key by hash, never the key", async () => {+ const db = new FakeDB();+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));+ vi.stubGlobal("fetch", fetchMock);+ const { ctx, settle } = testCtx();+ const res = await worker.fetch(+ new Request(`${ORIGIN}/api/dashboard/api-keys`, {+ method: "POST",+ headers: { cookie: await sessionCookie(), "content-type": "application/json" },+ body: JSON.stringify({ name: "ci" }),+ }),+ testEnv(db),+ ctx,+ );+ expect(res.status).toBe(201);+ const created = (await res.json()) as { id: string; key: string; createdAt: string };+ await settle();+ const syncCalls = fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/computer/keys/sync"));+ expect(syncCalls).toHaveLength(1);+ const init = syncCalls[0][1] as RequestInit;+ expect(String(syncCalls[0][0])).toBe(`${BLUE}/v1/computer/keys/sync`);+ expect(init.method).toBe("POST");+ const body = JSON.parse(String(init.body));+ expect(body).toEqual({+ key: {+ id: created.id,+ hash: await hashAPIKey(created.key),+ name: "ci",+ kind: "user",+ scopes: ["sandbox:*"],+ expiresAt: null,+ createdAt: created.createdAt,+ userId: USER,+ },+ });+ expect(String(init.body)).not.toContain(created.key);+ const token = claims(new Headers(init.headers).get("x-opencomputer-agent-token") ?? "");+ expect(token).toMatchObject({ org_id: ORG, user_id: USER, aud: "managedagents" });+ });++ it("reports a dashboard revoke by key id", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));+ vi.stubGlobal("fetch", fetchMock);+ const { ctx, settle } = testCtx();+ const res = await worker.fetch(+ new Request(`${ORIGIN}/api/dashboard/api-keys/key-9`, {+ method: "DELETE",+ headers: { cookie: await sessionCookie() },+ }),+ testEnv(new FakeDB()),+ ctx,+ );+ expect(res.status).toBe(204);+ await settle();+ expect(String(fetchMock.mock.calls[0][0])).toBe(`${BLUE}/v1/computer/keys/revoke`);+ expect(JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body))).toEqual({ keyId: "key-9" });+ });++ it("reports a CLI revoke by key id", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));+ vi.stubGlobal("fetch", fetchMock);+ const { ctx, settle } = testCtx();+ const res = await worker.fetch(+ new Request(`${ORIGIN}/auth/cli/credential`, { method: "DELETE", headers: { "x-api-key": key } }),+ testEnv(db),+ ctx,+ );+ expect(res.status).toBe(204);+ await settle();+ expect(String(fetchMock.mock.calls[0][0])).toBe(`${BLUE}/v1/computer/keys/revoke`);+ expect(JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body))).toEqual({ keyId: `key-${keySeq}` });+ });++ it("keeps the revoke when blue fails, and logs it", async () => {+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("down")));+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ const { ctx, settle } = testCtx();+ const res = await worker.fetch(+ new Request(`${ORIGIN}/api/dashboard/api-keys/key-9`, {+ method: "DELETE",+ headers: { cookie: await sessionCookie() },+ }),+ testEnv(new FakeDB()),+ ctx,+ );+ expect(res.status).toBe(204);+ await settle();+ expect(log).toHaveBeenCalledWith(expect.stringContaining("computer_keys.revoke_failed"));+ });++ it("skips the sync without MANAGED_AGENTS_API_URL", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const { ctx, settle } = testCtx();+ const res = await worker.fetch(+ new Request(`${ORIGIN}/api/dashboard/api-keys`, {+ method: "POST",+ headers: { cookie: await sessionCookie(), "content-type": "application/json" },+ body: "{}",+ }),+ testEnv(new FakeDB(), { MANAGED_AGENTS_API_URL: undefined }),+ ctx,+ );+ expect(res.status).toBe(201);+ await settle();+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/cloudflare-workers/api-edge/src/computer_api.ts b/cloudflare-workers/api-edge/src/computer_api.tsnew file mode 100644index 00000000..be4e4a47--- /dev/null+++ b/cloudflare-workers/api-edge/src/computer_api.ts@@ -0,0 +1,385 @@+// The computer's session API (serverless-agents-ws work 084): the public+// `/api/managed-agents/computer/*` routes, for API keys and dashboard+// sessions. Blue serves them at `/v1/computer/*` and already speaks the+// public contract (objects, errors, `Server-Timing`), so the edge only+// allows the documented routes, asserts who is calling and streams both+// ways: no body is rebuilt or buffered (long-polls hold for up to 60 s).+//+// Workspace files are the exception: `…/workspace/{archive,file,files}` go+// to the wire Worker, which checks the key itself, rather than through blue.+//+// This sits beside the dashboard surface in ./computer.ts, which keeps its+// own mount (`/api/dashboard/managed-agents/computer…`) and shaping.++import { computerEnabledFor } from "./computer";+import type { ManagedAgentsEnv } from "./managed_agents";+import type { RouteFamily } from "./route_family";++export const COMPUTER_API_PREFIX = "/api/managed-agents/computer";+const DEFAULT_WIRE_HTTP_URL = "https://wire.opencomputer.dev";++const COMPUTER_ROUTE = /^\/computer(?:\/|$)/;++// One path segment: an id (`cs_…`, `tn_…`, `ak_…`, a client-chosen session+// id, a foreign `toolu_…`) or a secret name. No dots first, no slashes, no+// percent-escapes, so nothing reaches blue that it would read as another path.+const SEG = "[A-Za-z0-9_][A-Za-z0-9._~:-]{0,199}";++const route = (pattern: string) => new RegExp(`^/computer${pattern}$`);++/** The documented routes (opc docs/api/http/*.mdx), method by method. */+const COMPUTER_API_ROUTES: ReadonlyArray<{+ methods: ReadonlySet<string>;+ pattern: RegExp;+}> = [+ { methods: new Set(["GET"]), pattern: route("/me") },+ { methods: new Set(["POST"]), pattern: route("/tickets") },+ { methods: new Set(["GET", "POST"]), pattern: route("/sessions") },+ { methods: new Set(["GET", "PATCH"]), pattern: route(`/sessions/${SEG}`) },+ {+ methods: new Set(["GET"]),+ pattern: route(`/sessions/${SEG}/capabilities`),+ },+ {+ methods: new Set(["POST"]),+ pattern: route(`/sessions/${SEG}/(?:interrupt|compact|suspend|resume)`),+ },+ { methods: new Set(["GET", "POST"]), pattern: route(`/sessions/${SEG}/turns`) },+ { methods: new Set(["GET"]), pattern: route(`/sessions/${SEG}/turns/${SEG}`) },+ {+ methods: new Set(["POST"]),+ pattern: route(`/sessions/${SEG}/turns/${SEG}/cancel`),+ },+ { methods: new Set(["GET"]), pattern: route(`/sessions/${SEG}/events`) },+ { methods: new Set(["GET"]), pattern: route(`/sessions/${SEG}/asks`) },+ { methods: new Set(["GET"]), pattern: route(`/sessions/${SEG}/asks/${SEG}`) },+ {+ methods: new Set(["POST"]),+ pattern: route(`/sessions/${SEG}/asks/${SEG}/(?:answer|dismiss)`),+ },+ // Secrets (docs/api/http/secrets.mdx).+ { methods: new Set(["GET"]), pattern: route("/secrets") },+ {+ methods: new Set(["PUT", "DELETE"]),+ pattern: route(`/(?:sessions/${SEG}|me|organization)/secrets/${SEG}`),+ },+];++const WORKSPACE_ROUTE = new RegExp(+ `^/computer/sessions/(${SEG})/workspace/(archive|file|files)$`,+);++/** The workspace routes the wire Worker serves, with their methods. */+export function computerWorkspaceRoute(+ method: string,+ suffix: string,+): { sessionID: string; op: string } | null {+ const match = WORKSPACE_ROUTE.exec(suffix);+ if (!match) return null;+ const [, sessionID, op] = match;+ if (method === "GET" || (method === "PUT" && op === "archive")) {+ return { sessionID, op };+ }+ return null;+}++export function isComputerApiRoute(method: string, suffix: string): boolean {+ if (computerWorkspaceRoute(method, suffix)) return true;+ return COMPUTER_API_ROUTES.some(+ (entry) => entry.methods.has(method) && entry.pattern.test(suffix),+ );+}++// ── errors and request ids ───────────────────────────────────────────────++const CROCKFORD = "0123456789abcdefghjkmnpqrstvwxyz";++/** `req_` + 16 lowercase Crockford base32 characters, as blue mints them. */+export function newRequestID(): string {+ const bytes = new Uint8Array(16);+ crypto.getRandomValues(bytes);+ let id = "req_";+ for (const byte of bytes) id += CROCKFORD[byte & 31];+ return id;+}++// A caller's own request id, echoed when it is a plain token.+const CLIENT_REQUEST_ID = /^[A-Za-z0-9._:-]{1,128}$/;++function clientRequestID(request: Request): string | null {+ const value = request.headers.get("x-request-id");+ return value && CLIENT_REQUEST_ID.test(value) ? value : null;+}++/** An edge-made error in the documented shape (docs/api/reference/errors.mdx). */+export function computerApiError(+ request: Request,+ status: number,+ code: string,+ message: string,+ extra: Record<string, unknown> = {},+): Response {+ const requestId = clientRequestID(request) ?? newRequestID();+ return Response.json(+ {+ error: {+ code,+ message,+ requestId,+ retryable: status === 429 || status >= 500,+ ...extra,+ },+ },+ {+ status,+ headers: { "x-request-id": requestId, "cache-control": "no-store" },+ },+ );+}++// ── streaming pass-through ───────────────────────────────────────────────++/** Request headers the computer API reads, beyond the proxy's own. */+const API_REQUEST_HEADERS = ["user-agent", "if-none-match"];++/** Response headers passed back from blue. */+const API_RESPONSE_HEADERS = [+ "content-type",+ "content-length",+ "content-encoding",+ "cache-control",+ "server-timing",+ "x-request-id",+ "x-opc-latest",+ "retry-after",+ "etag",+];++/** Request headers passed to the wire Worker, beside the caller's key. */+const WIRE_REQUEST_HEADERS = [+ "content-type",+ "content-encoding",+ "content-length",+ "idempotency-key",+ "if-none-match",+ "x-request-id",+ "user-agent",+ "accept",+];++/** Response headers passed back from the wire Worker. */+const WIRE_RESPONSE_HEADERS = [+ ...API_RESPONSE_HEADERS,+ "content-disposition",+];++const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);++function streamBack(upstream: Response, names: readonly string[]): Response {+ const headers = new Headers();+ for (const name of names) {+ const value = upstream.headers.get(name);+ if (value) headers.set(name, value);+ }+ // The runtime re-encodes a body it decoded when content-encoding is set,+ // so a length taken before that would be wrong.+ if (headers.has("content-encoding")) headers.delete("content-length");+ if (!headers.has("cache-control")) headers.set("cache-control", "no-store");+ return new Response(+ NULL_BODY_STATUSES.has(upstream.status) ? null : upstream.body,+ { status: upstream.status, statusText: upstream.statusText, headers },+ );+}++function upstreamUnavailable(request: Request, event: string, error: unknown) {+ console.error(+ JSON.stringify({+ level: "error",+ event,+ message: error instanceof Error ? error.message : String(error),+ }),+ );+ return computerApiError(+ request,+ 502,+ "unavailable",+ "The computer API is temporarily unavailable. Try again shortly.",+ );+}++function hasBody(method: string): boolean {+ return method !== "GET" && method !== "HEAD";+}++export const computerApiFamily: RouteFamily = {+ owns: (suffix) => COMPUTER_ROUTE.test(suffix),+ // The workspace routes are allowed on the mount but never reach blue: the+ // index routes them to the wire Worker first (proxyComputerWorkspace).+ allows: (method, suffix) =>+ !computerWorkspaceRoute(method, suffix) &&+ isComputerApiRoute(method, suffix),+ dashboardOnly: false,+ apiOnly: true,+ enabledFor: computerEnabledFor,+ // Unused: forward streams blue's contract body and errors back as they are.+ async shapeSuccess(_method, _suffix, upstream) {+ return upstream;+ },+ errorMessage: (_code, _status, _suffix, backendMessage) => backendMessage,+ async forward({ request, method, target, headers }) {+ for (const name of API_REQUEST_HEADERS) {+ const value = request.headers.get(name);+ if (value) headers.set(name, value);+ }+ // The caller's request id when it sent one; else blue mints a `req_` id+ // and returns it, rather than the edge's internal UUID.+ // Which contract the caller expects: `GET /computer/sessions` is the+ // dashboard's Slack-shaped list on the other mount, and a dashboard+ // session here carries no key claims to tell them apart. The proxy copies+ // only listed headers, so a client-sent value never reaches blue.+ headers.set("x-opencomputer-surface", "api");+ const requestID = clientRequestID(request);+ if (requestID) headers.set("x-request-id", requestID);+ else headers.delete("x-request-id");+ const init: RequestInit = { method, headers, redirect: "manual" };+ if (hasBody(method)) init.body = request.body;+ try {+ return streamBack(await fetch(target, init), API_RESPONSE_HEADERS);+ } catch (error) {+ return upstreamUnavailable(request, "computer_api.upstream_failed", error);+ }+ },+};++/**+ * `…/sessions/{id}/workspace/{archive,file,files}` → the wire Worker's+ * `/v1/sessions/{id}/workspace/{op}`, with the caller's own key: the wire+ * Worker checks it against its KV as it does on an upgrade, so no assertion+ * is minted. Bodies stream both ways (archives are tar streams).+ */+export async function proxyComputerWorkspace(+ request: Request,+ env: Pick<ManagedAgentsEnv, "WIRE_HTTP_URL">,+ workspace: { sessionID: string; op: string },+): Promise<Response> {+ const base = (env.WIRE_HTTP_URL || DEFAULT_WIRE_HTTP_URL).replace(/\/+$/, "");+ const target = new URL(+ `${base}/v1/sessions/${encodeURIComponent(workspace.sessionID)}/workspace/${workspace.op}`,+ );+ target.search = new URL(request.url).search;+ if (target.protocol !== "https:" && target.hostname !== "localhost") {+ return computerApiError(+ request,+ 503,+ "unavailable",+ "The computer API is temporarily unavailable. Try again shortly.",+ );+ }+ const headers = new Headers();+ for (const name of ["authorization", "x-api-key", ...WIRE_REQUEST_HEADERS]) {+ const value = request.headers.get(name);+ if (value) headers.set(name, value);+ }+ const method = request.method.toUpperCase();+ const init: RequestInit = { method, headers, redirect: "manual" };+ if (hasBody(method)) init.body = request.body;+ try {+ return streamBack(await fetch(target, init), WIRE_RESPONSE_HEADERS);+ } catch (error) {+ return upstreamUnavailable(request, "computer_api.wire_failed", error);+ }+}++// ── CORS ─────────────────────────────────────────────────────────────────++const CORS_ALLOW_HEADERS =+ "authorization, content-type, idempotency-key, x-request-id, if-none-match";+const CORS_ALLOW_METHODS = "GET, POST, PATCH, PUT, DELETE";+const CORS_EXPOSE_HEADERS =+ "server-timing, x-request-id, x-opc-latest, retry-after, etag";++/**+ * Whether a browser origin may call the computer API: the edge's own origin+ * (the dashboard is served by this Worker) and any listed in+ * COMPUTER_API_CORS_ORIGINS.+ */+export function computerApiOriginAllowed(+ request: Request,+ env: Pick<ManagedAgentsEnv, "COMPUTER_API_CORS_ORIGINS">,+): boolean {+ const origin = request.headers.get("origin");+ if (!origin) return false;+ if (origin === new URL(request.url).origin) return true;+ return (env.COMPUTER_API_CORS_ORIGINS ?? "")+ .split(",")+ .map((value) => value.trim().replace(/\/+$/, ""))+ .filter(Boolean)+ .includes(origin);+}++function corsHeaders(origin: string): Record<string, string> {+ return {+ "access-control-allow-origin": origin,+ "access-control-allow-credentials": "true",+ vary: "Origin",+ };+}++/** The answer to a preflight on the computer API. */+export function computerApiPreflight(+ request: Request,+ env: Pick<ManagedAgentsEnv, "COMPUTER_API_CORS_ORIGINS">,+): Response {+ const origin = request.headers.get("origin");+ if (!origin || !computerApiOriginAllowed(request, env)) {+ return new Response(null, { status: 204, headers: { vary: "Origin" } });+ }+ return new Response(null, {+ status: 204,+ headers: {+ ...corsHeaders(origin),+ "access-control-allow-headers": CORS_ALLOW_HEADERS,+ "access-control-allow-methods": CORS_ALLOW_METHODS,+ "access-control-max-age": "600",+ },+ });+}++/** Adds the CORS answer for an allowed origin to a computer API response. */+export function withComputerApiCors(+ request: Request,+ env: Pick<ManagedAgentsEnv, "COMPUTER_API_CORS_ORIGINS">,+ response: Response,+): Response {+ const origin = request.headers.get("origin");+ if (!origin || !computerApiOriginAllowed(request, env)) return response;+ // A WebSocket or otherwise immutable response is returned as it is.+ if (response.status === 101) return response;+ const headers = new Headers(response.headers);+ for (const [name, value] of Object.entries(corsHeaders(origin))) {+ headers.set(name, value);+ }+ headers.set("access-control-expose-headers", CORS_EXPOSE_HEADERS);+ return new Response(response.body, {+ status: response.status,+ statusText: response.statusText,+ headers,+ });+}++// ── credentials ──────────────────────────────────────────────────────────++/**+ * The API key a computer API request carries: `x-api-key` or+ * `Authorization: Bearer` (docs/api/authentication.mdx). Both present and+ * different is a 401, as documented.+ */+export function computerApiKey(+ request: Request,+): { key: string | null } | { conflict: true } {+ const header = request.headers.get("x-api-key");+ const authorization = request.headers.get("authorization");+ const bearer = authorization?.match(/^Bearer\s+(\S+)\s*$/i)?.[1] ?? null;+ if (header && bearer && header !== bearer) return { conflict: true };+ return { key: header || bearer };+}diff --git a/cloudflare-workers/api-edge/src/computer_keys.ts b/cloudflare-workers/api-edge/src/computer_keys.tsnew file mode 100644index 00000000..25ec068f--- /dev/null+++ b/cloudflare-workers/api-edge/src/computer_keys.ts@@ -0,0 +1,122 @@+// API key lifecycle → the computer (work 084). Blue keeps its own record of+// the organization's keys (by hash, never the key) so it can name the key+// that acted and refuse a revoked one at once rather than after the edge's+// auth cache ages out. The edge tells it when a key is created or revoked.+//+// Best-effort: callers hand the promise to ctx.waitUntil, failures are+// logged and never reach the person creating or revoking the key. Without+// MANAGED_AGENTS_API_URL or OC_MANAGED_AGENTS_SECRET it does nothing.++import {+ mintManagedAgentsAssertion,+ type ManagedAgentsEnv,+} from "./managed_agents";++export interface SyncedComputerKey {+ id: string;+ /** SHA-256 hex of the key. */+ hash: string;+ name: string;+ kind: "user" | "project";+ scopes: string[];+ expiresAt: string | null;+ createdAt: string;+ userId: string | null;+}++type SyncEnv = Pick<+ ManagedAgentsEnv,+ "MANAGED_AGENTS_API_URL" | "OC_MANAGED_AGENTS_SECRET"+>;++async function post(+ env: SyncEnv,+ orgID: string,+ userID: string | null,+ op: "sync" | "revoke",+ body: unknown,+): Promise<void> {+ const base = env.MANAGED_AGENTS_API_URL?.replace(/\/+$/, "");+ if (!base || !env.OC_MANAGED_AGENTS_SECRET) return;+ try {+ const assertion = await mintManagedAgentsAssertion(+ env.OC_MANAGED_AGENTS_SECRET,+ { orgID, userID },+ );+ const response = await fetch(`${base}/v1/computer/keys/${op}`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "x-opencomputer-agent-token": assertion,+ },+ body: JSON.stringify(body),+ });+ if (!response.ok) {+ console.error(+ JSON.stringify({+ level: "error",+ event: `computer_keys.${op}_failed`,+ status: response.status,+ }),+ );+ }+ await response.body?.cancel();+ } catch (error) {+ console.error(+ JSON.stringify({+ level: "error",+ event: `computer_keys.${op}_failed`,+ message: error instanceof Error ? error.message : String(error),+ }),+ );+ }+}++/** A key was created: asserted as its organization and creator. */+export function syncComputerKey(+ env: SyncEnv,+ orgID: string,+ key: SyncedComputerKey,+): Promise<void> {+ return post(env, orgID, key.userId, "sync", { key });+}++/** A key was revoked: asserted as its organization and the person revoking. */+export function revokeComputerKey(+ env: SyncEnv,+ orgID: string,+ actingUserID: string | null,+ keyID: string,+): Promise<void> {+ return post(env, orgID, actingUserID, "revoke", { keyId: keyID });+}++/** The sync shape of a key just created, from what createAPIKey returned. */+export function createdKeyForSync(+ created: {+ id: string;+ name: string;+ scopes?: string[] | string;+ expiresAt?: string | null;+ createdAt?: string;+ },+ hash: string,+ userID: string | null,+): SyncedComputerKey {+ const scopes = Array.isArray(created.scopes)+ ? created.scopes+ : (created.scopes ?? "")+ .split(",")+ .map((scope) => scope.trim())+ .filter(Boolean);+ return {+ id: created.id,+ hash,+ name: created.name,+ kind: "user",+ scopes,+ expiresAt: created.expiresAt ?? null,+ createdAt: created.createdAt ?? new Date().toISOString(),+ userId: userID,+ };+}diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 494ee668..8079c9bb 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -33,7 +33,8 @@ import {acknowledgeAgentSecurityNotification,listAgentSecurityNotifications,} from "./agent_security_notifications";-import { createAPIKey } from "./api_keys";+import { createAPIKeyWithHash } from "./api_keys";+import { createdKeyForSync, revokeComputerKey, syncComputerKey } from "./computer_keys";import {proxyManagedAgents,proxyPublicTemplateInspection,@@ -645,7 +646,12 @@ async function handleListAPIKeys(_req: Request, env: DashboardEnv, caller: Callereturn json(keys);}-async function handleCreateAPIKey(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {+async function handleCreateAPIKey(+ req: Request,+ env: DashboardEnv,+ ctx: ExecutionContext | undefined,+ caller: Caller,+): Promise<Response> {const body = await req.json<{ name?: string; expiresAt?: unknown }>().catch(() => ({} as { name?: string; expiresAt?: unknown }));const name = (body.name ?? "Untitled").trim() || "Untitled";@@ -656,16 +662,31 @@ async function handleCreateAPIKey(req: Request, env: DashboardEnv, caller: Calleif (ms <= Date.now()) return json({ error: "expiresAt must be in the future" }, 400);expiresAt = Math.floor(ms / 1000);}- return json(await createAPIKey(env, {+ const { created, hash } = await createAPIKeyWithHash(env, {orgID: caller.orgID,userID: caller.userID,name,expiresAt,- }), 201);+ });+ // Tell the computer API about the key (work 084); never the key itself.+ ctx?.waitUntil(+ syncComputerKey(env, caller.orgID, createdKeyForSync(created, hash, caller.userID)),+ );+ return json(created, 201);}-async function handleDeleteAPIKey(_req: Request, env: DashboardEnv, caller: Caller, keyID: string): Promise<Response> {- await env.OPENCOMPUTER_DB.prepare(`DELETE FROM api_keys WHERE id = ?1 AND org_id = ?2`).bind(keyID, caller.orgID).run();+async function handleDeleteAPIKey(+ _req: Request,+ env: DashboardEnv,+ ctx: ExecutionContext | undefined,+ caller: Caller,+ keyID: string,+): Promise<Response> {+ const result = await env.OPENCOMPUTER_DB.prepare(`DELETE FROM api_keys WHERE id = ?1 AND org_id = ?2`).bind(keyID, caller.orgID).run();+ // Only a key this org held is reported revoked (D1 says how many rows went).+ if (result?.meta?.changes !== 0) {+ ctx?.waitUntil(revokeComputerKey(env, caller.orgID, caller.userID, keyID));+ }return new Response(null, { status: 204 });}@@ -1033,7 +1054,7 @@ async function proxyToBrowserAPI(export async function handleDashboard(req: Request,env: DashboardEnv,- _ctx: ExecutionContext,+ ctx: ExecutionContext,path: string,): Promise<Response> {// /api/dashboard/* — strip the prefix for routing.@@ -1170,10 +1191,10 @@ export async function handleDashboard(// ── api keys ───────────────────────────────────────────────────────────if (sub === "/api-keys" && method === "GET") return handleListAPIKeys(req, env, caller);- if (sub === "/api-keys" && method === "POST") return handleCreateAPIKey(req, env, caller);+ if (sub === "/api-keys" && method === "POST") return handleCreateAPIKey(req, env, ctx, caller);{const m = sub.match(/^\/api-keys\/([^/]+)$/);- if (m && method === "DELETE") return handleDeleteAPIKey(req, env, caller, m[1]);+ if (m && method === "DELETE") return handleDeleteAPIKey(req, env, ctx, caller, m[1]);if (m && method === "PATCH") return handleRenameAPIKey(req, env, caller, m[1]);}diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 9cc8fe33..914d2d8c 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -55,7 +55,7 @@ import {type CellRow,type OrgPolicy,} from "./create_context_cache";-import { handleDashboard, type DashboardEnv } from "./dashboard";+import { authDashboard, handleDashboard, type DashboardEnv } from "./dashboard";import { handleAgentFeedback, isAgentFeedbackPath, type AgentFeedbackEnv } from "./agent_feedback";import {AGENT_SECURITY_NOTIFICATION_PATH,@@ -84,7 +84,7 @@ import * as secretStores from "./secret_stores";import * as snapshots from "./snapshots";import * as templates from "./templates";import * as webhooks from "./webhooks";-import { createAPIKey, hashAPIKey } from "./api_keys";+import { createAPIKey, createAPIKeyWithHash, hashAPIKey } from "./api_keys";import { envWithD1Retry } from "./d1_retry";import {handleAgentWebhookInvocation,@@ -97,7 +97,21 @@ import {handleComputerAgentConnect,handleManagedAgentChannelConnection,proxyManagedAgents,+ type AssertedAPIKey,} from "./managed_agents";+import {+ computerApiError,+ computerApiKey,+ computerApiOriginAllowed,+ computerApiPreflight,+ computerWorkspaceRoute,+ isComputerApiRoute,+ proxyComputerWorkspace,+ withComputerApiCors,+ COMPUTER_API_PREFIX,+} from "./computer_api";+import { computerEnabledFor } from "./computer";+import { createdKeyForSync, revokeComputerKey, syncComputerKey } from "./computer_keys";export interface Env extends DashboardEnv, AgentFeedbackEnv {CF_ADMIN_SECRET: string;@@ -110,6 +124,12 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv {CLI_AUTH_EXCHANGE_RATE_LIMIT: RateLimit;// Public CLI connect (work 082), per caller IP ahead of blue.COMPUTER_CONNECT_RATE_LIMIT?: RateLimit;+ // The computer API (work 084): the wire Worker's HTTP base for workspace+ // files (default https://wire.opencomputer.dev), and extra browser origins+ // allowed to call /api/managed-agents/computer/* (comma-separated; the+ // edge's own origin is always allowed).+ WIRE_HTTP_URL?: string;+ COMPUTER_API_CORS_ORIGINS?: string;// Dedicated HMAC secret for the Sessions API's minimal Agent Hook exposure// alert. It is intentionally not shared with other internal routes.OC_SECURITY_NOTIFICATION_SECRET?: string;@@ -398,6 +418,12 @@ interface Caller {// the Slack thread the key was minted for, when the gateway named one.principal?: "computer";sessionKey?: string;+ // The key itself, for the computer API's assertion (work 084): blue records+ // which key acted. Absent on provision tokens and on entries cached before+ // these fields existed (the computer path re-reads those).+ key?: AssertedAPIKey;+ userName?: string | null;+ userEmail?: string | null;}const COMPUTER_PRINCIPAL = "computer";@@ -415,9 +441,34 @@ function callerFromRow(row: AuthRow): Caller {...(row.role ? { role: row.role } : {}),...(computer ? { principal: "computer" as const } : {}),...(computer && row.session_key ? { sessionKey: row.session_key } : {}),+ ...(row.key_id && row.key_hash+ ? {+ key: {+ id: row.key_id,+ hash: row.key_hash,+ name: row.key_name ?? "",+ // api_keys has no project keys: every key belongs to its creator.+ kind: "user" as const,+ scopes: (row.key_scopes ?? "")+ .split(",")+ .map((scope) => scope.trim())+ .filter(Boolean),+ expiresAt: epochToISO(row.expires_at),+ createdAt: epochToISO(row.key_created_at) ?? new Date(0).toISOString(),+ },+ userName: row.user_name ?? null,+ userEmail: row.user_email ?? null,+ }+ : {}),};}+function epochToISO(seconds: number | null | undefined): string | null {+ return typeof seconds === "number" && Number.isFinite(seconds)+ ? new Date(seconds * 1000).toISOString()+ : null;+}+interface SandboxCreateResult {sandboxID?: string;workerID?: string;@@ -612,10 +663,13 @@ function bumpLastUsed(env: Env, hash: string, entry: AuthEntry, nowMs: number):}const AUTH_KEY_SQL = `SELECT k.org_id, k.created_by, k.expires_at, k.session_key,+ k.id AS key_id, k.key_hash, k.name AS key_name, k.scopes AS key_scopes,+ k.created_at AS key_created_at, u.name AS user_name, u.email AS user_email,CASE WHEN m.role IN ('owner', 'admin') THEN 'admin' ELSE m.role END AS roleFROM api_keys kLEFT JOIN org_memberships mON m.org_id = k.org_id AND m.user_id = k.created_by+ LEFT JOIN users u ON u.id = k.created_byWHERE k.key_hash = ?1`;// One row shape for both readers. refreshAuth repopulates the same cache tiers@@ -627,6 +681,13 @@ type AuthRow = {expires_at: number | null;role: string | null;session_key?: string | null;+ key_id?: string | null;+ key_hash?: string | null;+ key_name?: string | null;+ key_scopes?: string | null;+ key_created_at?: number | null;+ user_name?: string | null;+ user_email?: string | null;};// In-flight auth refreshes, keyed by hash — same single-flight shape as@@ -688,6 +749,10 @@ export interface AuthProbe {async function authenticate(req: Request, env: Env, ctx?: ExecutionContext, probe?: AuthProbe): Promise<Caller | null> {const apiKey = apiKeyFromRequest(req);if (!apiKey) return null;+ return authenticateKey(apiKey, env, ctx, probe);+}++async function authenticateKey(apiKey: string, env: Env, ctx?: ExecutionContext, probe?: AuthProbe): Promise<Caller | null> {// Act-as-org provisioning token (sessions-api): a signed JWT, not an osb_ key.// Recognized only when OC_PROVISION_SECRET is configured — inert otherwise, so// a stray JWT can't authenticate. The edge re-derives the org from the token;@@ -4452,7 +4517,7 @@ function providerErrorCode(body: Record<string, unknown> | null): string {return typeof body?.error === "string" ? body.error : "";}-async function authCLIExchange(req: Request, env: Env): Promise<Response> {+async function authCLIExchange(req: Request, env: Env, ctx?: ExecutionContext): Promise<Response> {const requestID = crypto.randomUUID();const startedAt = Date.now();const finish = (@@ -4583,11 +4648,20 @@ async function authCLIExchange(req: Request, env: Env): Promise<Response> {let credential;try {- credential = await createAPIKey(env, {+ const made = await createAPIKeyWithHash(env, {orgID: identity.org.id,userID: identity.user.id,name: credentialName,});+ credential = made.created;+ // Tell the computer API about the key (work 084); never the key itself.+ ctx?.waitUntil(+ syncComputerKey(+ env,+ identity.org.id,+ createdKeyForSync(made.created, made.hash, identity.user.id),+ ),+ );} catch {return finish(cliAuthError("credential_creation_failed", 503),@@ -4616,7 +4690,107 @@ async function authCLIExchange(req: Request, env: Env): Promise<Response> {});}-async function authCLIRevoke(req: Request, env: Env): Promise<Response> {+// ── computer API (work 084) ─────────────────────────────────────────────++const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);++/**+ * /api/managed-agents/computer/*: authenticates an API key (`x-api-key` or+ * `Authorization: Bearer`) or a dashboard session, then streams the call to+ * blue (or, for workspace files, to the wire Worker). Errors here use the+ * documented shape; blue's own pass through untouched.+ */+async function handleComputerApi(+ req: Request,+ env: Env,+ ctx: ExecutionContext,+ path: string,+): Promise<Response> {+ const method = req.method.toUpperCase();+ if (method === "OPTIONS") return computerApiPreflight(req, env);+ const suffix = path.slice("/api/managed-agents".length);+ if (!isComputerApiRoute(method, suffix)) {+ return computerApiError(req, 404, "not_found", "No such route.");+ }++ const credential = computerApiKey(req);+ if ("conflict" in credential) {+ return computerApiError(+ req,+ 401,+ "unauthenticated",+ "The x-api-key and Authorization headers name different keys.",+ );+ }+ let caller: Caller | null = null;+ let viaKey = false;+ if (credential.key) {+ viaKey = true;+ caller = await authenticateKey(credential.key, env, ctx);+ // Entries cached before the key fields existed: re-read the row once, so+ // blue always learns which key acted.+ if (caller && !caller.key && !caller.scope) {+ await refreshAuth(env, await hashAPIKey(credential.key));+ caller = await authenticateKey(credential.key, env, ctx);+ }+ if (caller?.scope) {+ return computerApiError(req, 403, "forbidden", "This credential cannot use the computer API.", {+ reason: "scope_missing",+ });+ }+ } else {+ const session = await authDashboard(req, env);+ if (session) {+ // A cookie rides along on cross-site requests SameSite=Lax still+ // allows (sibling subdomains); unsafe methods need an allowed Origin.+ if (!SAFE_METHODS.has(method) && !computerApiOriginAllowed(req, env)) {+ return computerApiError(req, 403, "forbidden", "Cross-origin request refused.", {+ reason: "origin_not_allowed",+ });+ }+ const membership = await env.OPENCOMPUTER_DB.prepare(+ `SELECT role FROM org_memberships WHERE org_id = ?1 AND user_id = ?2`,+ )+ .bind(session.orgID, session.userID)+ .first<{ role: string }>();+ if (!membership) {+ return computerApiError(req, 401, "unauthenticated", "Sign in again.");+ }+ caller = {+ orgID: session.orgID,+ userID: session.userID,+ role:+ membership.role === "owner" || membership.role === "admin"+ ? "admin"+ : membership.role,+ };+ }+ }+ if (!caller) {+ return computerApiError(req, 401, "unauthenticated", "Missing or invalid API key.");+ }+ if (!computerEnabledFor(env, caller.orgID)) {+ return computerApiError(req, 404, "not_found", "No such route.");+ }++ const workspace = computerWorkspaceRoute(method, suffix);+ if (workspace) {+ // The wire Worker checks the caller's key itself; a cookie is not one.+ if (!viaKey) {+ return computerApiError(+ req,+ 403,+ "forbidden",+ "Workspace files need an API key; dashboard sessions cannot read them here.",+ { reason: "key_required" },+ );+ }+ return proxyComputerWorkspace(req, env, workspace);+ }+ return proxyManagedAgents(req, env, caller, "/api/managed-agents");+}++async function authCLIRevoke(req: Request, env: Env, ctx?: ExecutionContext): Promise<Response> {const requestID = crypto.randomUUID();const startedAt = Date.now();const finish = (response: Response, result: string): Response => {@@ -4640,8 +4814,17 @@ async function authCLIRevoke(req: Request, env: Env): Promise<Response> {if (!caller || caller.scope) {return finish(cliAuthError("missing or invalid API key", 401), "unauthorized");}+ let keyID: string | null = caller.key?.id ?? null;try {const hash = await hashAPIKey(plainKey);+ if (!keyID && env.MANAGED_AGENTS_API_URL) {+ const row = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id FROM api_keys WHERE key_hash = ?1 AND org_id = ?2`,+ )+ .bind(hash, caller.orgID)+ .first<{ id?: string }>();+ keyID = row?.id ?? null;+ }await env.OPENCOMPUTER_DB.prepare(`DELETE FROM api_keys WHERE key_hash = ?1 AND org_id = ?2`,)@@ -4650,6 +4833,7 @@ async function authCLIRevoke(req: Request, env: Env): Promise<Response> {} catch {return finish(cliAuthError("credential_revocation_unavailable", 503), "storage_error");}+ if (keyID) ctx?.waitUntil(revokeComputerKey(env, caller.orgID, caller.userID, keyID));return finish(new Response(null, {status: 204,headers: { "cache-control": "no-store" },@@ -5382,19 +5566,15 @@ export default {// cache would hit and serve a subtly different caller.const rows = await env.OPENCOMPUTER_DB.prepare(`SELECT k.key_hash, k.org_id, k.created_by, k.expires_at, k.session_key,+ k.id AS key_id, k.name AS key_name, k.scopes AS key_scopes,+ k.created_at AS key_created_at, u.name AS user_name, u.email AS user_email,CASE WHEN m.role IN ('owner', 'admin') THEN 'admin' ELSE m.role END AS roleFROM api_keys kLEFT JOIN org_memberships mON m.org_id = k.org_id AND m.user_id = k.created_by+ LEFT JOIN users u ON u.id = k.created_byWHERE k.org_id = ?1`,- ).bind(parsed.org_id).all<{- key_hash: string;- org_id: string;- created_by: string | null;- expires_at: number | null;- role: string | null;- session_key: string | null;- }>();+ ).bind(parsed.org_id).all<AuthRow & { key_hash: string }>();const at = Date.now();let warmed = 0;@@ -5622,10 +5802,10 @@ export default {return authCLIStart(req, env);}if (path === "/auth/cli/device/exchange") {- return authCLIExchange(req, env);+ return authCLIExchange(req, env, ctx);}if (path === "/auth/cli/credential") {- return authCLIRevoke(req, env);+ return authCLIRevoke(req, env, ctx);}// Browser auth flow.@@ -5717,6 +5897,12 @@ export default {if (path.startsWith("/api/agent-webhooks/")) {return handleAgentWebhookInvocation(req, env);}+ // The computer's session API (work 084), for API keys and dashboard+ // sessions alike. Below the Slack and connect mounts above, which keep+ // their own credentials.+ if (path === COMPUTER_API_PREFIX || path.startsWith(`${COMPUTER_API_PREFIX}/`)) {+ return withComputerApiCors(req, env, await handleComputerApi(req, env, ctx, path));+ }if (path === "/api/managed-agents" ||path.startsWith("/api/managed-agents/")diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 7ce8dfb6..b48dd23d 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -1,6 +1,7 @@import { getAutumnCustomer } from "./autumn_webhook";import { FREE_CREDITS_PAYWALL } from "./billing_onramp";import { computerFamily } from "./computer";+import { computerApiFamily } from "./computer_api";import type { RouteFamily } from "./route_family";export interface ManagedAgentsEnv {@@ -15,6 +16,28 @@ export interface ManagedAgentsEnv {/** Per-IP cap on the public CLI connect route (work 082). */COMPUTER_CONNECT_RATE_LIMIT?: RateLimit;WORKER_ENV?: string;+ /** The wire Worker's HTTP base (work 084); default https://wire.opencomputer.dev. */+ WIRE_HTTP_URL?: string;+ /** Extra browser origins for /api/managed-agents/computer, comma-separated. */+ COMPUTER_API_CORS_ORIGINS?: string;+}++/**+ * The API key a request authenticated with (work 084), asserted to managed+ * agents so the computer API can apply the key's scopes and name the key.+ * Absent for dashboard sessions, which blue reads as "session credential,+ * all scopes".+ */+export interface AssertedAPIKey {+ id: string;+ /** SHA-256 hex of the key; the key itself never leaves the edge. */+ hash: string;+ name: string;+ kind: "user" | "project";+ /** The raw `scopes` column, split on commas (legacy keys: `sandbox:*`). */+ scopes: string[];+ expiresAt: string | null;+ createdAt: string;}export interface ManagedAgentsCaller {@@ -25,6 +48,11 @@ export interface ManagedAgentsCaller {principal?: "computer";/** The computer session (Slack thread) the key was minted for. */sessionKey?: string;+ /** Set only when the caller authenticated with an API key (work 084). */+ key?: AssertedAPIKey;+ /** The key creator's name and email, when the auth read loaded them. */+ userName?: string | null;+ userEmail?: string | null;}const DEFAULT_MANAGED_AGENTS_API_URL = "https://managedagents.opencomputer.dev";@@ -104,6 +132,17 @@ export async function mintManagedAgentsAssertion(if (caller.role) payload.role = caller.role;if (caller.principal) payload.principal = caller.principal;if (caller.principal && caller.sessionKey) payload.session_key = caller.sessionKey;+ if (caller.key) {+ payload.key_id = caller.key.id;+ payload.key_hash = caller.key.hash;+ payload.key_name = caller.key.name;+ payload.key_kind = caller.key.kind;+ payload.key_scopes = caller.key.scopes;+ payload.key_expires_at = caller.key.expiresAt;+ payload.key_created_at = caller.key.createdAt;+ if (caller.userName) payload.user_name = caller.userName;+ if (caller.userEmail) payload.user_email = caller.userEmail;+ }const encoder = new TextEncoder();const signingInput =`${b64url(encoder.encode(JSON.stringify(header)))}.` +@@ -295,7 +334,7 @@ async function publicErrorResponse(: undefined;const familyMessage =suffix !== undefined- ? routeFamilyFor(suffix)?.errorMessage(+ ? routeFamilyFor(suffix, DASHBOARD_MANAGED_AGENTS_PREFIX)?.errorMessage(backendCode,upstream.status,suffix,@@ -2720,16 +2759,34 @@ export function isGrantRoute(method: string, suffix: string): boolean {}// The route families the proxy dispatches to as a unit (see route_family.ts).-// Only the organization's computer so far (work 052); the other surfaces keep-// their branches below until each is ported.-const ROUTE_FAMILIES: ReadonlyArray<RouteFamily> = [computerFamily];+// Only the organization's computer so far: its dashboard surface (work 052)+// on the dashboard mount and its session API (work 084) on the API mount; the+// other surfaces keep their branches below until each is ported.+const ROUTE_FAMILIES: ReadonlyArray<RouteFamily> = [+ computerFamily,+ computerApiFamily,+];-function routeFamilyFor(suffix: string): RouteFamily | undefined {- return ROUTE_FAMILIES.find((family) => family.owns(suffix));+function routeFamilyFor(+ suffix: string,+ publicPrefix: string,+): RouteFamily | undefined {+ const dashboard = publicPrefix === DASHBOARD_MANAGED_AGENTS_PREFIX;+ return (+ ROUTE_FAMILIES.find(+ (family) =>+ family.owns(suffix) &&+ (dashboard ? !family.apiOnly : !family.dashboardOnly),+ ) ?? ROUTE_FAMILIES.find((family) => family.owns(suffix))+ );}-function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {- const family = routeFamilyFor(suffix);+function isAllowedManagedAgentsRoute(+ method: string,+ suffix: string,+ publicPrefix: string,+): boolean {+ const family = routeFamilyFor(suffix, publicPrefix);if (family) return family.allows(method, suffix);if (method === "GET" && suffix === "/account/runtime-profile") return true;if (method === "POST" && suffix === "/template-inspections") return true;@@ -3795,7 +3852,13 @@ export async function proxyManagedAgents() {return Response.json({ error: "route not found" }, { status: 404 });}- if (!isAllowedManagedAgentsRoute(request.method.toUpperCase(), suffix)) {+ if (+ !isAllowedManagedAgentsRoute(+ request.method.toUpperCase(),+ suffix,+ publicPrefix,+ )+ ) {return Response.json({ error: "route not found" }, { status: 404 });}if (@@ -3813,11 +3876,12 @@ export async function proxyManagedAgents({ status: 403 },);}- const family = routeFamilyFor(suffix);+ const family = routeFamilyFor(suffix, publicPrefix);if (family &&((family.dashboardOnly &&publicPrefix !== DASHBOARD_MANAGED_AGENTS_PREFIX) ||+ (family.apiOnly && publicPrefix === DASHBOARD_MANAGED_AGENTS_PREFIX) ||family.enabledFor?.(env, caller.orgID) === false)) {return Response.json({ error: "route not found" }, { status: 404 });@@ -3957,6 +4021,9 @@ export async function proxyManagedAgents("x-opencomputer-agent-token",await mintManagedAgentsAssertion(env.OC_MANAGED_AGENTS_SECRET, caller),);+ if (family?.forward) {+ return family.forward({ request, method, suffix, target, headers });+ }if (request.method.toUpperCase() === "POST" && suffix === "/deployments") {try {return await deploySourceAgent(request, base, headers);diff --git a/cloudflare-workers/api-edge/src/route_family.ts b/cloudflare-workers/api-edge/src/route_family.tsindex 184442b2..d01ad99c 100644--- a/cloudflare-workers/api-edge/src/route_family.ts+++ b/cloudflare-workers/api-edge/src/route_family.ts@@ -3,7 +3,8 @@// `proxyManagedAgents` looks a request's family up once and dispatches to it,// instead of branching per route at each of those four points.//-// Only the organization's computer (./computer.ts) is a family so far. The+// Only the organization's computer is a family so far: its dashboard surface+// (./computer.ts) and its session API (./computer_api.ts, work 084). The// Slack-setup, deployment-source, Linear and workspace-export routes still// take the hand-written branches in managed_agents.ts; each can be ported to// this interface on its own, without changing the others' behaviour.@@ -17,6 +18,8 @@ export interface RouteFamily {allows(method: string, suffix: string): boolean;/** Only the dashboard mount reaches the family; API keys get a 404. */dashboardOnly: boolean;+ /** Only the API mount (`/api/managed-agents`) reaches the family. */+ apiOnly?: boolean;/** Whether the organization has the family (rollouts); true when absent. */enabledFor?(env: ManagedAgentsEnv, orgID: string | null | undefined): boolean;/**@@ -38,4 +41,18 @@ export interface RouteFamily {suffix: string,backendMessage: string,): string;+ /**+ * Takes over the upstream exchange once the edge has allowed the route and+ * built `target` and `headers` (assertion included): for a family whose+ * backend already speaks the public contract, so bodies, statuses and+ * errors stream through instead of being rebuilt by shapeSuccess and+ * errorMessage.+ */+ forward?(args: {+ request: Request;+ method: string;+ suffix: string;+ target: URL;+ headers: Headers;+ }): Promise<Response>;}