An open-source, faster Devin alternative
TypeScript
Webhooks: per-webhook identity source replaces the provider header list
Igor Zalutski5e0eed9d0e79
diff --git a/cli/src/api.ts b/cli/src/api.tsindex 586daec6..1e05116b 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -169,6 +169,8 @@ export interface ManagedAgentWebhook {agentId: string;name: string;enabled: boolean;+ /** Delivery identity source, `header:<name>` or `body:<json-pointer>`. */+ identity?: string;invocationUrl: string;token?: string;createdAt: string;@@ -630,6 +632,7 @@ export class OpenComputerClient {name: string;environment: "development" | "production";agentId: string;+ identity?: string;}) {return this.request<{ webhook: ManagedAgentWebhook }>(`/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/webhooks`,@@ -639,6 +642,7 @@ export class OpenComputerClient {name: input.name,environment: input.environment,agentId: input.agentId,+ ...(input.identity !== undefined ? { identity: input.identity } : {}),}),},).then((result) => result.webhook);@@ -649,6 +653,8 @@ export class OpenComputerClient {webhookId: string;name?: string;enabled?: boolean;+ /** A source sets it; null clears it. */+ identity?: string | null;}) {return this.request<{ webhook: ManagedAgentWebhook }>(`/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/webhooks/${encodeURIComponent(input.webhookId)}`,@@ -657,6 +663,7 @@ export class OpenComputerClient {body: JSON.stringify({...(input.name !== undefined ? { name: input.name } : {}),...(input.enabled !== undefined ? { enabled: input.enabled } : {}),+ ...(input.identity !== undefined ? { identity: input.identity } : {}),}),},).then((result) => result.webhook);diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 5390b97f..82597839 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -1378,7 +1378,9 @@ export async function runCommand(for (const webhook of webhooks) {process.stdout.write(`${webhook.id} ${webhook.enabled ? "enabled " : "disabled"} ` +- `${webhook.name} ${webhook.invocationUrl}\n`,+ `${webhook.name} ${webhook.invocationUrl}` ++ (webhook.identity ? ` identity=${webhook.identity}` : "") ++ "\n",);}}@@ -1386,8 +1388,9 @@ export async function runCommand(}if (action === "create") {const name = args.shift()?.trim();+ const identity = option(args, "--identity");if (!name || args.length) {- throw new Error("Use `opencomputer webhooks create <name>`.");+ throw new Error("Use `opencomputer webhooks create <name> [--identity header:<name>|body:<json-pointer>]`.");}const existing = (await client.webhooks({projectId: project.projectId,@@ -1401,12 +1404,14 @@ export async function runCommand(name,environment,agentId,+ ...(identity ? { identity } : {}),}));if (globals.json) printJSON({ ...webhook, reused: Boolean(existing) });else {process.stdout.write(`${existing ? "Reused" : "Created"} ${webhook.name} (${webhook.id}) for ${agentId}@${environment}.\n` +`URL: ${webhook.invocationUrl}\n` ++ (webhook.identity ? `Identity: ${webhook.identity}\n` : "") +(existing? "The existing token remains unchanged; this URL omits it.\n": `Token: ${webhook.token ?? "unavailable"}\n` +@@ -1416,11 +1421,30 @@ export async function runCommand(return;}const webhookId = args.shift();+ const identityOption = action === "update" ? option(args, "--identity") : undefined;if (!webhookId || args.length) {throw new Error(- "Use `opencomputer webhooks list|create|enable|disable|rotate-token|remove`.",+ "Use `opencomputer webhooks list|create|update|enable|disable|rotate-token|remove`.",);}+ if (action === "update") {+ if (identityOption === undefined) {+ throw new Error("Use `opencomputer webhooks update <id> --identity header:<name>|body:<json-pointer>|none`.");+ }+ const webhook = await client.updateWebhook({+ projectId: project.projectId,+ webhookId,+ identity: identityOption === "none" ? null : identityOption,+ });+ if (globals.json) printJSON(webhook);+ else+ process.stdout.write(+ webhook.identity+ ? `${webhook.name} now takes its delivery identity from ${webhook.identity}.\n`+ : `${webhook.name} now treats every delivery without an Idempotency-Key as new.\n`,+ );+ return;+ }if (action === "enable" || action === "disable") {const webhook = await client.updateWebhook({projectId: project.projectId,@@ -1457,7 +1481,7 @@ export async function runCommand(return;}throw new Error(- "Use `opencomputer webhooks list|create|enable|disable|rotate-token|remove`.",+ "Use `opencomputer webhooks list|create|update|enable|disable|rotate-token|remove`.",);}diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 1794572c..64803f8a 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -378,9 +378,17 @@ describe("managed agents proxy", () => {);const headers = new Headers(init?.headers);expect(headers.get("authorization")).toBeNull();+ // The sender's own headers reach the backend, which reads whichever+ // one the webhook is configured to use as its identity.expect(headers.get("request-id")).toBe("sentry-delivery-1");expect(headers.get("sentry-hook-resource")).toBe("event_alert");- expect(headers.get("sentry-hook-signature")).toBeNull();+ expect(headers.get("sentry-hook-signature")).toBe("abc");+ // Credentials, transport, and edge-trusted headers do not.+ expect(headers.get("cookie")).toBeNull();+ expect(headers.get("x-oc-managed-sig")).toBeNull();+ expect(headers.get("x-api-key")).toBeNull();+ expect(headers.get("x-forwarded-for")).toBeNull();+ expect(headers.get("x-request-id")).not.toBe("spoofed");expect(await new Response(init?.body).json()).toEqual(sentryBody);return Response.json({request: {@@ -410,6 +418,11 @@ describe("managed agents proxy", () => {"request-id": "sentry-delivery-1","sentry-hook-resource": "event_alert","sentry-hook-signature": "abc",+ cookie: "session=1",+ "x-oc-managed-sig": "forged",+ "x-api-key": "forged",+ "x-forwarded-for": "1.2.3.4",+ "x-request-id": "spoofed",},body: JSON.stringify(sentryBody),},diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 716f70a3..6ea58696 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -476,6 +476,7 @@ function publicWebhook(agentId: webhook.agentId,name: webhook.name,enabled: webhook.enabled,+ ...(typeof webhook.identity === "string" ? { identity: webhook.identity } : {}),// The token is the credential; when this response carries it (create,// rotate), the URL carries it too and is shown once. Listings never do....(publicOrigin && id@@ -1346,17 +1347,29 @@ export async function handleManagedAgentChannelConnection(});}-// Headers that carry or select a delivery identity; the backend decides-// precedence (Sentry deliveries are identified by the alerted object named-// by `sentry-hook-resource`, not by the per-attempt `request-id`).-const WEBHOOK_DELIVERY_ID_HEADERS = [- "idempotency-key",- "sentry-hook-resource",- "x-github-delivery",- "stripe-signature",- "svix-id",- "request-id",-] as const;+// A webhook may read its delivery identity from any request header the+// sender chose at configuration time, so the sender's headers pass through+// except credentials, transport headers, and anything the backend trusts+// from this edge.+const WEBHOOK_HEADERS_NOT_FORWARDED = new Set([+ "authorization",+ "cookie",+ "host",+ "content-length",+ "connection",+ "transfer-encoding",+ "x-request-id",+ "x-api-key",+]);+const WEBHOOK_HEADER_PREFIXES_NOT_FORWARDED = ["x-oc-", "cf-", "x-forwarded-", "x-real-"];++function forwardableWebhookHeader(name: string): boolean {+ const lower = name.toLowerCase();+ return (+ !WEBHOOK_HEADERS_NOT_FORWARDED.has(lower) &&+ !WEBHOOK_HEADER_PREFIXES_NOT_FORWARDED.some((prefix) => lower.startsWith(prefix))+ );+}export async function handleAgentWebhookInvocation(request: Request,@@ -1420,9 +1433,8 @@ export async function handleAgentWebhookInvocation("x-request-id": crypto.randomUUID(),});if (authorization) headers.set("authorization", authorization);- for (const header of WEBHOOK_DELIVERY_ID_HEADERS) {- const value = request.headers.get(header);- if (value) headers.set(header, value);+ for (const [name, value] of request.headers) {+ if (forwardableWebhookHeader(name) && !headers.has(name)) headers.set(name, value);}try {const upstream = await fetch(target, {diff --git a/docs/agents/webhooks.mdx b/docs/agents/webhooks.mdxindex 144beebb..e81d5d57 100644--- a/docs/agents/webhooks.mdx+++ b/docs/agents/webhooks.mdx@@ -77,16 +77,27 @@ curl 'https://app.opencomputer.dev/api/managed-agents/projects/<project-id>/webh```Each delivery needs an identity so that a retry does not start a second-session. OpenComputer uses the first available of: your `Idempotency-Key`;-for Sentry event alerts and errors, the event id in the body under the-`Sentry-Hook-Resource` header, which stays the same across Sentry's retries-while its `Request-ID` does not; `X-GitHub-Delivery`; for Stripe, the event-id in the body; `Svix-Id`; and finally `Request-ID`. Other Sentry-notifications, such as issue and comment changes, use `Request-ID`.-Retrying with the same `Idempotency-Key` and a different body is a 409; a-provider retry under a derived identity returns the original request even-if the provider reserialized the body. If the original request had failed-to start, the retry starts it again. A body larger than 256 KiB once wrapped+session. A sender that can set headers sends `Idempotency-Key`. For a+provider that cannot, give the webhook an identity source when you create+it: a request header, or a JSON Pointer into the body.++```bash+opencomputer webhooks create sentry-alerts --agent current --environment production \+ --identity body:/data/event/event_id+opencomputer webhooks update <webhook-id> --identity header:X-GitHub-Delivery+opencomputer webhooks update <webhook-id> --identity none+```++Choose a value that stays the same when the provider retries and differs+between deliveries you want handled separately. Sentry's per-request+`Request-ID` changes on every retry, so for its issue alerts use the event+id in the body. Without a source, every delivery that sets no+`Idempotency-Key` starts a session.++Retrying with the same `Idempotency-Key` and a different body is a 409. A+retry under a configured source returns the original request even if the+provider reserialized the body. If the original request had failed to+start, the retry starts it again. A body larger than 256 KiB once wrappedas agent input is rejected with 400 before acknowledgement.## Read webhook input@@ -129,9 +140,9 @@ const payload = (input.payload ?? {}) as {const event = payload.data?.event;```-Configure the provider with the full webhook URL. Sentry's internal-integrations and GitHub repository webhooks accept it as is; both send a-delivery id header that OpenComputer uses as the request identity.+Configure the provider with the full webhook URL and set the webhook's+identity source to the field that names the delivery, for example+`body:/data/event/event_id` for a Sentry issue alert.Development and Production webhooks have separate URLs, tokens, and sessions.Disable or remove a webhook when its caller should no longer start sessions.diff --git a/web/src/managed-agents/Webhooks.tsx b/web/src/managed-agents/Webhooks.tsxindex c0b5e8ef..ea3fed19 100644--- a/web/src/managed-agents/Webhooks.tsx+++ b/web/src/managed-agents/Webhooks.tsx@@ -67,6 +67,7 @@ export function ManagedAgentWebhooks({const queryKey = ['managed-agent-webhooks', projectId, agentId, environment]const [creating, setCreating] = useState(false)const [name, setName] = useState('')+ const [identity, setIdentity] = useState('')const [credentials, setCredentials] = useState<ManagedAgentWebhook>()const [removing, setRemoving] = useState<ManagedAgentWebhook>()@@ -82,10 +83,12 @@ export function ManagedAgentWebhooks({agentId,environment,name: name.trim(),+ ...(identity.trim() ? { identity: identity.trim() } : {}),}),onSuccess: async (webhook) => {setCreating(false)setName('')+ setIdentity('')setCredentials(webhook)await queryClient.invalidateQueries({ queryKey })},@@ -160,6 +163,11 @@ export function ManagedAgentWebhooks({<p className="text-muted-foreground mt-1 max-w-xl truncate font-mono text-xs">{webhook.invocationUrl}</p>+ {webhook.identity ? (+ <p className="text-muted-foreground mt-1 font-mono text-xs">+ identity {webhook.identity}+ </p>+ ) : null}</div>),},@@ -265,6 +273,21 @@ export function ManagedAgentWebhooks({onChange={(event) => setName(event.target.value)}/></div>+ <div className="space-y-2">+ <Label htmlFor="webhook-identity">Delivery identity (optional)</Label>+ <Input+ id="webhook-identity"+ value={identity}+ maxLength={300}+ placeholder="body:/data/event/event_id or header:X-GitHub-Delivery"+ onChange={(event) => setIdentity(event.target.value)}+ />+ <p className="text-muted-foreground text-xs">+ Where a delivery's identity is read when the sender sets no+ Idempotency-Key, so a provider's retry does not start a second+ session. A header name, or a JSON Pointer into the body.+ </p>+ </div><DialogFooter><Button variant="outline" onClick={() => setCreating(false)}>Canceldiff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex c8385ad5..120e07d1 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -378,6 +378,7 @@ const webhookSchema = z.object({agentId: z.string(),name: z.string(),enabled: z.boolean(),+ identity: z.string().optional(),invocationUrl: z.string().url(),token: z.string().optional(),createdAt: z.string(),@@ -917,6 +918,7 @@ export async function createManagedAgentWebhook(input: {agentId: stringenvironment: 'development' | 'production'name: string+ identity?: string}) {return (await apiFetch(@@ -927,6 +929,7 @@ export async function createManagedAgentWebhook(input: {agentId: input.agentId,environment: input.environment,name: input.name,+ ...(input.identity ? { identity: input.identity } : {}),}),},webhookResponseSchema,