An open-source, faster Devin alternative
TypeScript
token-billing: address review P0s — safe deploy ordering + real disable rollback
Igor Zalutski08b85060bcac
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex e0c12891..2ef71ee1 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -981,14 +981,27 @@ export async function handleDashboard(// dashboard renders instead of 404-erroring on a missing route.if (sub === "/billing" && method === "GET") {const org = await env.OPENCOMPUTER_DB.prepare(- `SELECT plan, stripe_customer_id, stripe_subscription_id, free_credits_remaining_cents, credit_balance_cents, is_halted, max_concurrent_sandboxes, billing_provider, model_billing_status+ `SELECT plan, stripe_customer_id, stripe_subscription_id, free_credits_remaining_cents, credit_balance_cents, is_halted, max_concurrent_sandboxes, billing_providerFROM orgs WHERE id = ?1`,).bind(caller.orgID).first<{plan: string; stripe_customer_id: string | null; stripe_subscription_id: string | null;free_credits_remaining_cents: number; credit_balance_cents: number; is_halted: number;- max_concurrent_sandboxes: number; billing_provider: string; model_billing_status: string | null;+ max_concurrent_sandboxes: number; billing_provider: string;}>();if (!org) return json({ error: "org not found" }, 404);+ // Managed model access (token-billing §6.6) — read SEPARATELY + defensively so the+ // critical billing read above never depends on the phase-9 column. If schema_phase9+ // hasn't been applied yet (Worker deployed first), the column is missing → this+ // throws → managedAvailable=false, and existing billing is unaffected (P0 ordering).+ let managedAvailable = false;+ try {+ const m = await env.OPENCOMPUTER_DB.prepare(+ `SELECT model_billing_status FROM orgs WHERE id = ?1`,+ ).bind(caller.orgID).first<{ model_billing_status: string | null }>();+ managedAvailable = m?.model_billing_status === "active";+ } catch {+ /* phase-9 not migrated yet → Managed simply unavailable */+ }// Cross-check against the live DO state — the D1 mirror gets written by// the DO after every debit but lags a touch, and on initial signup the// column reads its column-default (500) before the DO has ever been@@ -1023,7 +1036,8 @@ export async function handleDashboard(// Managed model access (token-billing §6.6): the single gating authority the UI// reads to offer the "Managed" credential option. True only once the edge has// provisioned the org's OpenRouter key + bound it (model_billing_status='active').- managedAvailable: org.model_billing_status === "active",+ // Read defensively above so a missing phase-9 column never breaks billing.+ managedAvailable,// Upcoming-invoice + meters would come from Stripe API on demand;// surface stubs for now so the UI has stable keys to render against.upcomingInvoice: null,diff --git a/cloudflare-workers/api-edge/src/model_billing.test.ts b/cloudflare-workers/api-edge/src/model_billing.test.tsindex 4e961c26..c1088cd4 100644--- a/cloudflare-workers/api-edge/src/model_billing.test.ts+++ b/cloudflare-workers/api-edge/src/model_billing.test.ts@@ -7,6 +7,7 @@ import {patchOrKey,} from "./openrouter";import {+ disableManagedBilling,enableManagedBilling,type ManagedModelKeyRow,type ModelBillingEnv,@@ -59,6 +60,15 @@ class FakeStmt {return null;}+ // getAllKeyRows uses .all() (no status filter).+ async all<T>(): Promise<{ results: T[] }> {+ if (this.sql.includes("FROM managed_model_keys")) {+ const orgId = this.args[0] as string;+ return { results: this.db.keys.filter((k) => k.org_id === orgId) as T[] };+ }+ return { results: [] };+ }+async run(): Promise<void> {const s = this.sql;if (s.startsWith("UPDATE orgs SET model_billing_status")) {@@ -86,6 +96,11 @@ class FakeStmt {});return;}+ if (s.startsWith("DELETE FROM managed_model_keys")) {+ const orgId = this.args[0] as string;+ this.db.keys = this.db.keys.filter((k) => k.org_id !== orgId);+ return;+ }if (s.startsWith("UPDATE managed_model_keys SET")) {// parse "SET a = ?1, b = ?2 WHERE id = ?N"const setClause = s.slice(s.indexOf("SET ") + 4, s.indexOf(" WHERE"));@@ -136,6 +151,7 @@ function makeFetch(opts: RouterOpts = {}) {// sessions-api hand-offif (url.includes("/internal/managed-credential")) {if (method === "POST") return new Response(JSON.stringify({ managed_credential_id: "cred_bound" }), { status: 200 });+ if (method === "DELETE") return new Response(JSON.stringify({ deleted: 1 }), { status: 200 });// GET lookupreturn new Response(JSON.stringify({ managed_credential_id: opts.lookupCredId ?? null }), { status: 200 });}@@ -313,3 +329,33 @@ describe("enableManagedBilling state machine", () => {expect(db.keys[0].managed_credential_id).toBe("cred_bound");});});++describe("disableManagedBilling (rollback / hard offboard)", () => {+ it("deletes the OR key, revokes the sessions-api credential, drops rows, flips off", async () => {+ const db = new FakeDb();+ const orgId = seedOrg(db, { model_billing_status: "active" });+ db.keys.push({+ id: "mmk_1", org_id: orgId, or_key_hash: "hash-live", managed_credential_id: "cred_live",+ operation_id: "op_1", status: "active", committed_micro: 0, pending_from_micro: null,+ pending_to_micro: null, pending_idem: null, attempts: 0, last_error: null, created_at: 1, superseded_at: null,+ });+ const { spy, calls } = makeFetch();+ vi.stubGlobal("fetch", spy);++ await disableManagedBilling(makeEnv(db), orgId);++ expect(calls.find((c) => c.method === "DELETE" && c.url.includes("/keys/"))).toBeTruthy(); // OR key deleted+ expect(calls.find((c) => c.method === "DELETE" && c.url.includes("/internal/managed-credential"))).toBeTruthy(); // credential revoked+ expect(db.keys.length).toBe(0); // rows dropped+ expect(db.orgs.get(orgId)!.model_billing_status).toBe("off"); // flipped off+ });++ it("is a no-op-safe toggle when nothing is provisioned", async () => {+ const db = new FakeDb();+ const orgId = seedOrg(db, { model_billing_status: "off" });+ const { spy } = makeFetch();+ vi.stubGlobal("fetch", spy);+ await disableManagedBilling(makeEnv(db), orgId);+ expect(db.orgs.get(orgId)!.model_billing_status).toBe("off");+ });+});diff --git a/cloudflare-workers/api-edge/src/model_billing.ts b/cloudflare-workers/api-edge/src/model_billing.tsindex f1de348c..2a1957b4 100644--- a/cloudflare-workers/api-edge/src/model_billing.ts+++ b/cloudflare-workers/api-edge/src/model_billing.ts@@ -117,6 +117,20 @@ export async function getActiveKeyRow(env: ModelBillingEnv, orgId: string): Prom.first<ManagedModelKeyRow>();}+// All of an org's key rows (any status) — for the hard offboard sweep.+async function getAllKeyRows(env: ModelBillingEnv, orgId: string): Promise<ManagedModelKeyRow[]> {+ const res = await env.OPENCOMPUTER_DB.prepare(+ "SELECT * FROM managed_model_keys WHERE org_id = ?1",+ )+ .bind(orgId)+ .all<ManagedModelKeyRow>();+ return res.results ?? [];+}++async function deleteKeyRows(env: ModelBillingEnv, orgId: string): Promise<void> {+ await env.OPENCOMPUTER_DB.prepare("DELETE FROM managed_model_keys WHERE org_id = ?1").bind(orgId).run();+}+async function insertRow(env: ModelBillingEnv, row: { id: string; orgId: string; operationId: string; createdAt: number }): Promise<ManagedModelKeyRow> {await env.OPENCOMPUTER_DB.prepare("INSERT INTO managed_model_keys (id, org_id, operation_id, status, committed_micro, attempts, created_at) VALUES (?1, ?2, ?3, 'active', 0, 0, ?4)",@@ -193,7 +207,7 @@ async function hmacHex(secret: string, data: string): Promise<string> {// sessions-api. Returns the parsed JSON. `path` must start with HANDOFF_PATH.async function signedHandoff(env: ModelBillingEnv,- method: "POST" | "GET",+ method: "POST" | "GET" | "DELETE",path: string,body: string,): Promise<unknown> {@@ -210,7 +224,7 @@ async function signedHandoff("x-oc-managed-ts": ts,"x-oc-managed-sig": sig,},- body: method === "GET" ? undefined : body,+ body: method === "POST" ? body : undefined, // GET + DELETE carry no body});const text = await resp.text();if (!resp.ok) throw new Error(`managed-credential ${method} ${resp.status}: ${text.slice(0, 200)}`);@@ -248,6 +262,15 @@ async function lookupManagedCredential(return out?.managed_credential_id ?? null;}+// Revoke (soft-delete) the owner's managed credential(s) in sessions-api — the+// rollback counterpart of the bind. Idempotent (deleting none returns 0). Returns+// how many were deleted.+async function revokeManagedCredential(env: ModelBillingEnv, ownerId: string): Promise<number> {+ const qs = `?owner_id=${encodeURIComponent(ownerId)}`;+ const out = (await signedHandoff(env, "DELETE", HANDOFF_PATH + qs, "")) as { deleted?: number };+ return out?.deleted ?? 0;+}+// ── the state machine ───────────────────────────────────────────────────────export interface EnableResult {@@ -356,17 +379,26 @@ export async function reconcileManagedBilling(env: ModelBillingEnv, orgId: strinreturn enableManagedBilling(env, orgId);}-// disableManagedBilling marks the org's active key 'deleting' (§5.8). The metering-// cron (step 3) keeps polling it until spend quiesces, does a final debit, then-// DELETEs the OR key + revokes the credential, and flips the org 'off' once no-// usable key remains. We only move state here; we do NOT delete mid-spend.+// disableManagedBilling is the rollback path: a synchronous HARD offboard. The+// graceful-drain cron (§5.8 — keep polling until spend quiesces, final debit, then+// delete) isn't built yet, so disable does the teardown directly: delete the OR+// key(s), revoke the sessions-api managed credential, drop the key rows, flip the org+// off. Order matters — we only delete rows + flip off AFTER the OR key + credential+// are gone, so a partial failure throws and a retry completes cleanly (every step is+// idempotent). NOTE: a tiny final slice of spend may go unbilled (no drain); fine for+// rollback/test offboard. Replace with the graceful drain when step 3 lands.export async function disableManagedBilling(env: ModelBillingEnv, orgId: string): Promise<void> {- const row = await getActiveKeyRow(env, orgId);- if (row) {- await updateRow(env, row.id, { status: "deleting" });- console.log(`model-billing: org ${orgId} key ${row.or_key_hash} → deleting (drain + offboard handled by cron)`);- } else {- // Nothing usable to drain → off immediately.- await setOrgStatus(env, orgId, "off");+ const rows = await getAllKeyRows(env, orgId);+ // 1. Delete every OR key (idempotent: 404 = already gone). Kills the budget + the+ // sealed key's validity immediately, even if a later step fails.+ for (const row of rows) {+ if (row.or_key_hash) await deleteOrKey(env, row.or_key_hash);}+ // 2. Revoke the managed credential in sessions-api so the resolver stops resolving+ // Managed (the org-default-managed arm, §6.7.3). Throws on failure → retry.+ await revokeManagedCredential(env, ownerIdForOrg(orgId));+ // 3. Only now: drop the rows + flip off (so a mid-failure retry re-runs 1–2).+ await deleteKeyRows(env, orgId);+ await setOrgStatus(env, orgId, "off");+ console.log(`model-billing: org ${orgId} disabled (hard offboard: ${rows.length} key(s) deleted + credential revoked)`);}