An open-source, faster Devin alternative
TypeScript
api-edge: remove sandbox leftovers (custom domains, secret stores, sandbox webhooks, D1 sandbox reads)
Mohamed Habib via Computer622352093666
diff --git a/cloudflare-workers/api-edge/src/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.tsindex b8190117..a91eb30e 100644--- a/cloudflare-workers/api-edge/src/cli_auth.test.ts+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts@@ -148,7 +148,6 @@ function testEnv(db = new FakeDB()): Env {CF_ADMIN_SECRET: "",STRIPE_WEBHOOK_SECRET: "",EVENT_SECRET: "",- SECRET_ENCRYPTION_KEY: "",} as unknown as Env;}diff --git a/cloudflare-workers/api-edge/src/computer_api.test.ts b/cloudflare-workers/api-edge/src/computer_api.test.tsindex 8b6a21c6..e0201a40 100644--- a/cloudflare-workers/api-edge/src/computer_api.test.ts+++ b/cloudflare-workers/api-edge/src/computer_api.test.ts@@ -95,7 +95,6 @@ function testEnv(db: FakeDB, extra: Partial<Record<string, unknown>> = {}): EnvCF_ADMIN_SECRET: "",STRIPE_WEBHOOK_SECRET: "",EVENT_SECRET: "",- SECRET_ENCRYPTION_KEY: "",MANAGED_AGENTS_API_URL: BLUE,OC_MANAGED_AGENTS_SECRET: "assert-secret",WIRE_HTTP_URL: WIRE,diff --git a/cloudflare-workers/api-edge/src/crypto.ts b/cloudflare-workers/api-edge/src/crypto.tsdeleted file mode 100644index 53aba72b..00000000--- a/cloudflare-workers/api-edge/src/crypto.ts+++ /dev/null@@ -1,44 +0,0 @@-// AES-256-GCM helpers for secret-store envelope encryption.-//-// Wire format mirrors internal/crypto/encrypt.go: `nonce(12) || ciphertext`,-// stored as a BLOB in D1's secret_store_entries.encrypted_value. The same-// SECRET_ENCRYPTION_KEY (hex-encoded 32 bytes, lives in Infisical /shared/)-// is bound to the edge Worker as a secret AND distributed to every CP via-// the per-cell KV/SM sync — so a value encrypted here decrypts cleanly inside-// any cell, and vice versa.--const NONCE_LEN = 12;--async function importKey(hexKey: string): Promise<CryptoKey> {- if (hexKey.length !== 64) {- throw new Error(`SECRET_ENCRYPTION_KEY must be 64 hex chars (32 bytes), got ${hexKey.length}`);- }- const raw = new Uint8Array(32);- for (let i = 0; i < 32; i++) {- raw[i] = parseInt(hexKey.substr(i * 2, 2), 16);- }- return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);-}--export async function encryptSecret(hexKey: string, plaintext: string): Promise<Uint8Array> {- const key = await importKey(hexKey);- const nonce = new Uint8Array(NONCE_LEN);- crypto.getRandomValues(nonce);- const ct = new Uint8Array(- await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, key, new TextEncoder().encode(plaintext)),- );- // nonce || ciphertext+tag- const out = new Uint8Array(NONCE_LEN + ct.length);- out.set(nonce, 0);- out.set(ct, NONCE_LEN);- return out;-}--export async function decryptSecret(hexKey: string, blob: Uint8Array): Promise<string> {- if (blob.length < NONCE_LEN + 16) throw new Error("ciphertext too short");- const key = await importKey(hexKey);- const nonce = blob.subarray(0, NONCE_LEN);- const ct = blob.subarray(NONCE_LEN);- const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce }, key, ct);- return new TextDecoder().decode(pt);-}diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex c493a113..25dd57b0 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -8,8 +8,9 @@//// The sandbox-runtime proxy to the cells (/internal/dashboard/* for sessions,// PTY, agents, sandbox create, previews and snapshot deletes) was removed in-// 097 step 7.2. The D1-only sandbox reads (sessions, checkpoints, images) stay-// until the sandbox tables themselves are retired.+// 097 step 7.2, followed by the D1-only sandbox reads (sessions, checkpoints,+// images, per-sandbox usage), sandbox webhooks and org custom domains. The+// sandbox D1 tables and org columns stay until a later migration.import {autumnPurchase,@@ -25,7 +26,6 @@ import {} from "./autumn_webhook";import { planSchedule, summarizeWorkMinutePlan, trialEndsAt } from "./billing_summary";import { emitBillingEvent, type BillingEventsEnv } from "./billing_events";-import { handleWebhooksAPI, type WebhookEnv } from "./webhooks";import { createAPIKeyWithHash } from "./api_keys";import { createdKeyForSync, revokeComputerKey, syncComputerKey } from "./computer_keys";import {@@ -57,10 +57,6 @@ export interface DashboardEnv extends BillingEventsEnv {// "true" → new signups are provisioned on Autumn (Stage 2 switch). Default// off keeps merge dormant; existing orgs are never auto-migrated by this.AUTUMN_NEW_ORGS?: string;- // CF Custom Hostnames API token + zone (for /org/custom-domain). Optional —- // if unset the custom-domain endpoints return 503 (feature disabled).- CF_API_TOKEN?: string;- CF_ZONE_ID?: string;// Browser Sessions dashboard proxy. The browser API remains a separate// Worker; this edge Worker only translates dashboard cookie auth into the// internal service token plus org/user headers.@@ -173,16 +169,6 @@ function epochToISORequired(s: number | null | undefined): string {return new Date(((s ?? 0) || 0) * 1000).toISOString();}-// Cell ID → region, for the sandbox rows still listed from D1. Cell ids-// follow {cloud}-{region-with-hyphens}-{slot}, e.g.-// "azure-us-west-2-b" → region "us-west-2".-function cellToRegion(cellID: string): string {- // Strip first segment (cloud) and last segment (slot).- const parts = cellID.split("-");- if (parts.length < 3) return "";- return parts.slice(1, -1).join("-");-}-// shapeOrg maps a D1 orgs row to the frontend's Org interface (camelCase,// timestamps as ISO strings, integer-flag booleans).interface OrgRow {@@ -573,201 +559,6 @@ async function handleRenameAPIKey(req: Request, env: DashboardEnv, caller: Calle});}-// ── sessions list (cross-cell) ───────────────────────────────────────────--async function handleListSessions(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {- const url = new URL(req.url);- const status = url.searchParams.get("status") ?? "";- let stmt;- if (status) {- stmt = env.OPENCOMPUTER_DB.prepare(- `SELECT id, cell_id, worker_id, status, template_id, created_at, last_event_at, stopped_at- FROM sandboxes_index WHERE org_id = ?1 AND status = ?2 ORDER BY created_at DESC LIMIT 200`,- ).bind(caller.orgID, status);- } else {- stmt = env.OPENCOMPUTER_DB.prepare(- `SELECT id, cell_id, worker_id, status, template_id, created_at, last_event_at, stopped_at- FROM sandboxes_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT 200`,- ).bind(caller.orgID);- }- const { results } = await stmt.all<{- id: string; cell_id: string; worker_id: string | null; status: string;- template_id: string | null; created_at: number; last_event_at: number | null; stopped_at: number | null;- }>();- // Reshape to match the frontend's Session interface (camelCase, ISO timestamps).- const sessions = (results ?? []).map((r) => ({- id: r.id,- sandboxId: r.id,- orgId: caller.orgID,- template: r.template_id ?? "default",- region: cellToRegion(r.cell_id),- workerId: r.worker_id ?? "",- status: r.status,- startedAt: epochToISORequired(r.created_at),- stoppedAt: epochToISO(r.stopped_at),- cellId: r.cell_id, // bonus: surface the cell for cross-cell aware UI- }));- return json(sessions);-}--// ── checkpoints (cross-cell) ─────────────────────────────────────────────--async function handleListCheckpoints(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {- try {- const url = new URL(req.url);- const page = Math.max(1, parseInt(url.searchParams.get("page") ?? "1", 10) || 1);- const perPage = Math.min(100, Math.max(1, parseInt(url.searchParams.get("per_page") ?? "20", 10) || 20));- const offset = (page - 1) * perPage;-- const { results } = await env.OPENCOMPUTER_DB.prepare(- `SELECT id, sandbox_id, owner_cell_id, s3_url, size_bytes, golden_hash, workspace_size, created_at, expires_at, name, status, error_msg, failed_at, kind- FROM checkpoints_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT ?2 OFFSET ?3`,- ).bind(caller.orgID, perPage, offset).all<{- id: string; sandbox_id: string; owner_cell_id: string; s3_url: string | null;- size_bytes: number | null; golden_hash: string | null; workspace_size: number | null;- created_at: number; expires_at: number | null;- name: string | null;- status: string | null; error_msg: string | null; failed_at: number | null;- kind: string | null;- }>();- const totalRow = await env.OPENCOMPUTER_DB.prepare(`SELECT COUNT(*) AS c FROM checkpoints_index WHERE org_id = ?1`).bind(caller.orgID).first<{ c: number }>();- return json({- checkpoints: (results ?? []).map((r) => ({- id: r.id,- sandboxId: r.sandbox_id ?? "",- orgId: caller.orgID,- // Prefer the user-set name. Pre-fix this derived from s3_url which- // always ended in "rootfs.tar.zst" (every row showed the same name);- // the column was added + backfilled from cell PG sandbox_checkpoints- // so this now surfaces what customers actually called the checkpoint.- name: r.name && r.name.length > 0 ? r.name : r.id.slice(0, 8),- status: r.status ?? "ready",- sizeBytes: r.size_bytes ?? 0,- activeForks: 0,- totalForks: 0,- createdAt: epochToISORequired(r.created_at),- errorMsg: r.error_msg ?? undefined,- failedAt: r.failed_at ? epochToISORequired(r.failed_at) : undefined,- kind: r.kind === "disk_only" ? "disk_only" : "full",- cellId: r.owner_cell_id ?? "",- goldenHash: r.golden_hash ?? "",- })),- total: totalRow?.c ?? 0,- page, perPage,- });- } catch (err) {- console.error("handleListCheckpoints failed:", err);- return json({ error: `checkpoints failed: ${(err as Error).message}` }, 500);- }-}--async function handleDeleteCheckpoint(_req: Request, env: DashboardEnv, caller: Caller, cpID: string): Promise<Response> {- // Verify ownership before delete.- const row = await env.OPENCOMPUTER_DB.prepare(- `SELECT owner_cell_id FROM checkpoints_index WHERE id = ?1 AND org_id = ?2`,- ).bind(cpID, caller.orgID).first<{ owner_cell_id: string }>();- if (!row) return json({ error: "checkpoint not found" }, 404);- // Delete D1 row first (source of truth). Owning-cell blob cleanup is async- // via the cell's existing GC; we don't try to coordinate here.- await env.OPENCOMPUTER_DB.prepare(`DELETE FROM checkpoints_index WHERE id = ?1 AND org_id = ?2`).bind(cpID, caller.orgID).run();- return new Response(null, { status: 204 });-}--// ── custom domain (CF Custom Hostnames API) ──────────────────────────────--interface CFCustomHostname {- id: string;- status: string;- ssl: { status: string; txt_name?: string; txt_value?: string; validation_records?: { name: string; value: string }[] };- ownership_verification?: { name: string; value: string };-}--async function cfAPI(env: DashboardEnv, method: string, path: string, body?: any): Promise<Response> {- return fetch(`https://api.cloudflare.com/client/v4${path}`, {- method,- headers: {- authorization: `Bearer ${env.CF_API_TOKEN}`,- "content-type": "application/json",- },- body: body ? JSON.stringify(body) : undefined,- });-}--async function handleSetCustomDomain(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {- if (!env.CF_API_TOKEN || !env.CF_ZONE_ID) return json({ error: "Cloudflare not configured" }, 503);- const body = await req.json<{ domain?: string }>().catch(() => ({} as { domain?: string }));- const domain = (body.domain ?? "").trim().toLowerCase();- if (!domain) return json({ error: "domain required" }, 400);-- const org = await env.OPENCOMPUTER_DB.prepare(`SELECT cf_hostname_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ cf_hostname_id: string | null }>();- if (org?.cf_hostname_id) {- await cfAPI(env, "DELETE", `/zones/${env.CF_ZONE_ID}/custom_hostnames/${org.cf_hostname_id}`).catch(() => {});- }- const r = await cfAPI(env, "POST", `/zones/${env.CF_ZONE_ID}/custom_hostnames`, {- hostname: domain,- ssl: { method: "txt", type: "dv" },- });- if (!r.ok) return json({ error: `Cloudflare API: ${r.status} ${await r.text()}` }, 502);- const data = (await r.json<{ result: CFCustomHostname }>()).result;-- const verifyName = data.ownership_verification?.name ?? null;- const verifyValue = data.ownership_verification?.value ?? null;- let sslName: string | null = null;- let sslValue: string | null = null;- if (data.ssl.txt_name) { sslName = data.ssl.txt_name; sslValue = data.ssl.txt_value ?? null; }- else if (data.ssl.validation_records?.[0]) { sslName = data.ssl.validation_records[0].name; sslValue = data.ssl.validation_records[0].value; }-- await env.OPENCOMPUTER_DB.prepare(- `UPDATE orgs SET custom_domain = ?1, cf_hostname_id = ?2, domain_verification_status = ?3, domain_ssl_status = ?4,- verification_txt_name = ?5, verification_txt_value = ?6, ssl_txt_name = ?7, ssl_txt_value = ?8,- updated_at = ?9- WHERE id = ?10`,- ).bind(domain, data.id, data.status, data.ssl.status, verifyName, verifyValue, sslName, sslValue, Math.floor(Date.now() / 1000), caller.orgID).run();- const updated = await env.OPENCOMPUTER_DB.prepare(`SELECT * FROM orgs WHERE id = ?1`).bind(caller.orgID).first<OrgRow>();- return json(updated ? shapeOrg(updated) : null);-}--async function handleDeleteCustomDomain(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {- if (!env.CF_API_TOKEN || !env.CF_ZONE_ID) return json({ error: "Cloudflare not configured" }, 503);- const org = await env.OPENCOMPUTER_DB.prepare(`SELECT cf_hostname_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ cf_hostname_id: string | null }>();- if (org?.cf_hostname_id) {- await cfAPI(env, "DELETE", `/zones/${env.CF_ZONE_ID}/custom_hostnames/${org.cf_hostname_id}`).catch(() => {});- }- await env.OPENCOMPUTER_DB.prepare(- `UPDATE orgs SET custom_domain = NULL, cf_hostname_id = NULL,- domain_verification_status = 'none', domain_ssl_status = 'none',- verification_txt_name = NULL, verification_txt_value = NULL,- ssl_txt_name = NULL, ssl_txt_value = NULL, updated_at = ?1- WHERE id = ?2`,- ).bind(Math.floor(Date.now() / 1000), caller.orgID).run();- const updated = await env.OPENCOMPUTER_DB.prepare(`SELECT * FROM orgs WHERE id = ?1`).bind(caller.orgID).first<OrgRow>();- return json(updated ? shapeOrg(updated) : null);-}--async function handleRefreshCustomDomain(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {- if (!env.CF_API_TOKEN || !env.CF_ZONE_ID) return json({ error: "Cloudflare not configured" }, 503);- const org = await env.OPENCOMPUTER_DB.prepare(`SELECT cf_hostname_id FROM orgs WHERE id = ?1`).bind(caller.orgID).first<{ cf_hostname_id: string | null }>();- if (!org?.cf_hostname_id) return json({ error: "no custom domain configured" }, 400);- const r = await cfAPI(env, "GET", `/zones/${env.CF_ZONE_ID}/custom_hostnames/${org.cf_hostname_id}`);- if (!r.ok) return json({ error: `Cloudflare API: ${r.status}` }, 502);- const data = (await r.json<{ result: CFCustomHostname }>()).result;-- const verifyName = data.ownership_verification?.name ?? null;- const verifyValue = data.ownership_verification?.value ?? null;- let sslName: string | null = null, sslValue: string | null = null;- if (data.ssl.txt_name) { sslName = data.ssl.txt_name; sslValue = data.ssl.txt_value ?? null; }- else if (data.ssl.validation_records?.[0]) { sslName = data.ssl.validation_records[0].name; sslValue = data.ssl.validation_records[0].value; }-- await env.OPENCOMPUTER_DB.prepare(- `UPDATE orgs SET domain_verification_status = ?1, domain_ssl_status = ?2,- verification_txt_name = ?3, verification_txt_value = ?4,- ssl_txt_name = ?5, ssl_txt_value = ?6, updated_at = ?7- WHERE id = ?8`,- ).bind(data.status, data.ssl.status, verifyName, verifyValue, sslName, sslValue, Math.floor(Date.now() / 1000), caller.orgID).run();- const updated = await env.OPENCOMPUTER_DB.prepare(`SELECT * FROM orgs WHERE id = ?1`).bind(caller.orgID).first<OrgRow>();- return json(updated ? shapeOrg(updated) : null);-}-// ── credits + billing ────────────────────────────────────────────────────async function handleGetCredits(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {@@ -951,17 +742,6 @@ export async function handleDashboard(}if (sub === "/browser-profiles" && method === "GET") return proxyToBrowserAPI(req, env, caller, "/v1/profiles");- // ── Sandbox lifecycle webhooks ─────────────────────────────────────────- // Reuse the public /api/webhooks handler with the cookie-derived org, so the- // dashboard manages destinations/deliveries org-scoped without an osb_ key in- // the browser. The handler parses the path from the url arg; rewrite it back- // to /api/webhooks/*. env carries the Svix bindings at runtime.- if (sub === "/webhooks" || sub.startsWith("/webhooks/")) {- const whUrl = new URL(req.url);- whUrl.pathname = "/api" + sub;- return handleWebhooksAPI(req, env as unknown as WebhookEnv, caller, whUrl);- }-// ── identity / org ─────────────────────────────────────────────────────if (sub === "/me" && method === "GET") return handleMe(req, env, caller);if (sub === "/orgs" && method === "GET") return handleListOrgs(req, env, caller);@@ -981,9 +761,6 @@ export async function handleDashboard(if (m && method === "DELETE") return handleRevokeInvitation(req, env, caller, m[1]);}if (sub === "/org/credits" && method === "GET") return handleGetCredits(req, env, caller);- if (sub === "/org/custom-domain" && method === "PUT") return handleSetCustomDomain(req, env, caller);- if (sub === "/org/custom-domain" && method === "DELETE") return handleDeleteCustomDomain(req, env, caller);- if (sub === "/org/custom-domain/refresh" && method === "POST") return handleRefreshCustomDomain(req, env, caller);// ── api keys ───────────────────────────────────────────────────────────if (sub === "/api-keys" && method === "GET") return handleListAPIKeys(req, env, caller);@@ -994,21 +771,6 @@ export async function handleDashboard(if (m && method === "PATCH") return handleRenameAPIKey(req, env, caller, m[1]);}- // ── sessions: list from D1 sandboxes_index ─────────────────────────────- if (sub === "/sessions" && method === "GET") return handleListSessions(req, env, caller);-- // ── checkpoints ───────────────────────────────────────────────────────- if (sub === "/checkpoints" && method === "GET") return handleListCheckpoints(req, env, caller);- {- const m = sub.match(/^\/checkpoints\/([^/]+)$/);- if (m && method === "DELETE") return handleDeleteCheckpoint(req, env, caller, m[1]);- }-- // ── images: list from D1 images_index ──────────────────────────────────- if (sub === "/images" && method === "GET") {- return handleListImages(env, caller);- }-if (sub === "/billing/agent-subscriptions" && method === "GET") return handleListAgentSubscriptions(req, env, caller);// /billing — basic billing read used by the dashboard billing page.@@ -1107,9 +869,6 @@ export async function handleDashboard(if (sub === "/billing/invoices" && method === "GET") {return handleBillingInvoices(req, env, caller);}- if (sub === "/usage/sandboxes" && method === "GET") {- return handleSandboxUsage(req, env, caller);- }if (sub === "/billing/autumn" && method === "GET") {return handleAutumnBilling(req, env, caller);}@@ -1138,47 +897,6 @@ export async function handleDashboard(return json({ error: `not found: ${method} ${sub}` }, 404);}-// ── Images (cross-cell via D1 images_index) ────────────────────────────--interface ImagesRow {- id: string;- org_id: string;- owner_cell_id: string;- content_hash: string;- checkpoint_id: string | null;- name: string | null;- manifest: string;- status: string;- created_at: number;- last_used_at: number;-}--async function handleListImages(env: DashboardEnv, caller: Caller): Promise<Response> {- const { results } = await env.OPENCOMPUTER_DB.prepare(- `SELECT id, org_id, owner_cell_id, content_hash, checkpoint_id, name, manifest, status, created_at, last_used_at- FROM images_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT 200`,- )- .bind(caller.orgID)- .all<ImagesRow>();- const out = (results ?? []).map((r) => {- let manifest: unknown = {};- try { manifest = JSON.parse(r.manifest); } catch { /* keep empty */ }- return {- id: r.id,- orgId: r.org_id,- cellId: r.owner_cell_id,- contentHash: r.content_hash,- checkpointId: r.checkpoint_id,- name: r.name,- manifest,- status: r.status,- createdAt: new Date(r.created_at * 1000).toISOString(),- lastUsedAt: new Date(r.last_used_at * 1000).toISOString(),- };- });- return json(out);-}-// ── Stripe helpers ─────────────────────────────────────────────────────// stripeApi POSTs form-urlencoded to Stripe's REST API. GET is supported via@@ -1257,79 +975,6 @@ async function handleAutumnPortal(req: Request, env: DashboardEnv, caller: { org}}-// ── Per-sandbox usage breakdown ──────────────────────────────────────────--// Per-sandbox DISPLAY rate for PREPAID (autumn) orgs only — this breakdown is-// rendered solely in the autumn billing view, and this constant has exactly one-// consumer (handleSandboxUsage below). It is intentionally decoupled from-// internal/billing/pricing.go (legacy billing): the source of truth for prepaid-// charges is the Autumn `credits` credit-schema (credit_cost per compute-// feature), and these values MUST mirror it exactly or the breakdown won't-// reconcile with what's actually deducted. Current basis: $0.06/GB-hour-// (0.00001666666666 per GB-second × the tier's GB). Change the Autumn schema →-// change these too.-const AUTUMN_TIER_RATE_PER_SEC: Record<number, number> = {- 1024: 0.00001666666666,- 4096: 0.00006666666664,- 8192: 0.00013333333328,- 16384: 0.00026666666656,- 32768: 0.00053333333312,- 65536: 0.00106666666624,-};--// GET /api/dashboard/usage/sandboxes?days=N — per-sandbox compute cost over a-// recent window, for billing transparency. Sourced from D1 usage_samples-// (global across cells); disk overage is excluded (samples carry no disk size),-// so this is compute cost only. usage_samples is short-lived, hence the window.-async function handleSandboxUsage(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {- const url = new URL(req.url);- let days = Number.parseInt(url.searchParams.get("days") ?? "30", 10);- if (!Number.isFinite(days) || days < 1) days = 30;- if (days > 90) days = 90;- const cutoffMs = (Math.floor(Date.now() / 1000) - days * 86400) * 1000;-- const rows = await env.OPENCOMPUTER_DB.prepare(- `SELECT u.sandbox_id AS sandbox_id, u.memory_mb AS memory_mb, SUM(u.interval_s) AS secs,- MAX(si.status) AS status, MAX(si.created_at) AS created_at- FROM usage_samples u- LEFT JOIN sandboxes_index si ON si.id = u.sandbox_id- WHERE u.org_id = ?1 AND u.ts >= ?2- GROUP BY u.sandbox_id, u.memory_mb`,- )- .bind(caller.orgID, cutoffMs)- .all<{ sandbox_id: string; memory_mb: number; secs: number; status: string | null; created_at: number | null }>();-- // Fold per-(sandbox, tier) rows into per-sandbox totals.- const bySandbox = new Map<string, { costCents: number; seconds: number; status: string | null; createdAt: number | null }>();- for (const r of rows.results ?? []) {- const rate = AUTUMN_TIER_RATE_PER_SEC[r.memory_mb] ?? 0;- const secs = r.secs ?? 0;- const cur = bySandbox.get(r.sandbox_id) ?? { costCents: 0, seconds: 0, status: r.status, createdAt: r.created_at };- cur.costCents += secs * rate * 100;- cur.seconds += secs;- if (cur.status == null) cur.status = r.status;- if (cur.createdAt == null) cur.createdAt = r.created_at;- bySandbox.set(r.sandbox_id, cur);- }-- const sandboxes = [...bySandbox.entries()]- .map(([sandboxId, v]) => ({- sandboxId,- status: v.status ?? "deleted",- createdAt: v.createdAt ?? undefined,- seconds: Math.round(v.seconds),- // Keep FRACTIONAL cents. Rounding each sandbox to whole cents here meant a- // cheap/short sandbox (e.g. 4GB for ~15 min ≈ 0.5¢) showed $0.00, and the- // total summed already-zeroed rows — so a page of real usage read $0.00.- // The frontend formats the precision for display.- costCents: v.costCents,- }))- .sort((a, b) => b.costCents - a.costCents);-- const totalCents = sandboxes.reduce((s, x) => s + x.costCents, 0);- return json({ windowDays: days, totalCents, sandboxes });-}-// ── Autumn prepaid billing ───────────────────────────────────────────────// Concurrency plans the user can self-serve subscribe to. Mirrorsdiff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.tsindex dbf422d9..bfabff8f 100644--- a/cloudflare-workers/api-edge/src/index.test.ts+++ b/cloudflare-workers/api-edge/src/index.test.ts@@ -56,7 +56,6 @@ const env = {CF_ADMIN_SECRET: "",STRIPE_WEBHOOK_SECRET: "",EVENT_SECRET: "",- SECRET_ENCRYPTION_KEY: "",} as unknown as Env;const ctx = {diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 9d591113..92d9efad 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -47,8 +47,6 @@ import {} from "./billing_onramp";export { ManagedAgentBillingService } from "./managed_agent_billing_service";import { runRetentionSweep } from "./retention";-import * as secretStores from "./secret_stores";-import * as webhooks from "./webhooks";import { createAPIKey, createAPIKeyWithHash, hashAPIKey } from "./api_keys";import { envWithD1Retry } from "./d1_retry";import {@@ -114,13 +112,6 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv, LBROWSER_USAGE_HMAC_SECRET?: string;// Dedicated HMAC secret for finalized managed-agent runtime segments.AGENT_RUNTIME_USAGE_HMAC_SECRET?: string;- // Lives in Infisical /shared/. Used for envelope encryption of secret_store_entries.encrypted_value. Matches- // internal/crypto.Encryptor key format (hex-encoded 32 bytes).- SECRET_ENCRYPTION_KEY: string;- // Svix API token (managed webhook delivery). Region is in the token suffix.- SVIX_API_TOKEN: string;- // CF_API_TOKEN and CF_ZONE_ID are optional in DashboardEnv (custom domain- // feature gates on them). Inherited.ASSETS?: Fetcher;// Slack Connect per signup (slack_connect.ts), sent by the OpenComputer// Slack app: dormant unless the token@@ -2209,54 +2200,6 @@ export default {return json({ key: created.key, expiresAt: created.expiresAt });}- // /internal/webhooks/register — HMAC-auth'd, called by the CP at- // sandbox-create time to register inline webhooks (Svix endpoints) BEFORE- // the sandbox emits `created`. (.agents/work/sandbox-webhooks-rearchitecture.md)- // Not in 097 step 7.2's strip list: it touches only Svix and D1, and goes- // dead on its own once the cells stop calling it. Removed with the rest of- // the sandbox webhooks in a follow-up.- if (path === "/internal/webhooks/register") {- if (req.method !== "POST") return json({ error: "method not allowed" }, 405);- return webhooks.registerInlineWebhooksInternal(req, env, url);- }-- // /api/secret-stores — org-scoped CRUD with X-API-Key auth; replaced the- // legacy CP-side PG routes (deleted in the same PR as migration 041). Kept- // after the sandbox strip (097 step 7.2) because `oc secret` still calls it;- // it no longer pushes anything to cells.- if (path === "/api/secret-stores") {- const caller = await authenticate(req, env, ctx);- if (!caller) return json({ error: "missing or invalid API key" }, 401);- if (req.method === "POST") return secretStores.createStore(req, env, caller);- if (req.method === "GET") return secretStores.listStores(req, env, caller);- return json({ error: "method not allowed" }, 405);- }- {- // /api/secret-stores/:id, /api/secret-stores/:id/secrets, /:id/secrets/:name- const m = path.match(/^\/api\/secret-stores\/([^/]+)(?:\/secrets(?:\/([^/]+))?)?$/);- if (m) {- const storeID = m[1];- const entryName = m[2];- const isEntriesCollection = path.endsWith("/secrets");- const isEntry = !!entryName;- const caller = await authenticate(req, env, ctx);- if (!caller) return json({ error: "missing or invalid API key" }, 401);- if (isEntry) {- if (req.method === "PUT") return secretStores.setEntry(req, env, caller, storeID, entryName);- if (req.method === "DELETE") return secretStores.deleteEntry(req, env, caller, storeID, entryName);- return json({ error: "method not allowed" }, 405);- }- if (isEntriesCollection) {- if (req.method === "GET") return secretStores.listEntries(req, env, caller, storeID);- return json({ error: "method not allowed" }, 405);- }- if (req.method === "GET") return secretStores.getStore(req, env, caller, storeID);- if (req.method === "PUT") return secretStores.updateStore(req, env, caller, storeID);- if (req.method === "DELETE") return secretStores.deleteStore(req, env, caller, storeID);- return json({ error: "method not allowed" }, 405);- }- }-// Auth flows. CLI device auth is deliberately edge-brokered: WorkOS tokens// never cross this boundary and the CLI receives one ordinary OC org key.if (path === "/auth/cli/device") {@@ -2437,15 +2380,6 @@ export default {});}- // /api/webhooks* — sandbox lifecycle webhook management (Svix-backed,- // all-at-edge). Same X-API-Key auth as the rest of the public API; must- // precede the proxy catch-all below.- if (path === "/api/webhooks" || path.startsWith("/api/webhooks/")) {- const caller = await authenticate(req, env, ctx);- if (!caller) return json({ error: "missing or invalid API key" }, 401);- return webhooks.handleWebhooksAPI(req, env, caller, url);- }-// Any other /api/* path used to fall through to a sandbox cell. The cells// are gone (097 step 7.2), so it is an authenticated 404: an unknown key// still gets 401, and the SPA never answers an API path with index.html.diff --git a/cloudflare-workers/api-edge/src/secret_stores.ts b/cloudflare-workers/api-edge/src/secret_stores.tsdeleted file mode 100644index dd55eb12..00000000--- a/cloudflare-workers/api-edge/src/secret_stores.ts+++ /dev/null@@ -1,245 +0,0 @@-// Edge-side secret stores — replaces the legacy per-cell PG-backed-// /api/secret-stores routes. Stores live in D1; entries are envelope--// encrypted at the edge with SECRET_ENCRYPTION_KEY. The cell-facing side-// (the /internal/secret-stores HMAC endpoints and the refresh fan-out) was-// removed with the sandbox code in 097 step 7.2; only the D1 CRUD remains.-//-// JSON shapes mirror internal/api/projects.go (camelCase) so the existing-// CLI/SDK and dashboard talk to the edge unchanged.--import { encryptSecret } from "./crypto";--export interface SecretStoresEnv {- OPENCOMPUTER_DB: D1Database;- SECRET_ENCRYPTION_KEY: string;-}--interface Caller {- orgID: string;- userID: string | null;-}--function json(body: unknown, status = 200): Response {- return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });-}--// ── store shape mapping ──────────────────────────────────────────────────--interface StoreRow {- id: string;- org_id: string;- name: string;- egress_allowlist: string;- created_at: number;- updated_at: number;-}--function storeToJSON(row: StoreRow): Record<string, unknown> {- let allowlist: string[] = [];- try {- allowlist = JSON.parse(row.egress_allowlist) as string[];- } catch {- /* malformed JSON in D1 — degrade to empty list rather than 500 */- }- return {- id: row.id,- orgID: row.org_id,- name: row.name,- egressAllowlist: allowlist,- // ISO strings (not unix seconds) — matches the legacy CP /api/secret-stores- // shape that the Go CLI's struct expects. Storing seconds in D1 is fine;- // serialize for the wire.- createdAt: new Date(row.created_at * 1000).toISOString(),- updatedAt: new Date(row.updated_at * 1000).toISOString(),- };-}--// ── CRUD: stores ────────────────────────────────────────────────────────--export async function createStore(req: Request, env: SecretStoresEnv, caller: Caller): Promise<Response> {- const body = (await req.json().catch(() => null)) as { name?: string; egressAllowlist?: string[] } | null;- if (!body || !body.name) return json({ error: "name is required" }, 400);- const allowlist = Array.isArray(body.egressAllowlist) ? body.egressAllowlist : [];-- const id = crypto.randomUUID();- const now = Math.floor(Date.now() / 1000);- try {- await env.OPENCOMPUTER_DB.prepare(- `INSERT INTO secret_stores (id, org_id, name, egress_allowlist, created_at, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?5)`,- )- .bind(id, caller.orgID, body.name, JSON.stringify(allowlist), now)- .run();- } catch (e) {- // UNIQUE(org_id, name) collision → 409- const msg = (e as Error).message ?? "";- if (/UNIQUE/.test(msg)) return json({ error: "a store with that name already exists" }, 409);- throw e;- }- return json(- storeToJSON({ id, org_id: caller.orgID, name: body.name, egress_allowlist: JSON.stringify(allowlist), created_at: now, updated_at: now }),- 201,- );-}--export async function listStores(_req: Request, env: SecretStoresEnv, caller: Caller): Promise<Response> {- const { results } = await env.OPENCOMPUTER_DB.prepare(- `SELECT id, org_id, name, egress_allowlist, created_at, updated_at- FROM secret_stores WHERE org_id = ?1 ORDER BY name ASC`,- )- .bind(caller.orgID)- .all<StoreRow>();- return json((results ?? []).map(storeToJSON));-}--async function loadStore(env: SecretStoresEnv, orgID: string, id: string): Promise<StoreRow | null> {- return env.OPENCOMPUTER_DB.prepare(- `SELECT id, org_id, name, egress_allowlist, created_at, updated_at- FROM secret_stores WHERE id = ?1 AND org_id = ?2`,- )- .bind(id, orgID)- .first<StoreRow>();-}--export async function getStore(_req: Request, env: SecretStoresEnv, caller: Caller, id: string): Promise<Response> {- const row = await loadStore(env, caller.orgID, id);- if (!row) return json({ error: "secret store not found" }, 404);- return json(storeToJSON(row));-}--export async function updateStore(req: Request, env: SecretStoresEnv, caller: Caller, id: string): Promise<Response> {- const existing = await loadStore(env, caller.orgID, id);- if (!existing) return json({ error: "secret store not found" }, 404);- const body = (await req.json().catch(() => null)) as { name?: string | null; egressAllowlist?: string[] | null } | null;-- const name = typeof body?.name === "string" ? body.name : existing.name;- const allowlist = Array.isArray(body?.egressAllowlist) ? body!.egressAllowlist! : (JSON.parse(existing.egress_allowlist) as string[]);- const now = Math.floor(Date.now() / 1000);- await env.OPENCOMPUTER_DB.prepare(- `UPDATE secret_stores SET name = ?1, egress_allowlist = ?2, updated_at = ?3- WHERE id = ?4 AND org_id = ?5`,- )- .bind(name, JSON.stringify(allowlist), now, id, caller.orgID)- .run();- return json(- storeToJSON({ id, org_id: caller.orgID, name, egress_allowlist: JSON.stringify(allowlist), created_at: existing.created_at, updated_at: now }),- );-}--export async function deleteStore(_req: Request, env: SecretStoresEnv, caller: Caller, id: string): Promise<Response> {- const row = await loadStore(env, caller.orgID, id);- if (!row) return json({ error: "secret store not found" }, 404);- // Cascade-delete entries (D1 doesn't enforce FK CASCADE — do it explicitly).- await env.OPENCOMPUTER_DB.batch([- env.OPENCOMPUTER_DB.prepare(`DELETE FROM secret_store_entries WHERE store_id = ?1`).bind(id),- env.OPENCOMPUTER_DB.prepare(`DELETE FROM secret_stores WHERE id = ?1 AND org_id = ?2`).bind(id, caller.orgID),- ]);- return new Response(null, { status: 204 });-}--// ── CRUD: entries ──────────────────────────────────────────────────────--interface EntryRow {- id: string;- store_id: string;- name: string;- encrypted_value: ArrayBuffer | Uint8Array;- allowed_hosts: string;- created_at: number;- updated_at: number;-}--function entryToJSON(row: EntryRow, includeValue = false): Record<string, unknown> {- let hosts: string[] = [];- try {- hosts = JSON.parse(row.allowed_hosts) as string[];- } catch {- /* malformed JSON */- }- const out: Record<string, unknown> = {- name: row.name,- allowedHosts: hosts,- createdAt: new Date(row.created_at * 1000).toISOString(),- updatedAt: new Date(row.updated_at * 1000).toISOString(),- };- if (includeValue) {- const bytes = row.encrypted_value instanceof Uint8Array ? row.encrypted_value : new Uint8Array(row.encrypted_value);- out.encryptedValueB64 = btoa(String.fromCharCode(...bytes));- }- return out;-}--export async function setEntry(- req: Request,- env: SecretStoresEnv,- caller: Caller,- storeID: string,- name: string,-): Promise<Response> {- if (!name) return json({ error: "secret name required" }, 400);- const store = await loadStore(env, caller.orgID, storeID);- if (!store) return json({ error: "secret store not found" }, 404);-- const body = (await req.json().catch(() => null)) as { value?: string; allowedHosts?: string[] } | null;- if (!body || typeof body.value !== "string" || body.value === "") {- return json({ error: 'secret value required: {"value": "...", "allowedHosts": [...]}' }, 400);- }- const hosts = Array.isArray(body.allowedHosts) ? body.allowedHosts.map((h) => h.trim()) : [];- if (hosts.some((h) => h === "")) return json({ error: "allowedHosts entries cannot be empty" }, 400);-- const encrypted = await encryptSecret(env.SECRET_ENCRYPTION_KEY, body.value);- const now = Math.floor(Date.now() / 1000);- const id = crypto.randomUUID();- // UPSERT on (store_id, name).- await env.OPENCOMPUTER_DB.prepare(- `INSERT INTO secret_store_entries (id, store_id, name, encrypted_value, allowed_hosts, created_at, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)- ON CONFLICT(store_id, name) DO UPDATE SET- encrypted_value = excluded.encrypted_value,- allowed_hosts = excluded.allowed_hosts,- updated_at = excluded.updated_at`,- )- .bind(id, storeID, name, encrypted, JSON.stringify(hosts), now)- .run();-- // This used to fan the new value out to running sandboxes on every active- // cell. The cells are retired (097 step 7.2), so nothing is refreshed; the- // response keeps its shape for the CLI.- return json({ name, status: "set", refreshed: 0, cellsContacted: 0, failures: [] });-}--export async function deleteEntry(- _req: Request,- env: SecretStoresEnv,- caller: Caller,- storeID: string,- name: string,-): Promise<Response> {- const store = await loadStore(env, caller.orgID, storeID);- if (!store) return json({ error: "secret store not found" }, 404);- const res = await env.OPENCOMPUTER_DB.prepare(- `DELETE FROM secret_store_entries WHERE store_id = ?1 AND name = ?2`,- )- .bind(storeID, name)- .run();- if ((res.meta?.changes ?? 0) === 0) return json({ error: "secret entry not found" }, 404);- return new Response(null, { status: 204 });-}--export async function listEntries(- _req: Request,- env: SecretStoresEnv,- caller: Caller,- storeID: string,-): Promise<Response> {- const store = await loadStore(env, caller.orgID, storeID);- if (!store) return json({ error: "secret store not found" }, 404);- const { results } = await env.OPENCOMPUTER_DB.prepare(- `SELECT id, store_id, name, encrypted_value, allowed_hosts, created_at, updated_at- FROM secret_store_entries WHERE store_id = ?1 ORDER BY name ASC`,- )- .bind(storeID)- .all<EntryRow>();- // Never return plaintext or ciphertext on the user-facing route — names only.- return json((results ?? []).map((r) => entryToJSON(r, false)));-}diff --git a/cloudflare-workers/api-edge/src/webhooks.ts b/cloudflare-workers/api-edge/src/webhooks.tsdeleted file mode 100644index e303ce48..00000000--- a/cloudflare-workers/api-edge/src/webhooks.ts+++ /dev/null@@ -1,656 +0,0 @@-// Sandbox webhook management at the edge (all-Svix-at-edge). api-edge owns-// /api/webhooks CRUD + /test + /deliveries, backed by Svix Apps/Endpoints, with-// a small D1 index (webhook_destinations + orgs.has_webhooks). events-ingest does-// the delivery push. The CP never touches Svix; for inline-on-create it calls the-// HMAC-auth'd /internal/webhooks/register here.-// See .agents/work/sandbox-webhooks-rearchitecture.md §3-§4, §8.--import { SvixClient, SvixError, type EndpointParams } from "../../shared/svix";--export interface WebhookEnv {- OPENCOMPUTER_DB: D1Database;- SVIX_API_TOKEN: string;- EVENT_SECRET: string;-}--export interface Caller {- orgID: string;- userID: string | null;-}--// ── helpers ────────────────────────────────────────────────────────────────--function json(body: unknown, status = 200): Response {- return new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- });-}--function randomHex(nBytes: number): string {- return [...crypto.getRandomValues(new Uint8Array(nBytes))]- .map((b) => b.toString(16).padStart(2, "0"))- .join("");-}--const nowSec = (): number => Math.floor(Date.now() / 1000);--function svix(env: WebhookEnv): SvixClient | null {- if (!env.SVIX_API_TOKEN) return null;- return new SvixClient(env.SVIX_API_TOKEN);-}--// Map a SvixError to our public {error}+status; default 502 for upstream faults.-function svixErrorResponse(e: unknown): Response {- if (e instanceof SvixError) {- // 4xx from Svix (bad input) → surface as 400; upstream/transient → 502.- const status = e.status >= 400 && e.status < 500 ? 400 : 502;- return json({ error: `webhook provider error: ${e.message}` }, status);- }- return json({ error: e instanceof Error ? e.message : "internal error" }, 500);-}--interface DestRow {- id: string;- org_id: string;- svix_app_id: string;- svix_endpoint_id: string;- url: string;- event_types: string;- sandbox_id: string | null;- name: string | null;- disabled: number;- created_at: number;- updated_at: number;- deleted_at: number | null;-}--function toWire(r: DestRow): Record<string, unknown> {- let eventTypes: string[] = [];- try {- eventTypes = JSON.parse(r.event_types || "[]");- } catch {- eventTypes = [];- }- return {- id: r.id,- url: r.url,- eventTypes,- sandboxId: r.sandbox_id,- name: r.name,- enabled: r.disabled === 0,- hasSecret: true, // Svix always generates a signing secret- createdAt: new Date(r.created_at * 1000).toISOString(),- updatedAt: new Date(r.updated_at * 1000).toISOString(),- };-}--async function getDest(env: WebhookEnv, orgID: string, id: string): Promise<DestRow | null> {- return env.OPENCOMPUTER_DB.prepare(- "SELECT * FROM webhook_destinations WHERE id = ?1 AND org_id = ?2 AND deleted_at IS NULL",- )- .bind(id, orgID)- .first<DestRow>();-}--// Refresh orgs.has_webhooks from the live destination count (the events-ingest-// dormancy gate). Called after create/delete.-async function refreshHasWebhooks(env: WebhookEnv, orgID: string): Promise<void> {- const row = await env.OPENCOMPUTER_DB.prepare(- "SELECT COUNT(*) AS n FROM webhook_destinations WHERE org_id = ?1 AND deleted_at IS NULL",- )- .bind(orgID)- .first<{ n: number }>();- const has = (row?.n ?? 0) > 0 ? 1 : 0;- await env.OPENCOMPUTER_DB.prepare("UPDATE orgs SET has_webhooks = ?1 WHERE id = ?2")- .bind(has, orgID)- .run();-}--function isHttpsURL(u: unknown): u is string {- if (typeof u !== "string") return false;- try {- return new URL(u).protocol === "https:";- } catch {- return false;- }-}--// The concrete sandbox lifecycle event types. Svix filterTypes are exact (no-// wildcards) and must be registered before use — keep in sync with the docs/SDK.-const SANDBOX_EVENT_TYPES = [- "sandbox.created",- "sandbox.ready",- "sandbox.hibernated",- "sandbox.resumed",- "sandbox.stopped",- "sandbox.migrated",- "sandbox.checkpoint.created",- "sandbox.forked",- "sandbox.scaled",- "sandbox.preview_url.changed",-];--// invalidEventTypes returns the requested filters that aren't part of the fixed-// sandbox taxonomy (after accounting for "prefix.*" wildcards). Registration-// rejects these up front (400) rather than silently registering a type that can-// never fire — and it keeps us from polluting the Svix account with arbitrary-// event types. Empty/undefined ("all types") is always valid.-function invalidEventTypes(filters?: string[] | null): string[] {- if (!filters || filters.length === 0) return [];- const known = new Set(SANDBOX_EVENT_TYPES);- const bad: string[] = [];- for (const f of filters) {- if (f.endsWith(".*")) {- const prefix = f.slice(0, -1); // keep the trailing "."- if (!SANDBOX_EVENT_TYPES.some((t) => t.startsWith(prefix))) bad.push(f);- } else if (!known.has(f)) {- bad.push(f);- }- }- return bad;-}--// expandEventTypes turns a user filter (which may use "prefix.*", e.g. "sandbox.*")-// into concrete Svix filterTypes. undefined / empty → no filter (all types).-function expandEventTypes(filters?: string[] | null): string[] | undefined {- if (!filters || filters.length === 0) return undefined;- const out = new Set<string>();- for (const f of filters) {- if (f.endsWith(".*")) {- const prefix = f.slice(0, -1); // keep the trailing "."- for (const t of SANDBOX_EVENT_TYPES) if (t.startsWith(prefix)) out.add(t);- } else {- out.add(f);- }- }- return out.size ? [...out] : undefined;-}--// Create a Svix endpoint for (org, optional sandbox) + persist the index row.-// Shared by POST /api/webhooks and the inline-create internal endpoint.-async function createDestination(- env: WebhookEnv,- sx: SvixClient,- orgID: string,- spec: { url: string; eventTypes?: string[]; sandboxId?: string | null; name?: string | null; secret?: string; metadata?: Record<string, string>; enabled?: boolean },-): Promise<{ wire: Record<string, unknown>; secret: string }> {- const app = await sx.ensureApplication(orgID, `org:${orgID}`);- // Svix filterTypes are exact + must exist: expand wildcards and register each.- const filterTypes = expandEventTypes(spec.eventTypes);- if (filterTypes) await Promise.all(filterTypes.map((t) => sx.ensureEventType(t)));-- const epParams: EndpointParams = { url: spec.url };- if (spec.name) epParams.description = spec.name;- if (filterTypes) epParams.filterTypes = filterTypes;- if (spec.sandboxId) epParams.channels = [spec.sandboxId];- if (spec.secret) epParams.secret = spec.secret;- if (spec.enabled === false) epParams.disabled = true;- const ep = await sx.createEndpoint(app.id, epParams);- if (spec.metadata && Object.keys(spec.metadata).length) {- await sx.setEndpointHeaders(app.id, ep.id, spec.metadata);- }- const secret = spec.secret ?? (await sx.getEndpointSecret(app.id, ep.id));-- const id = "whk_" + randomHex(12);- const ts = nowSec();- const disabled = spec.enabled === false ? 1 : 0;- try {- await env.OPENCOMPUTER_DB.prepare(- `INSERT INTO webhook_destinations- (id, org_id, svix_app_id, svix_endpoint_id, url, event_types, sandbox_id, name, disabled, created_at, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)`,- )- .bind(id, orgID, app.id, ep.id, spec.url, JSON.stringify(spec.eventTypes ?? []), spec.sandboxId ?? null, spec.name ?? null, disabled, ts)- .run();- } catch (e) {- // Roll back the Svix endpoint so a D1 failure doesn't leave an orphan.- await sx.deleteEndpoint(app.id, ep.id).catch(() => {});- throw e;- }- await refreshHasWebhooks(env, orgID);-- return {- // Same shape as toWire (list/get) + the one-time secret, so create/list/get- // are consistent (hasSecret + updatedAt included).- wire: {- id,- url: spec.url,- eventTypes: spec.eventTypes ?? [],- sandboxId: spec.sandboxId ?? null,- name: spec.name ?? null,- enabled: disabled === 0,- hasSecret: true,- createdAt: new Date(ts * 1000).toISOString(),- updatedAt: new Date(ts * 1000).toISOString(),- },- secret,- };-}--// ── public API: /api/webhooks* ───────────────────────────────────────────────--// handleWebhooksAPI dispatches an authenticated /api/webhooks* request. Returns-// a Response (the caller has already authenticated and matched the path prefix).-export async function handleWebhooksAPI(- req: Request,- env: WebhookEnv,- caller: Caller,- url: URL,-): Promise<Response> {- const sx = svix(env);- if (!sx) return json({ error: "webhooks are not configured on this deployment" }, 503);-- // Path after "/api/webhooks": "", "/:id", "/:id/test", "/:id/deliveries",- // "/:id/deliveries/:deliveryId", "/:id/deliveries/:deliveryId/redeliver".- const rest = url.pathname.replace(/^\/api\/webhooks/, "").replace(/^\//, "");- const seg = rest === "" ? [] : rest.split("/");- const method = req.method;-- try {- // /api/webhooks- if (seg.length === 0) {- if (method === "POST") return await createWebhook(req, env, sx, caller);- if (method === "GET") return await listWebhooks(env, caller);- return json({ error: "method not allowed" }, 405);- }-- const id = seg[0];-- // /api/webhooks/:id- if (seg.length === 1) {- if (method === "GET") {- const row = await getDest(env, caller.orgID, id);- return row ? json(toWire(row)) : json({ error: "webhook not found" }, 404);- }- if (method === "PATCH") return await patchWebhook(req, env, sx, caller, id);- if (method === "DELETE") return await deleteWebhook(env, sx, caller, id);- return json({ error: "method not allowed" }, 405);- }-- // /api/webhooks/:id/test- if (seg.length === 2 && seg[1] === "test" && method === "POST") {- return await testWebhook(env, sx, caller, id);- }-- // /api/webhooks/:id/secret — reveal the current signing secret (owner only,- // already authenticated by API key). Re-fetchable any time, like Svix's- // App Portal; rotation is PATCH {rotateSecret:true}.- if (seg.length === 2 && seg[1] === "secret" && method === "GET") {- return await getSecretWebhook(env, sx, caller, id);- }-- // /api/webhooks/:id/deliveries- if (seg.length === 2 && seg[1] === "deliveries" && method === "GET") {- return await listDeliveries(env, sx, caller, id);- }-- // /api/webhooks/:id/deliveries/:deliveryId- if (seg.length === 3 && seg[1] === "deliveries" && method === "GET") {- return await getDelivery(env, sx, caller, id, seg[2]);- }-- // /api/webhooks/:id/deliveries/:deliveryId/redeliver- if (seg.length === 4 && seg[1] === "deliveries" && seg[3] === "redeliver" && method === "POST") {- return await redeliver(env, sx, caller, id, seg[2]);- }-- return json({ error: "not found" }, 404);- } catch (e) {- return svixErrorResponse(e);- }-}--async function createWebhook(req: Request, env: WebhookEnv, sx: SvixClient, caller: Caller): Promise<Response> {- // Read the raw body once: needed both to parse and to fingerprint for idempotency.- const rawBody = await req.text();- let body: {- url?: string;- eventTypes?: string[];- sandboxId?: string;- name?: string;- metadata?: Record<string, string>;- secret?: string;- enabled?: boolean;- };- try {- body = rawBody ? JSON.parse(rawBody) : {};- } catch {- return json({ error: "invalid JSON body" }, 400);- }- if (!isHttpsURL(body.url)) return json({ error: "url must be a valid https URL" }, 400);- const badTypes = invalidEventTypes(body.eventTypes);- if (badTypes.length) {- return json({ error: `unknown event type(s): ${badTypes.join(", ")}` }, 400);- }-- // Idempotency: a retried create with the same Idempotency-Key returns the same- // destination (200) instead of a duplicate. Reusing a key with a DIFFERENT body- // is a client error → 409 (we fingerprint the request body). Fast path first.- const idemKey = req.headers.get("Idempotency-Key") ?? undefined;- const reqHash = idemKey ? await sha256Hex(rawBody) : undefined;- if (idemKey) {- const prior = await env.OPENCOMPUTER_DB.prepare(- "SELECT destination_id, request_hash FROM webhook_idempotency WHERE org_id = ?1 AND idempotency_key = ?2",- )- .bind(caller.orgID, idemKey)- .first<{ destination_id: string; request_hash: string | null }>();- if (prior) {- if (prior.request_hash && prior.request_hash !== reqHash) {- return json({ error: "Idempotency-Key already used with a different request body" }, 409);- }- return idempotentReplay(env, sx, caller, prior.destination_id);- }- }-- const { wire, secret } = await createDestination(env, sx, caller.orgID, {- url: body.url,- eventTypes: body.eventTypes,- sandboxId: body.sandboxId ?? null,- name: body.name ?? null,- metadata: body.metadata,- secret: body.secret,- enabled: body.enabled,- });-- if (idemKey) {- // Claim the key atomically (PK conflict = a concurrent create already won).- await env.OPENCOMPUTER_DB.prepare(- "INSERT INTO webhook_idempotency (org_id, idempotency_key, destination_id, request_hash, created_at) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(org_id, idempotency_key) DO NOTHING",- )- .bind(caller.orgID, idemKey, wire.id, reqHash ?? null, nowSec())- .run();- const winner = await env.OPENCOMPUTER_DB.prepare(- "SELECT destination_id, request_hash FROM webhook_idempotency WHERE org_id = ?1 AND idempotency_key = ?2",- )- .bind(caller.orgID, idemKey)- .first<{ destination_id: string; request_hash: string | null }>();- if (winner && winner.destination_id !== wire.id) {- // Lost a concurrent race — drop our just-created duplicate.- await deleteDestinationById(env, sx, caller.orgID, wire.id as string);- if (winner.request_hash && winner.request_hash !== reqHash) {- return json({ error: "Idempotency-Key already used with a different request body" }, 409);- }- return idempotentReplay(env, sx, caller, winner.destination_id);- }- }- // Secret is returned on create (Svix-generated unless supplied; re-fetchable via GET /:id/secret).- return json({ ...wire, secret }, 201);-}--// sha256Hex — request-body fingerprint for Idempotency-Key conflict detection.-async function sha256Hex(s: string): Promise<string> {- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s));- return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");-}--// idempotentReplay returns an existing destination + its (re-fetched) signing-// secret with 200 — the response to a retried idempotent create.-async function idempotentReplay(env: WebhookEnv, sx: SvixClient, caller: Caller, destId: string): Promise<Response> {- const row = await getDest(env, caller.orgID, destId);- if (!row) return json({ error: "webhook not found" }, 404); // tombstoned/cross-org — shouldn't happen- let secret: string | undefined;- try {- secret = await sx.getEndpointSecret(row.svix_app_id, row.svix_endpoint_id);- } catch {- /* best-effort: omit secret, it's re-fetchable via GET /:id/secret */- }- return json(secret ? { ...toWire(row), secret } : toWire(row), 200);-}--// deleteDestinationById removes the Svix endpoint + soft-deletes the row. Used to-// clean up the loser of a concurrent idempotent-create race.-async function deleteDestinationById(env: WebhookEnv, sx: SvixClient, orgID: string, id: string): Promise<void> {- const row = await getDest(env, orgID, id);- if (!row) return;- try {- await sx.deleteEndpoint(row.svix_app_id, row.svix_endpoint_id);- } catch {- /* best-effort */- }- await env.OPENCOMPUTER_DB.prepare("UPDATE webhook_destinations SET deleted_at = ?1 WHERE id = ?2")- .bind(nowSec(), id)- .run();- await refreshHasWebhooks(env, orgID);-}--async function listWebhooks(env: WebhookEnv, caller: Caller): Promise<Response> {- const rows = await env.OPENCOMPUTER_DB.prepare(- "SELECT * FROM webhook_destinations WHERE org_id = ?1 AND deleted_at IS NULL ORDER BY created_at DESC",- )- .bind(caller.orgID)- .all<DestRow>();- return json({ data: (rows.results ?? []).map(toWire) });-}--async function patchWebhook(req: Request, env: WebhookEnv, sx: SvixClient, caller: Caller, id: string): Promise<Response> {- const row = await getDest(env, caller.orgID, id);- if (!row) return json({ error: "webhook not found" }, 404);- let body: { url?: string; eventTypes?: string[] | null; enabled?: boolean; name?: string; rotateSecret?: boolean };- try {- body = await req.json();- } catch {- return json({ error: "invalid JSON body" }, 400);- }- if (body.url !== undefined && !isHttpsURL(body.url)) return json({ error: "url must be a valid https URL" }, 400);- if (body.eventTypes) {- const badTypes = invalidEventTypes(body.eventTypes);- if (badTypes.length) return json({ error: `unknown event type(s): ${badTypes.join(", ")}` }, 400);- }-- // Index filter (original strings): null clears it, undefined keeps the stored- // one. The Svix endpoint gets the expanded + registered concrete types.- let originalTypes: string[];- if (body.eventTypes === null) originalTypes = [];- else if (body.eventTypes !== undefined) originalTypes = body.eventTypes;- else {- try {- originalTypes = JSON.parse(row.event_types || "[]");- } catch {- originalTypes = [];- }- }- const filterTypes = expandEventTypes(originalTypes);- if (filterTypes) await Promise.all(filterTypes.map((t) => sx.ensureEventType(t)));-- // updateEndpoint is a full PUT replace — send the complete desired state so- // untouched fields (enabled, name, scope) aren't reset.- const disabledNum = body.enabled !== undefined ? (body.enabled ? 0 : 1) : row.disabled;- const newName = body.name !== undefined ? body.name : row.name;- const ep: EndpointParams = { url: body.url ?? row.url, disabled: disabledNum === 1 };- if (filterTypes) ep.filterTypes = filterTypes; // omit → all types- if (row.sandbox_id) ep.channels = [row.sandbox_id];- if (newName) ep.description = newName;-- await sx.updateEndpoint(row.svix_app_id, row.svix_endpoint_id, ep);-- // Optional secret rotation. Svix keeps the old secret valid for a rollover- // window, so in-flight deliveries still verify against the previous secret.- let rotatedSecret: string | undefined;- if (body.rotateSecret) {- rotatedSecret = await sx.rotateEndpointSecret(row.svix_app_id, row.svix_endpoint_id);- }-- await env.OPENCOMPUTER_DB.prepare(- "UPDATE webhook_destinations SET url = ?1, event_types = ?2, name = ?3, disabled = ?4, updated_at = ?5 WHERE id = ?6",- )- .bind(ep.url, JSON.stringify(originalTypes), newName, disabledNum, nowSec(), id)- .run();-- const updated = await getDest(env, caller.orgID, id);- if (!updated) return json({ error: "webhook not found" }, 404);- // Return the new secret once, on rotation only (the GET /secret route can- // re-fetch it later).- return json(rotatedSecret ? { ...toWire(updated), secret: rotatedSecret } : toWire(updated));-}--async function deleteWebhook(env: WebhookEnv, sx: SvixClient, caller: Caller, id: string): Promise<Response> {- const row = await getDest(env, caller.orgID, id);- if (!row) return json({ error: "webhook not found" }, 404);- try {- await sx.deleteEndpoint(row.svix_app_id, row.svix_endpoint_id);- } catch (e) {- // If the Svix endpoint is already gone, proceed to tombstone locally.- if (!(e instanceof SvixError) || e.status !== 404) throw e;- }- await env.OPENCOMPUTER_DB.prepare("UPDATE webhook_destinations SET deleted_at = ?1 WHERE id = ?2")- .bind(nowSec(), id)- .run();- await refreshHasWebhooks(env, caller.orgID);- return new Response(null, { status: 204 });-}--async function testWebhook(env: WebhookEnv, sx: SvixClient, caller: Caller, id: string): Promise<Response> {- const row = await getDest(env, caller.orgID, id);- if (!row) return json({ error: "webhook not found" }, 404);- // Pick a concrete type the endpoint will accept (expand any wildcard filter).- let stored: string[] = [];- try {- stored = JSON.parse(row.event_types || "[]");- } catch {- /* none */- }- const expanded = expandEventTypes(stored);- const eventType = expanded && expanded.length ? expanded[0] : "sandbox.created";- const sandboxId = row.sandbox_id ?? "sb-test";- const eventId = `test.${id}.${randomHex(6)}`;- // Send the REAL delivered envelope (the WebhookDelivery<SandboxLifecycleEvent>- // shape verifyWebhook returns), marked with data.test=true, so a consumer- // exercises its actual parser — not a reduced synthetic body.- const msg = await sx.createMessage(row.svix_app_id, {- eventType,- payload: {- type: eventType,- sandboxId,- eventId,- event: {- id: eventId,- ts: new Date().toISOString(),- orgId: caller.orgID,- sandboxId,- type: eventType,- data: { test: true },- },- },- eventId,- channels: row.sandbox_id ? [row.sandbox_id] : undefined,- });- return json({ ok: true, eventType, messageId: msg.id });-}--async function getSecretWebhook(env: WebhookEnv, sx: SvixClient, caller: Caller, id: string): Promise<Response> {- const row = await getDest(env, caller.orgID, id);- if (!row) return json({ error: "webhook not found" }, 404);- const secret = await sx.getEndpointSecret(row.svix_app_id, row.svix_endpoint_id);- return json({ secret });-}--async function listDeliveries(env: WebhookEnv, sx: SvixClient, caller: Caller, id: string): Promise<Response> {- const row = await getDest(env, caller.orgID, id);- if (!row) return json({ error: "webhook not found" }, 404);- const attempts = await sx.listEndpointAttempts(row.svix_app_id, row.svix_endpoint_id, 50);- const data = attempts.map((a) => ({- id: a.msgId, // the redeliver/get key- attemptId: a.id,- status: a.status === 0 ? "success" : a.status === 1 ? "pending" : "failed",- responseStatusCode: a.responseStatusCode,- timestamp: a.timestamp,- }));- return json({ data });-}--async function getDelivery(env: WebhookEnv, sx: SvixClient, caller: Caller, id: string, deliveryID: string): Promise<Response> {- const row = await getDest(env, caller.orgID, id);- if (!row) return json({ error: "webhook not found" }, 404);- const msg = await sx.getMessage(row.svix_app_id, deliveryID);- return json({- id: msg.id,- eventType: msg.eventType,- eventId: msg.eventId,- payload: msg.payload,- timestamp: msg.timestamp,- });-}--async function redeliver(env: WebhookEnv, sx: SvixClient, caller: Caller, id: string, deliveryID: string): Promise<Response> {- const row = await getDest(env, caller.orgID, id);- if (!row) return json({ error: "webhook not found" }, 404);- await sx.resendMessage(row.svix_app_id, deliveryID, row.svix_endpoint_id);- return json({ ok: true });-}--// ── internal: inline-on-create registration (CP → edge, HMAC-auth'd) ─────────--async function hmacHex(secret: string, data: string): Promise<string> {- const key = await crypto.subtle.importKey(- "raw",- new TextEncoder().encode(secret),- { name: "HMAC", hash: "SHA-256" },- false,- ["sign"],- );- const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data));- return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");-}--function constantTimeEqual(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;-}--// registerInlineWebhooksInternal handles POST /internal/webhooks/register, called-// by the CP at sandbox-create time (before the sandbox emits `created`). HMAC over-// {ts}.{path}{query}.{body} with EVENT_SECRET, ±5min — same scheme as the other-// /internal POST endpoints. Body: {orgId, sandboxId, webhooks:[{url,eventTypes?,secret?}]}.-export async function registerInlineWebhooksInternal(req: Request, env: WebhookEnv, url: URL): Promise<Response> {- const sx = svix(env);- if (!sx) return json({ error: "webhooks are not configured" }, 503);-- const ts = req.headers.get("X-Timestamp") ?? "";- const sig = req.headers.get("X-Signature") ?? "";- if (!ts || !sig) return json({ error: "missing signature" }, 400);- const tsNum = Number.parseInt(ts, 10);- if (!Number.isFinite(tsNum) || Math.abs(nowSec() - tsNum) > 5 * 60) {- return json({ error: "timestamp out of window" }, 401);- }- const rawBody = await req.text();- const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}.${rawBody}`);- if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);-- let body: { orgId?: string; sandboxId?: string; webhooks?: Array<{ url: string; eventTypes?: string[]; secret?: string }> };- try {- body = JSON.parse(rawBody);- } catch {- return json({ error: "invalid JSON body" }, 400);- }- if (!body.orgId || !body.sandboxId || !Array.isArray(body.webhooks)) {- return json({ error: "orgId, sandboxId, webhooks required" }, 400);- }-- const out: Array<{ id: string; url: string; secret?: string }> = [];- for (const spec of body.webhooks) {- // best-effort: skip structurally-invalid specs (the CP also validates these- // up front, so this is a defense-in-depth guard, not the primary check).- if (!isHttpsURL(spec.url)) continue;- const badTypes = invalidEventTypes(spec.eventTypes);- if (badTypes.length) {- console.error(`registerInlineWebhooks: ${body.sandboxId}: skipping spec with unknown event type(s): ${badTypes.join(", ")}`);- continue;- }- try {- const { wire, secret } = await createDestination(env, sx, body.orgId, {- url: spec.url,- eventTypes: spec.eventTypes,- sandboxId: body.sandboxId,- secret: spec.secret,- });- // Return the secret only when Svix generated it (caller didn't supply one).- out.push({ id: wire.id as string, url: spec.url, ...(spec.secret ? {} : { secret }) });- } catch (e) {- console.error(`registerInlineWebhooks: ${body.sandboxId}: ${e instanceof Error ? e.message : e}`);- }- }- return json({ webhooks: out });-}diff --git a/cloudflare-workers/api-edge/wrangler.igor-dev.toml b/cloudflare-workers/api-edge/wrangler.igor-dev.tomlindex 32720003..8d372683 100644--- a/cloudflare-workers/api-edge/wrangler.igor-dev.toml+++ b/cloudflare-workers/api-edge/wrangler.igor-dev.toml@@ -1,7 +1,7 @@# api-edge — `igor-dev` personal dev edge in **Mo's CF account (b8f23cb8)**.# A prod-mirror of the api-edge Worker sitting in front of Igor's GCP dev box:# one worker that serves the dashboard SPA from [assets] AND handles /auth-# (WorkOS) + /api/dashboard (edge-native, read from D1) + /api/webhooks — the+# (WorkOS) + /api/dashboard (edge-native, read from D1) — the# same code path as prod's single edge.## Differs from prod: no public routes (uses the workers.dev URL), no autumn@@ -19,7 +19,7 @@# WORKOS_API_KEY, WORKOS_CLIENT_ID — staging WorkOS (same app as the dev box)# SESSION_JWT_SECRET — signs oc_session; must == the box's# OPENSANDBOX_SESSION_JWT_SECRET to wire it as a cell-# EVENT_SECRET, SVIX_API_TOKEN — webhooks e2e (PR #410), optional+# EVENT_SECRET — /internal/* HMAC, optional# WorkOS dashboard (staging env): allowlist https://<worker>.workers.dev/auth/callback# and set it as the Sign-out redirect.diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex 52a941c3..10ef4c94 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -116,9 +116,7 @@ deleted_classes = ["VmSession"]# STRIPE_API_KEY — Stripe LIVE mode API key (sk_live_...)# WORKOS_API_KEY — prod WorkOS app API key# WORKOS_CLIENT_ID — prod WorkOS client identifier-# EVENT_SECRET — fresh prod HMAC for /internal/autumn-* and-# /internal/webhooks/* callers-# SECRET_ENCRYPTION_KEY — envelope-encryption key for D1 secret_store_entries+# EVENT_SECRET — fresh prod HMAC for /internal/autumn-* callers# OPENROUTER_PROVISIONING_KEY — OpenRouter MANAGEMENT/provisioning key (mints# per-org inference keys + reads analytics). Token# billing dormant until this is set. (token-billing.md)diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex 2b235fa3..e9c90e3d 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -115,7 +115,7 @@ deleted_classes = ["VmSession"]# STRIPE_API_KEY — for creating Stripe customer + subscription on /mark-pro# WORKOS_API_KEY — server-side WorkOS API for /auth/login# WORKOS_CLIENT_ID — WorkOS client identifier-# EVENT_SECRET — HMAC for /internal/autumn-* and /internal/webhooks/* callers+# EVENT_SECRET — HMAC for /internal/autumn-* callers# OPENROUTER_PROVISIONING_KEY — OpenRouter MANAGEMENT/provisioning key (token# billing; mints per-org keys + reads analytics). Dormant# until set. See .agents/work/token-billing.md.