An open-source, faster Devin alternative
TypeScript
fix(flue): scope gateway tokens and fence deploy epochs
Igor Zalutski0a1aa9cbb9ae
diff --git a/cloudflare-workers/oc-gateway/scripts/mint.ts b/cloudflare-workers/oc-gateway/scripts/mint.tsindex 953c4c93..aa2ebc44 100644--- a/cloudflare-workers/oc-gateway/scripts/mint.ts+++ b/cloudflare-workers/oc-gateway/scripts/mint.ts@@ -2,16 +2,23 @@// prod, binding the token as the tenant script's OC_SESSION_TOKEN env var; this is the dev/e2e helper.// On first use it also generates an Ed25519 keypair.//-// Generate + mint (PUBLIC + PRIVATE key printed on stderr; the token on stdout):+// Generate + mint (the exact CP + gateway provisioning values on stderr; token on stdout):// node --experimental-strip-types scripts/mint.ts --org org_1 --agent agt_1 --ep 1// → set the gateway's GATEWAY_TOKEN_PUBLIC_KEY secret from the printed value.-// Reuse a private key so the gateway's public key stays fixed across mints:-// GATEWAY_TOKEN_PRIVATE_KEY=<b64url-pkcs8> node ... scripts/mint.ts --org org_1 --agent agt_1 --ep 2+// Reuse the control-plane private value so the gateway public key stays fixed:+// V3_GATEWAY_TOKEN_PRIVATE_KEY=<base64-pkcs8-pem> node ... scripts/mint.ts ...import { mintDeployToken, type DeployClaims } from "../src/token.ts";const b64url = (buf: ArrayBuffer) => Buffer.from(buf).toString("base64url");-const fromB64url = (s: string) => Buffer.from(s, "base64url");+const pemFromDer = (der: ArrayBuffer) => {+ const body = Buffer.from(der).toString("base64").match(/.{1,64}/g)?.join("\n") ?? "";+ return `-----BEGIN PRIVATE KEY-----\n${body}\n-----END PRIVATE KEY-----\n`;+};+const derFromPemB64 = (value: string) => {+ const pem = Buffer.from(value, "base64").toString("utf8");+ return Buffer.from(pem.replace(/-----[^-]+-----/g, "").replace(/\s/g, ""), "base64");+};function arg(name: string, def?: string): string | undefined {const i = process.argv.indexOf(`--${name}`);@@ -21,14 +28,17 @@ function arg(name: string, def?: string): string | undefined {const ED = { name: "Ed25519" } as const;let privateKey: CryptoKey;-const existing = process.env.GATEWAY_TOKEN_PRIVATE_KEY;+const existing = process.env.V3_GATEWAY_TOKEN_PRIVATE_KEY;if (existing) {- privateKey = await crypto.subtle.importKey("pkcs8", fromB64url(existing), ED, true, ["sign"]);+ privateKey = await crypto.subtle.importKey("pkcs8", derFromPemB64(existing), ED, true, ["sign"]);} else {const kp = (await crypto.subtle.generateKey(ED, true, ["sign", "verify"])) as CryptoKeyPair;privateKey = kp.privateKey;- console.error(`GATEWAY_TOKEN_PUBLIC_KEY=${b64url(await crypto.subtle.exportKey("raw", kp.publicKey))}`);- console.error(`GATEWAY_TOKEN_PRIVATE_KEY=${b64url(await crypto.subtle.exportKey("pkcs8", kp.privateKey))}`);+ const publicValue = b64url(await crypto.subtle.exportKey("raw", kp.publicKey));+ const privateValue = Buffer.from(pemFromDer(await crypto.subtle.exportKey("pkcs8", kp.privateKey)), "utf8").toString("base64");+ console.error(`V3_GATEWAY_TOKEN_PRIVATE_KEY=${privateValue}`);+ console.error(`V3_GATEWAY_TOKEN_PUBLIC_KEY=${publicValue}`);+ console.error(`GATEWAY_TOKEN_PUBLIC_KEY=${publicValue}`);}const now = Math.floor(Date.now() / 1000);@@ -38,6 +48,7 @@ const claims: DeployClaims = {org: arg("org", "org_1")!,agt: arg("agent", "agt_1")!,ep: ep != null ? Number(ep) : undefined,+ scopes: ["gateway:invoke", "sandbox:use", "repo:use", "ingest:write"],iat: now,exp: now + ttl,};diff --git a/cloudflare-workers/oc-gateway/src/budget.ts b/cloudflare-workers/oc-gateway/src/budget.tsindex 430ec25d..53afc5e3 100644--- a/cloudflare-workers/oc-gateway/src/budget.ts+++ b/cloudflare-workers/oc-gateway/src/budget.ts@@ -59,8 +59,10 @@ export class SpendCounter {// POST /check {default_budget_micro?} → GATE a NEW call (used ONLY at the hard org+agt grain). On// first sight of an unprovisioned key, adopt the gateway's default cap (server-side; never from the- // token). Allowed while spent < budget; the last in-flight call can overshoot by at most one call's- // cost — bounded and acceptable for "refuse past the limit". Runs BEFORE the model call, DO-serialized.+ // token). Allowed while spent < budget. Because /add lands after each response, the real overshoot+ // bound is budget + the sum of every call concurrently in flight at the check boundary (not one+ // call). The org's OpenRouter key cap remains the hard monetary ceiling. Runs before the call and+ // is DO-serialized.if (url.pathname === "/check") {const s = await this.load();if (!s.provisioned && typeof body.default_budget_micro === "number") {diff --git a/cloudflare-workers/oc-gateway/src/deploylease.ts b/cloudflare-workers/oc-gateway/src/deploylease.tsindex 839f2792..190b0c60 100644--- a/cloudflare-workers/oc-gateway/src/deploylease.ts+++ b/cloudflare-workers/oc-gateway/src/deploylease.ts@@ -37,7 +37,8 @@ export class DeployLease {if (url.pathname === "/gate") {const l = await this.load();const ep = typeof body.ep === "number" ? body.ep : null;- if (ep == null) return Response.json({ ok: true, fenced: false, floor: l.floor }); // no epoch → no fence+ // Rollout compatibility only while unprovisioned. Once a floor exists, omission fails closed.+ if (ep == null) return Response.json({ ok: l.floor === 0, fenced: l.floor > 0, floor: l.floor, missing_epoch: l.floor > 0 });if (ep < l.floor) return Response.json({ ok: false, fenced: true, floor: l.floor });if (ep > l.floor) {l.floor = ep;diff --git a/cloudflare-workers/oc-gateway/src/index.ts b/cloudflare-workers/oc-gateway/src/index.tsindex 2d420329..9138e746 100644--- a/cloudflare-workers/oc-gateway/src/index.ts+++ b/cloudflare-workers/oc-gateway/src/index.ts@@ -81,6 +81,18 @@ function bearer(h: Headers): string | null {return x ? x.trim() : null;}+function timingSafeEqual(a: string, b: string): boolean {+ if (a.length !== b.length) return false;+ let diff = 0;+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);+ return diff === 0;+}++function validSessionId(value: string | null): string | null {+ const id = value?.trim() ?? "";+ return id.length <= 128 && /^ses_[A-Za-z0-9_-]+$/.test(id) ? id : null;+}+const json = (obj: unknown, status = 200) =>new Response(JSON.stringify(obj), { status, headers: { "content-type": "application/json" } });@@ -106,13 +118,13 @@ export default {const token = bearer(req.headers);if (!token) return json({ error: { type: "unauthorized", message: "missing deploy token" } }, 401);const nowSec = Math.floor(Date.now() / 1000);- const v = await verifyDeployToken(env.GATEWAY_TOKEN_PUBLIC_KEY, token, nowSec);+ const v = await verifyDeployToken(env.GATEWAY_TOKEN_PUBLIC_KEY, token, nowSec, "gateway:invoke");if (!v.ok) return json({ error: { type: "unauthorized", message: `invalid deploy token: ${v.reason}` } }, 401);const { org: orgId, agt: agentId, ep } = v.claims;// Best-effort per-session attribution — the header may be stale under co-location; used for// tracking only, never gated. Absent → we simply skip the per-session record (the call proceeds).- const sessionId = req.headers.get("x-oc-session")?.trim() || null;+ const sessionId = validSessionId(req.headers.get("x-oc-session"));// (b) lease-epoch fence — a rotated/revoked deploy token stops verifying (per org+agt, DO-serialized).const leaseStub = env.DEPLOY_LEASE.get(env.DEPLOY_LEASE.idFromName(`${orgId}:${agentId}`));@@ -186,7 +198,9 @@ export default {ctx.waitUntil(meter(meterCopy, isStream, env, {agentBudget,- sessionCounter: sessionId ? env.SPEND_COUNTER.get(env.SPEND_COUNTER.idFromName(`sess:${sessionId}`)) : null,+ sessionCounter: sessionId+ ? env.SPEND_COUNTER.get(env.SPEND_COUNTER.idFromName(`sess:${orgId}:${agentId}:${sessionId}`))+ : null,sessionId, orgId, agentId,}),);@@ -208,7 +222,7 @@ function parseUsdMicro(usd?: string): number | null {async function admin(req: Request, env: Env, url: URL): Promise<Response> {if (!env.GATEWAY_ADMIN_SECRET) return json({ error: { type: "not_found" } }, 404);const auth = bearer(req.headers);- if (auth !== env.GATEWAY_ADMIN_SECRET) return json({ error: { type: "unauthorized" } }, 401);+ if (!auth || !timingSafeEqual(auth, env.GATEWAY_ADMIN_SECRET)) return json({ error: { type: "unauthorized" } }, 401);if (req.method !== "POST") return json({ error: { type: "method_not_allowed" } }, 405);const body = (await req.json().catch(() => ({}))) as Record<string, unknown>;diff --git a/cloudflare-workers/oc-gateway/src/token.ts b/cloudflare-workers/oc-gateway/src/token.tsindex 311bd99e..e47d11a8 100644--- a/cloudflare-workers/oc-gateway/src/token.ts+++ b/cloudflare-workers/oc-gateway/src/token.ts@@ -17,7 +17,7 @@// explicitly-revoked deploy token stops verifying even before `exp`.//// MINT↔VERIFY CONTRACT (W7 mints; the gateway verifies):-// alg "EdDSA"; claims { org, agt, iat, exp, ep? }; the gateway is configured with+// alg "EdDSA"; claims { org, agt, iat, exp, ep?, scopes[] }; the gateway is configured with// GATEWAY_TOKEN_PUBLIC_KEY = base64url(raw 32-byte Ed25519 public key).export interface DeployClaims {@@ -27,6 +27,8 @@ export interface DeployClaims {agt: string;/** lease/deploy epoch (monotonic per (org, agt)). Below the DeployLease floor → fenced. Omit = no fence. */ep?: number;+ /** Explicit tenant capabilities; the gateway requires `gateway:invoke`. */+ scopes: Array<"gateway:invoke" | "sandbox:use" | "repo:use" | "ingest:write">;/** issued-at / expiry (seconds). */iat: number;exp: number;@@ -57,7 +59,12 @@ async function importPublicKey(publicKeyB64url: string): Promise<CryptoKey> {export type VerifyResult = { ok: true; claims: DeployClaims } | { ok: false; reason: string };/** Verify a per-deploy EdDSA token: alg pin + signature + exp/iat + required claims (org, agt). */-export async function verifyDeployToken(publicKeyB64url: string, token: string, nowSec: number): Promise<VerifyResult> {+export async function verifyDeployToken(+ publicKeyB64url: string,+ token: string,+ nowSec: number,+ requiredScope?: DeployClaims["scopes"][number],+): Promise<VerifyResult> {const parts = token.split(".");if (parts.length !== 3) return { ok: false, reason: "malformed" };const [header, payload, sig] = parts;@@ -94,6 +101,14 @@ export async function verifyDeployToken(publicKeyB64url: string, token: string,if (typeof claims.exp !== "number" || claims.exp <= nowSec) return { ok: false, reason: "expired" };if (typeof claims.iat === "number" && claims.iat > nowSec + 60) return { ok: false, reason: "future_iat" };if (!claims.org || !claims.agt) return { ok: false, reason: "missing_claims" };+ if (!Array.isArray(claims.scopes) || claims.scopes.some((scope) =>+ scope !== "gateway:invoke" && scope !== "sandbox:use" && scope !== "repo:use" && scope !== "ingest:write")) {+ return { ok: false, reason: "bad_scopes" };+ }+ if (claims.ep !== undefined && (!Number.isSafeInteger(claims.ep) || claims.ep < 0)) {+ return { ok: false, reason: "bad_epoch" };+ }+ if (requiredScope && !claims.scopes.includes(requiredScope)) return { ok: false, reason: "missing_scope" };return { ok: true, claims };}diff --git a/cloudflare-workers/oc-gateway/test/integration.test.ts b/cloudflare-workers/oc-gateway/test/integration.test.tsindex a698ab3b..49cf79f7 100644--- a/cloudflare-workers/oc-gateway/test/integration.test.ts+++ b/cloudflare-workers/oc-gateway/test/integration.test.ts@@ -10,7 +10,7 @@ import { describe, it, expect, beforeEach, beforeAll, vi, afterEach } from "viteimport worker, { Env } from "../src/index.js";import { SpendCounter } from "../src/budget.js";import { DeployLease } from "../src/deploylease.js";-import { generateKeyPair, mintDeployToken } from "../src/token.js";+import { generateKeyPair, mintDeployToken, type DeployClaims } from "../src/token.js";const OR_KEY = "sk-or-v1-FAKE-org-key";const OR_BASE = "https://mock-openrouter.test/api";@@ -89,9 +89,9 @@ const post = (token?: string, session?: string, body = MSG) => new Request("http},body,});-const mint = async (o: Partial<{ org: string; agt: string; ep: number; iat: number; exp: number }> = {}) => {+const mint = async (o: Partial<{ org: string; agt: string; ep: number; scopes: DeployClaims["scopes"]; iat: number; exp: number }> = {}) => {const now = Math.floor(Date.now() / 1000);- return mintDeployToken(PRIV, { org: "org_1", agt: "agt_1", iat: now, exp: now + 3600, ...o });+ return mintDeployToken(PRIV, { org: "org_1", agt: "agt_1", scopes: ["gateway:invoke"], iat: now, exp: now + 3600, ...o });};const stateOf = async (inst: { fetch(r: Request): Promise<Response> }) =>(await inst.fetch(new Request("https://do/state"))).json() as Promise<{ spent_micro: number }>;@@ -180,8 +180,8 @@ describe("gateway on-path flow (resolved seam)", () => {expect(ry.status).toBe(200);expect(rz.status).toBe(402); // org+agt cap hit across sessions// best-effort per-session tracking recorded each session's own spend separately- expect((await stateOf(spend.instances.get("sess:ses_x")!)).spent_micro).toBe(20_000);- expect((await stateOf(spend.instances.get("sess:ses_y")!)).spent_micro).toBe(20_000);+ expect((await stateOf(spend.instances.get("sess:org_1:agt_1:ses_x")!)).spent_micro).toBe(20_000);+ expect((await stateOf(spend.instances.get("sess:org_1:agt_1:ses_y")!)).spent_micro).toBe(20_000);// and the authoritative org+agt grain summed themexpect((await stateOf(spend.instances.get("agt:org_1:agt_1")!)).spent_micro).toBe(40_000);});@@ -192,7 +192,7 @@ describe("gateway on-path flow (resolved seam)", () => {const token = await mint();for (let i = 0; i < 3; i++) { const c = ctx(); const r = await worker.fetch(post(token, "ses_hot"), env, c); await drain(c); expect(r.status).toBe(200); }// the session accumulated $0.30 but was never blocked (no per-session hard gate)- expect((await stateOf(spend.instances.get("sess:ses_hot")!)).spent_micro).toBe(300_000);+ expect((await stateOf(spend.instances.get("sess:org_1:agt_1:ses_hot")!)).spent_micro).toBe(300_000);});it("fences a superseded deploy lease epoch (401 token_superseded)", async () => {diff --git a/cloudflare-workers/oc-gateway/test/logic.test.ts b/cloudflare-workers/oc-gateway/test/logic.test.tsindex 1067d6db..c1b1ae37 100644--- a/cloudflare-workers/oc-gateway/test/logic.test.ts+++ b/cloudflare-workers/oc-gateway/test/logic.test.ts@@ -13,7 +13,7 @@ import { DeployLease } from "../src/deploylease.js";const now = 1_800_000_000;const b64url = (o: unknown) => btoa(JSON.stringify(o)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");const claims = (o: Partial<DeployClaims> = {}): DeployClaims => ({- org: "org_1", agt: "agt_1", ep: 2, iat: now, exp: now + 3600, ...o,+ org: "org_1", agt: "agt_1", ep: 2, scopes: ["gateway:invoke", "sandbox:use"], iat: now, exp: now + 3600, ...o,});function fakeState(): DurableObjectState {@@ -58,11 +58,18 @@ describe("deploy token (EdDSA, per-deploy {org, agt})", () => {});it("rejects a token missing org/agt", async () => {const { privateKey, publicKeyB64url } = await generateKeyPair();- const t = await mintDeployToken(privateKey, { org: "", agt: "", iat: now, exp: now + 3600 });+ const t = await mintDeployToken(privateKey, { org: "", agt: "", scopes: ["gateway:invoke"], iat: now, exp: now + 3600 });const v = await verifyDeployToken(publicKeyB64url, t, now);expect(v.ok).toBe(false);if (!v.ok) expect(v.reason).toBe("missing_claims");});+ it("requires the named capability", async () => {+ const { privateKey, publicKeyB64url } = await generateKeyPair();+ const token = await mintDeployToken(privateKey, claims({ scopes: ["sandbox:use"] }));+ const v = await verifyDeployToken(publicKeyB64url, token, now, "gateway:invoke");+ expect(v.ok).toBe(false);+ if (!v.ok) expect(v.reason).toBe("missing_scope");+ });it("pins alg=EdDSA — rejects an alg-swap (none/HS256) header", async () => {const { privateKey, publicKeyB64url } = await generateKeyPair();const [, p, s] = (await mintDeployToken(privateKey, claims())).split(".");@@ -116,10 +123,12 @@ describe("DeployLease DO — lease-epoch fence + bump (revocation)", () => {expect(stale.fenced).toBe(true);expect(stale.ok).toBe(false);});- it("a token with no epoch is never fenced (opt-in fence)", async () => {+ it("an epoch-less token fails closed once a floor exists", async () => {const l = new DeployLease(fakeState());await call(l, "/gate", { ep: 5 }); // raise the floor- expect((await call(l, "/gate", {})).fenced).toBe(false); // no ep → passes+ const missing = await call(l, "/gate", {});+ expect(missing.fenced).toBe(true);+ expect(missing.ok).toBe(false);});it("bump revokes without a redeploy (raise the floor above the live token)", async () => {const l = new DeployLease(fakeState());diff --git a/sdks/flue/src/gateway.ts b/sdks/flue/src/gateway.tsindex eb8c9e9a..5cf20cfa 100644--- a/sdks/flue/src/gateway.ts+++ b/sdks/flue/src/gateway.ts@@ -8,10 +8,10 @@// The secret DOES live on the per-REQUEST env (`c.env`) — the same source ocSandbox reads at run time.// Fix: bind the apiKey at RUN scope from the exported `route` middleware, reading OC_SESSION_TOKEN from// `c.env` by DIRECT property access (NEVER spread c.env — the CF env is a proxy and spreading it throws)-// and OC_GATEWAY from the ambient snapshot, once per isolate. The token is per-DEPLOY (identical for every-// session), so the MODULE(isolate)-scoped registry holds one static value with NO cross-session race; the-// upstream per-request headers(ctx)/getApiKey(ctx) ask is only needed IF a PER-SESSION token is later-// introduced. registerProvider still takes a static apiKey / getApiKey has no turn context — fine here.+// and OC_GATEWAY from the ambient snapshot. The token is per-DEPLOY (identical for every session), so+// rebinding it is race-free. The route also sets a best-effort X-OC-Session header; that static registry+// header can race under co-location and is never an authorization boundary. Exact attribution still needs+// the upstream per-request headers(ctx) resolver.import { registerProvider } from "@flue/runtime";import type { AgentInitializerContext, AgentRouteHandler } from "@flue/runtime";@@ -38,12 +38,13 @@ export interface OcEnv {* model specifier resolves); attaches the apiKey only when the per-deploy OC_SESSION_TOKEN is present in* this snapshot. Returns true only when the apiKey actually landed — callers use that to stop rebinding.* No-op when OC_GATEWAY is unset (local `flue dev` falls through to pi-ai's env-var key lookup). */-function bindOcProvider(env: OcEnv): boolean {+function bindOcProvider(env: OcEnv, sessionId?: string): boolean {const gw = env.OC_GATEWAY;if (!gw) return false;registerProvider("anthropic", {baseUrl: `${gw.replace(/\/+$/, "")}/anthropic`,...(env.OC_SESSION_TOKEN ? { apiKey: env.OC_SESSION_TOKEN } : {}),+ ...(sessionId ? { headers: { "X-OC-Session": sessionId } } : {}),});return Boolean(env.OC_SESSION_TOKEN);}@@ -61,16 +62,13 @@ export function useOcGateway(ctx: AgentInitializerContext<OcEnv>): void {bindOcProvider(ocResolveEnv<OcEnv>(ctx.env));}-/** Set once the run-scope apiKey bind lands (module/isolate-scoped; the token is deploy-static so one- * bind serves every co-located session — no per-session race). */-let ocProviderBound = false;-/*** The HTTP-transport opt-in every OC-hosted agent MUST export as `route` (an agent is reachable at* `/agents/:name/:id` only when its module exports `route` — flue-app.ts). ALSO the run-scope binder for* the token seam: on each request (where the request ALS is entered and OC_SESSION_TOKEN is readable) it- * (re)binds the provider's apiKey, once per isolate, BEFORE the turn's model call runs via `next()`. A- * first `?view=updates` read that predates the token just leaves the flag false and retries next request.+ * (re)binds the provider's apiKey and best-effort session attribution BEFORE the turn's model call+ * runs via `next()`. The provider registry is isolate-global, so the session header is visibility-only+ * until Flue exposes a per-request provider resolver; hard enforcement remains org+agent in the token.* The OC dispatch Worker is the auth boundary (013 §3 B5), so the transport itself adds none.*/export const route: AgentRouteHandler = async (c, next) => {@@ -79,10 +77,9 @@ export const route: AgentRouteHandler = async (c, next) => {// key"). The secret IS on the REQUEST env (c.env) — the same source ocSandbox reads in createSessionEnv.// Read the token from c.env by DIRECT property access (never spread c.env — the CF env is a proxy and// spreading it throws, which would break the request), and take OC_GATEWAY from the ambient snapshot.- if (!ocProviderBound) {- const amb = ocResolveEnv<OcEnv>(undefined);- const token = (c.env as OcEnv | undefined)?.OC_SESSION_TOKEN ?? amb.OC_SESSION_TOKEN;- ocProviderBound = bindOcProvider({ ...amb, ...(token ? { OC_SESSION_TOKEN: token } : {}) });- }+ const amb = ocResolveEnv<OcEnv>(undefined);+ const token = (c.env as OcEnv | undefined)?.OC_SESSION_TOKEN ?? amb.OC_SESSION_TOKEN;+ const sessionId = c.req.param("id") || undefined;+ bindOcProvider({ ...amb, ...(token ? { OC_SESSION_TOKEN: token } : {}) }, sessionId);return next();};