An open-source, faster Devin alternative
TypeScript
084 contract r1: edge project_key 403, accept-encoding to wire, per-key HTTP rate limit
Igor Zalutski via Computer30b54d1adac6
diff --git a/cloudflare-workers/api-edge/src/computer_api.test.ts b/cloudflare-workers/api-edge/src/computer_api.test.tsindex 22f781f3..2433325a 100644--- a/cloudflare-workers/api-edge/src/computer_api.test.ts+++ b/cloudflare-workers/api-edge/src/computer_api.test.ts@@ -164,6 +164,36 @@ async function sessionCookie(secret = "test-session-secret"): Promise<string> {return `oc_session=${input}.${b64url(sig)}`;}+// An act-as-org provisioning token (sessions-api): the project-scoped credential.+async function provisionToken(secret: string): 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: "sessions-api",+ aud: "opencomputer-api",+ scope: "sandbox-provision",+ org_id: ORG,+ iat: now,+ exp: now + 600,+ }),+ ),+ );+ 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 `${input}.${b64url(sig)}`;+}+function claims(token: string): Record<string, unknown> {return JSON.parse(atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")),@@ -292,6 +322,96 @@ describe("computer API allowlist", () => {expect(res.status).toBe(404);expect(fetchMock).not.toHaveBeenCalled();});++ it("refuses a project-scoped credential with 403 project_key", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const token = await provisionToken("provision-secret");+ const res = await worker.fetch(+ api("/me", { headers: { authorization: `Bearer ${token}` } }),+ testEnv(new FakeDB(), { OC_PROVISION_SECRET: "provision-secret" }),+ testCtx().ctx,+ );+ expect(res.status).toBe(403);+ expect(res.headers.get("x-request-id")).toMatch(/^req_/);+ const body = (await res.json()) as { error: Record<string, unknown> };+ expect(body.error).toMatchObject({ code: "forbidden", reason: "project_key", retryable: false });+ expect(body.error.message).toEqual(expect.any(String));+ expect(body.error.requestId).toMatch(/^req_/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("leaves a key's missing scope to blue, passing its 403 through", async () => {+ const db = new FakeDB();+ const key = await addKey(db, { scopes: "sandbox:*" });+ const refusal = {+ error: { code: "forbidden", reason: "missing_scope", message: "Needs computer:write.", requestId: "req_blue", retryable: false },+ };+ const fetchMock = vi.fn().mockResolvedValue(Response.json(refusal, { status: 403 }));+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/sessions", { method: "POST", headers: { "x-api-key": key, "content-type": "application/json" }, body: "{}" }),+ testEnv(db),+ testCtx().ctx,+ );+ expect(res.status).toBe(403);+ expect(await res.json()).toEqual(refusal);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});++describe("computer API rate limit", () => {+ it("limits per key id and answers 429 with Retry-After and retryAfterMs", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const limit = vi.fn().mockResolvedValue({ success: false });+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/me", { headers: { "x-api-key": key } }),+ testEnv(db, { COMPUTER_API_RATE_LIMIT: { limit } }),+ testCtx().ctx,+ );+ expect(res.status).toBe(429);+ expect(res.headers.get("retry-after")).toBe("60");+ const body = (await res.json()) as { error: Record<string, unknown> };+ expect(body.error).toMatchObject({ code: "rate_limited", retryable: true, retryAfterMs: 60_000 });+ expect(body.error.requestId).toMatch(/^req_/);+ expect(limit).toHaveBeenCalledWith({ key: db.keys.get(await hashAPIKey(key))!.id });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("passes a key under the limit, and fails open when the limiter errors", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const fetchMock = vi.fn(async () => Response.json({ ok: true }));+ vi.stubGlobal("fetch", fetchMock);+ for (const limit of [+ vi.fn().mockResolvedValue({ success: true }),+ vi.fn().mockRejectedValue(new Error("limiter down")),+ ]) {+ const res = await worker.fetch(+ api("/me", { headers: { "x-api-key": key } }),+ testEnv(db, { COMPUTER_API_RATE_LIMIT: { limit } }),+ testCtx().ctx,+ );+ expect(res.status).toBe(200);+ expect(limit).toHaveBeenCalledTimes(1);+ }+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("does not count dashboard sessions", async () => {+ const limit = vi.fn().mockResolvedValue({ success: false });+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ ok: true })));+ const res = await worker.fetch(+ api("/me", { headers: { cookie: await sessionCookie() } }),+ testEnv(new FakeDB(), { COMPUTER_API_RATE_LIMIT: { limit } }),+ testCtx().ctx,+ );+ expect(res.status).toBe(200);+ expect(limit).not.toHaveBeenCalled();+ });});describe("computer API proxy to blue", () => {@@ -569,6 +689,24 @@ describe("workspace files go to the wire Worker", () => {expect(headers.get("x-api-key")).toBe(key);});+ it("forwards accept-encoding so the archive can come back compressed", async () => {+ const db = new FakeDB();+ const key = await addKey(db);+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(new Uint8Array([1]), { headers: { "content-type": "application/x-tar", "content-encoding": "zstd" } }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const res = await worker.fetch(+ api("/sessions/cs_1/workspace/archive", {+ headers: { "x-api-key": key, "accept-encoding": "zstd, gzip" },+ }),+ testEnv(db),+ testCtx().ctx,+ );+ expect(sent(fetchMock).headers.get("accept-encoding")).toBe("zstd, gzip");+ expect(res.headers.get("content-encoding")).toBe("zstd");+ });+it("refuses a dashboard session with key_required", async () => {const fetchMock = vi.fn();vi.stubGlobal("fetch", fetchMock);diff --git a/cloudflare-workers/api-edge/src/computer_api.ts b/cloudflare-workers/api-edge/src/computer_api.tsindex 91d1547f..545ca873 100644--- a/cloudflare-workers/api-edge/src/computer_api.ts+++ b/cloudflare-workers/api-edge/src/computer_api.ts@@ -172,6 +172,8 @@ const WIRE_REQUEST_HEADERS = ["x-request-id","user-agent","accept",+ // The archive is compressed only when the caller asks for it.+ "accept-encoding",];/** Response headers passed back from the wire Worker. */diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 914d2d8c..64678a73 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -124,6 +124,8 @@ 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): HTTP calls per API key, ahead of blue.+ COMPUTER_API_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@@ -4693,6 +4695,9 @@ async function authCLIExchange(req: Request, env: Env, ctx?: ExecutionContext):// ── computer API (work 084) ─────────────────────────────────────────────const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);+// The Workers rate limit counts per 60 s window; a refused caller waits for+// the next one.+const COMPUTER_API_RATE_LIMIT_RETRY_SEC = 60;/*** /api/managed-agents/computer/*: authenticates an API key (`x-api-key` or@@ -4733,11 +4738,28 @@ async function handleComputerApi(await refreshAuth(env, await hashAPIKey(credential.key));caller = await authenticateKey(credential.key, env, ctx);}+ // The only non-user credential is the act-as-org provisioning token, a+ // project-scoped credential: the computer API is a person's.if (caller?.scope) {return computerApiError(req, 403, "forbidden", "This credential cannot use the computer API.", {- reason: "scope_missing",+ reason: "project_key",});}+ if (caller?.key && env.COMPUTER_API_RATE_LIMIT) {+ // Per key, ahead of blue. A limiter error fails open: blue still+ // authorizes every call.+ const allowed = await env.COMPUTER_API_RATE_LIMIT.limit({ key: caller.key.id }).then(+ (r) => r.success,+ () => true,+ );+ if (!allowed) {+ const response = computerApiError(req, 429, "rate_limited", "Too many requests for this key. Slow down.", {+ retryAfterMs: COMPUTER_API_RATE_LIMIT_RETRY_SEC * 1000,+ });+ response.headers.set("retry-after", String(COMPUTER_API_RATE_LIMIT_RETRY_SEC));+ return response;+ }+ }} else {const session = await authDashboard(req, env);if (session) {diff --git a/cloudflare-workers/api-edge/wrangler.igor-dev.toml b/cloudflare-workers/api-edge/wrangler.igor-dev.tomlindex aaa99827..64e6ead0 100644--- a/cloudflare-workers/api-edge/wrangler.igor-dev.toml+++ b/cloudflare-workers/api-edge/wrangler.igor-dev.toml@@ -70,6 +70,15 @@ namespace_id = "2026102311"limit = 20period = 60+# Computer API (work 084): HTTP calls per API key, ahead of blue.+[[ratelimits]]+name = "COMPUTER_API_RATE_LIMIT"+namespace_id = "2026102611"++ [ratelimits.simple]+ limit = 600+ period = 60+# CreditAccount DO is self-hosted by this worker (script_name defaults to self).[[durable_objects.bindings]]name = "CREDIT_ACCOUNT"diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex a03f227d..4f7824ff 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -68,6 +68,15 @@ namespace_id = "2026102301"limit = 20period = 60+# Computer API (work 084): HTTP calls per API key, ahead of blue.+[[ratelimits]]+name = "COMPUTER_API_RATE_LIMIT"+namespace_id = "2026102601"++ [ratelimits.simple]+ limit = 600+ period = 60+[[durable_objects.bindings]]name = "CREDIT_ACCOUNT"class_name = "CreditAccount"diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex 0d35a5be..fd318d84 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -90,6 +90,15 @@ namespace_id = "2026102321"limit = 20period = 60+# Computer API (work 084): HTTP calls per API key, ahead of blue.+[[ratelimits]]+name = "COMPUTER_API_RATE_LIMIT"+namespace_id = "2026102621"++ [ratelimits.simple]+ limit = 600+ period = 60+[[durable_objects.bindings]]name = "CREDIT_ACCOUNT"class_name = "CreditAccount"