An open-source, faster Devin alternative
TypeScript
Address webhook-review findings (P1–P3)
Igor Zalutskidf6294f7bf62
diff --git a/docs/agent-sessions/webhooks.mdx b/docs/agent-sessions/webhooks.mdxindex be26313b..348ee22e 100644--- a/docs/agent-sessions/webhooks.mdx+++ b/docs/agent-sessions/webhooks.mdx@@ -127,7 +127,7 @@ Delivery = {- **HTTPS only.** Private, loopback, link-local, and cloud-metadata addresses are refused.- **At-least-once.** Retried with exponential backoff; after the max attempts a delivery is **dead-lettered** (inspect and redeliver it above). A duplicate can still arrive — a delivery interrupted after it reached you, or a replayed turn — so **dedupe on `webhook-id`** (it equals the event id).-- **Signed with [Standard Webhooks](https://www.standardwebhooks.com).** Every request carries `webhook-id`, `webhook-timestamp`, and `webhook-signature` — so you can verify with an off-the-shelf library instead of hand-rolling. `webhook-signature` = `v1,<base64(HMAC-SHA256(secret, "{webhook-id}.{webhook-timestamp}.{rawBody}"))>`. Verify against the **raw request body, before parsing it**; `webhook-timestamp` guards replay; your `secret` (`whsec_…`) is write-only — set once, never returned. Plus `X-OC-Delivery-ID` and `X-OC-Session-ID` for correlation.+- **Signed with [Standard Webhooks](https://www.standardwebhooks.com) — when the destination has a `secret`.** Every request carries `webhook-id` and `webhook-timestamp`; if the destination was created with a `secret`, it also carries `webhook-signature` (= `v1,<base64(HMAC-SHA256(secret, "{webhook-id}.{webhook-timestamp}.{rawBody}"))>`). **Set a `secret` to get signed deliveries** — without one, requests are unsigned. Verify against the **raw request body, before parsing it**; `webhook-timestamp` guards replay; your `secret` (`whsec_…`) is write-only — set once, never returned. Plus `X-OC-Delivery-ID` and `X-OC-Session-ID` for correlation.- A delivery succeeds on HTTP `2xx`.### Verify a webhookdiff --git a/sdks/typescript/README.md b/sdks/typescript/README.mdindex e3f29b77..91a3a13c 100644--- a/sdks/typescript/README.md+++ b/sdks/typescript/README.md@@ -48,13 +48,14 @@ const agent = await oc.agents.create({});// Per request — hand off durable work, route the callback via metadata:-await oc.sessions.create({+const session = await oc.sessions.create({agent: agent.id,input: "Review PR #42",metadata: { pullNumber: 42 }, // echoed back verbatim in the webhookidempotencyKey: deliveryId, // retry-safe- destinations: [{ url: "https://app.example.com/oc-callback", secret: process.env.OC_WEBHOOK_SECRET! }],});+// Register a SIGNED callback (inline create-time destinations can't carry a secret):+await session.destinations.create({ url: "https://app.example.com/oc-callback", secret: process.env.OC_WEBHOOK_SECRET! });// In your webhook handler — verify the signature, then fetch the result:const delivery = await verifyWebhook(rawBody, request.headers, process.env.OC_WEBHOOK_SECRET!);@@ -66,10 +67,19 @@ if (delivery.type === "turn.completed") {## Configuration-| Option | Env Variable | Default |-|-----------|------------------------|--------------------------|-| `apiUrl` | `OPENCOMPUTER_API_URL` | `https://app.opencomputer.dev` |-| `apiKey` | `OPENCOMPUTER_API_KEY` | (none) |+**Sandboxes** (`Sandbox`):++| Option | Env Variable | Default |+|----------|------------------------|----------------------------------|+| `apiUrl` | `OPENCOMPUTER_API_URL` | `https://app.opencomputer.dev` |+| `apiKey` | `OPENCOMPUTER_API_KEY` | (none) |++**Durable Agent Sessions** (`OpenComputer`):++| Option | Env Variable | Default |+|-----------|------------------------|------------------------------------|+| `baseUrl` | — | `https://api.opencomputer.dev/v3` |+| `apiKey` | `OPENCOMPUTER_API_KEY` | (none) |## Licensediff --git a/sdks/typescript/src/agents/agents.ts b/sdks/typescript/src/agents/agents.tsindex 260f8792..c2411430 100644--- a/sdks/typescript/src/agents/agents.ts+++ b/sdks/typescript/src/agents/agents.ts@@ -27,7 +27,8 @@ export class Agents {constructor(private readonly http: Http) {}create(params: CreateAgentParams): Promise<Agent> {- return this.http.request("POST", "/agents", { body: params });+ // Idempotent by name server-side → safe to auto-retry transient failures.+ return this.http.request("POST", "/agents", { body: params, idempotent: true });}get(id: string): Promise<Agent> {return this.http.request("GET", `/agents/${id}`);diff --git a/sdks/typescript/src/agents/webhooks.test.ts b/sdks/typescript/src/agents/webhooks.test.tsindex d7953ecb..d279f50f 100644--- a/sdks/typescript/src/agents/webhooks.test.ts+++ b/sdks/typescript/src/agents/webhooks.test.ts@@ -3,12 +3,22 @@ import { verifyWebhook, WebhookVerificationError } from "./webhooks.js";const SECRET = "whsec_" + btoa("super-secret-key-bytes-123456");+// Mirror the backend's key derivation (strip whsec_, base64 if it round-trips, else raw UTF-8).+function keyBytesFor(secret: string): Uint8Array {+ const s = secret.startsWith("whsec_") ? secret.slice("whsec_".length) : secret;+ try {+ const bin = atob(s);+ const decoded = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) decoded[i] = bin.charCodeAt(i);+ let re = "";+ for (let i = 0; i < decoded.length; i++) re += String.fromCharCode(decoded[i]);+ if (decoded.length > 0 && btoa(re).replace(/=+$/, "") === s.replace(/=+$/, "")) return decoded;+ } catch { /* not base64 */ }+ return new TextEncoder().encode(secret);+}+async function sign(id: string, ts: number, body: string, secret: string): Promise<string> {- const keyB64 = secret.startsWith("whsec_") ? secret.slice("whsec_".length) : secret;- const bin = atob(keyB64);- const keyBytes = new Uint8Array(bin.length);- for (let i = 0; i < bin.length; i++) keyBytes[i] = bin.charCodeAt(i);- const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);+ const key = await crypto.subtle.importKey("raw", new Uint8Array(keyBytesFor(secret)), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${ts}.${body}`)));let b = "";for (let i = 0; i < mac.length; i++) b += String.fromCharCode(mac[i]);@@ -56,4 +66,10 @@ describe("verifyWebhook", () => {it("throws on missing headers", async () => {await expect(verifyWebhook(body, {}, SECRET, { nowSeconds: ts })).rejects.toThrow(/missing/);});++ it("verifies a raw (non-base64) secret — backend signs with UTF-8 bytes", async () => {+ const raw = "testsecret"; // not a whsec_/base64 secret → both sides use UTF-8 key bytes+ const delivery = await verifyWebhook(body, hdr(await sign(id, ts, body, raw)), raw, { nowSeconds: ts });+ expect(delivery.type).toBe("turn.completed");+ });});diff --git a/sdks/typescript/src/agents/webhooks.ts b/sdks/typescript/src/agents/webhooks.tsindex e0b4487f..e4c3e5c8 100644--- a/sdks/typescript/src/agents/webhooks.ts+++ b/sdks/typescript/src/agents/webhooks.ts@@ -63,6 +63,23 @@ function bytesToBase64(bytes: Uint8Array): string {return btoa(bin);}+/**+ * Derive the HMAC key bytes EXACTLY as the backend does (delivery signing): strip the+ * `whsec_` prefix, use the base64-decoded bytes if the remainder round-trips as base64,+ * otherwise fall back to the raw UTF-8 bytes of the ORIGINAL secret. So a destination made+ * with a non-base64 secret (e.g. `"testsecret"`) verifies, matching what the server signed.+ */+function secretKeyBytes(secret: string): Uint8Array<ArrayBuffer> {+ const s = secret.startsWith("whsec_") ? secret.slice("whsec_".length) : secret;+ try {+ const decoded = base64ToBytes(s);+ if (decoded.length > 0 && bytesToBase64(decoded).replace(/=+$/, "") === s.replace(/=+$/, "")) return decoded;+ } catch {+ /* not base64 → raw bytes below */+ }+ return new Uint8Array(new TextEncoder().encode(secret));+}+/** Constant-time string compare (equal length → no early-exit on content). */function timingSafeEqual(a: string, b: string): boolean {if (a.length !== b.length) return false;@@ -103,11 +120,14 @@ export async function verifyWebhook<E = Event>(throw new WebhookVerificationError("webhook-timestamp outside tolerance (possible replay)");}- const keyBytes = base64ToBytes(secret.startsWith("whsec_") ? secret.slice("whsec_".length) : secret);- const cryptoKey = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);- const msg = new Uint8Array(new TextEncoder().encode(`${id}.${ts}.${rawBody}`));- const mac = new Uint8Array(await crypto.subtle.sign("HMAC", cryptoKey, msg));- const expected = bytesToBase64(mac);+ let expected: string;+ try {+ const cryptoKey = await crypto.subtle.importKey("raw", secretKeyBytes(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);+ const msg = new Uint8Array(new TextEncoder().encode(`${id}.${ts}.${rawBody}`));+ expected = bytesToBase64(new Uint8Array(await crypto.subtle.sign("HMAC", cryptoKey, msg)));+ } catch (err) {+ throw new WebhookVerificationError(`could not compute signature: ${err instanceof Error ? err.message : String(err)}`);+ }// Header is space-separated "v1,<sig>" entries (multiple during secret rotation).const matched = sigHeader.split(" ").some((entry) => {