An open-source, faster Devin alternative
TypeScript
api-edge: remove sessions-api /v3 proxy, fallback and act-as-org auth (097 step 7.1)
Mohamed Habib via Computere834bfc0de36
diff --git a/cloudflare-workers/api-edge/scripts/enable-model-billing.mjs b/cloudflare-workers/api-edge/scripts/enable-model-billing.mjsindex 6e833276..b08c3bbb 100644--- a/cloudflare-workers/api-edge/scripts/enable-model-billing.mjs+++ b/cloudflare-workers/api-edge/scripts/enable-model-billing.mjs@@ -7,8 +7,9 @@// --org <org_id> [--disable]//// Prereqs on the edge: OPENROUTER_PROVISIONING_KEY + OC_MANAGED_CRED_HMAC_SECRET set;-// the matching OC_MANAGED_CRED_HMAC_SECRET set on sessions-api. The edge mints the-// org's OpenRouter key and binds it to sessions-api as a managed credential, then+// the matching OC_MANAGED_CRED_HMAC_SECRET set on the managed agents backend (blue),+// and MANAGED_AGENTS_API_URL set on the edge. The edge mints the org's OpenRouter+// key and binds it to the managed agents backend as a managed credential, then// flips orgs.model_billing_status='active' (→ /billing.managedAvailable=true).import { createHmac } from "node:crypto";diff --git a/cloudflare-workers/api-edge/scripts/stack.mjs b/cloudflare-workers/api-edge/scripts/stack.mjsindex dc081bf2..384e6b85 100644--- a/cloudflare-workers/api-edge/scripts/stack.mjs+++ b/cloudflare-workers/api-edge/scripts/stack.mjs@@ -146,8 +146,6 @@ async function up() {SESSION_JWT_SECRET: secrets.SESSION_JWT_SECRET,CF_ADMIN_SECRET: secrets.CF_ADMIN_SECRET,SECRET_ENCRYPTION_KEY: secrets.SECRET_ENCRYPTION_KEY,- OC_ORG_TOKEN_SECRET: secrets.OC_ORG_TOKEN_SECRET,- OC_PROVISION_SECRET: secrets.OC_PROVISION_SECRET,EVENT_SECRET: secrets.EVENT_SECRET,});@@ -380,7 +378,6 @@ function writeConfig(stack) {WORKER_ENV: name,BURST_CELL_ID: "",MANAGED_AGENTS_API_URL: stack.edgeUrl ?? "",- SESSIONS_API_URL: stack.edgeUrl ?? "",MANAGED_DEFAULT_BUDGET_USD: "5",// Preview stacks give every organization its computer (work 052).COMPUTER_ENABLED_FOR_ALL: "true",@@ -574,8 +571,6 @@ function loadSecrets() {"SESSION_JWT_SECRET","CF_ADMIN_SECRET","SECRET_ENCRYPTION_KEY",- "OC_ORG_TOKEN_SECRET",- "OC_PROVISION_SECRET","EVENT_SECRET",]) {secrets[key] ??= randomBytes(32).toString("hex");diff --git a/cloudflare-workers/api-edge/src/computer_api.test.ts b/cloudflare-workers/api-edge/src/computer_api.test.tsindex 6d71ea3d..8b6a21c6 100644--- a/cloudflare-workers/api-edge/src/computer_api.test.ts+++ b/cloudflare-workers/api-edge/src/computer_api.test.ts@@ -165,7 +165,7 @@ 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.+// A JWT shaped like the removed act-as-org provisioning token.async function provisionToken(secret: string): Promise<string> {const enc = new TextEncoder();const now = Math.floor(Date.now() / 1000);@@ -325,21 +325,16 @@ describe("computer API allowlist", () => {expect(fetchMock).not.toHaveBeenCalled();});- it("refuses a project-scoped credential with 403 project_key", async () => {+ it("no longer accepts an act-as-org provisioning token", 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" }),+ testEnv(new FakeDB(), { OC_PROVISION_SECRET: "provision-secret" } as never),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(res.status).toBe(401);expect(fetchMock).not.toHaveBeenCalled();});diff --git a/cloudflare-workers/api-edge/src/computer_telemetry.ts b/cloudflare-workers/api-edge/src/computer_telemetry.tsindex 6deb2eb4..864e77b3 100644--- a/cloudflare-workers/api-edge/src/computer_telemetry.ts+++ b/cloudflare-workers/api-edge/src/computer_telemetry.ts@@ -26,7 +26,6 @@ export type EdgeAuth =| "missing"| "invalid"| "conflicting"- | "project_key"| "not_member"| "origin"| "key_required"diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex f609e958..e6085e87 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -71,13 +71,6 @@ export interface DashboardEnv extends BillingEventsEnv {// if unset the custom-domain endpoints return 503 (feature disabled).CF_API_TOKEN?: string;CF_ZONE_ID?: string;- // Durable Agent Sessions (/v3) — the dashboard proxies /api/dashboard/v3/* to- // this sessions-api host, asserting the logged-in OC org via a short-lived- // signed OC org token (OC_ORG_TOKEN_SECRET, shared with sessions-api). No osb_- // key in the browser, no key custody. Both optional — if OC_ORG_TOKEN_SECRET is- // unset the proxy 503s.- SESSIONS_API_URL?: string;- OC_ORG_TOKEN_SECRET?: string;// Browser Sessions dashboard proxy. The browser API remains a separate// Worker; this edge Worker only translates dashboard cookie auth into the// internal service token plus org/user headers.@@ -179,26 +172,6 @@ async function mintCellCapToken(secret: string, orgID: string, cellID: string, preturn signingInput + "." + b64url(sig);}-// OC org token: a short-lived HS256 token carrying the OC org id, signed with-// OC_ORG_TOKEN_SECRET (shared with sessions-api). /v3 trusts it and sets owner =-// the asserted org — same "act for org X" shape as the cell cap-token, so no-// osb_ key reaches the browser and /v3 never custodies a customer key.-async function mintOrgToken(secret: string, orgID: string, userID: string | null): Promise<string> {- const now = Math.floor(Date.now() / 1000);- const header = { alg: "HS256", typ: "JWT" };- const payload: Record<string, unknown> = {- sub: orgID, iss: "opencomputer", aud: "sessions-api-v3", iat: now, exp: now + 120,- org_id: orgID,- };- if (userID) payload.user_id = userID;- const enc = new TextEncoder();- const signingInput =- b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));- 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(signingInput));- return signingInput + "." + b64url(sig);-}-function b64url(buf: ArrayBuffer | Uint8Array): string {const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);let s = "";@@ -982,47 +955,6 @@ async function workosUpdateOrg(env: DashboardEnv, workosOrgID: string, name: str});}-// Proxy /api/dashboard/v3/* → sessions-api /v3/*, asserting the logged-in OC org-// via a signed org-token in X-OC-Org-Token (a distinct header so /v3 doesn't-// mistake it for a bearer client token). Forwards only what /v3 needs (never the-// dashboard cookie); streams the response through unchanged so SSE passes back.-async function proxyToV3(- req: Request,- env: DashboardEnv,- caller: Caller,- sub: string,-): Promise<Response> {- if (!env.OC_ORG_TOKEN_SECRET) {- return json({ error: "agent sessions not configured" }, 503);- }- const base = (env.SESSIONS_API_URL ?? "https://api.opencomputer.dev").replace(- /\/$/,- "",- );- const url = new URL(req.url);- const target = base + sub + url.search;- const orgToken = await mintOrgToken(env.OC_ORG_TOKEN_SECRET, caller.orgID, caller.userID);-- const headers = new Headers();- headers.set("x-oc-org-token", orgToken);- const ct = req.headers.get("content-type");- if (ct) headers.set("content-type", ct);- const accept = req.headers.get("accept");- if (accept) headers.set("accept", accept);- const lastEventID = req.headers.get("last-event-id");- if (lastEventID) headers.set("last-event-id", lastEventID);- // Forward client idempotency keys so dashboard create-session / steer are safe- // to retry end-to-end (sessions-api dedups on this header).- const idem = req.headers.get("idempotency-key");- if (idem) headers.set("idempotency-key", idem);-- const init: RequestInit = { method: req.method, headers, redirect: "manual" };- if (req.method !== "GET" && req.method !== "HEAD") {- init.body = await req.arrayBuffer(); // binary-safe — req.text() UTF-8-mangles zip/binary uploads- }- return fetch(target, init);-}-async function proxyToBrowserAPI(req: Request,env: DashboardEnv,@@ -1122,14 +1054,6 @@ export async function handleDashboard();}- // ── Durable Agent Sessions (/v3) — proxy to sessions-api ────────────────- // Cookie-gated above. We inject OC_V3_KEY downstream so the osb_ key never- // reaches the browser. (/v3 is per-key today, so this is that key's- // workspace; org-scoping is a later refinement.)- if (sub === "/v3" || sub.startsWith("/v3/")) {- return proxyToV3(req, env, caller, sub);- }-// ── Browser Sessions — proxy to the dedicated browser Worker ───────────if (sub === "/browsers" && method === "GET") return proxyToBrowserAPI(req, env, caller, "/v1/browsers");if (sub === "/browser-usage" && method === "GET") return proxyToBrowserAPI(req, env, caller, "/v1/browser-usage");diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.tsindex cb1067e5..c4cd711a 100644--- a/cloudflare-workers/api-edge/src/index.test.ts+++ b/cloudflare-workers/api-edge/src/index.test.ts@@ -283,8 +283,8 @@ describe("api-edge sandbox create", () => {});});-// The scoped-secret boundary added so sessions-api can ensure-provision Managed at-// agent-create without holding the broad CF_ADMIN_SECRET. Asserts the auth gate only+// The scoped-secret boundary that lets the managed agents backend ensure-provision+// Managed without holding the broad CF_ADMIN_SECRET. Asserts the auth gate only// (provisioning itself isn't exercised: getOrg → null → 500, which is still ≠ 401).describe("/internal/model-billing/enable — scoped-secret auth boundary", () => {const ADMIN = "admin-secret";diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 0faee0af..fe1962b6 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -182,11 +182,6 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv, L// Optional alpha Burst Sandbox cell. When unset, burst=true creates// fail closed rather than silently landing on on-demand capacity.BURST_CELL_ID?: string;- // act-as-org provisioning (agent-sandbox-ownership): shared HS256 secret with- // sessions-api. When set, authenticate() accepts a signed "act for org X" JWT- // as the API key so /v3 sandboxes are owned by + billed to the customer org.- // Unset → the feature is inert (JWT keys rejected). See dashboard.ts.- OC_PROVISION_SECRET?: string;// Slack Connect per signup (slack_connect.ts), sent by the OpenComputer// Slack app: dormant unless the token// and SINCE (unix seconds) are set.@@ -199,8 +194,9 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv, LOPENROUTER_PROVISIONING_KEY: string;OPENROUTER_BASE_URL?: string; // default https://openrouter.ai/api/v1OPENROUTER_MARKUP_BPS?: string; // env-default markup (bps) when the org's is 0- // DEDICATED HMAC secret for handing a freshly-minted OR key to sessions-api- // (NOT the generic internal-auth — this route carries a live model key). §6.7.5.+ // DEDICATED HMAC secret for handing a freshly-minted OR key to the managed+ // agents backend (blue) (NOT the generic internal-auth — this route carries a+ // live model key). §6.7.5.OC_MANAGED_CRED_HMAC_SECRET: string;// Edge claim (pool_stock.ts): per-cell Durable Object stocking pre-reserved// hot pool boxes so default-shape creates are answered at the edge with zero@@ -436,17 +432,14 @@ interface Caller {orgID: string;userID: string | null;role?: string;- // Set only for act-as-org provisioning tokens (sessions-api). Least-privilege:- // the dispatch gates these to sandbox + secret-store routes (provisionScopeGate).- scope?: "sandbox-provision";// Set only for the organization's computer (work 080): its one-hour keys are// created_by COMPUTER_PRINCIPAL, a reserved id no person has. sessionKey is// 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).+ // which key acted. Absent on entries cached before these fields existed (the+ // computer path re-reads those).key?: AssertedAPIKey;userName?: string | null;userEmail?: string | null;@@ -779,17 +772,6 @@ async function authenticate(req: Request, env: Env, ctx?: ExecutionContext, prob}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;- // create stamps it, sub-ops match it, billing follows it.- if (- env.OC_PROVISION_SECRET &&- !apiKey.startsWith("osb_") &&- apiKey.split(".").length === 3- ) {- return verifyProvisionToken(env.OC_PROVISION_SECRET, apiKey);- }const tHash = Date.now();const hash = await hashAPIKey(apiKey);if (probe) probe.hashMs = Date.now() - tHash;@@ -4865,18 +4847,10 @@ async function computerApiCall(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) {+ if (caller && !caller.key) {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) {- facts.auth = "project_key";- return computerApiError(req, 403, "forbidden", "This credential cannot use the computer API.", {- 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.@@ -4979,7 +4953,7 @@ async function authCLIRevoke(req: Request, env: Env, ctx?: ExecutionContext): Pr} catch {return finish(cliAuthError("credential_revocation_unavailable", 503), "storage_error");}- if (!caller || caller.scope) {+ if (!caller) {return finish(cliAuthError("missing or invalid API key", 401), "unauthorized");}let keyID: string | null = caller.key?.id ?? null;@@ -5181,59 +5155,6 @@ async function verifySessionJWT(secret: string, token: string): Promise<SessionC}}-// Verify an act-as-org provisioning token (sessions-api → OC sandbox API),-// presented as the API key. HS256 signed with OC_PROVISION_SECRET; asserts-// "operate as org X". Mintable only by the secret holder; we re-derive org X-// from the verified token (never a client field). See agent-sandbox-ownership.md.-async function verifyProvisionToken(secret: string, token: string): Promise<Caller | null> {- const parts = token.split(".");- if (parts.length !== 3) return null;- const [headerB64, payloadB64, sigB64] = parts;- const enc = new TextEncoder();- const key = await crypto.subtle.importKey(- "raw",- enc.encode(secret),- { name: "HMAC", hash: "SHA-256" },- false,- ["sign"],- );- const expected = await crypto.subtle.sign("HMAC", key, enc.encode(`${headerB64}.${payloadB64}`));- if (b64url(expected) !== sigB64) return null;- try {- const p = JSON.parse(atob(payloadB64.replace(/-/g, "+").replace(/_/g, "/"))) as {- iss?: string; aud?: string; exp?: number; iat?: number; org_id?: string; scope?: string;- };- const now = Math.floor(Date.now() / 1000);- const SKEW = 120; // clock-skew tolerance (s)- const MAX_AGE = 6 * 3600; // sanity cap on lifetime; turn tokens live ~40min (maxTurnSeconds 1800 + 600)- if (p.iss !== "sessions-api" || p.aud !== "opencomputer-api") return null;- // P1-1: require the provisioning scope (gated to sandbox + secret-store routes).- if (p.scope !== "sandbox-provision") return null;- // P1-2: require finite exp + iat; reject expired, future-dated, or absurd-lifetime- // tokens (a no-exp token is no longer accepted).- if (typeof p.exp !== "number" || typeof p.iat !== "number") return null;- if (p.exp <= now) return null;- if (p.iat > now + SKEW) return null;- if (p.exp - p.iat > MAX_AGE || p.exp > now + MAX_AGE + SKEW) return null;- // P1-2: validate org_id shape (OC orgs are UUIDs).- if (typeof p.org_id !== "string" ||- !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(p.org_id)) return null;- return { orgID: p.org_id, userID: null, scope: "sandbox-provision" };- } catch {- return null;- }-}--// Provision-scoped tokens (sessions-api act-as-org) are least-privilege: usable-// ONLY for sandbox + secret-store provisioning, never snapshots/images/other org-// resources. Call after authenticate() on any route OUTSIDE that allowlist to 403-// a provision token; returns null (pass) for normal org keys.-function provisionScopeGate(caller: Caller, path: string): Response | null {- if (caller.scope !== "sandbox-provision") return null;- if (path.startsWith("/api/sandboxes") || path.startsWith("/api/secret-stores")) return null;- return json({ error: "forbidden: provision-scoped token is limited to sandbox + secret-store operations" }, 403);-}-// ── Stripe webhook ───────────────────────────────────────────────────────//// Stripe POSTs subscription / invoice events. We verify the signature,@@ -5777,8 +5698,9 @@ export default {const sig = req.headers.get("X-Signature") ?? "";const body = await req.text();// CF_ADMIN_SECRET authorizes both ops. `enable` is additionally accepted with the- // scoped OC_MANAGED_CRED_HMAC_SECRET, so sessions-api can ensure-provision at- // agent-create without holding the broad admin secret. `disable` stays admin-only.+ // scoped OC_MANAGED_CRED_HMAC_SECRET (shared only with the managed agents+ // backend), so it can ensure-provision without holding the broad admin secret.+ // `disable` stays admin-only.const adminOk = constantTimeEqual(await hmacHex(env.CF_ADMIN_SECRET, `${ts}.${body}`), sig);const managedOk =path === "/internal/model-billing/enable" && env.OC_MANAGED_CRED_HMAC_SECRET@@ -5920,7 +5842,6 @@ export default {if (path === "/api/snapshots") {const caller = await authenticate(req, env, ctx);if (!caller) return json({ error: "missing or invalid API key" }, 401);- { const g = provisionScopeGate(caller, path); if (g) return g; }if (req.method === "GET") return snapshots.listSnapshots(env, caller);if (req.method === "POST") return proxyToCellAuthed(req, env, caller); // build → home_cell, SSEreturn json({ error: "method not allowed" }, 405);@@ -5936,7 +5857,6 @@ export default {const isPublishToggle = sub === "/publish" || sub === "/unpublish";const caller = await authenticate(req, env, ctx);if (!caller) return json({ error: "missing or invalid API key" }, 401);- { const g = provisionScopeGate(caller, path); if (g) return g; }// Patches, publish/unpublish, and delete are cell-work — route to the// cell that owns the snapshot bytes (looked up from D1), not "any active// cell". is_public lives in the owning cell's image_cache.@@ -5959,7 +5879,6 @@ export default {if (path === "/api/images") {const caller = await authenticate(req, env, ctx);if (!caller) return json({ error: "missing or invalid API key" }, 401);- { const g = provisionScopeGate(caller, path); if (g) return g; }if (req.method === "GET") return snapshots.listImages(env, caller);return json({ error: "method not allowed" }, 405);}@@ -6079,8 +5998,6 @@ export default {if (!caller) {return json({ error: "missing or invalid API key" }, 401);}- const scopeError = provisionScopeGate(caller, path);- if (scopeError) return scopeError;if (path === "/api/managed-agents/sessions" && req.method === "POST") {try {const billing = await enableManagedBilling(env, caller.orgID, (id) =>@@ -6227,7 +6144,6 @@ export default {if (cpm) {const caller = await authenticate(req, env, ctx);if (!caller) return json({ error: "missing or invalid API key" }, 401);- { const g = provisionScopeGate(caller, path); if (g) return g; }const cpRow = await env.OPENCOMPUTER_DB.prepare(`SELECT owner_cell_id FROM checkpoints_index WHERE id = ?1`,).bind(cpm[1]).first<{ owner_cell_id: string }>();@@ -6317,8 +6233,7 @@ export default {// world. proxyToCellAuthed streams the response (SSE-safe). This is a// backstop; prefer adding a native handler for high-traffic resources.// /api/whoami — return the authenticated caller's org (+ user). Lets a- // trusted service resolve an osb_ key to its OC org without custodying it- // (agent-sandbox-ownership Phase 0.5: sessions-api maps osb_ → oc-org:<id>).+ // trusted service resolve an osb_ key to its OC org without custodying it.// /api/billing/credits — API-key credit status for the CLI (plan, balance,// low-balance flag, checkout deep links). See billing_onramp.ts.if (path === "/api/billing/credits" && req.method === "GET") {@@ -6330,14 +6245,6 @@ export default {if (path === "/api/whoami" && req.method === "GET") {const caller = await authenticate(req, env, ctx);if (!caller) return json({ error: "missing or invalid API key" }, 401);- if (caller.scope) {- return json({- org_id: caller.orgID,- user_id: caller.userID,- email: null,- org_name: null,- });- }const identity = await env.OPENCOMPUTER_DB.prepare(`SELECT o.name AS org_name, u.email AS emailFROM orgs odiff --git a/cloudflare-workers/api-edge/src/model_billing.test.ts b/cloudflare-workers/api-edge/src/model_billing.test.tsindex fe0d9253..9d7481c2 100644--- a/cloudflare-workers/api-edge/src/model_billing.test.ts+++ b/cloudflare-workers/api-edge/src/model_billing.test.ts@@ -116,7 +116,7 @@ class FakeStmt {}}-// ── fetch router: OpenRouter + Autumn + sessions-api ────────────────────────+// ── fetch router: OpenRouter + Autumn + managed agents backend ──────────────interface RouterOpts {remainingCredits?: number; // Autumn balance@@ -150,7 +150,7 @@ function makeFetch(opts: RouterOpts = {}) {if (method === "PATCH") return new Response(JSON.stringify({ data: { hash: "hash-abc", limit: body?.limit } }), { status: 200 });return new Response(JSON.stringify({ data: { hash: "hash-abc", usage: 0.5, limit: 5, disabled: false } }), { status: 200 });}- // sessions-api hand-off+ // managed agents backend hand-offif (url.includes("/internal/managed-credential")) {if (method === "POST") return new Response(JSON.stringify({ managed_credential_id: "cred_bound" }), { status: 200 });if (method === "DELETE") return new Response(JSON.stringify({ deleted: 1 }), { status: 200 });@@ -169,7 +169,7 @@ function makeEnv(db: FakeDb): ModelBillingEnv {OPENROUTER_BASE_URL: "https://or.test/api/v1",AUTUMN_SECRET_KEY: "autumn-key",AUTUMN_BASE_URL: "https://autumn.test/v1",- SESSIONS_API_URL: "https://sa.test",+ MANAGED_AGENTS_API_URL: "https://blue.test",OC_MANAGED_CRED_HMAC_SECRET: "hmac-secret",};}@@ -410,7 +410,7 @@ describe("enableManagedBilling state machine", () => {});describe("disableManagedBilling (rollback / hard offboard)", () => {- it("deletes the OR key, revokes the sessions-api credential, drops rows, flips off", async () => {+ it("deletes the OR key, revokes the managed credential, drops rows, flips off", async () => {const db = new FakeDb();const orgId = seedOrg(db, { model_billing_status: "active" });db.keys.push({@@ -437,4 +437,15 @@ describe("disableManagedBilling (rollback / hard offboard)", () => {await disableManagedBilling(makeEnv(db), orgId);expect(db.orgs.get(orgId)!.model_billing_status).toBe("off");});++ it("refuses the hand-off when MANAGED_AGENTS_API_URL is unset (no fallback)", async () => {+ const db = new FakeDb();+ const orgId = seedOrg(db, { model_billing_status: "active" });+ const { spy } = makeFetch();+ vi.stubGlobal("fetch", spy);+ const env = { ...makeEnv(db), MANAGED_AGENTS_API_URL: undefined };+ await expect(disableManagedBilling(env, orgId)).rejects.toThrow(/MANAGED_AGENTS_API_URL unset/);+ expect(spy).not.toHaveBeenCalled();+ expect(db.orgs.get(orgId)!.model_billing_status).toBe("active");+ });});diff --git a/cloudflare-workers/api-edge/src/model_billing.ts b/cloudflare-workers/api-edge/src/model_billing.tsindex d83fd5ea..457a63e7 100644--- a/cloudflare-workers/api-edge/src/model_billing.ts+++ b/cloudflare-workers/api-edge/src/model_billing.ts@@ -16,14 +16,12 @@ import {export interface ModelBillingEnv extends OpenRouterEnv, AutumnApiEnv {OPENCOMPUTER_DB: D1Database;- // sessions-api base URL (shared with the dashboard /v3 proxy). Default = prod.- SESSIONS_API_URL?: string;- // Private managed-agent backend. Preferred for new Serverless Agent key- // custody; SESSIONS_API_URL remains a compatibility fallback during rollout.+ // Private managed agents backend (blue) base URL. Required for the managed+ // credential hand-off; the hand-off fails clearly if it is unset.MANAGED_AGENTS_API_URL?: string;// DEDICATED HMAC secret for the plaintext-key hand-off (§6.7.5 / P2-f). NOT the// generic internal-auth secret — this route carries a live model key. Shared- // only with sessions-api.+ // only with the managed agents backend (blue).OC_MANAGED_CRED_HMAC_SECRET: string;// Optional env-default markup (basis points) when the org row's is 0. Org wins.OPENROUTER_MARKUP_BPS?: string;@@ -39,7 +37,6 @@ const DEFAULT_MANAGED_BUDGET_USD = 10;const MAX_PROVISION_ATTEMPTS = 5;// Accepted clock skew on the hand-off HMAC (replay window, §6.7.5).const HANDOFF_SKEW_SEC = 60;-const DEFAULT_SESSIONS_API = "https://api.opencomputer.dev";const HANDOFF_PATH = "/internal/managed-credential";export type ManagedKeyStatus = "active" | "superseded" | "deleting";@@ -71,8 +68,8 @@ interface OrgBillingRow {halt_reason?: string | null;}-// sessions-api owner id for an OC org. MUST match sessions-api's ownerIdForOrg-// (src/v3/auth/org-token.ts) — the managed credential is stored + resolved under it.+// Managed agents backend owner id for an OC org. MUST match the backend's owner id+// for the org — the managed credential is stored + resolved under it.export function ownerIdForOrg(orgId: string): string {return "oc-org:" + orgId;}@@ -219,7 +216,7 @@ async function budgetFor(env: ModelBillingEnv, org: OrgBillingRow): Promise<numbreturn defaultBudgetUsd(env);}-// ── edge → sessions-api hand-off (HMAC, §6.7.5) ─────────────────────────────+// ── edge → managed agents backend hand-off (HMAC, §6.7.5) ───────────────────async function hmacHex(secret: string, data: string): Promise<string> {const key = await crypto.subtle.importKey(@@ -234,7 +231,7 @@ async function hmacHex(secret: string, data: string): Promise<string> {}// Signs `${ts}.${method}.${path}.${body}` (path includes query) and calls-// sessions-api. Returns the parsed JSON. `path` must start with HANDOFF_PATH.+// the managed agents backend (blue). Returns the parsed JSON. `path` must start with HANDOFF_PATH.async function signedHandoff(env: ModelBillingEnv,method: "POST" | "GET" | "DELETE",@@ -244,11 +241,10 @@ async function signedHandoff(if (!env.OC_MANAGED_CRED_HMAC_SECRET) {throw new Error("model-billing: OC_MANAGED_CRED_HMAC_SECRET unset — refusing hand-off");}- const base = (- env.MANAGED_AGENTS_API_URL ??- env.SESSIONS_API_URL ??- DEFAULT_SESSIONS_API- ).replace(/\/+$/, "");+ if (!env.MANAGED_AGENTS_API_URL) {+ throw new Error("model-billing: MANAGED_AGENTS_API_URL unset — refusing hand-off");+ }+ const base = env.MANAGED_AGENTS_API_URL.replace(/\/+$/, "");const ts = Math.floor(Date.now() / 1000).toString();const sig = await hmacHex(env.OC_MANAGED_CRED_HMAC_SECRET, `${ts}.${method}.${path}.${body}`);const resp = await fetch(`${base}${path}`, {@@ -265,7 +261,7 @@ async function signedHandoff(return text ? JSON.parse(text) : null;}-// Hand the freshly-minted plaintext OR key to sessions-api to seal. Idempotent per+// Hand the freshly-minted plaintext OR key to the managed agents backend to seal. Idempotent per// (owner_id, operation_id): a re-call rotates rather than duplicates. Returns the// managed_credential_id. The plaintext is NEVER persisted on the edge.async function bindManagedCredential(@@ -296,7 +292,7 @@ async function lookupManagedCredential(return out?.managed_credential_id ?? null;}-// Revoke (soft-delete) the owner's managed credential(s) in sessions-api — the+// Revoke (soft-delete) the owner's managed credential(s) in the managed agents backend — the// rollback counterpart of the bind. Idempotent (deleting none returns 0). Returns// how many were deleted.async function revokeManagedCredential(env: ModelBillingEnv, ownerId: string): Promise<number> {@@ -379,8 +375,8 @@ async function driveProvisioning(env: ModelBillingEnv, org: OrgBillingRow, row:await updateRow(env, row.id, { or_key_hash: created.data.hash, attempts: 0, last_error: null });row.or_key_hash = created.data.hash;- // Step 3: hand the plaintext to sessions-api immediately (still in memory,- // never persisted). On success persist the credential id.+ // Step 3: hand the plaintext to the managed agents backend immediately+ // (still in memory, never persisted). On success persist the credential id.const credId = await bindManagedCredential(env, {ownerId: ownerIdForOrg(org.id),orKeyHash: created.data.hash,@@ -447,7 +443,7 @@ export async function reconcileManagedBilling(env: ModelBillingEnv, orgId: strin// disableManagedBilling is the rollback path: a synchronous HARD offboard. The// graceful-drain cron (§5.8 — keep polling until spend quiesces, final debit, then// delete) isn't built yet, so disable does the teardown directly: delete the OR-// key(s), revoke the sessions-api managed credential, drop the key rows, flip the org+// key(s), revoke the managed agents backend credential, drop the key rows, flip the org// off. Order matters — we only delete rows + flip off AFTER the OR key + credential// are gone, so a partial failure throws and a retry completes cleanly (every step is// idempotent). NOTE: a tiny final slice of spend may go unbilled (no drain); fine for@@ -459,8 +455,9 @@ export async function disableManagedBilling(env: ModelBillingEnv, orgId: string)for (const row of rows) {if (row.or_key_hash) await deleteOrKey(env, row.or_key_hash);}- // 2. Revoke the managed credential in sessions-api so the resolver stops resolving- // Managed (the org-default-managed arm, §6.7.3). Throws on failure → retry.+ // 2. Revoke the managed credential in the managed agents backend so the+ // resolver stops resolving Managed (the org-default-managed arm, §6.7.3).+ // Throws on failure → retry.await revokeManagedCredential(env, ownerIdForOrg(orgId));// 3. Only now: drop the rows + flip off (so a mid-failure retry re-runs 1–2).await deleteKeyRows(env, orgId);diff --git a/cloudflare-workers/api-edge/src/openrouter.ts b/cloudflare-workers/api-edge/src/openrouter.tsindex 110d7200..e2c4a5cc 100644--- a/cloudflare-workers/api-edge/src/openrouter.ts+++ b/cloudflare-workers/api-edge/src/openrouter.ts@@ -3,8 +3,8 @@// API call with it: mint per-org inference keys, read their cumulative spend, push// caps, delete on offboard, and read account analytics. The minted inference keys// are the per-org billing keys; their plaintext is returned by `POST /keys` exactly-// ONCE and is never re-fetchable — the edge hands it straight to sessions-api to seal-// (it is never persisted on the edge). This keeps the "Autumn/OR are edge-native"+// ONCE and is never re-fetchable — the edge hands it straight to the managed agents+// backend (blue) to seal (it is never persisted on the edge). This keeps the "Autumn/OR are edge-native"// invariant: one OR secret, in one place.//// Surfaces + behaviours verified live 2026-06-29 (§9.7 spike, token-billing.md):@@ -40,7 +40,7 @@ export interface OpenRouterKey {// POST /keys response: the plaintext key (returned ONCE) + the key metadata.export interface OpenRouterCreatedKey {- key: string; // plaintext inference key — hand to sessions-api, never persist on edge+ key: string; // plaintext inference key — hand to the managed agents backend, never persist on edgedata: OpenRouterKey;}diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex a4c5ed23..f6720856 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -164,7 +164,7 @@ deleted_classes = ["VmSession"]# per-org inference keys + reads analytics). Token# billing dormant until this is set. (token-billing.md)# OC_MANAGED_CRED_HMAC_SECRET — dedicated HMAC for handing a minted OR key to-# sessions-api (shared only with sessions-api; NOT the+# the managed agents backend (shared only with it; NOT the# generic internal-auth — this route carries a live key)# OC_SECURITY_NOTIFICATION_SECRET — dedicated HMAC for minimal Agent Hook# exposure alerts from sessions-apidiff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex b82fece0..c06a5d2c 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -169,7 +169,7 @@ deleted_classes = ["VmSession"]# billing; mints per-org keys + reads analytics). Dormant# until set. See .agents/work/token-billing.md.# OC_MANAGED_CRED_HMAC_SECRET — dedicated HMAC for the minted-OR-key hand-off to-# sessions-api (shared only with sessions-api).+# the managed agents backend (shared only with it).# OC_SECURITY_NOTIFICATION_SECRET — dedicated HMAC for minimal Agent Hook# exposure alerts from sessions-api.# OC_MANAGED_AGENTS_SECRET — dedicated HS256 secret shared only with the