Skip to content

An open-source, faster Devin alternative

TypeScript

sdk: add verifyWebhook helper + README leads with Durable Agent Sessions

Igor Zalutski988f5cdbfd83
diff --git a/docs/agent-sessions/webhooks.mdx b/docs/agent-sessions/webhooks.mdx
index e3172c0f..be26313b 100644
--- a/docs/agent-sessions/webhooks.mdx
+++ b/docs/agent-sessions/webhooks.mdx
@@ -132,7 +132,20 @@ Delivery = {
### Verify a webhook
-Use a [Standard Webhooks](https://www.standardwebhooks.com) library:
+The SDK ships a verifier — no extra dependency, runs in Node / Cloudflare Workers / browsers — that checks the signature and returns the parsed envelope:
+
+```ts
+import { verifyWebhook } from "@opencomputer/sdk";
+
+// rawBody = the RAW request body string, read BEFORE JSON.parse.
+// Throws on a missing / expired / invalid signature.
+const delivery = await verifyWebhook(rawBody, request.headers, process.env.OC_WEBHOOK_SECRET!);
+if (delivery.type === "turn.completed") {
+ // route on delivery.metadata, then fetch the result
+}
+```
+
+Or verify with any [Standard Webhooks](https://www.standardwebhooks.com) library directly:
```js
import { Webhook } from "standardwebhooks";
diff --git a/sdks/typescript/README.md b/sdks/typescript/README.md
index a209ceba..e3f29b77 100644
--- a/sdks/typescript/README.md
+++ b/sdks/typescript/README.md
@@ -1,6 +1,8 @@
# @opencomputer/sdk
-TypeScript SDK for [OpenComputer](https://github.com/diggerhq/opensandbox) — cloud sandbox platform.
+The official TypeScript SDK for [OpenComputer](https://github.com/diggerhq/opensandbox): **cloud sandboxes** and **Durable Agent Sessions** (managed background agents).
+
+> This one package covers both surfaces — install **`@opencomputer/sdk`**. (The older `@opencomputer/agents-sdk` is superseded; use this instead.)
## Install
@@ -27,6 +29,41 @@ const content = await sandbox.files.read("/tmp/test.txt");
await sandbox.kill();
```
+## Durable Agent Sessions
+
+Run a managed background agent: define an agent once, then create sessions that stream durable events and call back on completion.
+
+```typescript
+import { OpenComputer, verifyWebhook } from "@opencomputer/sdk";
+
+const oc = new OpenComputer({ apiKey: process.env.OPENCOMPUTER_API_KEY! });
+
+// Bootstrap once — idempotent by name (safe on every deploy):
+const agent = await oc.agents.create({
+ name: "reviewer",
+ runtime: "claude", // or "codex"
+ model: "anthropic/claude-opus-4-8",
+ prompt: "Review the diff. Run tests. Explain risks.",
+ key: process.env.ANTHROPIC_API_KEY!, // sealed; never enters the sandbox
+});
+
+// Per request — hand off durable work, route the callback via metadata:
+await oc.sessions.create({
+ agent: agent.id,
+ input: "Review PR #42",
+ metadata: { pullNumber: 42 }, // echoed back verbatim in the webhook
+ idempotencyKey: deliveryId, // retry-safe
+ destinations: [{ 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!);
+if (delivery.type === "turn.completed") {
+ const session = await oc.sessions.get(delivery.sessionId);
+ const { result } = await session.result();
+}
+```
+
## Configuration
| Option | Env Variable | Default |
diff --git a/sdks/typescript/src/agents/index.ts b/sdks/typescript/src/agents/index.ts
index 75002eae..6a288c74 100644
--- a/sdks/typescript/src/agents/index.ts
+++ b/sdks/typescript/src/agents/index.ts
@@ -9,6 +9,8 @@ export { Credentials } from "./credentials.js";
export type { CreateCredentialParams } from "./credentials.js";
export { Destinations, Deliveries } from "./destinations.js";
export type { CreateDestinationParams, UpdateDestinationParams } from "./destinations.js";
+export { verifyWebhook, WebhookVerificationError } from "./webhooks.js";
+export type { WebhookDelivery, VerifyWebhookOptions } from "./webhooks.js";
export * from "./types.js";
export * from "./errors.js";
diff --git a/sdks/typescript/src/agents/webhooks.test.ts b/sdks/typescript/src/agents/webhooks.test.ts
new file mode 100644
index 00000000..d7953ecb
--- /dev/null
+++ b/sdks/typescript/src/agents/webhooks.test.ts
@@ -0,0 +1,59 @@
+import { describe, it, expect } from "vitest";
+import { verifyWebhook, WebhookVerificationError } from "./webhooks.js";
+
+const SECRET = "whsec_" + btoa("super-secret-key-bytes-123456");
+
+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 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]);
+ return "v1," + btoa(b);
+}
+
+describe("verifyWebhook", () => {
+ const id = "msg_1";
+ const ts = 1_700_000_000;
+ const body = JSON.stringify({
+ type: "turn.completed", sessionId: "ses_1", eventId: "msg_1",
+ metadata: { pull_number: 7 }, event: { id: "evt_1", type: "turn.completed" },
+ });
+ const hdr = (sig: string) => ({ "webhook-id": id, "webhook-timestamp": String(ts), "webhook-signature": sig });
+
+ it("accepts a valid signature and returns the parsed envelope (metadata verbatim)", async () => {
+ const delivery = await verifyWebhook(body, hdr(await sign(id, ts, body, SECRET)), SECRET, { nowSeconds: ts });
+ expect(delivery.type).toBe("turn.completed");
+ expect(delivery.eventId).toBe("msg_1");
+ expect(delivery.metadata).toEqual({ pull_number: 7 });
+ });
+
+ it("rejects a tampered body", async () => {
+ const sig = await sign(id, ts, body, SECRET);
+ await expect(verifyWebhook(body + " ", hdr(sig), SECRET, { nowSeconds: ts })).rejects.toThrow(WebhookVerificationError);
+ });
+
+ it("rejects an out-of-tolerance timestamp (replay)", async () => {
+ const sig = await sign(id, ts, body, SECRET);
+ await expect(verifyWebhook(body, hdr(sig), SECRET, { nowSeconds: ts + 10_000 })).rejects.toThrow(/tolerance/);
+ });
+
+ it("rejects a wrong secret", async () => {
+ const sig = await sign(id, ts, body, SECRET);
+ const wrong = "whsec_" + btoa("different-key-bytes-000000");
+ await expect(verifyWebhook(body, hdr(sig), wrong, { nowSeconds: ts })).rejects.toThrow(WebhookVerificationError);
+ });
+
+ it("accepts when one of several rotated signatures matches", async () => {
+ const good = await sign(id, ts, body, SECRET);
+ const delivery = await verifyWebhook(body, hdr(`v1,bogus ${good}`), SECRET, { nowSeconds: ts });
+ expect(delivery.sessionId).toBe("ses_1");
+ });
+
+ it("throws on missing headers", async () => {
+ await expect(verifyWebhook(body, {}, SECRET, { nowSeconds: ts })).rejects.toThrow(/missing/);
+ });
+});
diff --git a/sdks/typescript/src/agents/webhooks.ts b/sdks/typescript/src/agents/webhooks.ts
new file mode 100644
index 00000000..e0b4487f
--- /dev/null
+++ b/sdks/typescript/src/agents/webhooks.ts
@@ -0,0 +1,125 @@
+// Webhook verification for Durable Agent Sessions destinations.
+//
+// Deliveries are signed with the Standard Webhooks scheme (https://www.standardwebhooks.com):
+// headers `webhook-id`, `webhook-timestamp`, `webhook-signature`, where
+// webhook-signature = "v1,<base64(HMAC-SHA256(secret, `${id}.${timestamp}.${rawBody}`))>"
+// and the secret is the destination's `whsec_…` value. The header may carry several
+// space-separated signatures (key rotation); any match passes.
+//
+// Implemented with Web Crypto (no Node-only deps) so it runs in Cloudflare Workers,
+// browsers, Deno, and Node 16+ — the same places the SDK runs. Verify against the RAW
+// request body, BEFORE JSON-parsing it.
+
+import type { Event } from "./types.js";
+
+/** The envelope OpenComputer POSTs to a destination (see the Webhooks docs). */
+export interface WebhookDelivery<E = Event> {
+ /** The event type — route on this (e.g. `turn.completed`). */
+ type: string;
+ sessionId: string;
+ /** Equals the `webhook-id` header — dedupe on it. */
+ eventId: string;
+ /** The session's opaque routing state, verbatim (`null` when unset). */
+ metadata: Record<string, unknown> | null;
+ /** The full event — the same shape the SSE stream emits. */
+ event: E;
+}
+
+export interface VerifyWebhookOptions {
+ /** Max allowed clock skew between now and `webhook-timestamp`, in seconds (default 300). */
+ toleranceSeconds?: number;
+ /** Override "now" (unix seconds) — for testing. */
+ nowSeconds?: number;
+}
+
+export class WebhookVerificationError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "WebhookVerificationError";
+ }
+}
+
+type HeaderBag = Record<string, string | string[] | undefined>;
+
+function header(headers: HeaderBag | Headers, name: string): string | undefined {
+ if (typeof (headers as Headers).get === "function") {
+ return (headers as Headers).get(name) ?? undefined; // Headers.get is case-insensitive
+ }
+ const bag = headers as HeaderBag;
+ const v = bag[name] ?? bag[name.toLowerCase()];
+ return Array.isArray(v) ? v[0] : v;
+}
+
+function base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {
+ const bin = atob(b64);
+ const out = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
+ return out;
+}
+
+function bytesToBase64(bytes: Uint8Array): string {
+ let bin = "";
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
+ return btoa(bin);
+}
+
+/** 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;
+ let diff = 0;
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
+ return diff === 0;
+}
+
+/**
+ * Verify a webhook delivery and return its parsed envelope. Throws
+ * {@link WebhookVerificationError} on a missing/expired/invalid signature.
+ *
+ * ```ts
+ * import { verifyWebhook } from "@opencomputer/sdk";
+ * // in your handler — pass the RAW body string, not a parsed object:
+ * const delivery = await verifyWebhook(rawBody, request.headers, process.env.OC_WEBHOOK_SECRET!);
+ * if (delivery.type === "turn.completed") { /* route via delivery.metadata *\/ }
+ * ```
+ */
+export async function verifyWebhook<E = Event>(
+ rawBody: string,
+ headers: HeaderBag | Headers,
+ secret: string,
+ opts: VerifyWebhookOptions = {},
+): Promise<WebhookDelivery<E>> {
+ const id = header(headers, "webhook-id");
+ const ts = header(headers, "webhook-timestamp");
+ const sigHeader = header(headers, "webhook-signature");
+ if (!id || !ts || !sigHeader) {
+ throw new WebhookVerificationError("missing webhook-id / webhook-timestamp / webhook-signature header");
+ }
+
+ const tolerance = opts.toleranceSeconds ?? 300;
+ const now = opts.nowSeconds ?? Math.floor(Date.now() / 1000);
+ const tsNum = Number(ts);
+ if (!Number.isFinite(tsNum)) throw new WebhookVerificationError("invalid webhook-timestamp");
+ if (Math.abs(now - tsNum) > tolerance) {
+ 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);
+
+ // Header is space-separated "v1,<sig>" entries (multiple during secret rotation).
+ const matched = sigHeader.split(" ").some((entry) => {
+ const comma = entry.indexOf(",");
+ if (comma < 0) return false;
+ return entry.slice(0, comma) === "v1" && timingSafeEqual(entry.slice(comma + 1), expected);
+ });
+ if (!matched) throw new WebhookVerificationError("no matching webhook signature");
+
+ try {
+ return JSON.parse(rawBody) as WebhookDelivery<E>;
+ } catch {
+ throw new WebhookVerificationError("signature valid but body is not JSON");
+ }
+}