An open-source, faster Devin alternative
TypeScript
fix(webhooks): reconcile impl with the documented contract (review round 3)
Igor Zalutskifad367a826b5
diff --git a/cloudflare-workers/api-edge/src/webhooks.ts b/cloudflare-workers/api-edge/src/webhooks.tsindex 8f850c5d..b5b5b24f 100644--- a/cloudflare-workers/api-edge/src/webhooks.ts+++ b/cloudflare-workers/api-edge/src/webhooks.ts@@ -131,6 +131,26 @@ const SANDBOX_EVENT_TYPES = ["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 {@@ -249,6 +269,13 @@ export async function handleWebhooksAPI(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/deliveriesif (seg.length === 2 && seg[1] === "deliveries" && method === "GET") {return await listDeliveries(env, sx, caller, id);@@ -286,6 +313,10 @@ async function createWebhook(req: Request, env: WebhookEnv, sx: SvixClient, callreturn 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);+ }const { wire, secret } = await createDestination(env, sx, caller.orgID, {url: body.url,@@ -312,13 +343,17 @@ async function listWebhooks(env: WebhookEnv, caller: Caller): Promise<Response>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 };+ 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.@@ -346,6 +381,13 @@ async function patchWebhook(req: Request, env: WebhookEnv, sx: SvixClient, calleawait 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",)@@ -353,7 +395,10 @@ async function patchWebhook(req: Request, env: WebhookEnv, sx: SvixClient, calle.run();const updated = await getDest(env, caller.orgID, id);- return updated ? json(toWire(updated)) : json({ error: "webhook not found" }, 404);+ 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> {@@ -393,6 +438,13 @@ async function testWebhook(env: WebhookEnv, sx: SvixClient, caller: Caller, id: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);@@ -479,7 +531,14 @@ export async function registerInlineWebhooksInternal(req: Request, env: WebhookEconst out: Array<{ id: string; url: string; secret?: string }> = [];for (const spec of body.webhooks) {- if (!isHttpsURL(spec.url)) continue; // best-effort: skip invalid, like the shipped path+ // 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,diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.tsindex 2716d90f..fdcd2248 100644--- a/cloudflare-workers/events-ingest/src/index.ts+++ b/cloudflare-workers/events-ingest/src/index.ts@@ -499,28 +499,35 @@ export default {// transient Svix error → 503 so the CP forwarder retries the batch (the// event id is the Idempotency-Key, so re-sends dedupe); a permanent (4xx)// error for one event is logged and skipped. (rearchitecture §3.1)- if (!env.SVIX_API_TOKEN) {- // Misconfiguration guard: api-edge can register webhooks while this Worker- // silently drops deliveries if the token is only set on one side.- if (fresh.some((e) => e.type.startsWith("sandbox."))) {- console.warn("events-ingest: SVIX_API_TOKEN unset — sandbox webhook events are NOT being delivered to Svix");+ const webhookEvents = fresh.filter(+ (e) => e.type.startsWith("sandbox.") && e.org_id && e.sandbox_id,+ );+ if (webhookEvents.length > 0) {+ const whOrgIds = [...new Set(webhookEvents.map((e) => e.org_id as string))];+ let hasWebhooks: Set<string>;+ try {+ hasWebhooks = await fetchHasWebhooks(env, whOrgIds);+ } catch (err) {+ console.error("events-ingest: has_webhooks lookup failed", err);+ return jsonResponse({ error: "webhook org lookup failed" }, 503);}- } else {- const webhookEvents = fresh.filter(- (e) => e.type.startsWith("sandbox.") && e.org_id && e.sandbox_id,- );- if (webhookEvents.length > 0) {- const whOrgIds = [...new Set(webhookEvents.map((e) => e.org_id as string))];- let hasWebhooks: Set<string>;- try {- hasWebhooks = await fetchHasWebhooks(env, whOrgIds);- } catch (err) {- console.error("events-ingest: has_webhooks lookup failed", err);- return jsonResponse({ error: "webhook org lookup failed" }, 503);+ // Only orgs with a registered destination are eligible (dormancy gate);+ // dormant orgs cost zero Svix calls.+ const eligible = webhookEvents.filter((e) => hasWebhooks.has(e.org_id as string));+ if (eligible.length > 0) {+ // Fail closed: webhook-eligible events but no Svix token on this Worker.+ // api-edge can register destinations (which sets has_webhooks) while this+ // Worker's token is unset — silently 202-ing here would be "configured+ // management, dead delivery" and lose the events. 503 instead so the CP+ // forwarder keeps the batch in its PEL and retries once the token is set.+ if (!env.SVIX_API_TOKEN) {+ console.error(+ `events-ingest: SVIX_API_TOKEN unset but ${eligible.length} webhook-eligible event(s) present — returning 503 so the forwarder retries (set the token to recover)`,+ );+ return jsonResponse({ error: "webhook delivery not configured" }, 503);}const sx = new SvixClient(env.SVIX_API_TOKEN);- for (const e of webhookEvents) {- if (!hasWebhooks.has(e.org_id as string)) continue; // dormant org+ for (const e of eligible) {try {await sx.createMessage(e.org_id as string, {eventType: e.type,diff --git a/cloudflare-workers/shared/svix.ts b/cloudflare-workers/shared/svix.tsindex 9c3b3cde..16b53310 100644--- a/cloudflare-workers/shared/svix.ts+++ b/cloudflare-workers/shared/svix.ts@@ -159,6 +159,20 @@ export class SvixClient {return out.key;}+ // Rotate the endpoint's signing secret. Pass `key` to set a specific secret+ // (whsec_…); omit to have Svix generate one. Svix keeps the old secret valid+ // for a rollover window so in-flight deliveries still verify. Returns the new+ // current secret (re-fetched, since the rotate call itself returns no body).+ async rotateEndpointSecret(appID: string, epID: string, key?: string): Promise<string> {+ await this.do(+ "rotate_endpoint_secret",+ "POST",+ `/api/v1/app/${appID}/endpoint/${epID}/secret/rotate/`,+ key ? { key } : {},+ );+ return this.getEndpointSecret(appID, epID);+ }+// Custom headers delivered on every request to the endpoint — how// per-destination registration metadata rides each delivery.async setEndpointHeaders(appID: string, epID: string, headers: Record<string, string>): Promise<void> {diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 2692965a..6328c48e 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -642,10 +642,10 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty// session row, which must exist before the worker looks it up.sandboxID := "sb-" + uuid.New().String()[:8]- // Register inline webhooks at the edge (Svix) BEFORE the session is created- // (CreateSandboxSessionWithStatus records sandbox.created) and before the- // worker boots, so the endpoint exists before `created` is relayed. Cleaned up- // below if the gRPC create fails.+ // Register inline webhooks at the edge (Svix) BEFORE the session row and the+ // worker boot, so the endpoint exists well before `created` is relayed. On+ // this remote path `created` is emitted only at the pending→running promotion+ // (i.e. on successful create), so a failed create relays no `created` at all.var inlineWebhooks []types.SandboxWebhookResultif hasOrg && len(cfg.Webhooks) > 0 {inlineWebhooks = s.registerInlineWebhooksEdge(ctx, orgID, sandboxID, cfg.Webhooks)diff --git a/internal/db/store.go b/internal/db/store.goindex 5f8a8fb6..ce1c0d73 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -810,19 +810,26 @@ func (s *Store) CreateSandboxSessionWithStatus(ctx context.Context, sandboxID stif err != nil {return nil, fmt.Errorf("failed to create sandbox session: %w", err)}- // Record sandbox.created in-tx (deterministic id → at most one per sandbox).- // This is the single webhook source for `created`: the worker's stream- // "created" feeds D1 sandboxes_index, not webhooks. The edge applies the- // dormancy gate. (sandbox-webhooks-rearchitecture.md)- createdData, _ := json.Marshal(map[string]string{"template": template})- if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{- ID: sandboxID + ":sandbox.created",- OrgID: orgID,- SandboxID: sandboxID,- Type: "sandbox.created",- Data: createdData,- }); err != nil {- return nil, err+ // Record sandbox.created in-tx (deterministic id → at most one per sandbox),+ // but ONLY when the row is born already-created (status != "pending"). The+ // combined/local path inserts the session AFTER the worker has spawned, so+ // `created` is truthful here. The "pending" path (remote/fork: insert row →+ // gRPC create → promote to running) must NOT emit `created` at insert: the+ // create can still fail, and a consumer must never receive `created` for a+ // sandbox whose API create then errored. That path emits `created` at the+ // pending→running promotion (updateSandboxSessionStatus), so it fires only on+ // success. (sandbox-webhooks-rearchitecture.md)+ if status != "pending" {+ createdData, _ := json.Marshal(map[string]string{"template": template})+ if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{+ ID: sandboxID + ":sandbox.created",+ OrgID: orgID,+ SandboxID: sandboxID,+ Type: "sandbox.created",+ Data: createdData,+ }); err != nil {+ return nil, err+ }}if err := tx.Commit(ctx); err != nil {return nil, err@@ -898,8 +905,9 @@ func (s *Store) updateSandboxSessionStatus(ctx context.Context, sandboxID, statu// path, so this never doubles with the worker-origin `resumed`). Other// worker-origin events (created/resumed/migrated) arrive via the ingress.if affected && (terminal || status == "hibernated" || status == "running") {+ var template string_ = tx.QueryRow(ctx,- `SELECT org_id FROM sandbox_sessions WHERE sandbox_id = $1`, sandboxID).Scan(&orgID)+ `SELECT org_id, template FROM sandbox_sessions WHERE sandbox_id = $1`, sandboxID).Scan(&orgID, &template)if orgID != uuid.Nil {var evType, evID stringvar data json.RawMessage@@ -924,6 +932,23 @@ func (s *Store) updateSandboxSessionStatus(ctx context.Context, sandboxID, statuevType = "sandbox.hibernated"evID = fmt.Sprintf("%s:sandbox.hibernated:%d", sandboxID, n)case "running":+ // Pending→running promotion = the create actually succeeded, so+ // emit sandbox.created HERE for the remote/fork paths (which insert+ // the row as "pending" and DON'T emit created at insert). A consumer+ // therefore never sees `created` for a create that then failed.+ // Deterministic id → idempotent if the promote re-runs, and wake+ // takes a different code path so this only ever fires on first boot.+ // Recorded before `ready` below → smaller seq → relayed first.+ createdData, _ := json.Marshal(map[string]string{"template": template})+ if cerr := recordLifecycleEvent(ctx, tx, LifecycleEvent{+ ID: sandboxID + ":sandbox.created",+ OrgID: orgID,+ SandboxID: sandboxID,+ Type: "sandbox.created",+ Data: createdData,+ }); cerr != nil {+ return fmt.Errorf("record created event: %w", cerr)+ }// Boot promotion = ready. Deterministic id dedups a repeat// "running" update on an already-running row (idempotent promote).evType = "sandbox.ready"diff --git a/sdks/typescript/src/agents/webhooks.test.ts b/sdks/typescript/src/agents/webhooks.test.tsindex fc222d6b..32976821 100644--- a/sdks/typescript/src/agents/webhooks.test.ts+++ b/sdks/typescript/src/agents/webhooks.test.ts@@ -73,4 +73,28 @@ describe("verifyWebhook", () => {const delivery = await verifyWebhook(body, hdr(await sign(id, ts, body, raw)), raw, { nowSeconds: ts });expect(delivery.type).toBe("turn.completed");});++ it("sandbox dialect: deliveryId + dedupeId both come from svix-id", async () => {+ const svixId = "msg_svix_1";+ const sbBody = JSON.stringify({+ type: "sandbox.created", sandboxId: "sb_1", eventId: "sb_1:sandbox.created",+ event: { id: "sb_1:sandbox.created", type: "sandbox.created", data: {} },+ });+ const sig = await sign(svixId, ts, sbBody, SECRET);+ const headers = { "svix-id": svixId, "svix-timestamp": String(ts), "svix-signature": sig };+ const delivery = await verifyWebhook(sbBody, headers, SECRET, { nowSeconds: ts });+ expect(delivery.deliveryId).toBe(svixId);+ expect(delivery.dedupeId).toBe(svixId);+ });++ it("session dialect: deliveryId = X-OC-Delivery-ID, dedupeId = eventId (webhook-id is the eventId)", async () => {+ const sig = await sign(id, ts, body, SECRET); // id == eventId == "msg_1"+ const headers = {+ "webhook-id": id, "webhook-timestamp": String(ts), "webhook-signature": sig,+ "x-oc-delivery-id": "dlv_99",+ };+ const delivery = await verifyWebhook(body, headers, SECRET, { nowSeconds: ts });+ expect(delivery.deliveryId).toBe("dlv_99"); // the delivery-row id, NOT webhook-id+ expect(delivery.dedupeId).toBe("msg_1"); // eventId+ });});diff --git a/sdks/typescript/src/agents/webhooks.ts b/sdks/typescript/src/agents/webhooks.tsindex b4577703..e5e9f929 100644--- a/sdks/typescript/src/agents/webhooks.ts+++ b/sdks/typescript/src/agents/webhooks.ts@@ -31,10 +31,17 @@ export interface WebhookDelivery<E = Event> {/** The underlying event id — app-level correlation. */eventId: string;/**- * The delivery id, set by {@link verifyWebhook} from the `svix-id` (sandbox) / `webhook-id`- * (session) header — stable across retries and redelivery, so dedupe on it.+ * The delivery id, set by {@link verifyWebhook}. **Sandbox** webhooks: the Svix message id+ * (`svix-id`). **Session** webhooks: the delivery-row id (`X-OC-Delivery-ID` header) — note the+ * session `webhook-id` header is the *eventId*, not a delivery id, so it is NOT used here.*/deliveryId?: string;+ /**+ * The idempotency key to dedupe on — stable across retries and redelivery. **Sandbox**: the+ * Svix message id (`svix-id`). **Session**: the `eventId`. Prefer this over {@link deliveryId}+ * for "have I already processed this?" checks.+ */+ dedupeId?: string;/*** Opaque routing metadata. On **session** webhooks this is carried in the body. On **sandbox*** webhooks, per-destination metadata is delivered as custom HTTP **headers** (set at@@ -159,10 +166,22 @@ export async function verifyWebhook<E = Event>(try {// Normalize so the returned envelope + nested event match the SDK's camelCase types- // (the wire event is snake-cased, e.g. `turn_id`). Set deliveryId from the verified id- // header (svix-id / webhook-id) — stable across retries + redelivery; dedupe on it.+ // (the wire event is snake-cased, e.g. `turn_id`). The two products use different header+ // dialects + delivery-id ownership, so resolve deliveryId/dedupeId by dialect:+ // - Sandbox (Svix): `svix-id` is BOTH the stable delivery id and the dedupe key.+ // - Session: the signed `webhook-id` is the *eventId* (dedupe on it); the delivery-row id+ // rides separately in `X-OC-Delivery-ID`.const delivery = normalize(JSON.parse(rawBody)) as WebhookDelivery<E>;- if (delivery.deliveryId == null) delivery.deliveryId = id;+ const svixId = header(headers, "svix-id");+ if (svixId) {+ delivery.deliveryId = svixId;+ delivery.dedupeId = svixId;+ } else {+ const deliveryRowId = header(headers, "x-oc-delivery-id");+ if (deliveryRowId) delivery.deliveryId = deliveryRowId;+ // webhook-id == eventId for sessions; prefer the body's eventId, fall back to the header.+ delivery.dedupeId = delivery.eventId ?? id;+ }return delivery;} catch {throw new WebhookVerificationError("signature valid but body is not JSON");diff --git a/sdks/typescript/src/webhooks.ts b/sdks/typescript/src/webhooks.tsindex 29ccecf3..967b4473 100644--- a/sdks/typescript/src/webhooks.ts+++ b/sdks/typescript/src/webhooks.ts@@ -2,15 +2,16 @@//// PREVIEW: newly available functionality; the surface may change.//-// Register a destination and OpenComputer delivers sandbox lifecycle events to it as a-// small, signed envelope — at-least-once, retried, dead-lettered, and redeliverable. This is-// the management client (org API key, server-side); to VERIFY an incoming delivery in your-// handler use `verifyWebhook` (exported from the package root, shared with session webhooks).+// Register a destination and OpenComputer delivers sandbox lifecycle events to it as a small,+// signed envelope — at-least-once, retried with managed backoff, and redeliverable (delivery is+// handled by Svix). This is the management client (org API key, server-side); to VERIFY an+// incoming delivery in your handler use `verifyWebhook` (exported from the package root, shared+// with session webhooks).//// import { Webhooks } from "@opencomputer/sdk";// const webhooks = new Webhooks({ apiKey: process.env.OPENCOMPUTER_API_KEY });// const { id, secret } = await webhooks.create({ url: "https://app.example.com/oc" });-// // `secret` is shown ONCE — store it now; you'll need it to verify deliveries.+// // `secret` verifies deliveries; it's returned here and re-fetchable via webhooks.getSecret(id).import type { WebhookDelivery } from "./agents/webhooks.js";@@ -67,9 +68,9 @@ export type SandboxLifecycleEvent = SandboxLifecycleEventBase &/*** The delivered envelope for sandbox webhooks: the shared {@link WebhookDelivery} carrying a- * {@link SandboxLifecycleEvent} under `event`. Delivered by Svix; `sandboxId` and `deliveryId`- * are always set, and `deliveryId` equals the `svix-id` header (stable across retries — dedupe- * on it). Per-destination registration metadata arrives as custom HTTP headers, not in the body.+ * {@link SandboxLifecycleEvent} under `event`. Delivered by Svix; `sandboxId`, `deliveryId`, and+ * `dedupeId` are always set, and all equal the `svix-id` header (stable across retries — dedupe on+ * `dedupeId`). Per-destination registration metadata arrives as custom HTTP headers, not in the body.** Verify an incoming request with: `verifyWebhook<SandboxLifecycleEvent>(rawBody, headers, secret)`.*/@@ -86,7 +87,7 @@ export interface WebhookDestination {/** Scoped to one sandbox, or `null` for all of the org's sandboxes. */sandboxId: string | null;enabled: boolean;- /** Whether a signing secret is set (the secret itself is never returned after create). */+ /** Whether a signing secret is set; fetch the value any time with {@link Webhooks.getSecret}. */hasSecret: boolean;createdAt: string;updatedAt: string;@@ -94,33 +95,33 @@ export interface WebhookDestination {export interface CreateWebhookParams {url: string;- /** Optional unique name (per org) — makes create get-or-create / idempotent. */+ /** Optional display name for the destination. */name?: string;- /** Signing secret. Omit and OpenComputer generates a `whsec_…` one, returned ONCE on create. */+ /** Signing secret. Omit and OpenComputer generates a `whsec_…` one (re-fetchable via {@link Webhooks.getSecret}). */secret?: string;- /** Event-type allow-list (exact or `prefix.*`); default all. */+ /** Event-type allow-list (exact, e.g. `sandbox.stopped`, or `prefix.*`); default all. Unknown types are rejected. */eventTypes?: string[];/** Scope to one sandbox; omit for all of the org's sandboxes. */sandboxId?: string;enabled?: boolean;- /** Idempotency-Key header — a timed-out retry returns the same destination, never a duplicate. */- idempotencyKey?: string;}-/** The create response — the only time `secret` is ever returned (and only when generated). */+/** The create response — includes the signing `secret` (also re-fetchable later via {@link Webhooks.getSecret}). */export interface CreateWebhookResult extends WebhookDestination {- /** The signing secret (`whsec_…`). Returned ONCE, only when OpenComputer generated it. Store it now. */+ /** The signing secret (`whsec_…`). Returned here on create, and re-fetchable any time via {@link Webhooks.getSecret}. */secret?: string;}export interface UpdateWebhookParams {url?: string;- /** Pass `null` to clear the allow-list (deliver all types). */+ /** Pass `null` to clear the allow-list (deliver all types). Unknown types are rejected. */eventTypes?: string[] | null;enabled?: boolean;- /** Set a caller-supplied signing secret (you keep it; it isn't echoed back). */- secret?: string;- /** Generate a NEW signing secret — returned once on the response (see {@link CreateWebhookResult}). */+ /**+ * Rotate to a NEW Svix-generated signing secret — returned on the response (see+ * {@link CreateWebhookResult}). The previous secret stays valid for a short rollover window so+ * in-flight deliveries still verify. (To set a specific secret, create a new destination.)+ */rotateSecret?: boolean;name?: string;}@@ -253,32 +254,18 @@ export class Webhooks {}/**- * Register a destination. Returns HTTP 201 (new) or 200 (an existing destination- * matched by `name`). The response includes `secret` once iff OpenComputer- * generated it. With an `idempotencyKey`, a retried call returns the same- * destination + secret; if a same-key request is concurrently in flight the- * server replies 409 `idempotency_in_progress` (retryable) — this method- * automatically waits (honoring `Retry-After`) and retries a few times.+ * Register a destination (HTTP 201). Each call creates a new destination — there is no+ * get-or-create. The response includes the signing `secret` (also re-fetchable later via+ * {@link getSecret}). Unknown `eventTypes` are rejected with a 400.*/async create(params: CreateWebhookParams): Promise<CreateWebhookResult> {- const { idempotencyKey, ...body } = params;- for (let attempt = 0; ; attempt++) {- const resp = await fetch(`${this.apiUrl}/webhooks`, {- method: "POST",- headers: this.headers(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined),- body: JSON.stringify(body),- });- if (resp.ok) return resp.json();- if (resp.status === 409 && attempt < 5) {- const body409 = (await resp.clone().json().catch(() => ({}))) as { code?: string };- if (body409.code === "idempotency_in_progress") {- const retryAfter = Number(resp.headers.get("Retry-After")) || 1;- await new Promise((r) => setTimeout(r, retryAfter * 1000));- continue;- }- }- return fail(resp, "create webhook");- }+ const resp = await fetch(`${this.apiUrl}/webhooks`, {+ method: "POST",+ headers: this.headers(),+ body: JSON.stringify(params),+ });+ if (!resp.ok) return fail(resp, "create webhook");+ return resp.json();}async list(): Promise<WebhookDestination[]> {@@ -294,6 +281,17 @@ export class Webhooks {return resp.json();}+ /**+ * Fetch the destination's current signing secret (`whsec_…`). Re-fetchable any time by the+ * owner (API key) — use it to verify deliveries. Rotate with `update(id, { rotateSecret: true })`.+ */+ async getSecret(id: string): Promise<string> {+ const resp = await fetch(`${this.apiUrl}/webhooks/${id}/secret`, { headers: this.headers() });+ if (!resp.ok) return fail(resp, "get webhook secret");+ const body = (await resp.json()) as { secret: string };+ return body.secret;+ }+/** Update a destination — pause/resume (`enabled`), retune `eventTypes`, change `url`, or rotate `secret`. */async update(id: string, params: UpdateWebhookParams): Promise<CreateWebhookResult> {const resp = await fetch(`${this.apiUrl}/webhooks/${id}`, {@@ -305,7 +303,7 @@ export class Webhooks {return resp.json();}- /** Soft-delete a destination. Its delivery history is retained; pending deliveries are canceled. */+ /** Delete a destination (removes its Svix endpoint). Delivery history for a deleted destination is no longer queryable. */async delete(id: string): Promise<void> {const resp = await fetch(`${this.apiUrl}/webhooks/${id}`, { method: "DELETE", headers: this.headers() });if (!resp.ok) return fail(resp, "delete webhook");