TypeScript
feat(server): webhook filters fan out over arrays with a [] path wildcard (#23282)
Julius Marmingedefb7e6e6b87
diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.tsindex 111870be9bb..567cb927273 100644--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts@@ -118,7 +118,7 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", {const ScheduleTaskTool = Tool.make("schedule_task", {description:- "Create persistent work in the app scheduler that runs even when no turn is active. Pass schedule as a STRUCTURED OBJECT, never JSON text. Timers: {type:'interval', everyMs:3600000} is hourly; {type:'fixed_time', timeOfDay:'09:00', weekdays:[1,2,3,4,5]} is weekday mornings; report the returned nextRunAt. Webhook dedupe accepts replayKey and coalesceKey templates with coalesceWindowSeconds (10–3600, default 120); replay keys expire after 7 days and coalescing keeps the latest payload in a window measured from its first delivery. Webhooks: {type:'webhook'} runs once per request to a generated URL. The run sees the request ONLY through prompt placeholders: {{body.path}} (e.g. {{body.action}}, {{body.release.tag_name}}), {{headers.name}}, {{query.name}}, {{body}}, or {{request}} (method, headers with credentials redacted, and body). Each value arrives framed as untrusted request data, and $skill, @file or /command mentions inside it do not act; without a signature, anyone with the URL can trigger a run. For a sender that signs requests, first call request_secret so the user enters the secret privately (never ask for it in chat or invent one), then set signature with the returned secretRef, e.g. GitHub: {type:'webhook', signature:{header:'x-hub-signature-256', encoding:'hex', prefix:'sha256=', secretRef}}. To run only for some requests, add filters, all of which must match, e.g. filters:[{path:'headers.x-github-event', op:'equals', value:'pull_request'}, {path:'body.action', op:'in', value:['opened','reopened']}]; ops are equals, notEquals, in, startsWith and exists. The result's webhookUrl is the public URL to give the user; if it is absent, this environment has no T3 Connect managed tunnel, so tell the user to enable T3 Connect remote access rather than sharing a path. Omit projectId for this thread's project. In this thread's project, runs post into THIS thread by default (bindToCurrentThread=true), which suits an orchestrator that sees every trigger, delegates work, and can dedupe against what is in flight; use false only when the user wants a fresh top-level thread per run. Elsewhere each run launches a fresh thread. Provider, model, and runtime settings inherit from this thread, or from the project default when there is no calling thread.",+ "Create persistent work in the app scheduler that runs even when no turn is active. Pass schedule as a STRUCTURED OBJECT, never JSON text. Timers: {type:'interval', everyMs:3600000} is hourly; {type:'fixed_time', timeOfDay:'09:00', weekdays:[1,2,3,4,5]} is weekday mornings; report the returned nextRunAt. Webhook dedupe accepts replayKey and coalesceKey templates with coalesceWindowSeconds (10–3600, default 120); replay keys expire after 7 days and coalescing keeps the latest payload in a window measured from its first delivery. Webhooks: {type:'webhook'} runs once per request to a generated URL. The run sees the request ONLY through prompt placeholders: {{body.path}} (e.g. {{body.action}}, {{body.release.tag_name}}), {{headers.name}}, {{query.name}}, {{body}}, or {{request}} (method, headers with credentials redacted, and body). Each value arrives framed as untrusted request data, and $skill, @file or /command mentions inside it do not act; without a signature, anyone with the URL can trigger a run. For a sender that signs requests, first call request_secret so the user enters the secret privately (never ask for it in chat or invent one), then set signature with the returned secretRef, e.g. GitHub: {type:'webhook', signature:{header:'x-hub-signature-256', encoding:'hex', prefix:'sha256=', secretRef}}. To run only for some requests, add filters, all of which must match, e.g. filters:[{path:'headers.x-github-event', op:'equals', value:'pull_request'}, {path:'body.action', op:'in', value:['opened','reopened']}]; ops are equals, notEquals, in, startsWith and exists. A path segment ending in [] fans out over an array: {path:'body.issue.labels[].name', op:'equals', value:'needs more info'} matches when any label has that name, and notEquals only when none does. The result's webhookUrl is the public URL to give the user; if it is absent, this environment has no T3 Connect managed tunnel, so tell the user to enable T3 Connect remote access rather than sharing a path. Omit projectId for this thread's project. In this thread's project, runs post into THIS thread by default (bindToCurrentThread=true), which suits an orchestrator that sees every trigger, delegates work, and can dedupe against what is in flight; use false only when the user wants a fresh top-level thread per run. Elsewhere each run launches a fresh thread. Provider, model, and runtime settings inherit from this thread, or from the project default when there is no calling thread.",parameters: OrchestratorMcpScheduleTaskInput,success: OrchestratorMcpScheduleTaskResult,failure: OrchestratorMcpFailure,diff --git a/apps/server/src/scheduledTasks/webhookFilter.test.ts b/apps/server/src/scheduledTasks/webhookFilter.test.tsnew file mode 100644index 00000000000..1194a1aed51--- /dev/null+++ b/apps/server/src/scheduledTasks/webhookFilter.test.ts@@ -0,0 +1,95 @@+import { assert, describe, it } from "@effect/vitest";++import { findFailedWebhookFilter } from "./webhookFilter.ts";+import type { WebhookRequest } from "./webhookTemplate.ts";++const issueComment: WebhookRequest = {+ method: "POST",+ path: "/api/hooks/task-1",+ query: "",+ headers: { "content-type": "application/json", "x-github-event": "issue_comment" },+ bodyText: JSON.stringify({+ action: "created",+ issue: { number: 7, labels: [{ name: "bug" }, { name: "needs more info" }], assignees: [] },+ comment: { user: { login: "reporter", type: "User" } },+ }),+};++describe("findFailedWebhookFilter", () => {+ it("matches a wildcard path when any element matches", () => {+ assert.isNull(+ findFailedWebhookFilter(+ [+ { path: "body.issue.labels[].name", op: "equals", value: "needs more info" },+ { path: "body.issue.labels[].name", op: "in", value: ["needs more info", "triage"] },+ { path: "body.issue.labels[].name", op: "startsWith", value: "needs" },+ { path: "body.issue.labels[].name", op: "exists" },+ ],+ issueComment,+ ),+ );+ assert.deepEqual(+ findFailedWebhookFilter(+ [{ path: "body.issue.labels[].name", op: "equals", value: "wontfix" }],+ issueComment,+ ),+ { index: 0, path: "body.issue.labels[].name" },+ );+ });++ it("fails notEquals on a wildcard path when any element equals the value", () => {+ assert.deepEqual(+ findFailedWebhookFilter(+ [{ path: "body.issue.labels[].name", op: "notEquals", value: "bug" }],+ issueComment,+ ),+ { index: 0, path: "body.issue.labels[].name" },+ );+ assert.isNull(+ findFailedWebhookFilter(+ [{ path: "body.issue.labels[].name", op: "notEquals", value: "wontfix" }],+ issueComment,+ ),+ );+ });++ it("treats an empty or missing wildcard list as nothing to match", () => {+ assert.deepEqual(+ findFailedWebhookFilter(+ [{ path: "body.issue.assignees[].login", op: "exists" }],+ issueComment,+ ),+ { index: 0, path: "body.issue.assignees[].login" },+ );+ assert.isNull(+ findFailedWebhookFilter(+ [{ path: "body.issue.assignees[].login", op: "notEquals", value: "anyone" }],+ issueComment,+ ),+ );+ assert.deepEqual(+ findFailedWebhookFilter([{ path: "body.issue.number[].x", op: "exists" }], issueComment),+ { index: 0, path: "body.issue.number[].x" },+ );+ });++ it("still compares scalars without a wildcard", () => {+ assert.isNull(+ findFailedWebhookFilter(+ [+ { path: "body.action", op: "equals", value: "created" },+ { path: "body.comment.user.type", op: "notEquals", value: "Bot" },+ ],+ issueComment,+ ),+ );+ // A list without a wildcard in the path only satisfies exists.+ assert.deepEqual(+ findFailedWebhookFilter(+ [{ path: "body.issue.labels", op: "equals", value: "bug" }],+ issueComment,+ ),+ { index: 0, path: "body.issue.labels" },+ );+ });+});diff --git a/apps/server/src/scheduledTasks/webhookFilter.ts b/apps/server/src/scheduledTasks/webhookFilter.tsindex 6f880ef7ceb..882f3003642 100644--- a/apps/server/src/scheduledTasks/webhookFilter.ts+++ b/apps/server/src/scheduledTasks/webhookFilter.ts@@ -13,11 +13,7 @@ function scalarText(value: unknown): string | undefined {return undefined;}-/** Placeholders render null as missing, so filters treat it the same way. */-function matchesWebhookFilter(filter: ScheduledTaskWebhookFilter, value: unknown): boolean {- if (filter.op === "exists") return value !== undefined && value !== null;- const text = scalarText(value);- if (text === undefined) return false;+function matchesScalar(filter: ScheduledTaskWebhookFilter, text: string): boolean {switch (filter.op) {case "equals":return text === filter.value;@@ -27,9 +23,29 @@ function matchesWebhookFilter(filter: ScheduledTaskWebhookFilter, value: unknownreturn filter.value.includes(text);case "startsWith":return text.startsWith(filter.value);+ case "exists":+ return true;}}+/**+ * Placeholders render null as missing, so filters treat it the same way. A+ * path with a `[]` wildcard resolves to a list: `equals`, `in` and+ * `startsWith` match when any element does, `notEquals` only when none equals+ * the value, and `exists` when the list has an element.+ */+function matchesWebhookFilter(filter: ScheduledTaskWebhookFilter, value: unknown): boolean {+ if (Array.isArray(value) && /\[\]/.test(filter.path)) {+ const texts = value.map(scalarText).filter((text): text is string => text !== undefined);+ if (filter.op === "notEquals") return texts.every((text) => text !== filter.value);+ return texts.some((text) => matchesScalar(filter, text));+ }+ if (filter.op === "exists") return value !== undefined && value !== null;+ const text = scalarText(value);+ if (text === undefined) return false;+ return matchesScalar(filter, text);+}+/** The first filter the request fails, or null when every filter matches. */export function findFailedWebhookFilter(filters: ReadonlyArray<ScheduledTaskWebhookFilter>,diff --git a/apps/server/src/scheduledTasks/webhookTemplate.test.ts b/apps/server/src/scheduledTasks/webhookTemplate.test.tsindex b5ac2e69aa3..6aa23e12b03 100644--- a/apps/server/src/scheduledTasks/webhookTemplate.test.ts+++ b/apps/server/src/scheduledTasks/webhookTemplate.test.ts@@ -165,6 +165,23 @@ describe("renderWebhookPrompt", () => {);});+ it("renders a [] wildcard as the list of matching values", () => {+ const rendered = renderWebhookPrompt(+ "Labels: {{body.pull_request.labels[]}} Names: {{body.reviewers[].login}}",+ {+ ...githubPullRequest,+ bodyText: JSON.stringify({+ pull_request: { labels: ["bug", "ui"] },+ reviewers: [{ login: "ada" }, { name: "no login" }, { login: "bob" }],+ }),+ },+ "id",+ true,+ );+ assert.equal(rendered.prompt, 'Labels: [\n "bug",\n "ui"\n] Names: [\n "ada",\n "bob"\n]');+ assert.deepEqual(rendered.missing, []);+ });+it("does not resolve inherited object properties", () => {const rendered = renderWebhookPrompt("{{body.constructor}}{{body.__proto__}}{{headers.constructor}}{{headers.__proto__}}",diff --git a/apps/server/src/scheduledTasks/webhookTemplate.ts b/apps/server/src/scheduledTasks/webhookTemplate.tsindex 063d41a7ec4..84e2599dc0d 100644--- a/apps/server/src/scheduledTasks/webhookTemplate.ts+++ b/apps/server/src/scheduledTasks/webhookTemplate.ts@@ -83,12 +83,30 @@ function parseBody(request: WebhookRequest): unknown {}}+const WILDCARD = /^(.*)\[\]$/;++/**+ * Walks `segments` from `root`. A segment ending in `[]` names an array and+ * the rest of the path applies to each element, so `labels[].name` resolves+ * to the list of every label's name. Elements without the rest of the path+ * are dropped; a wildcard on a non-array resolves to undefined.+ */function lookup(root: unknown, segments: ReadonlyArray<string>): unknown {let current = root;- for (const segment of segments) {+ for (const [index, segment] of segments.entries()) {if (current === null || typeof current !== "object") return undefined;- if (!Object.hasOwn(current, segment)) return undefined;- current = (current as Record<string, unknown>)[segment];+ const wildcard = WILDCARD.exec(segment);+ const key = wildcard ? wildcard[1]! : segment;+ if (!Object.hasOwn(current, key)) return undefined;+ current = (current as Record<string, unknown>)[key];+ if (!wildcard) continue;+ if (!Array.isArray(current)) return undefined;+ const rest = segments.slice(index + 1);+ return current.flatMap((element) => {+ const value = rest.length === 0 ? element : lookup(element, rest);+ if (value === undefined) return [];+ return rest.some((part) => WILDCARD.test(part)) && Array.isArray(value) ? value : [value];+ });}return current;}diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.tsindex 67e2314a8b0..3e1ad5fbdf3 100644--- a/packages/contracts/src/scheduledTask.ts+++ b/packages/contracts/src/scheduledTask.ts@@ -109,7 +109,7 @@ const WebhookFilterPath = TrimmedNonEmptyString.check(Schema.isPattern(/^(body|headers|query)(\.|$)/),).annotate({description:- "Request value to test, in placeholder syntax without braces: headers.x-github-event, body.action, query.source.",+ "Request value to test, in placeholder syntax without braces: headers.x-github-event, body.action, query.source. A segment ending in [] fans out over an array, so body.issue.labels[].name tests every label's name.",});/**@@ -134,7 +134,7 @@ export const ScheduledTaskWebhookFilter = Schema.Union([Schema.Struct({ path: WebhookFilterPath, op: Schema.Literal("exists") }),]).annotate({description:- "Scalars compare as strings; objects and arrays only satisfy 'exists'. Every op but 'exists' fails when the path is missing.",+ "Scalars compare as strings; objects and arrays only satisfy 'exists'. Every op but 'exists' fails when the path is missing. A [] wildcard path yields a list: equals, in and startsWith match when any element does, notEquals when no element equals the value, exists when the list is not empty.",});export type ScheduledTaskWebhookFilter = typeof ScheduledTaskWebhookFilter.Type;export type ScheduledTaskWebhookFilterOp = ScheduledTaskWebhookFilter["op"];