Skip to content

An open-source, faster Devin alternative

TypeScript

feat(oc-gateway): W3 gateway to the resolved token seam (per-deploy token, org+agt enforcement)

Igor Zalutski78b0f7bb7d8e
diff --git a/cloudflare-workers/oc-gateway/README.md b/cloudflare-workers/oc-gateway/README.md
index 5c0f30b7..9f7c46a2 100644
--- a/cloudflare-workers/oc-gateway/README.md
+++ b/cloudflare-workers/oc-gateway/README.md
@@ -1,8 +1,8 @@
-# oc-gateway — thin per-session Worker over OpenRouter
+# oc-gateway — thin OC Worker over OpenRouter (W3, productionized)
-**W3 (productionized) / Lane L2** for the Flue-native agent type (`oc-bg-agents .agents/work/flue-native-buildout.md`, design `013 §4`). Implements **inter-lane Contract #1** (Gateway HTTP contract), hardened from the 1a spike (`spike/oc-gateway`, #486) and **live-verified** against real OpenRouter.
+**Buildout W3** for the Flue-native agent type (`oc-bg-agents .agents/work/flue-native-buildout.md`, design `013 §4`, contract **#1**). Productionizes the `spike/oc-gateway` (#486) reference to the **resolved token seam** (2026-07-05, option b + the co-location refinement).
-It **extends** the shipped managed-model path (does not replace it): org-level spend keeps flowing through the org's single OpenRouter inference key → the existing `model_meter` cron → Autumn (`opencomputer/cloudflare-workers/api-edge/src/{model_billing,model_meter,openrouter}.ts`, `token-billing.md`). The gateway only adds the injection point a CF Worker needs (it can't use the box secrets-proxy) plus **per-session sub-metering + on-path budget enforcement**.
+It **extends** the shipped managed-model path (does not replace it): org-level spend keeps flowing through the org's single OpenRouter inference key → the existing `model_meter` cron → Autumn (`opencomputer/cloudflare-workers/api-edge/src/{model_billing,model_meter,openrouter}.ts`, `token-billing.md`). The gateway only adds the injection point a CF Worker needs (it can't use the box secrets-proxy) plus **org+agt budget enforcement + best-effort per-session sub-metering**. It pushes **nothing** to Autumn.
---
@@ -10,10 +10,18 @@ It **extends** the shipped managed-model path (does not replace it): org-level s
### 1. Path shape
+An unmodified Flue app registers a managed provider at the gateway **inside `defineAgent`**:
+
```ts
-registerProvider('anthropic', { baseUrl: `${env.OC_GATEWAY}/anthropic`, apiKey: <session_token> });
+registerProvider('anthropic', {
+ baseUrl: `${env.OC_GATEWAY}/anthropic`,
+ apiKey: env.OC_SESSION_TOKEN, // the per-DEPLOY token (bound by W7 as an env var)
+ headers: { 'X-OC-Session': id }, // the DO's own init id = ses_… — best-effort attribution
+});
```
+The provider client appends its native tail; the gateway strips the provider prefix and forwards to the OpenRouter base the box path already uses (`credential.ts` `MANAGED_ANTHROPIC_BASE = https://openrouter.ai/api`):
+
| Gateway request | Forwarded to OpenRouter |
|---|---|
| `POST {gw}/anthropic/v1/messages` | `POST https://openrouter.ai/api/v1/messages` (Claude-Code path) |
@@ -22,44 +30,58 @@ registerProvider('anthropic', { baseUrl: `${env.OC_GATEWAY}/anthropic`, apiKey:
Rule: `/{provider}/<tail>` → `<OR base for provider> + <tail>`, query string preserved. `cloudflare/<model>` is **out of scope** — `env.AI.run()` bypasses `fetch`, so the gateway can't meter it (design §4).
-### 2. Per-session token — EdDSA, with a lease-epoch fence
+### 2. The deploy token — per-DEPLOY, EdDSA, lease-fenced
+
+**Resolved token seam.** The token is **per-DEPLOY**, not per-session. Flue's `registerProvider` `apiKey` is a static string only, and its provider registry is isolate-global while CF co-locates many session-DOs of one agent's script in one isolate — so per-session data injected via `registerProvider` (the token OR the header) **races** across co-located sessions. Therefore the token carries only `(org, agt)` and the **hard cost-safety boundary is at the org+agt grain**.
-A compact **EdDSA (Ed25519) JWT** the tenant Worker holds as the provider `apiKey`. The **minter** (control plane / session DO) holds the private key; the **gateway holds only the public key** (`GATEWAY_TOKEN_PUBLIC_KEY` = base64url raw 32-byte Ed25519 public key) — the same asymmetry as the turn token, so a compromised gateway can't forge tokens.
+**Claims:** `{ org, agt, iat, exp, ep? }` — **no** `sub:session`, **no** `bud`.
+- `org` — selects the org's OpenRouter inference key (never leaves the gateway).
+- `agt` — the deploy this token authorizes; the enforcement + lease-fence key with `org`.
+- `ep` — optional monotonic deploy epoch; a token below the current lease floor is fenced.
-**Claims:** `{ sub: ses_, org, agt, bud?, ep?, iat, exp }` — `sub` = sub-meter/budget key; `org` selects the org's OR key; `bud` = per-session USD cap (omit/0 = uncapped); `ep` = lease/turn epoch.
+**Prod hardening over the spike:**
+- **EdDSA (Ed25519):** the minter (W7 deploy pipeline) holds the private key; the gateway holds only `GATEWAY_TOKEN_PUBLIC_KEY` — a compromised gateway can't forge tokens. Alg pinned (rejects `none`/HS256 swaps).
+- **Lease-epoch fence** (`DeployLease` DO, per `${org}:${agt}`): the floor rises to a token's `ep` on first use, so a **rotated** deploy's higher-epoch token instantly supersedes older tokens (401 `token_superseded`). A **revoke without redeploy** is `POST /admin/lease/bump {org, agt, min_epoch}`.
-**Transport:** `Authorization: Bearer <token>` or `x-api-key: <token>`. **Verify:** alg pinned to `EdDSA` (rejects `none`/HS256 swaps) + signature + `exp`/`iat` + required claims → `401` on failure.
+**Transport:** `Authorization: Bearer <token>` **or** `x-api-key: <token>`. Verify = alg-pin + signature + `exp`/`iat` + `org`/`agt` present. Failure → `401`.
-**Lease-epoch fence:** the `SessionBudget` DO tracks a monotonic `max_epoch`; a token whose `ep` is below it is **superseded** → `401 {code:"token_superseded"}`. A newer epoch bumps the watermark, invalidating older-epoch tokens still in flight (DO-serialized). Omitted `ep` skips the fence.
+### 3. Enforcement grain (co-location refinement)
-> **Mint↔verify seam (confirm with the orchestrator):** W1 signs the EdDSA token; default delivery = per-turn token (option a) read by Flue's `getApiKey`, so the meter attributes by `sub` unspoofably. The gateway is configured with the public key only.
+- **HARD (the 402): org+agt.** `SpendCounter` DO keyed `agt:${org}:${agt}` — race-free (the value comes from the token, identical for every co-located session of the agent). `/check` gates **before** the call; over → `402 budget_exceeded`. Budget is looked up **server-side** (provisioned via `/admin/agent/budget`, else `AGENT_BUDGET_USD_DEFAULT`) — **never** carried in the token.
+- **BEST-EFFORT per session: `X-OC-Session`.** `SpendCounter` DO keyed `sess:<session>` — the gateway only **records** spend here for per-session visibility (dashboard W11). It is **never gated**, so a co-location race can't wrongly block a legitimate session. Exact per-session enforcement is deferred to an upstream Flue per-request resolver (tracked ask — see below).
-### 3. Request/response passthrough
+### 4. Request/response passthrough
-- **Body:** buffered (small), **`cache_control` stripped for caching-unsafe models** (§6), `usage:{include:true}` injected so OR echoes cost, re-serialized; all else preserved.
-- **Auth swap:** the tenant token is stripped; `Authorization: Bearer <org OR key>` set; `http-referer`/`x-title` added. Everything else (`anthropic-version`, …) passes through.
-- **Response:** OR's status/headers/body returned **untouched** — JSON or `text/event-stream` (SSE straight through). Transparent proxy on the response path.
+- **Request body:** buffered (model requests are small), `usage:{include:true}` injected so OpenRouter echoes cost, re-serialized. `cache_control` stripped for caching-unsafe models (§6). All other fields preserved.
+- **Auth swap:** the tenant's `Authorization`/`x-api-key` **and** the `X-OC-Session` header are stripped; `Authorization: Bearer <org OR key>` set. `http-referer`/`x-title` added for OR attribution. Everything else passes through. **No raw provider key ever reaches the tenant** — it holds only the deploy token; the OR key lives in the gateway.
+- **Response:** OpenRouter's status, headers, body returned **untouched** — JSON or `text/event-stream`.
-### 4. Metering + reconciliation
+### 5. Metering + reconciliation — one cost-source-of-truth
-- **On-path sub-meter** in a `SessionBudget` **DO** (strongly consistent — serializes concurrent calls so subagents can't double-spend). `POST /check` gates **before** (`spent < budget`) + runs the epoch fence; `POST /add` commits cost **after** (via `waitUntil`), idempotent on the OR generation id.
-- **Cost source:** the `usage.cost` (USD) OR echoes per response (`cost.ts`; SSE terminal usage). Fallback `GET /api/v1/generation?id=` (unwired).
-- **One cost-source-of-truth:** the gateway forwards through the **org's existing OR key**, so OR's per-key usage still captures Flue spend → `model_meter` cron → Autumn, **exactly as the brain-box path does**. The gateway builds no billing path and pushes nothing to Autumn; its counter is enforcement + per-session display only (optionally emitted to `OC_INGEST`).
-- **Budget refusal:** `402 {error:{type:"budget_exceeded", code:"insufficient_quota"}, oc:{spent_usd,budget_usd}}` — a provider-style error so the turn terminates and the tailer maps it to outcome `budget_exceeded`. Bounded **one-call overshoot** (a call that passes pre-check but tips the total over) is accepted.
+- **On-path sub-meter:** `/check` gates (org+agt) before; `/add` commits cost after (off the response path via `waitUntil`), idempotent on the OpenRouter generation id. Recorded at the org+agt grain (authoritative for enforcement) **and** best-effort per session.
+- **Cost source:** the `usage.cost` (USD) OpenRouter echoes per response (`cost.ts`; SSE terminal usage). Exact-cost fallback `GET /api/v1/generation?id=<id>` (documented, unwired).
+- **Reconciliation:** the gateway forwards through the **org's existing OR inference key**, so OR's per-key cumulative usage still captures Flue spend → `model_meter` cron → Autumn, **exactly as the brain-box path does today**. The gateway builds **no** billing path and pushes **nothing** to Autumn. Its counters are for **enforcement + display only**; they and OR's per-key usage are independent by design.
+- **Budget refusal:** `402 {error:{type:"budget_exceeded", code:"insufficient_quota"}, oc:{org,agent,spent_usd,budget_usd}}` — a provider-style error so the Flue turn terminates and the tailer maps it to outcome `budget_exceeded` (§8). *The exact shape Flue surfaces cleanly is a live-verify item.*
-### 5. Org OpenRouter key resolution
+### 6. Org OpenRouter key resolution (from Infisical, via a sessions-api seam)
-The gateway maps `org_id → OR inference key`. The plaintext lives in **Infisical**, sealed by sessions-api (edge `managed_model_keys` owns the key lifecycle; `credential.ts resolveManagedSecret`). A CF Worker can't reach Infisical, so the gateway resolves through a **dedicated internal sessions-api seam** (mirrors the edge's dedicated-secret plaintext-key hand-off — a route carrying a live key gets its own secret):
+The managed OR **inference** key's plaintext lives in **Infisical**, referenced by the org's managed credential and resolved only by `sessions-api` `resolveManagedSecret` (`credential.ts`). A CF Worker can't reach Infisical or the box secrets-proxy (design §4), so the gateway resolves it through a **dedicated internal sessions-api route** — mirroring the edge's dedicated-secret plaintext-key hand-off (`model_billing.ts §6.7.5`: a route carrying a live key gets its **own** secret, not the generic internal-auth one):
```
-POST {GATEWAY_ORKEY_URL} Authorization: Bearer {GATEWAY_ORKEY_SECRET} {"org": orgId} → {"key": "sk-or-..."}
+POST {GATEWAY_ORKEY_URL} Authorization: Bearer {GATEWAY_ORKEY_SECRET} body {"org": orgId}
+ → 200 {"key": "sk-or-..."} (resolveManagedSecret for the org's active managed credential)
```
-Cached per org in-isolate (60s TTL — bounds exposure + avoids per-call hits). `TEST_OR_KEY` short-circuits resolution for the acceptance run. **L3 seam to build:** the route reusing `resolveManagedSecret` (flagged in the W3 PR).
+The plaintext is cached per-org in-isolate with a 60 s TTL. `TEST_OR_KEY` short-circuits resolution for the acceptance run. **This route is the one control-plane seam W3 needs sessions-api to add** (see "seam questions").
+
+### 7. Prompt-caching safety
+
+Some models route (via OpenRouter) to a backend that rejects Anthropic `cache_control` breakpoints (`claude-3-haiku` → OR→Bedrock 400s; `claude-haiku-4.5` works). The gateway **strips `cache_control`** from the body for an env-extensible denylist (`CACHE_CONTROL_UNSAFE_MODELS`) so the call still completes; caching-safe models are untouched.
-### 6. Prompt-caching safety
+### 8. Control-plane admin routes (guarded by `GATEWAY_ADMIN_SECRET`)
-Some models route (via OR) to a backend that rejects Anthropic `cache_control` — `anthropic/claude-3-haiku` (→ Bedrock) **400s** the whole request. The gateway **strips `cache_control`** from the body for an env-extensible denylist (`models.ts`, `CACHE_CONTROL_UNSAFE_MODELS`); caching-capable models are untouched.
+- `POST /admin/agent/budget {org, agt, budget_usd|null}` — provision the org+agt hard cap (W1/W7 seam).
+- `POST /admin/lease/bump {org, agt, min_epoch}` — revoke deploy tokens below `min_epoch` (no redeploy).
---
@@ -67,37 +89,41 @@ Some models route (via OR) to a backend that rejects Anthropic `cache_control`
| File | Role |
|---|---|
-| `src/index.ts` | the Worker: verify → epoch-fence + budget gate → org-key inject → cache-safe + usage → forward → tee-meter → passthrough |
-| `src/token.ts` | EdDSA session token verify + mint/keygen helpers (Web Crypto, no deps) |
-| `src/budget.ts` | `SessionBudget` DO — per-session spend counter + hard gate + epoch fence (µ$ integers) |
-| `src/orgkey.ts` | org OR-key resolver — internal seam + per-isolate cache + test override |
-| `src/models.ts` | `cache_control` safety (unsafe-model denylist + strip) |
+| `src/index.ts` | verify deploy token → lease fence → org+agt hard gate → org-key inject → forward → tee-meter → passthrough |
+| `src/token.ts` | EdDSA per-deploy token mint/verify (Web Crypto, no deps) |
+| `src/budget.ts` | `SpendCounter` DO — keyed spend counter + hard gate (µ$ integers); org+agt (hard) + per-session (tracked) |
+| `src/deploylease.ts` | `DeployLease` DO — per-(org,agt) lease-epoch floor (rotation/revocation fence) |
+| `src/orgkey.ts` | org OR-key resolution via the dedicated sessions-api seam (`TEST_OR_KEY` override for tests) |
| `src/cost.ts` | per-response cost extraction (JSON + SSE) |
-| `scripts/mint.ts` | EdDSA mint helper (generates a keypair; mints a session token) |
-| `test/` | `logic` (15) + `integration` (8, real handler + real DO vs mock OR) — **23 green** |
+| `src/models.ts` | `cache_control` safety (strip for unsafe models) |
+| `scripts/mint.ts` | mint a per-deploy token for live verification |
+| `test/` | `logic` (20) + `integration` (11) — **31 green** |
-## Verification
+## Verification status
-**Unit + integration (`npx vitest run`, 23 green):** EdDSA mint/verify + alg-pin + wrong-key/expired/tamper; `SessionBudget` epoch fence + budget gate + `/add` idempotency; `cache_control` strip; cost extraction; and the full on-path flow through the real handler (401 no/bad token, org-key injection with the session token never reaching OR, `usage.include`, passthrough, on-path 402, epoch fence 401, cache_control strip).
+- **In-process integration (green, CI-able):** `npx vitest run` drives the real worker handler + real `SpendCounter`/`DeployLease` DOs with `fetch` stubbed to a mock OpenRouter. Proves: 401 (no/expired/superseded token), forward with **org-key injection** (deploy token never reaches OR; session header never egresses) + `usage.include`, body passthrough, **org+agt hard enforcement** with bounded overshoot, **co-location** (two sessions share the org+agt cap), **per-session tracked-but-never-gated**, `cache_control` strip, admin provision.
+- **Live turn:** one real `anthropic/*` turn through a local `wrangler dev` gateway → OpenRouter, against a **$1-capped throwaway** OR inference key minted from `OPENROUTER_PROVISIONING_KEY` and torn down after.
-**Live acceptance (run 2026-07-05 against real OpenRouter via `wrangler dev --local`, throwaway $1-capped OR key, torn down after):**
-- Happy path — a real `anthropic/claude-haiku-4.5` turn completed gateway → OpenRouter → `200`, answer `pong`, `usage.cost` echoed; **no OR key in the response**; token ≠ key.
-- Budget — `bud=$0.000001`: call 1 `200` (spent $3.8e-05) → call 2 **`402 budget_exceeded`** on-path.
-- cache_control — `claude-3-haiku` with a `cache_control` block: **via gateway `200`** (stripped) vs **direct-to-OR `400`** (proves the strip is necessary and works).
-- Epoch fence — epoch 2 adopted → epoch 1 **`401 token_superseded`**. Auth — no/garbage token **`401`**.
-
-### Reproduce the live run
+### Live verification
```bash
-# secrets in .dev.vars (gitignored): the gateway's public key + a real OR key
-GATEWAY_TOKEN_PUBLIC_KEY=<from scripts/mint.ts stderr>
-TEST_OR_KEY=<a real openrouter inference key>
-
-npx wrangler dev --port 8791 --local
-# mint a token with the matching private key, then POST a real turn:
-GATEWAY_TOKEN_PRIVATE_KEY=<b64url pkcs8> node --experimental-strip-types scripts/mint.ts \
- --session ses_live --org org_1 --budget 0.05
-curl -sN -X POST http://localhost:8791/anthropic/v1/messages \
- -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
- -d '{"model":"anthropic/claude-haiku-4.5","max_tokens":16,"messages":[{"role":"user","content":"say pong"}]}'
+nvm use 22.19
+# 1. mint a $1-capped throwaway OR inference key + an Ed25519 keypair + a deploy token; write .dev.vars
+# (helper reads OPENROUTER_PROVISIONING_KEY from a path arg — never sourced, never printed)
+# 2. run the gateway locally (real DOs, real egress to openrouter.ai)
+npx wrangler dev --port 8799
+# 3. one real anthropic turn THROUGH the gateway (unmodified-Flue shape)
+curl -sN -X POST http://localhost:8799/anthropic/v1/messages \
+ -H "authorization: Bearer $TOKEN" -H "x-oc-session: ses_live" -H 'content-type: application/json' \
+ -d '{"model":"anthropic/claude-haiku-4.5","max_tokens":64,"messages":[{"role":"user","content":"say hi"}]}'
+# → a real completion; OR bills the throwaway key; a low AGENT_BUDGET_USD_DEFAULT makes the 2nd call 402.
+# 4. tear down: DELETE the OR key (by hash) and stop wrangler.
```
+
+**Acceptance (buildout W3):** a real turn completes gateway → OpenRouter; the deploy token verifies (org+agt) and yields **no raw provider key** to the tenant; the org+agt budget refuses on-path (402); per-session spend is tracked by `X-OC-Session`. Org spend stays on the existing OpenRouter→Autumn cron.
+
+## Seam questions for the control plane (W1/W7)
+
+1. **Org OR-key route (required to leave `TEST_OR_KEY`):** sessions-api must expose `POST {GATEWAY_ORKEY_URL}` (dedicated bearer) returning `{key}` = `resolveManagedSecret` for the org's active managed credential.
+2. **Per-agent budget provisioning (optional):** if a per-(org,agt) cap other than `AGENT_BUDGET_USD_DEFAULT` is wanted, W1/W7 calls `POST /admin/agent/budget`.
+3. **Lease epoch (`ep`) minting:** W7 should mint a monotonic per-(org,agt) `ep` into the deploy token so rotation auto-fences; a leaked token is revoked via `POST /admin/lease/bump`.
diff --git a/cloudflare-workers/oc-gateway/scripts/mint.ts b/cloudflare-workers/oc-gateway/scripts/mint.ts
index 35641d19..953c4c93 100644
--- a/cloudflare-workers/oc-gateway/scripts/mint.ts
+++ b/cloudflare-workers/oc-gateway/scripts/mint.ts
@@ -1,13 +1,14 @@
-// Mint a per-session gateway token (EdDSA). The control plane mints these in prod; this is the
-// dev/e2e helper. On first use it also generates an Ed25519 keypair.
+// Mint a per-DEPLOY gateway token (EdDSA). The control plane / deploy pipeline (W7) mints these in
+// 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 key + PRIVATE key printed on stderr; the token on stdout):
-// node --experimental-strip-types scripts/mint.ts --session ses_test --org org_1 --budget 0.50
-// → set the gateway's secret from the printed GATEWAY_TOKEN_PUBLIC_KEY.
+// Generate + mint (PUBLIC + PRIVATE key printed on stderr; the 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 --session ses_x --ep 2
+// GATEWAY_TOKEN_PRIVATE_KEY=<b64url-pkcs8> node ... scripts/mint.ts --org org_1 --agent agt_1 --ep 2
-import { mintSessionToken, type SessionClaims } from "../src/token.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");
@@ -32,15 +33,12 @@ if (existing) {
const now = Math.floor(Date.now() / 1000);
const ttl = Number(arg("ttl", "3600"));
-const budget = Number(arg("budget", "0")); // USD; 0 = uncapped
const ep = arg("ep");
-const claims: SessionClaims = {
- sub: arg("session", "ses_test")!,
+const claims: DeployClaims = {
org: arg("org", "org_1")!,
agt: arg("agent", "agt_1")!,
- bud: budget > 0 ? budget : undefined,
ep: ep != null ? Number(ep) : undefined,
iat: now,
exp: now + ttl,
};
-console.log(await mintSessionToken(privateKey, claims));
+console.log(await mintDeployToken(privateKey, claims));
diff --git a/cloudflare-workers/oc-gateway/src/budget.ts b/cloudflare-workers/oc-gateway/src/budget.ts
index f2c3bdb9..430ec25d 100644
--- a/cloudflare-workers/oc-gateway/src/budget.ts
+++ b/cloudflare-workers/oc-gateway/src/budget.ts
@@ -1,26 +1,36 @@
-// SessionBudget — the per-session on-path spend counter + hard-limit gate (design 013 §4/§8).
+// SpendCounter — a strongly-consistent keyed spend counter + optional hard gate (design 013 §4/§8).
//
-// WHY A DO (and not KV): enforcement must be read-then-write consistent. Concurrent model calls in
-// one session (subagents, parallel tools) racing on KV would double-spend past the cap. A DO
-// serializes /check and /add per session, so the running total is authoritative. This is the
-// "authoritative, not best-effort observe()" the design calls for.
+// GRAINS (resolved token seam + co-location refinement 2026-07-05). Flue's provider registry is
+// isolate-global and CF co-locates many session-DOs of one agent's script in one isolate, so ANY
+// per-session data injected via registerProvider (the static token OR an X-OC-Session header) races
+// across co-located sessions. Therefore the gateway uses this counter at TWO grains:
+// • HARD (cost-safety boundary): keyed `${org}:${agt}` — race-free because the per-DEPLOY token
+// carries org+agt and nothing per-session. The gateway /check-gates here and returns 402 when over.
+// This matches today's org-level OpenRouter→Autumn model; cost-safety is unchanged.
+// • TRACKING (best-effort): keyed by the X-OC-Session header — the gateway only /add-records here for
+// per-session visibility (dashboard W11) + soft budgets. It NEVER /check-gates a session instance,
+// so a co-location race can never wrongly 402 a legitimate session. Exact per-session enforcement
+// is deferred to an upstream Flue per-request resolver (tracked upstream ask, off the critical path).
//
-// This counter is for ENFORCEMENT + per-session display ONLY — it is NOT a billing source. Org-level
-// spend stays on the org's single OpenRouter inference key → the existing model_meter cron → Autumn
-// (one cost-source-of-truth, unchanged). The gateway sub-meter and OR's per-key usage are independent
-// by design; they need not reconcile to the penny.
+// The budget is looked up SERVER-SIDE here — NEVER carried in the token. It is set by the control plane
+// (POST /provision) or falls back to the gateway's configured default on first /check.
//
-// Money is tracked in integer MICRODOLLARS (µ$, 1e-6 USD) to avoid float drift, matching model_meter.
+// WHY A DO (not KV): enforcement must be read-then-write consistent — concurrent calls (subagents,
+// parallel tools) racing on KV would double-spend past the cap. A DO serializes /check and /add.
+//
+// This counter is for ENFORCEMENT + display ONLY — NOT a billing source. Org-level spend stays on the
+// org's single OpenRouter inference key → the existing model_meter cron → Autumn (one cost-source-of-
+// truth). Money is integer MICRODOLLARS (µ$, 1e-6 USD) to avoid float drift, matching model_meter.
interface State {
spent_micro: number;
budget_micro: number | null; // null = uncapped
+ provisioned: boolean; // true once the control plane set an explicit cap (default no longer applies)
calls: number;
updated: number;
- max_epoch: number; // highest lease/turn epoch seen; a token with a lower `ep` is fenced (superseded)
}
-export class SessionBudget {
+export class SpendCounter {
private state: DurableObjectState;
constructor(state: DurableObjectState) {
this.state = state;
@@ -28,39 +38,44 @@ export class SessionBudget {
private async load(): Promise<State> {
const s = await this.state.storage.get<State>("s");
- return s ?? { spent_micro: 0, budget_micro: null, calls: 0, updated: 0, max_epoch: 0 };
+ return s ?? { spent_micro: 0, budget_micro: null, provisioned: false, calls: 0, updated: 0 };
}
async fetch(req: Request): Promise<Response> {
const url = new URL(req.url);
const body = req.method === "POST" ? ((await req.json().catch(() => ({}))) as Record<string, unknown>) : {};
- // POST /check {budget_micro, ep?} → (1) lease-epoch fence, then (2) budget gate.
- //
- // FENCE (finding: "close the freeze-flags"): `max_epoch` is monotonic. A token whose `ep` is
- // BELOW the highest epoch seen is superseded — reject it (`fenced`). A new epoch (>= max) is
- // adopted and bumps the watermark, invalidating any still-in-flight older-epoch tokens. Omitted
- // `ep` skips the fence (uncapped/legacy mint). This runs BEFORE the model call, DO-serialized.
- //
- // GATE: return whether a NEW call is allowed (spent < budget). The last in-flight call can
- // overshoot by at most one call's cost — bounded and acceptable for "refuse past the limit".
+ // POST /provision {budget_micro} — the control plane sets this grain's explicit cap (W1/W7 seam).
+ // `budget_micro: null` = uncapped. Marks it provisioned so the gateway default is ignored.
+ if (url.pathname === "/provision") {
+ const s = await this.load();
+ if (typeof body.budget_micro === "number") s.budget_micro = Math.max(0, Math.round(body.budget_micro));
+ else if (body.budget_micro === null) s.budget_micro = null;
+ s.provisioned = true;
+ s.updated = Date.now();
+ await this.state.storage.put("s", s);
+ return Response.json({ ok: true, budget_micro: s.budget_micro });
+ }
+
+ // 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.
if (url.pathname === "/check") {
const s = await this.load();
- const ep = typeof body.ep === "number" ? body.ep : null;
- if (ep != null && ep < s.max_epoch) {
- return Response.json({ allowed: false, fenced: true, spent_micro: s.spent_micro, budget_micro: s.budget_micro });
+ if (!s.provisioned && typeof body.default_budget_micro === "number") {
+ s.budget_micro = Math.max(0, Math.round(body.default_budget_micro));
}
- if (ep != null && ep > s.max_epoch) s.max_epoch = ep;
- if (typeof body.budget_micro === "number") s.budget_micro = body.budget_micro;
- else if (body.budget_micro === null) s.budget_micro = null;
const allowed = s.budget_micro == null || s.spent_micro < s.budget_micro;
+ s.updated = Date.now();
await this.state.storage.put("s", s);
- return Response.json({ allowed, fenced: false, spent_micro: s.spent_micro, budget_micro: s.budget_micro });
+ return Response.json({ allowed, spent_micro: s.spent_micro, budget_micro: s.budget_micro });
}
- // POST /add {cost_micro} → commit a completed call's cost (called from waitUntil after the
- // response). Idempotency is keyed by the caller (an OpenRouter generation id) so a retried
- // meter never double-counts.
+ // POST /add {cost_micro, idem} → commit a completed call's cost (from waitUntil, after the response).
+ // Called at BOTH grains. Idempotent on the caller's key (an OpenRouter generation id) so a retried
+ // meter never double-counts. Each DO instance has its own idem namespace, so the same generation id
+ // recorded at the org+agt grain and the session grain does not collide.
if (url.pathname === "/add") {
const s = await this.load();
const costMicro = typeof body.cost_micro === "number" ? Math.max(0, Math.round(body.cost_micro)) : 0;
@@ -72,11 +87,12 @@ export class SessionBudget {
}
s.spent_micro += costMicro;
s.calls += 1;
+ s.updated = Date.now();
await this.state.storage.put("s", s);
return Response.json({ spent_micro: s.spent_micro, calls: s.calls });
}
- // GET /state → per-session spend (dashboard, §9).
+ // GET /state → spend at this grain (dashboard, §9).
if (url.pathname === "/state") {
const s = await this.load();
return Response.json(s);
diff --git a/cloudflare-workers/oc-gateway/src/deploylease.ts b/cloudflare-workers/oc-gateway/src/deploylease.ts
new file mode 100644
index 00000000..839f2792
--- /dev/null
+++ b/cloudflare-workers/oc-gateway/src/deploylease.ts
@@ -0,0 +1,70 @@
+// DeployLease — the per-(org, agt) lease-epoch floor that fences a rotated or revoked deploy token
+// (design 013 §4 / buildout W3 "lease-epoch fence"). Keyed by `${org}:${agt}`.
+//
+// The deploy token (token.ts) carries a monotonic `ep` (deploy epoch, minted by W7). This DO holds
+// the current floor for an (org, agt):
+// - GATE: a token whose `ep` is BELOW the floor is fenced (superseded). A token at/above the floor
+// is admitted and RAISES the floor to its `ep` — so the moment a redeploy's higher-epoch token is
+// first used, every still-in-flight older-epoch token stops verifying. This is the rotation fence,
+// automatic, no control-plane action required.
+// - BUMP: the control plane raises the floor explicitly to REVOKE without a redeploy (e.g. a leaked
+// token): POST /bump {min_epoch} sets floor = max(floor, min_epoch). To revoke epoch E, bump to E+1.
+//
+// A DO (not KV) so the floor is read-then-write consistent under concurrent calls. A token with no
+// `ep` skips the fence entirely (lenient — the fence is opt-in on the mint side).
+
+interface Lease {
+ floor: number; // highest deploy epoch admitted / bumped; a token with ep < floor is fenced
+ updated: number;
+}
+
+export class DeployLease {
+ private state: DurableObjectState;
+ constructor(state: DurableObjectState) {
+ this.state = state;
+ }
+
+ private async load(): Promise<Lease> {
+ const l = await this.state.storage.get<Lease>("l");
+ return l ?? { floor: 0, updated: 0 };
+ }
+
+ async fetch(req: Request): Promise<Response> {
+ const url = new URL(req.url);
+ const body = req.method === "POST" ? ((await req.json().catch(() => ({}))) as Record<string, unknown>) : {};
+
+ // POST /gate {ep?} → { ok, fenced, floor }. Fence ep < floor; adopt (raise floor) on ep >= floor.
+ 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
+ if (ep < l.floor) return Response.json({ ok: false, fenced: true, floor: l.floor });
+ if (ep > l.floor) {
+ l.floor = ep;
+ l.updated = Date.now();
+ await this.state.storage.put("l", l);
+ }
+ return Response.json({ ok: true, fenced: false, floor: l.floor });
+ }
+
+ // POST /bump {min_epoch} → raise the floor for an explicit revocation. floor = max(floor, min_epoch).
+ if (url.pathname === "/bump") {
+ const l = await this.load();
+ const min = typeof body.min_epoch === "number" ? Math.round(body.min_epoch) : null;
+ if (min != null && min > l.floor) {
+ l.floor = min;
+ l.updated = Date.now();
+ await this.state.storage.put("l", l);
+ }
+ return Response.json({ floor: l.floor });
+ }
+
+ // GET /state → the current floor (ops / dashboard).
+ if (url.pathname === "/state") {
+ const l = await this.load();
+ return Response.json(l);
+ }
+
+ return new Response("not found", { status: 404 });
+ }
+}
diff --git a/cloudflare-workers/oc-gateway/src/index.ts b/cloudflare-workers/oc-gateway/src/index.ts
index f92c1e65..2d420329 100644
--- a/cloudflare-workers/oc-gateway/src/index.ts
+++ b/cloudflare-workers/oc-gateway/src/index.ts
@@ -1,34 +1,55 @@
-// oc-gateway — the thin per-session Worker over OpenRouter (design 013 §4, buildout contract #1 / W3).
+// oc-gateway — the thin OC Worker over OpenRouter (design 013 §4, buildout contract #1 / W3).
//
-// An unmodified Flue app does:
-// registerProvider('anthropic', { baseUrl: `${env.OC_GATEWAY}/anthropic`, apiKey: <session_token> })
-// and this Worker, on every model call:
-// (a) verifies the per-session EdDSA token → (org, agent, session, budget, epoch);
-// (b) fences a superseded lease epoch, then gates on the per-session budget ON-PATH (§8);
-// (c) injects the ORG's OpenRouter inference key (resolved from the credential store; never exposed);
-// (d) makes the body prompt-caching-safe, injects usage accounting, forwards to OpenRouter;
-// (e) sub-meters the response cost per session (SessionBudget DO), leaving ORG-level spend on that
-// same OR key → the existing model_meter cron → Autumn (one cost-source-of-truth).
+// An unmodified Flue app registers the managed provider INSIDE defineAgent (resolved token seam):
+// registerProvider('anthropic', {
+// baseUrl: `${env.OC_GATEWAY}/anthropic`,
+// apiKey: env.OC_SESSION_TOKEN, // the per-DEPLOY token — authorizes (org, agt) only
+// headers: { 'X-OC-Session': id }, // the DO's own init id = ses_… — BEST-EFFORT attribution
+// });
//
-// It builds NOTHING new for billing: org spend flows through the org's single OR key exactly as the
-// brain-box path does today; the gateway only adds per-session sub-metering + enforcement.
+// COST-SAFETY GRAIN (co-location refinement 2026-07-05). Flue's provider registry is isolate-global and
+// CF co-locates many session-DOs of one agent's script in one isolate, so per-session data injected via
+// registerProvider (the token OR the X-OC-Session header) RACES across co-located sessions. Therefore:
+// - HARD enforcement (the 402) is at the **org+agt** grain — carried by the per-DEPLOY token, so it is
+// race-free. This matches today's org-level OpenRouter→Autumn model; cost-safety is unchanged.
+// - The X-OC-Session header is **best-effort per-session attribution** — recorded for visibility only,
+// never gated (a co-location race must not wrongly block a legitimate session). Exact per-session
+// enforcement is deferred to an upstream Flue per-request resolver (tracked ask, off the critical path).
+//
+// On every model call the Worker:
+// (a) verifies the per-DEPLOY EdDSA token → (org, agt, ep). No session id, no budget in the token.
+// (b) fences a superseded lease epoch (DeployLease DO, per org+agt) — a rotated/revoked token stops.
+// (c) HARD-gates the org+agt budget ON-PATH (SpendCounter DO, keyed `${org}:${agt}`; budget looked up
+// server-side, never in the token — §8). Over → 402 budget_exceeded.
+// (d) injects the ORG's OpenRouter inference key (resolved from the credential store; never exposed).
+// (e) makes the body prompt-caching-safe, injects usage accounting, forwards to OpenRouter.
+// (f) sub-meters the response cost at the org+agt grain (authoritative) AND best-effort per session
+// (X-OC-Session), leaving ORG-level spend on that same OR key → the existing model_meter cron →
+// Autumn (one cost-source-of-truth). The gateway pushes NOTHING to Autumn.
-import { verifySessionToken } from "./token.js";
+import { verifyDeployToken } from "./token.js";
import { costFromJson, costFromStream } from "./cost.js";
import { resolveOrgKey } from "./orgkey.js";
import { unsafeModelMatchers, modelNeedsCacheStrip, stripCacheControl } from "./models.js";
-export { SessionBudget } from "./budget.js";
+export { SpendCounter } from "./budget.js";
+export { DeployLease } from "./deploylease.js";
export interface Env {
- // base64url raw 32-byte Ed25519 PUBLIC key. The minter (control plane) holds the private key.
+ // base64url raw 32-byte Ed25519 PUBLIC key. The minter (control plane / W7) holds the private key.
GATEWAY_TOKEN_PUBLIC_KEY: string;
- // Per-session budget counter + gate + epoch fence.
- SESSION_BUDGET: DurableObjectNamespace;
+ // Spend counter + gate. Used at org+agt grain (hard) and per-session grain (tracked-only).
+ SPEND_COUNTER: DurableObjectNamespace;
+ // Per-(org, agt) lease-epoch floor that fences rotated/revoked deploy tokens.
+ DEPLOY_LEASE: DurableObjectNamespace;
+ // Default HARD budget (USD) per org+agt, applied to an unprovisioned grain on first sight. Unset = uncapped.
+ AGENT_BUDGET_USD_DEFAULT?: string;
// Org OR-key seam (orgkey.ts): dedicated internal sessions-api route + its bearer secret.
GATEWAY_ORKEY_URL?: string;
GATEWAY_ORKEY_SECRET?: string;
// Acceptance-test single-key override (bypasses the seam). Never set in multi-org prod.
TEST_OR_KEY?: string;
+ // Bearer that guards the control-plane admin routes (/admin/*). Unset → admin routes 404.
+ GATEWAY_ADMIN_SECRET?: string;
// Override OpenRouter base for tests; default = prod.
OPENROUTER_BASE?: string;
// Extra comma-separated model patterns whose OR route rejects cache_control (models.ts).
@@ -71,42 +92,60 @@ export default {
return json({ status: "ok", service: "oc-gateway" });
}
+ // Control-plane admin routes (provision an org+agt budget, revoke a deploy lease). Guarded by a
+ // dedicated bearer; absent secret → not exposed. These are the W1/W7 control-plane seams.
+ if (url.pathname.startsWith("/admin/")) {
+ return admin(req, env, url);
+ }
+
const target = forwardUrl(env.OPENROUTER_BASE || OR_BASE_DEFAULT, url.pathname);
if (!target) return json({ error: { type: "not_found", message: "unknown gateway path" } }, 404);
if (req.method !== "POST") return json({ error: { type: "method_not_allowed" } }, 405);
- // (a) verify the per-session token (EdDSA — gateway holds only the public key).
+ // (a) verify the per-DEPLOY token (EdDSA — gateway holds only the public key).
const token = bearer(req.headers);
- if (!token) return json({ error: { type: "unauthorized", message: "missing session token" } }, 401);
+ if (!token) return json({ error: { type: "unauthorized", message: "missing deploy token" } }, 401);
const nowSec = Math.floor(Date.now() / 1000);
- const v = await verifySessionToken(env.GATEWAY_TOKEN_PUBLIC_KEY, token, nowSec);
- if (!v.ok) return json({ error: { type: "unauthorized", message: `invalid session token: ${v.reason}` } }, 401);
- const { sub: sessionId, org: orgId, bud, ep } = v.claims;
-
- // (b) lease-epoch fence + budget gate — ON-PATH, before the model call (§8), DO-serialized.
- const doStub = env.SESSION_BUDGET.get(env.SESSION_BUDGET.idFromName(sessionId));
- const budgetMicro = typeof bud === "number" && bud > 0 ? Math.round(bud * 1e6) : null;
- const check = await doStub
- .fetch("https://do/check", { method: "POST", body: JSON.stringify({ budget_micro: budgetMicro, ep }) })
- .then((r) => r.json() as Promise<{ allowed: boolean; fenced?: boolean; spent_micro: number; budget_micro: number | null }>);
- if (check.fenced) {
- // A superseded lease epoch — the token was minted for an older turn. 401 so the caller re-mints.
- return json({ error: { type: "unauthorized", message: "session token superseded (stale lease epoch)", code: "token_superseded" } }, 401);
+ const v = await verifyDeployToken(env.GATEWAY_TOKEN_PUBLIC_KEY, token, nowSec);
+ 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;
+
+ // (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}`));
+ const gate = await leaseStub
+ .fetch("https://do/gate", { method: "POST", body: JSON.stringify({ ep }) })
+ .then((r) => r.json() as Promise<{ ok: boolean; fenced?: boolean; floor: number }>);
+ if (gate.fenced) {
+ return json({ error: { type: "unauthorized", message: "deploy token superseded (stale lease epoch)", code: "token_superseded" } }, 401);
}
+
+ // (c) HARD budget gate at the org+agt grain — ON-PATH, before the model call (§8), DO-serialized,
+ // race-free (org+agt from the token). Budget looked up SERVER-SIDE (provisioned cap, else the
+ // gateway default); NEVER carried in the token.
+ const agentKey = `agt:${orgId}:${agentId}`;
+ const agentBudget = env.SPEND_COUNTER.get(env.SPEND_COUNTER.idFromName(agentKey));
+ const defaultBudgetMicro = parseUsdMicro(env.AGENT_BUDGET_USD_DEFAULT);
+ const check = await agentBudget
+ .fetch("https://do/check", { method: "POST", body: JSON.stringify({ default_budget_micro: defaultBudgetMicro }) })
+ .then((r) => r.json() as Promise<{ allowed: boolean; spent_micro: number; budget_micro: number | null }>);
if (!check.allowed) {
- // Refuse past the per-session budget. Shaped as a provider-style error so the Flue/pi-ai turn
+ // Refuse past the org+agt budget. Shaped as a provider-style error so the Flue/pi-ai turn
// terminates and the tailer maps it to outcome `budget_exceeded` (§8). Exact shape = live-verify.
return json({
- error: { type: "budget_exceeded", message: "per-session model budget exhausted", code: "insufficient_quota" },
- oc: { session: sessionId, spent_usd: check.spent_micro / 1e6, budget_usd: (check.budget_micro ?? 0) / 1e6 },
+ error: { type: "budget_exceeded", message: "org/agent model budget exhausted", code: "insufficient_quota" },
+ oc: { org: orgId, agent: agentId, spent_usd: check.spent_micro / 1e6, budget_usd: (check.budget_micro ?? 0) / 1e6 },
}, 402);
}
- // (c) resolve the ORG's OpenRouter inference key (from the credential-store seam; never exposed).
+ // (d) resolve the ORG's OpenRouter inference key (from the credential-store seam; never exposed).
const orKey = await resolveOrgKey(env, orgId, Date.now());
if (!orKey) return json({ error: { type: "server_error", message: "no OpenRouter key resolved for org" } }, 500);
- // (d) rewrite the body: strip cache_control for caching-unsafe models, inject usage:{include:true}
+ // (e) rewrite the body: strip cache_control for caching-unsafe models, inject usage:{include:true}
// so OpenRouter echoes cost (openrouter.ts precedent). Model bodies are small; buffer is fine.
const rawBody = await req.text();
let outBody = rawBody;
@@ -123,10 +162,12 @@ export default {
/* not JSON — forward verbatim */
}
- // forward to OpenRouter with the org key swapped in. Strip the tenant's auth; pass the rest.
+ // forward to OpenRouter with the org key swapped in. Strip the tenant's auth + the session header;
+ // pass the rest.
const fwdHeaders = new Headers(req.headers);
fwdHeaders.delete("x-api-key");
fwdHeaders.delete("authorization");
+ fwdHeaders.delete("x-oc-session");
fwdHeaders.set("authorization", `Bearer ${orKey}`);
fwdHeaders.set("content-type", req.headers.get("content-type") || "application/json");
fwdHeaders.set("content-length", String(new TextEncoder().encode(outBody).length));
@@ -137,22 +178,76 @@ export default {
const forwardTarget = target + (url.search || "");
const upstream = await fetch(forwardTarget, { method: "POST", headers: fwdHeaders, body: outBody });
- // (e) sub-meter the response cost per session, off the response path (waitUntil).
+ // (f) sub-meter the response cost, off the response path (waitUntil): authoritative at the org+agt
+ // grain + best-effort per session (for the dashboard). Passing the same generation id to both
+ // grains is safe — each DO instance has its own idempotency namespace.
const isStream = (upstream.headers.get("content-type") || "").includes("text/event-stream");
const meterCopy = upstream.clone();
- ctx.waitUntil(meter(meterCopy, isStream, doStub, env, { sessionId, orgId }));
+ ctx.waitUntil(
+ meter(meterCopy, isStream, env, {
+ agentBudget,
+ sessionCounter: sessionId ? env.SPEND_COUNTER.get(env.SPEND_COUNTER.idFromName(`sess:${sessionId}`)) : null,
+ sessionId, orgId, agentId,
+ }),
+ );
// Passthrough: return OpenRouter's response (status + headers + body) untouched to Flue.
return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers: upstream.headers });
},
};
+/** Parse a USD string into integer µ$, or null (uncapped) if unset/invalid/≤0. */
+function parseUsdMicro(usd?: string): number | null {
+ if (!usd) return null;
+ const n = Number(usd);
+ if (!Number.isFinite(n) || n <= 0) return null;
+ return Math.round(n * 1e6);
+}
+
+// ── Control-plane admin routes (guarded by GATEWAY_ADMIN_SECRET) ──
+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 (req.method !== "POST") return json({ error: { type: "method_not_allowed" } }, 405);
+ const body = (await req.json().catch(() => ({}))) as Record<string, unknown>;
+
+ // POST /admin/agent/budget {org, agt, budget_usd|null} — provision the org+agt HARD cap (W1/W7 seam).
+ if (url.pathname === "/admin/agent/budget") {
+ const org = typeof body.org === "string" ? body.org : null;
+ const agt = typeof body.agt === "string" ? body.agt : null;
+ if (!org || !agt) return json({ error: { type: "bad_request", message: "org, agt required" } }, 400);
+ const budgetMicro = body.budget_usd === null ? null : parseUsdMicro(String(body.budget_usd));
+ const stub = env.SPEND_COUNTER.get(env.SPEND_COUNTER.idFromName(`agt:${org}:${agt}`));
+ const r = await stub.fetch("https://do/provision", { method: "POST", body: JSON.stringify({ budget_micro: budgetMicro }) });
+ return new Response(r.body, { status: r.status, headers: { "content-type": "application/json" } });
+ }
+
+ // POST /admin/lease/bump {org, agt, min_epoch} — revoke deploy tokens below min_epoch (no redeploy).
+ if (url.pathname === "/admin/lease/bump") {
+ const org = typeof body.org === "string" ? body.org : null;
+ const agt = typeof body.agt === "string" ? body.agt : null;
+ const minEpoch = typeof body.min_epoch === "number" ? body.min_epoch : null;
+ if (!org || !agt || minEpoch == null) return json({ error: { type: "bad_request", message: "org, agt, min_epoch required" } }, 400);
+ const stub = env.DEPLOY_LEASE.get(env.DEPLOY_LEASE.idFromName(`${org}:${agt}`));
+ const r = await stub.fetch("https://do/bump", { method: "POST", body: JSON.stringify({ min_epoch: minEpoch }) });
+ return new Response(r.body, { status: r.status, headers: { "content-type": "application/json" } });
+ }
+
+ return json({ error: { type: "not_found" } }, 404);
+}
+
async function meter(
resp: Response,
isStream: boolean,
- doStub: DurableObjectStub,
env: Env,
- ctx: { sessionId: string; orgId: string },
+ ctx: {
+ agentBudget: DurableObjectStub;
+ sessionCounter: DurableObjectStub | null;
+ sessionId: string | null;
+ orgId: string;
+ agentId: string;
+ },
): Promise<void> {
try {
if (resp.status >= 400) return; // a failed provider call bills nothing
@@ -160,18 +255,24 @@ async function meter(
? await costFromStream(resp.body ?? new ReadableStream())
: costFromJson(await resp.text());
const costMicro = extracted.costUsd != null ? Math.round(extracted.costUsd * 1e6) : 0;
- await doStub.fetch("https://do/add", {
+ // Authoritative: the org+agt grain that gates.
+ await ctx.agentBudget.fetch("https://do/add", {
method: "POST",
body: JSON.stringify({ cost_micro: costMicro, idem: extracted.generationId }),
});
- // Per-session spend telemetry (dashboard, §9) — best-effort; NOT a billing source (org billing
- // is OR→cron→Autumn). Absent OC_INGEST_URL → skip.
+ // Best-effort per-session tracking (visibility only; never gated).
+ if (ctx.sessionCounter) {
+ await ctx.sessionCounter
+ .fetch("https://do/add", { method: "POST", body: JSON.stringify({ cost_micro: costMicro, idem: extracted.generationId }) })
+ .catch(() => {});
+ }
+ // Per-session spend telemetry (dashboard, §9) — best-effort; NOT a billing source. Absent → skip.
if (env.OC_INGEST_URL) {
await fetch(env.OC_INGEST_URL, {
method: "POST",
headers: { "content-type": "application/json", ...(env.OC_INGEST_AUTH ? { "x-internal-auth": env.OC_INGEST_AUTH } : {}) },
body: JSON.stringify({
- name: "gateway.model_call", session: ctx.sessionId, org: ctx.orgId,
+ name: "gateway.model_call", session: ctx.sessionId, org: ctx.orgId, agent: ctx.agentId,
cost_usd: extracted.costUsd, cost_source: extracted.source, generation_id: extracted.generationId,
}),
}).catch(() => {});
diff --git a/cloudflare-workers/oc-gateway/test/integration.test.ts b/cloudflare-workers/oc-gateway/test/integration.test.ts
index ef3d0c15..a698ab3b 100644
--- a/cloudflare-workers/oc-gateway/test/integration.test.ts
+++ b/cloudflare-workers/oc-gateway/test/integration.test.ts
@@ -1,15 +1,16 @@
-// In-process integration: the REAL worker handler + the REAL SessionBudget DO, with `fetch`
+// In-process integration: the REAL worker handler + REAL SpendCounter/DeployLease DOs, with `fetch`
// stubbed to a mock OpenRouter. Proves the whole on-path flow deterministically without wrangler:
-// token verify → per-session budget gate → org-key injection → forward → cost sub-meter →
-// passthrough → refusal past budget. (The wrangler-dev + curl variant is documented in README.md;
-// this is the CI-able equivalent.)
-//
+// deploy-token verify → lease fence → HARD org+agt budget gate → org-key injection → forward → cost
+// sub-meter (org+agt authoritative + best-effort per session) → passthrough → 402 over budget.
+// Reflects the resolved token seam + co-location refinement: HARD enforcement is org+agt (race-free);
+// the X-OC-Session header is best-effort per-session tracking, never gated.
// Run: npx vitest run
import { describe, it, expect, beforeEach, beforeAll, vi, afterEach } from "vitest";
import worker, { Env } from "../src/index.js";
-import { SessionBudget } from "../src/budget.js";
-import { generateKeyPair, mintSessionToken } from "../src/token.js";
+import { SpendCounter } from "../src/budget.js";
+import { DeployLease } from "../src/deploylease.js";
+import { generateKeyPair, mintDeployToken } from "../src/token.js";
const OR_KEY = "sk-or-v1-FAKE-org-key";
const OR_BASE = "https://mock-openrouter.test/api";
@@ -28,27 +29,30 @@ function fakeState() {
} } as unknown as DurableObjectState;
}
-// ── a fake SESSION_BUDGET namespace: one real SessionBudget instance per name ──
-function fakeBudgetNamespace() {
- const instances = new Map<string, SessionBudget>();
- return {
+// ── a fake DO namespace: one real instance of `Klass` per name; `instances` exposed for assertions ──
+function fakeNamespace<T extends { fetch(r: Request): Promise<Response> }>(Klass: new (s: DurableObjectState) => T) {
+ const instances = new Map<string, T>();
+ const ns = {
idFromName: (n: string) => ({ toString: () => n, name: n }) as unknown as DurableObjectId,
get: (id: DurableObjectId) => {
const name = (id as unknown as { name: string }).name;
- if (!instances.has(name)) instances.set(name, new SessionBudget(fakeState()));
+ if (!instances.has(name)) instances.set(name, new Klass(fakeState()));
const inst = instances.get(name)!;
return { fetch: (input: RequestInfo, init?: RequestInit) => inst.fetch(new Request(typeof input === "string" ? input : (input as Request).url, init)) } as unknown as DurableObjectStub;
},
} as unknown as DurableObjectNamespace;
+ return { ns, instances };
}
let lastAuthToOR: string | null;
let lastBodyToOR: Record<string, unknown> | null;
+let lastHeadersToOR: Headers | null;
function mockFetch(perCallCost: number) {
return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === "string" ? input : input.toString();
- lastAuthToOR = new Headers(init?.headers).get("authorization");
+ lastHeadersToOR = new Headers(init?.headers);
+ lastAuthToOR = lastHeadersToOR.get("authorization");
lastBodyToOR = init?.body ? JSON.parse(init.body as string) : null;
expect(url.startsWith(OR_BASE)).toBe(true); // forwarded to the OR base, tail preserved
return new Response(JSON.stringify({
@@ -60,8 +64,12 @@ function mockFetch(perCallCost: number) {
});
}
-function env(): Env {
- return { GATEWAY_TOKEN_PUBLIC_KEY: PUB, TEST_OR_KEY: OR_KEY, OPENROUTER_BASE: OR_BASE, SESSION_BUDGET: fakeBudgetNamespace() };
+// a fresh env each test; `spend`/`lease` handles let us assert on per-grain DO state.
+function mkEnv(extra: Partial<Env> = {}) {
+ const spend = fakeNamespace(SpendCounter);
+ const lease = fakeNamespace(DeployLease);
+ const env = { GATEWAY_TOKEN_PUBLIC_KEY: PUB, TEST_OR_KEY: OR_KEY, OPENROUTER_BASE: OR_BASE, SPEND_COUNTER: spend.ns, DEPLOY_LEASE: lease.ns, ...extra } as Env;
+ return { env, spend, lease };
}
// waitUntil runs the metering; collect the promises so we can await them (the meter is off-path).
@@ -72,65 +80,84 @@ function ctx(): ExecutionContext {
async function drain(c: ExecutionContext) { await Promise.all((c as unknown as { _pending: Promise<unknown>[] })._pending); }
const MSG = JSON.stringify({ model: "anthropic/claude-sonnet-5", max_tokens: 16, messages: [{ role: "user", content: "ping" }] });
-const post = (token?: string) => new Request("https://gw.test/anthropic/v1/messages", {
+const post = (token?: string, session?: string, body = MSG) => new Request("https://gw.test/anthropic/v1/messages", {
method: "POST",
- headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
- body: MSG,
+ headers: {
+ "content-type": "application/json",
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
+ ...(session ? { "x-oc-session": session } : {}),
+ },
+ body,
});
-
-describe("gateway on-path flow", () => {
- beforeEach(() => { lastAuthToOR = null; lastBodyToOR = null; });
+const mint = async (o: Partial<{ org: string; agt: string; ep: number; 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 });
+};
+const stateOf = async (inst: { fetch(r: Request): Promise<Response> }) =>
+ (await inst.fetch(new Request("https://do/state"))).json() as Promise<{ spent_micro: number }>;
+
+describe("gateway on-path flow (resolved seam)", () => {
+ beforeEach(() => { lastAuthToOR = null; lastBodyToOR = null; lastHeadersToOR = null; });
afterEach(() => vi.restoreAllMocks());
it("GET /healthz → ok", async () => {
- const res = await worker.fetch(new Request("https://gw.test/healthz"), env(), ctx());
+ const { env } = mkEnv();
+ const res = await worker.fetch(new Request("https://gw.test/healthz"), env, ctx());
expect(res.status).toBe(200);
expect((await res.json() as { status: string }).status).toBe("ok");
});
- it("rejects a POST with no session token (401)", async () => {
- const res = await worker.fetch(post(), env(), ctx());
+ it("rejects a POST with no deploy token (401)", async () => {
+ const { env } = mkEnv();
+ const res = await worker.fetch(post(), env, ctx());
expect(res.status).toBe(401);
});
- it("rejects an invalid/expired token (401)", async () => {
+ it("rejects an expired token (401)", async () => {
+ const { env } = mkEnv();
const now = Math.floor(Date.now() / 1000);
- const expired = await mintSessionToken(PRIV, { sub: "ses_x", org: "org_1", agt: "a", iat: now - 10, exp: now - 5 });
- const res = await worker.fetch(post(expired), env(), ctx());
+ const expired = await mint({ iat: now - 10, exp: now - 5 });
+ const res = await worker.fetch(post(expired), env, ctx());
expect(res.status).toBe(401);
});
- it("forwards a valid turn: injects the ORG key (not the session token), adds usage.include, passes the body through", async () => {
+ it("forwards a valid turn: injects the ORG key (not the deploy token), adds usage.include, passes the body through, does NOT leak the session header to OR", async () => {
vi.stubGlobal("fetch", mockFetch(0.02));
- const now = Math.floor(Date.now() / 1000);
- const token = await mintSessionToken(PRIV, { sub: "ses_ok", org: "org_1", agt: "a", bud: 1, iat: now, exp: now + 3600 });
- const e = env();
+ const { env } = mkEnv();
+ const token = await mint();
const c = ctx();
- const res = await worker.fetch(post(token), e, c);
+ const res = await worker.fetch(post(token, "ses_ok"), env, c);
expect(res.status).toBe(200);
const body = await res.json() as { content: { text: string }[] };
expect(body.content[0].text).toBe("pong");
- // the ORG key was injected; the session token never reached OpenRouter
+ // the ORG key was injected; the deploy token never reached OpenRouter (no raw key to the tenant either)
expect(lastAuthToOR).toBe(`Bearer ${OR_KEY}`);
expect(lastAuthToOR).not.toContain(token);
- // usage.include was injected so OR echoes cost
+ // the session header is an OC-internal signal — it must not egress to OpenRouter
+ expect(lastHeadersToOR?.get("x-oc-session")).toBeNull();
+ // usage.include injected so OR echoes cost
expect(lastBodyToOR?.usage).toMatchObject({ include: true });
- // original request fields preserved
expect(lastBodyToOR?.model).toBe("anthropic/claude-sonnet-5");
await drain(c);
});
- it("enforces the per-session budget ON-PATH: refuses once spend reaches the cap (402)", async () => {
- vi.stubGlobal("fetch", mockFetch(0.02)); // $0.02 per call
- const now = Math.floor(Date.now() / 1000);
- // budget $0.03 → call1 (spent 0<0.03) ok→0.02; call2 (0.02<0.03) ok→0.04; call3 (0.04≥0.03) refused.
- const token = await mintSessionToken(PRIV, { sub: "ses_budget", org: "org_1", agt: "a", bud: 0.03, iat: now, exp: now + 3600 });
- const e = env();
-
- const c1 = ctx(); const r1 = await worker.fetch(post(token), e, c1); await drain(c1);
- const c2 = ctx(); const r2 = await worker.fetch(post(token), e, c2); await drain(c2);
- const c3 = ctx(); const r3 = await worker.fetch(post(token), e, c3); await drain(c3);
+ it("proceeds WITHOUT an X-OC-Session header (best-effort attribution, not required)", async () => {
+ vi.stubGlobal("fetch", mockFetch(0.01));
+ const { env } = mkEnv();
+ const c = ctx();
+ const res = await worker.fetch(post(await mint()), env, c); // no session header
+ expect(res.status).toBe(200);
+ await drain(c);
+ });
+ it("HARD-enforces the org+agt budget ON-PATH: refuses once org+agt spend reaches the cap (402)", async () => {
+ vi.stubGlobal("fetch", mockFetch(0.02)); // $0.02 per call
+ // default org+agt budget $0.03 → call1 (0<0.03) ok→0.02; call2 (0.02<0.03) ok→0.04; call3 refused.
+ const { env } = mkEnv({ AGENT_BUDGET_USD_DEFAULT: "0.03" });
+ const token = await mint();
+ const c1 = ctx(); const r1 = await worker.fetch(post(token, "ses_a"), env, c1); await drain(c1);
+ const c2 = ctx(); const r2 = await worker.fetch(post(token, "ses_a"), env, c2); await drain(c2);
+ const c3 = ctx(); const r3 = await worker.fetch(post(token, "ses_a"), env, c3); await drain(c3);
expect(r1.status).toBe(200);
expect(r2.status).toBe(200);
expect(r3.status).toBe(402);
@@ -140,40 +167,74 @@ describe("gateway on-path flow", () => {
expect(refusal.oc.budget_usd).toBeCloseTo(0.03, 5);
});
- it("uncapped session (no bud claim) never refuses", async () => {
- vi.stubGlobal("fetch", mockFetch(1.0));
- const now = Math.floor(Date.now() / 1000);
- const token = await mintSessionToken(PRIV, { sub: "ses_uncapped", org: "org_1", agt: "a", iat: now, exp: now + 3600 });
- const e = env();
- for (let i = 0; i < 3; i++) { const c = ctx(); const r = await worker.fetch(post(token), e, c); await drain(c); expect(r.status).toBe(200); }
+ it("co-location: two DIFFERENT sessions of the same org+agt SHARE the hard budget (grain is org+agt, not per-session)", async () => {
+ vi.stubGlobal("fetch", mockFetch(0.02));
+ const { env, spend } = mkEnv({ AGENT_BUDGET_USD_DEFAULT: "0.03" });
+ const token = await mint();
+ // ses_x spends $0.02, ses_y spends $0.02 → org+agt total $0.04 ≥ $0.03 → the next call (either
+ // session) is refused. This is exactly the race-free property: budget is on the token's org+agt.
+ const cx = ctx(); const rx = await worker.fetch(post(token, "ses_x"), env, cx); await drain(cx);
+ const cy = ctx(); const ry = await worker.fetch(post(token, "ses_y"), env, cy); await drain(cy);
+ const cz = ctx(); const rz = await worker.fetch(post(token, "ses_z"), env, cz); await drain(cz);
+ expect(rx.status).toBe(200);
+ 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);
+ // and the authoritative org+agt grain summed them
+ expect((await stateOf(spend.instances.get("agt:org_1:agt_1")!)).spent_micro).toBe(40_000);
});
- it("fences a superseded lease epoch (401 token_superseded)", async () => {
+ it("per-session counter is TRACKED but NEVER gated: a session over its own spend is not 402'd", async () => {
+ vi.stubGlobal("fetch", mockFetch(0.10)); // $0.10/call, well over any per-session intuition
+ const { env, spend } = mkEnv(); // no org+agt cap → uncapped hard grain
+ 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);
+ });
+
+ it("fences a superseded deploy lease epoch (401 token_superseded)", async () => {
vi.stubGlobal("fetch", mockFetch(0.001));
- const now = Math.floor(Date.now() / 1000);
- const e = env(); // same namespace → same DO for ses_ep across calls
- const t2 = await mintSessionToken(PRIV, { sub: "ses_ep", org: "org_1", agt: "a", ep: 2, iat: now, exp: now + 3600 });
- const c2 = ctx(); const r2 = await worker.fetch(post(t2), e, c2); await drain(c2);
+ const { env } = mkEnv(); // same DEPLOY_LEASE namespace → same lease for org_1:agt_1
+ const t2 = await mint({ ep: 2 });
+ const c2 = ctx(); const r2 = await worker.fetch(post(t2, "ses_ep"), env, c2); await drain(c2);
expect(r2.status).toBe(200); // adopt epoch 2
- const t1 = await mintSessionToken(PRIV, { sub: "ses_ep", org: "org_1", agt: "a", ep: 1, iat: now, exp: now + 3600 });
- const r1 = await worker.fetch(post(t1), e, ctx()); // the old turn's token — superseded
+ const t1 = await mint({ ep: 1 });
+ const r1 = await worker.fetch(post(t1, "ses_ep"), env, ctx()); // the old deploy's token — superseded
expect(r1.status).toBe(401);
expect((await r1.json() as { error: { code?: string } }).error.code).toBe("token_superseded");
});
it("strips cache_control for a caching-unsafe model, still injects usage.include", async () => {
vi.stubGlobal("fetch", mockFetch(0.001));
- const now = Math.floor(Date.now() / 1000);
- const token = await mintSessionToken(PRIV, { sub: "ses_cc", org: "org_1", agt: "a", iat: now, exp: now + 3600 });
+ const { env } = mkEnv();
+ const token = await mint();
const body = JSON.stringify({
model: "anthropic/claude-3-haiku", max_tokens: 16,
system: [{ type: "text", text: "s", cache_control: { type: "ephemeral" } }],
messages: [{ role: "user", content: "ping" }],
});
- const req = new Request("https://gw.test/anthropic/v1/messages", { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body });
- const c = ctx(); const r = await worker.fetch(req, env(), c); await drain(c);
+ const c = ctx(); const r = await worker.fetch(post(token, "ses_cc", body), env, c); await drain(c);
expect(r.status).toBe(200);
expect(JSON.stringify(lastBodyToOR).includes("cache_control")).toBe(false);
expect(lastBodyToOR?.usage).toMatchObject({ include: true });
});
+
+ it("admin: provision an org+agt cap, then it gates (402); guarded by GATEWAY_ADMIN_SECRET", async () => {
+ vi.stubGlobal("fetch", mockFetch(0.05));
+ const { env } = mkEnv({ GATEWAY_ADMIN_SECRET: "adm" });
+ // unauthorized admin call is rejected
+ const bad = await worker.fetch(new Request("https://gw.test/admin/agent/budget", { method: "POST", headers: { authorization: "Bearer nope", "content-type": "application/json" }, body: JSON.stringify({ org: "org_1", agt: "agt_1", budget_usd: 0.04 }) }), env, ctx());
+ expect(bad.status).toBe(401);
+ // provision a $0.04 cap
+ const prov = await worker.fetch(new Request("https://gw.test/admin/agent/budget", { method: "POST", headers: { authorization: "Bearer adm", "content-type": "application/json" }, body: JSON.stringify({ org: "org_1", agt: "agt_1", budget_usd: 0.04 }) }), env, ctx());
+ expect(prov.status).toBe(200);
+ const token = await mint();
+ const c1 = ctx(); const r1 = await worker.fetch(post(token, "s1"), env, c1); await drain(c1); // 0→0.05
+ const c2 = ctx(); const r2 = await worker.fetch(post(token, "s1"), env, c2); await drain(c2); // 0.05≥0.04 → 402
+ expect(r1.status).toBe(200);
+ expect(r2.status).toBe(402);
+ });
});
diff --git a/cloudflare-workers/oc-gateway/test/logic.test.ts b/cloudflare-workers/oc-gateway/test/logic.test.ts
index d8ce67af..1067d6db 100644
--- a/cloudflare-workers/oc-gateway/test/logic.test.ts
+++ b/cloudflare-workers/oc-gateway/test/logic.test.ts
@@ -1,96 +1,134 @@
-// Pure-logic tests (no Workers runtime needed): EdDSA token crypto, the SessionBudget DO's epoch
-// fence + budget gate + idempotency (over a fake DurableObjectState), cache_control safety, and cost
-// extraction. The full on-path flow (forward + meter) is exercised by the live integration in
-// README.md / scripts/e2e. Run: npx vitest run
+// Pure-logic tests (no Workers runtime needed): EdDSA per-deploy token crypto, the SpendCounter DO's
+// budget gate + idempotency + provision, the DeployLease DO's epoch fence + bump, cache_control safety,
+// and cost extraction. The full on-path flow (forward + meter) is exercised by test/integration.test.ts.
+// Run: npx vitest run
import { describe, it, expect } from "vitest";
-import { generateKeyPair, mintSessionToken, verifySessionToken, type SessionClaims } from "../src/token.js";
+import { generateKeyPair, mintDeployToken, verifyDeployToken, type DeployClaims } from "../src/token.js";
import { costFromJson, costFromStream } from "../src/cost.js";
import { unsafeModelMatchers, modelNeedsCacheStrip, stripCacheControl } from "../src/models.js";
-import { SessionBudget } from "../src/budget.js";
+import { SpendCounter } from "../src/budget.js";
+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<SessionClaims> = {}): SessionClaims => ({
- sub: "ses_abc", org: "org_1", agt: "agt_1", bud: 0.5, ep: 2, iat: now, exp: now + 3600, ...o,
+const claims = (o: Partial<DeployClaims> = {}): DeployClaims => ({
+ org: "org_1", agt: "agt_1", ep: 2, iat: now, exp: now + 3600, ...o,
});
-describe("session token (EdDSA)", () => {
+function fakeState(): DurableObjectState {
+ const m = new Map<string, unknown>();
+ return { storage: { get: async (k: string) => m.get(k), put: async (k: string, v: unknown) => void m.set(k, v) } } as unknown as DurableObjectState;
+}
+const call = async (o: { fetch(r: Request): Promise<Response> }, path: string, body?: unknown) =>
+ (await o.fetch(new Request(`https://do${path}`, { method: "POST", body: JSON.stringify(body ?? {}) }))).json() as Promise<Record<string, unknown>>;
+
+describe("deploy token (EdDSA, per-deploy {org, agt})", () => {
it("mint → verify round-trips the claims", async () => {
const { privateKey, publicKeyB64url } = await generateKeyPair();
- const v = await verifySessionToken(publicKeyB64url, await mintSessionToken(privateKey, claims()), now);
+ const v = await verifyDeployToken(publicKeyB64url, await mintDeployToken(privateKey, claims()), now);
expect(v.ok).toBe(true);
if (v.ok) {
- expect(v.claims.sub).toBe("ses_abc");
expect(v.claims.org).toBe("org_1");
- expect(v.claims.bud).toBe(0.5);
+ expect(v.claims.agt).toBe("agt_1");
expect(v.claims.ep).toBe(2);
+ // resolved seam: no per-session data in the token
+ const raw = v.claims as unknown as Record<string, unknown>;
+ expect(raw.sub).toBeUndefined();
+ expect(raw.bud).toBeUndefined();
}
});
it("rejects a token signed by a different key (gateway holds only the public key)", async () => {
const a = await generateKeyPair();
const b = await generateKeyPair();
- const v = await verifySessionToken(b.publicKeyB64url, await mintSessionToken(a.privateKey, claims()), now);
+ const v = await verifyDeployToken(b.publicKeyB64url, await mintDeployToken(a.privateKey, claims()), now);
expect(v.ok).toBe(false);
});
it("rejects a tampered payload", async () => {
const { privateKey, publicKeyB64url } = await generateKeyPair();
- const [h, , s] = (await mintSessionToken(privateKey, claims())).split(".");
- const v = await verifySessionToken(publicKeyB64url, `${h}.${b64url(claims({ org: "org_evil" }))}.${s}`, now);
+ const [h, , s] = (await mintDeployToken(privateKey, claims())).split(".");
+ const v = await verifyDeployToken(publicKeyB64url, `${h}.${b64url(claims({ org: "org_evil" }))}.${s}`, now);
expect(v.ok).toBe(false);
});
it("rejects an expired token", async () => {
const { privateKey, publicKeyB64url } = await generateKeyPair();
- const v = await verifySessionToken(publicKeyB64url, await mintSessionToken(privateKey, claims({ exp: now - 1 })), now);
+ const v = await verifyDeployToken(publicKeyB64url, await mintDeployToken(privateKey, claims({ exp: now - 1 })), now);
expect(v.ok).toBe(false);
if (!v.ok) expect(v.reason).toBe("expired");
});
+ 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 v = await verifyDeployToken(publicKeyB64url, t, now);
+ expect(v.ok).toBe(false);
+ if (!v.ok) expect(v.reason).toBe("missing_claims");
+ });
it("pins alg=EdDSA — rejects an alg-swap (none/HS256) header", async () => {
const { privateKey, publicKeyB64url } = await generateKeyPair();
- const [, p, s] = (await mintSessionToken(privateKey, claims())).split(".");
- const v = await verifySessionToken(publicKeyB64url, `${b64url({ alg: "none", typ: "JWT" })}.${p}.${s}`, now);
+ const [, p, s] = (await mintDeployToken(privateKey, claims())).split(".");
+ const v = await verifyDeployToken(publicKeyB64url, `${b64url({ alg: "none", typ: "JWT" })}.${p}.${s}`, now);
expect(v.ok).toBe(false);
if (!v.ok) expect(v.reason).toBe("unexpected_alg");
});
});
-describe("SessionBudget DO — epoch fence + budget gate + idempotency", () => {
- function fakeState(): DurableObjectState {
- const m = new Map<string, unknown>();
- return { storage: { get: async (k: string) => m.get(k), put: async (k: string, v: unknown) => void m.set(k, v) } } as unknown as DurableObjectState;
- }
- const call = async (bd: SessionBudget, path: string, body: unknown) =>
- (await bd.fetch(new Request(`https://do${path}`, { method: "POST", body: JSON.stringify(body) }))).json() as Promise<Record<string, unknown>>;
+describe("SpendCounter DO — budget gate + idempotency + provision", () => {
+ it("gates on the budget (spent < budget), applies the default on first check", async () => {
+ const c = new SpendCounter(fakeState());
+ const capMicro = 1_000_000; // $1.00 in µ$
+ expect((await call(c, "/check", { default_budget_micro: capMicro })).allowed).toBe(true);
+ await call(c, "/add", { cost_micro: 600_000, idem: "g1" });
+ expect((await call(c, "/check", { default_budget_micro: capMicro })).allowed).toBe(true); // 0.6 < 1.0
+ await call(c, "/add", { cost_micro: 600_000, idem: "g2" }); // now 1.2 > 1.0
+ expect((await call(c, "/check", { default_budget_micro: capMicro })).allowed).toBe(false);
+ });
- it("fences a stale lease epoch (monotonic)", async () => {
- const bd = new SessionBudget(fakeState());
- expect((await call(bd, "/check", { ep: 1 })).allowed).toBe(true);
- expect((await call(bd, "/check", { ep: 2 })).allowed).toBe(true); // adopt the newer epoch
- const stale = await call(bd, "/check", { ep: 1 }); // the old turn's token is now superseded
- expect(stale.fenced).toBe(true);
- expect(stale.allowed).toBe(false);
+ it("a provisioned cap wins over the gateway default", async () => {
+ const c = new SpendCounter(fakeState());
+ await call(c, "/provision", { budget_micro: 100_000 }); // $0.10 explicit
+ await call(c, "/add", { cost_micro: 150_000, idem: "x" });
+ // default is huge, but the provisioned $0.10 cap is what gates
+ expect((await call(c, "/check", { default_budget_micro: 999_000_000 })).allowed).toBe(false);
});
- it("gates on the per-session budget (spent < budget)", async () => {
- const bd = new SessionBudget(fakeState());
- const cap = 1_000_000; // $1.00 in µ$
- expect((await call(bd, "/check", { budget_micro: cap, ep: 1 })).allowed).toBe(true);
- await call(bd, "/add", { cost_micro: 600_000, idem: "g1" });
- expect((await call(bd, "/check", { budget_micro: cap, ep: 1 })).allowed).toBe(true); // 0.6 < 1.0
- await call(bd, "/add", { cost_micro: 600_000, idem: "g2" }); // now 1.2 > 1.0
- expect((await call(bd, "/check", { budget_micro: cap, ep: 1 })).allowed).toBe(false);
+ it("uncapped (no budget, no default) never gates", async () => {
+ const c = new SpendCounter(fakeState());
+ await call(c, "/add", { cost_micro: 5_000_000, idem: "big" });
+ expect((await call(c, "/check", {})).allowed).toBe(true);
});
it("dedupes /add by generation id (retried meter never double-counts)", async () => {
- const bd = new SessionBudget(fakeState());
- await call(bd, "/add", { cost_micro: 100_000, idem: "gen-x" });
- const second = await call(bd, "/add", { cost_micro: 100_000, idem: "gen-x" });
+ const c = new SpendCounter(fakeState());
+ await call(c, "/add", { cost_micro: 100_000, idem: "gen-x" });
+ const second = await call(c, "/add", { cost_micro: 100_000, idem: "gen-x" });
expect(second.deduped).toBe(true);
- const st = (await (await bd.fetch(new Request("https://do/state"))).json()) as { spent_micro: number };
+ const st = (await (await c.fetch(new Request("https://do/state"))).json()) as { spent_micro: number };
expect(st.spent_micro).toBe(100_000);
});
});
+describe("DeployLease DO — lease-epoch fence + bump (revocation)", () => {
+ it("fences a stale deploy epoch (monotonic floor)", async () => {
+ const l = new DeployLease(fakeState());
+ expect((await call(l, "/gate", { ep: 1 })).fenced).toBe(false);
+ expect((await call(l, "/gate", { ep: 2 })).fenced).toBe(false); // adopt the newer epoch → floor 2
+ const stale = await call(l, "/gate", { ep: 1 }); // the old deploy's token is now superseded
+ expect(stale.fenced).toBe(true);
+ expect(stale.ok).toBe(false);
+ });
+ it("a token with no epoch is never fenced (opt-in fence)", 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
+ });
+ it("bump revokes without a redeploy (raise the floor above the live token)", async () => {
+ const l = new DeployLease(fakeState());
+ expect((await call(l, "/gate", { ep: 3 })).fenced).toBe(false); // floor 3, current token ep=3 valid
+ await call(l, "/bump", { min_epoch: 4 }); // revoke everything below 4
+ expect((await call(l, "/gate", { ep: 3 })).fenced).toBe(true); // the still-live ep=3 token now fences
+ });
+});
+
describe("cache_control safety", () => {
const m = unsafeModelMatchers();
it("flags claude-3-haiku, leaves sonnet alone", () => {
diff --git a/cloudflare-workers/oc-gateway/wrangler.toml b/cloudflare-workers/oc-gateway/wrangler.toml
index 827313e2..8b103ca1 100644
--- a/cloudflare-workers/oc-gateway/wrangler.toml
+++ b/cloudflare-workers/oc-gateway/wrangler.toml
@@ -3,23 +3,31 @@ main = "src/index.ts"
compatibility_date = "2025-06-01"
compatibility_flags = ["nodejs_compat"]
-# The per-session spend counter + hard-limit gate (design 013 §4/§8).
+# Spend counter + hard gate (design 013 §4/§8). Used at org+agt grain (hard 402) and per-session
+# grain (tracked-only). Strongly consistent, so concurrent calls can't double-spend past the cap.
[[durable_objects.bindings]]
-name = "SESSION_BUDGET"
-class_name = "SessionBudget"
+name = "SPEND_COUNTER"
+class_name = "SpendCounter"
+
+# Per-(org, agt) lease-epoch floor — fences a rotated/revoked deploy token (design 013 §4).
+[[durable_objects.bindings]]
+name = "DEPLOY_LEASE"
+class_name = "DeployLease"
[[migrations]]
tag = "v1"
-new_sqlite_classes = ["SessionBudget"]
+new_sqlite_classes = ["SpendCounter", "DeployLease"]
# Secrets (set with `wrangler secret put …`, never in this file):
# GATEWAY_TOKEN_PUBLIC_KEY — base64url raw 32-byte Ed25519 PUBLIC key (minter holds the private key)
# GATEWAY_ORKEY_SECRET — bearer for the dedicated sessions-api org-OR-key seam (carries a live key)
+# GATEWAY_ADMIN_SECRET — bearer that guards the control-plane admin routes (/admin/*)
# TEST_OR_KEY — acceptance-test single OR key override (bypasses the seam); never in prod
# OC_INGEST_AUTH — optional, per-session spend telemetry auth
[vars]
# GATEWAY_ORKEY_URL — the internal sessions-api route that returns an org's OR key {org}→{key}.
+# AGENT_BUDGET_USD_DEFAULT — default HARD budget (USD) per org+agt for an unprovisioned grain; unset = uncapped.
# OPENROUTER_BASE — leave unset for prod (https://openrouter.ai/api); override for a mock in tests.
# CACHE_CONTROL_UNSAFE_MODELS — extra comma-separated model patterns to strip cache_control for.
# OC_INGEST_URL — optional per-session spend sink.