From c4464c89edf19fff6900a5f6496d7cb5439dd012 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 9 Oct 2026 22:22:28 +0000 Subject: [PATCH 1/5] Replace webhook JavaScript handlers with validated JSON conditions and explicit cutover --- .github/workflows/deploy.yml | 25 ++ docs/cloudflare-tail.md | 2 +- docs/job-trigger-context.md | 4 +- docs/webhook-conditions.md | 78 +++++ package-lock.json | 153 +++++++-- package.json | 5 +- packages/api-client/src/schema.d.ts | 150 +++++--- .../migrations/0013_webhook_conditions.sql | 43 +++ .../migrations/build-manager-conditions.json | 60 ++++ packages/api/package.json | 2 + .../scripts/restore-webhook-conditions.mjs | 20 ++ .../validate-webhook-conditions-cutover.ts | 42 +++ .../scripts/webhook-conditions-cutover.mjs | 15 + packages/api/src/api-contract.ts | 20 +- packages/api/src/auth-api.ts | 2 +- packages/api/src/custom-handler.ts | 70 ---- packages/api/src/flow-schemas.ts | 7 +- packages/api/src/flow-service.ts | 6 +- .../api/src/postgres/automation-scheduler.ts | 17 +- packages/api/src/postgres/schema.ts | 8 +- packages/api/src/postgres/webhook-service.ts | 12 +- packages/api/src/protected-api.ts | 22 +- packages/api/src/trigger-context.ts | 6 +- packages/api/src/types.ts | 1 - packages/api/src/webhook-conditions.ts | 80 +++++ packages/api/src/webhook-trigger.ts | 7 +- packages/api/test/cloudflare-tail.test.ts | 2 +- packages/api/test/conditions-api.test.ts | 58 ++++ .../api/test/conditions-runtime-paths.test.ts | 92 +++++ packages/api/test/custom-handler.test.ts | 61 ---- packages/api/test/trigger-context.test.ts | 8 +- packages/api/test/webhook-conditions.test.ts | 71 ++++ packages/api/test/webhook-trigger.test.ts | 10 +- packages/api/wrangler.jsonc | 1 - .../src/features/jobs/conditions-editor.tsx | 28 ++ packages/app/src/features/jobs/detail.tsx | 2 +- .../app/src/features/jobs/handler-test.tsx | 13 - .../app/src/features/jobs/provider-fields.tsx | 6 +- packages/app/test/editor.browser.test.mjs | 51 ++- packages/docs/api/authentication.mdx | 2 +- packages/docs/concepts.mdx | 2 +- packages/docs/integrations/triggers.mdx | 52 +++ packages/docs/llms-full.txt | 2 +- packages/docs/mcp/tools.mdx | 2 +- packages/docs/openapi.yaml | 324 +++++++++++------- scripts/webhook-conditions-runtime.test.mjs | 19 + scripts/worker-infrastructure-baseline.json | 1 - 47 files changed, 1256 insertions(+), 408 deletions(-) create mode 100644 docs/webhook-conditions.md create mode 100644 packages/api/migrations/0013_webhook_conditions.sql create mode 100644 packages/api/migrations/build-manager-conditions.json create mode 100644 packages/api/scripts/restore-webhook-conditions.mjs create mode 100644 packages/api/scripts/validate-webhook-conditions-cutover.ts create mode 100644 packages/api/scripts/webhook-conditions-cutover.mjs delete mode 100644 packages/api/src/custom-handler.ts create mode 100644 packages/api/src/webhook-conditions.ts create mode 100644 packages/api/test/conditions-api.test.ts create mode 100644 packages/api/test/conditions-runtime-paths.test.ts delete mode 100644 packages/api/test/custom-handler.test.ts create mode 100644 packages/api/test/webhook-conditions.test.ts create mode 100644 packages/app/src/features/jobs/conditions-editor.tsx delete mode 100644 packages/app/src/features/jobs/handler-test.tsx create mode 100644 scripts/webhook-conditions-runtime.test.mjs diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index f8701c22..775949e3 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -5,6 +5,11 @@ on: branches: - main workflow_dispatch: + inputs: + validate_conditions_only: + description: Validate GEN-2158 on its isolated Neon clone without deploying + type: boolean + default: false permissions: contents: read @@ -15,7 +20,23 @@ concurrency: cancel-in-progress: false jobs: + validate-conditions: + if: github.event_name == 'workflow_dispatch' && inputs.validate_conditions_only + runs-on: ubuntu-latest + environment: production + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 24 + cache: npm + - run: npm ci + - name: Validate explicit cutover on isolated Neon branch + run: npx tsx packages/api/scripts/validate-webhook-conditions-cutover.ts --neon + env: + DATABASE_URL: ${{ secrets.DATABASE_URL }} deploy: + if: github.event_name != 'workflow_dispatch' || !inputs.validate_conditions_only name: Deploy app and marketing site runs-on: ubuntu-latest timeout-minutes: 15 @@ -84,5 +105,9 @@ jobs: path: ${{ runner.temp }}/factorize-app-release retention-days: 35 if-no-files-found: error + - name: Restore explicitly migrated webhook triggers after conditions deployment + run: node packages/api/scripts/restore-webhook-conditions.mjs https://app.factorize.sh + env: + DATABASE_URL: ${{ secrets.DATABASE_URL }} - name: Verify public production routing after deployment run: node scripts/verify-public-routing.mjs https://app.factorize.sh --wait diff --git a/docs/cloudflare-tail.md b/docs/cloudflare-tail.md index 892c4d84..d211e754 100644 --- a/docs/cloudflare-tail.md +++ b/docs/cloudflare-tail.md @@ -28,4 +28,4 @@ For caught internal failures, log a structured event: console.error(JSON.stringify({ event: "factorize_unexpected_failure", component: "billing", message: error.message })); ``` -Do not include request bodies, headers, credentials, or prompts in the structured log. Expected 4xx/domain failures remain ordinary Tail events unless the Job handler explicitly accepts them. +Do not include request bodies, headers, credentials, or prompts in the structured log. Expected 4xx/domain failures remain ordinary Tail events unless the Job conditions explicitly accept them. diff --git a/docs/job-trigger-context.md b/docs/job-trigger-context.md index d716b54f..b01a58db 100644 --- a/docs/job-trigger-context.md +++ b/docs/job-trigger-context.md @@ -21,13 +21,13 @@ The available value beneath a slug is: | Cloudflare Tail | Complete sanitized Tail delivery, plus `provider`, `event`, `delivery_id` | | Job lifecycle | `source_job_id`, `source_run_id`, `final_state`, `transitioned_at`, `observation_destination` | -Every trigger returned by `GET /api/v1/jobs` and `GET /api/v1/jobs/:id` (and the corresponding MCP `list_jobs` and `get_job` tools) includes a `reflection` object. It contains the stable `slug`, trigger kind/provider, whether the result is dynamic, and a flat `paths` list with nested path, basic value type, description, and occasional example. The Job editor consumes this same canonical contract for Mustache autocomplete. A webhook with a replacing handler reports `dynamic: true` and an explicit `*`/`unknown` fallback because arbitrary handler output cannot be inferred safely. +Every trigger returned by `GET /api/v1/jobs` and `GET /api/v1/jobs/:id` (and the corresponding MCP `list_jobs` and `get_job` tools) includes a `reflection` object. It contains the stable `slug`, trigger kind/provider, whether the result is dynamic, and a flat `paths` list with nested path, basic value type, description, and occasional example. The Job editor consumes this same canonical contract for Mustache autocomplete. Webhook conditions preserve normal provider context reflection. Manual invocation accepts an optional display `name`, `prompt`, JSON object `data`, and `idempotencyKey`. The display name is used as the run name, while prompt and data are exposed beneath the manual trigger slug. `idempotencyKey` is the client-facing value and must not include the reserved internal `manual:` prefix. Reusing the same value returns the original invocation. Run inspection exposes that reusable value as `invocation.idempotency_key`, while `invocation.claim_key` is the internal prefixed claim and must not be passed back to the invocation API. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted. Run inspection returns `context` as the complete persisted object and `invocation.trigger_id` as the trigger that fired. Parameter-era stored Jobs are migrated: old context and parameters are retained beneath `legacy_context` and `legacy_parameters` in the corresponding trigger context. They are not used as global template variables. -Every webhook trigger may also define `handlerCode` containing one synchronous `function handler(webhook)` declaration. Factorize runs it only after provider authentication and trigger scoping, inside an isolated Worker with no bindings or outbound network access. Returning `false` rejects the delivery, `true` retains the default value above, and a JSON-compatible object replaces that value beneath the stable trigger slug. Timeouts, exceptions, and invalid return values are recorded in webhook activity and never create a run. REST `POST /api/v1/job-handlers/test` and MCP `test_job_webhook_handler` exercise the same isolation boundary without creating an invocation. +Webhook triggers may define optional declarative `conditions`; they filter without replacing context. See [webhook conditions](webhook-conditions.md) for operators, JSONPath, limits and preview behavior. Prompt and run-name templates render plain text: double-brace substitutions preserve URLs, quotes, Markdown, and code without HTML entity escaping. Triple-brace substitutions remain supported. Literal entity text in job context is preserved, not decoded. The web UI escapes rendered values when displaying them. This applies to new runs; existing persisted prompts are unchanged. diff --git a/docs/webhook-conditions.md b/docs/webhook-conditions.md new file mode 100644 index 00000000..3f2f7146 --- /dev/null +++ b/docs/webhook-conditions.md @@ -0,0 +1,78 @@ +# Webhook conditions + +Webhook trigger configuration accepts optional `conditions`, a json-rules-engine +condition tree, not a full rule/engine configuration. No conditions means no +additional filtering. `all`, `any`, and `not` compose leaf conditions; empty groups +are invalid. Invalid configuration or evaluation failures never create a run. +Provider authentication, scope/event/action selection and matchRules still apply. + +```json +{"all":[{"fact":"webhook","path":"$.check_suite.conclusion","operator":"equal","value":"success"},{"fact":"webhook","path":"$.check_suite.head_branch","operator":"startsWith","value":"feature/"}]} +``` + +`webhook` is the only fact. It contains the prepared context the job receives: +original provider fields, provider/event/delivery_id metadata, and existing +Linear `issue`/ClickUp `task` aliases. Tail context has already been sanitized. +Delayed GitHub dequeue verification still checks an open PR targeting main, +retries unresolved mergeability, and only proceeds on confirmed conflict. Its +prepared pull_request includes verified mergeable=false and mergeable_state. +Conditions use the latest trigger configuration and never transform context. + +JSONPath supports `$`, ordinary `.property` and quoted bracket properties, +array indexes `[0]`, and wildcards `[*]`/`.*`. No recursive descent, slices, +unions, filters, scripts or executable expressions are accepted; expression +evaluation is disabled. A scalar path returns its selected value (including an +array when selecting an array field). A wildcard path always returns an array +of matches, even for zero or one match. Missing scalar paths yield undefined. +`notEqual` may match missing fields; null and missing are distinct. Malformed +paths are configuration errors, not non-matches. + +| Operator | Configured value | Semantics | +| --- | --- | --- | +| equal / notEqual | string, number, boolean or null | Strict scalar equality/inequality; string IDs differ from numeric IDs | +| lessThan / lessThanInclusive / greaterThan / greaterThanInclusive | finite number | Both operands must be finite numbers; strings/null/missing do not match | +| in / notIn | array of scalar values | Strict membership/non-membership of the selected value in the configured array | +| contains / doesNotContain | scalar | Strict array membership/non-membership; a non-array selected value does not match | +| startsWith | string | String prefix; missing/null/non-string selected values do not match | + +Boolean negation follows the library semantics: `not` negates a valid result, +including a non-match due to a wrong operand type. No existence operator is +introduced. Conditions are limited to 16,384 serialized UTF-8 bytes, depth 16 +(root counts as 1), 128 nodes, and 512 characters per path. User priorities, +fact references in values, callbacks and network facts are rejected. + +The editor provides conditions JSON and prepared-example JSON textareas. +POST `/api/v1/job-conditions/test` and MCP `test_job_webhook_conditions` accept +`{conditions?, webhook}` with flows:write authorization. The context is limited +to 262,144 serialized bytes; the HTTP request is limited to 300,000 bytes. +They return `decision: match | no-match | error` plus plain JSON result details. +Configuration/request validation errors return a validation error. Details with +no `result` were not evaluated, and must not be displayed as failed. The preview +does not authenticate the example, route events, verify live GitHub state, or +invoke jobs. Runtime activity stores only concise decisions, never these values. + +## Explicit GEN-2158 cutover + +Migration 0013 inventories **every stored trigger**, including disabled and +removed triggers. It recognizes only the exact reviewed Build Manager source, +job ID and trigger slug/event/action. Any additional or changed handler aborts +the transaction for explicit review; no arbitrary JavaScript is translated. +It records prior enabled state, disables affected triggers, removes the legacy +property and installs the three exclusion groups in +`packages/api/migrations/build-manager-conditions.json`. Absent check_suite +matches, preserving the old early return for selected completed events. +Trigger identity, routing and prompt context stay intact. A database constraint +rejects future writes of the removed property. + +Before production, validate on an isolated Neon branch and inventory again. +The production workflow migrates before deploying the conditions Worker, then +runs `restore-webhook-conditions.mjs` only after deployment. The public session +response's `X-Factorize-Webhook-Conditions: v1` marker gates restoration. On any +migration/deployment/verification failure, affected triggers remain disabled. +Restoration rejects changed conditions or prematurely enabled triggers and +restores the recorded prior enabled state transactionally. After deployment, +verify the canonical authenticated preview on exclusion/accepted examples, +trigger identity/configuration/enabled state, and no stored legacy property. +Do not deploy the old runtime over the converted data: disable migrated triggers +first if a backend rollback becomes necessary. A frontend-only rollback must +retain the conditions API/runtime. diff --git a/package-lock.json b/package-lock.json index f0d50a4e..1d5e36a7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1195,7 +1195,8 @@ "@cloudflare/workerd-linux-64": "1.20251118.0", "@cloudflare/workerd-linux-arm64": "1.20251118.0", "@cloudflare/workerd-windows-64": "1.20251118.0" - } + }, + "peer": true }, "node_modules/@cloudflare/vitest-pool-workers/node_modules/wrangler": { "version": "4.50.0", @@ -1360,7 +1361,8 @@ "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-5.20260910.1.tgz", "integrity": "sha512-heMipAW1SEPWaXCcleaxGMOEpvq/F4UKdc02Gb3xiLx1La5mE6VPFGBmOTGMt7kn+qX4L8D2WsYCfmrC4kKxLw==", "devOptional": true, - "license": "MIT OR Apache-2.0" + "license": "MIT OR Apache-2.0", + "peer": true }, "node_modules/@cspotcode/source-map-support": { "version": "0.8.1", @@ -2918,6 +2920,30 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@jsep-plugin/assignment": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@jsep-plugin/assignment/-/assignment-1.3.0.tgz", + "integrity": "sha512-VVgV+CXrhbMI3aSusQyclHkenWSAm95WaiKrMxRFam3JSUiIaQjoMIw2sEs/OX4XifnqeQUN4DYbJjlA8EfktQ==", + "license": "MIT", + "engines": { + "node": ">= 10.16.0" + }, + "peerDependencies": { + "jsep": "^0.4.0||^1.0.0" + } + }, + "node_modules/@jsep-plugin/regex": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@jsep-plugin/regex/-/regex-1.0.4.tgz", + "integrity": "sha512-q7qL4Mgjs1vByCaTnDFcBnV9HS7GVPJX5vyVoCgZHNSC9rjwIlmbXG5sUuorR5ndfHAIlJ8pVStxvjXHbNvtUg==", + "license": "MIT", + "engines": { + "node": ">= 10.16.0" + }, + "peerDependencies": { + "jsep": "^0.4.0||^1.0.0" + } + }, "node_modules/@modelcontextprotocol/core": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz", @@ -2954,7 +2980,8 @@ }, "engines": { "node": ">=20" - } + }, + "peer": true }, "node_modules/@napi-rs/lzma-linux-x64-gnu": { "version": "1.5.1", @@ -4188,7 +4215,8 @@ "license": "MIT", "dependencies": { "@types/ms": "*" - } + }, + "peer": true }, "node_modules/@types/deep-eql": { "version": "4.0.2", @@ -4263,7 +4291,8 @@ "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" - } + }, + "peer": true }, "node_modules/@types/react": { "version": "19.3.0", @@ -4272,7 +4301,8 @@ "license": "MIT", "dependencies": { "csstype": "^3.2.2" - } + }, + "peer": true }, "node_modules/@types/react-dom": { "version": "19.3.0", @@ -4383,7 +4413,8 @@ }, "funding": { "url": "https://opencollective.com/vitest" - } + }, + "peer": true }, "node_modules/@vitest/snapshot": { "version": "3.2.7", @@ -4398,7 +4429,8 @@ }, "funding": { "url": "https://opencollective.com/vitest" - } + }, + "peer": true }, "node_modules/@vitest/spy": { "version": "3.2.7", @@ -4670,6 +4702,15 @@ "dev": true, "license": "MIT" }, + "node_modules/clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==", + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, "node_modules/color": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", @@ -5580,6 +5621,12 @@ "@types/estree": "^1.0.0" } }, + "node_modules/eventemitter2": { + "version": "6.4.9", + "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-6.4.9.tgz", + "integrity": "sha512-JEPTiaOt9f04oa6NOkc4aH+nVp5I3wEjpHbIPqfgCdD5v5bUzy7xQqwcVO2aDQgOWhI28da57HksMrzK9HlRxg==", + "license": "MIT" + }, "node_modules/exit-hook": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-2.2.1.tgz", @@ -5734,7 +5781,14 @@ }, "engines": { "node": ">=20.0.0" - } + }, + "peer": true + }, + "node_modules/hash-it": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/hash-it/-/hash-it-6.0.1.tgz", + "integrity": "sha512-qhl8+l4Zwi1eLlL3lja5ywmDQnBzLEJxd0QJoAVIgZpgQbdtVZrN5ypB0y3VHwBlvAalpcbM2/A6x7oUks5zNg==", + "license": "MIT" }, "node_modules/hast-util-to-jsx-runtime": { "version": "2.3.6", @@ -5783,7 +5837,8 @@ "license": "MIT", "engines": { "node": ">=16.9.0" - } + }, + "peer": true }, "node_modules/html-url-attributes": { "version": "3.0.1", @@ -5908,7 +5963,8 @@ "license": "MIT", "bin": { "jiti": "lib/jiti-cli.mjs" - } + }, + "peer": true }, "node_modules/js-levenshtein": { "version": "1.1.6", @@ -5950,6 +6006,31 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/jsep": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/jsep/-/jsep-1.4.0.tgz", + "integrity": "sha512-B7qPcEVE3NVkmSJbaYxvv4cHkVW7DQsZz13pUMrfS8z8Q/BuShN+gcTXrUlPiGqM2/t/EEaI030bpxMqY8gMlw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 10.16.0" + } + }, + "node_modules/json-rules-engine": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/json-rules-engine/-/json-rules-engine-7.3.1.tgz", + "integrity": "sha512-NyRTQZllvAt7AQ3g9P7/t4nIwlEB+EyZV7y8/WgXfZWSlpcDryt1UH9CsoU+Z+MDvj8umN9qqEcbE6qnk9JAHw==", + "license": "ISC", + "dependencies": { + "clone": "^2.1.2", + "eventemitter2": "^6.4.4", + "hash-it": "^6.0.0", + "jsonpath-plus": "^10.3.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", @@ -5957,6 +6038,24 @@ "dev": true, "license": "MIT" }, + "node_modules/jsonpath-plus": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/jsonpath-plus/-/jsonpath-plus-10.3.0.tgz", + "integrity": "sha512-8TNmfeTCk2Le33A3vRRwtuworG/L5RrgMvdjhKZxvyShO+mBu2fP50OWUjRLNtvw344DdDarFh9buFAZs5ujeA==", + "license": "MIT", + "dependencies": { + "@jsep-plugin/assignment": "^1.3.0", + "@jsep-plugin/regex": "^1.0.4", + "jsep": "^1.4.0" + }, + "bin": { + "jsonpath": "bin/jsonpath-cli.js", + "jsonpath-plus": "bin/jsonpath-cli.js" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/kleur": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", @@ -5995,7 +6094,8 @@ "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" - } + }, + "peer": true }, "node_modules/lightningcss-android-arm64": { "version": "1.32.0", @@ -7100,7 +7200,8 @@ "pg-native": { "optional": true } - } + }, + "peer": true }, "node_modules/pg-cloudflare": { "version": "1.4.0", @@ -7308,7 +7409,8 @@ "license": "MIT", "engines": { "node": ">=0.10.0" - } + }, + "peer": true }, "node_modules/react-dom": { "version": "19.3.0", @@ -7320,7 +7422,8 @@ }, "peerDependencies": { "react": "^19.3.0" - } + }, + "peer": true }, "node_modules/react-markdown": { "version": "10.1.0", @@ -7508,7 +7611,8 @@ "license": "MIT", "engines": { "node": ">=10" - } + }, + "peer": true }, "node_modules/seroval-plugins": { "version": "1.6.9", @@ -7876,7 +7980,8 @@ }, "engines": { "node": ">=14.17" - } + }, + "peer": true }, "node_modules/undici": { "version": "7.29.0", @@ -7903,7 +8008,8 @@ "license": "MIT", "dependencies": { "pathe": "^2.0.3" - } + }, + "peer": true }, "node_modules/unified": { "version": "11.0.5", @@ -8109,7 +8215,8 @@ "yaml": { "optional": true } - } + }, + "peer": true }, "node_modules/vite-node": { "version": "3.2.4", @@ -8205,7 +8312,8 @@ "jsdom": { "optional": true } - } + }, + "peer": true }, "node_modules/whatwg-mimetype": { "version": "3.0.0", @@ -8253,7 +8361,8 @@ "@cloudflare/workerd-linux-64": "1.20260910.1", "@cloudflare/workerd-linux-arm64": "1.20260910.1", "@cloudflare/workerd-windows-64": "1.20260910.1" - } + }, + "peer": true }, "node_modules/wrangler": { "version": "4.131.0", @@ -8893,6 +9002,8 @@ "cron-parser": "^5.10.1", "drizzle-orm": "^0.45.2", "hono": "^4.11.4", + "json-rules-engine": "^7.3.1", + "jsonpath-plus": "^10.3.0", "mustache": "^4.2.0", "pg": "8.16.3", "zod": "^4.6.2" diff --git a/package.json b/package.json index 03889c7b..353a5f29 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "build:marketing": "npm run build:marketing --workspace=factorize-marketing", "build:css": "npm run build:app", "test": "npm run test --workspaces --if-present", - "check": "npm run check:hosting && npm run check:boundaries && npm run check:client && npm run check --workspace=factorize-app && npm run check --workspace=factorize && npm run test:hosting-runtime && npm run test:oauth-runtime && npm run test:rollback-runtime && npm run check --workspace=factorize-marketing && npm run check --workspace=factorize-tail-relay", + "check": "npm run check:hosting && npm run check:boundaries && npm run check:client && npm run check --workspace=factorize-app && npm run check --workspace=factorize && npm run test:conditions-runtime && npm run test:hosting-runtime && npm run test:oauth-runtime && npm run test:rollback-runtime && npm run check --workspace=factorize-marketing && npm run check --workspace=factorize-tail-relay", "deploy": "npm run deploy:marketing && npm run deploy:app && npm run deploy:tail-relay", "deploy:marketing": "npm run deploy --workspace=factorize-marketing", "deploy:app": "npm run deploy --workspace=factorize", @@ -29,7 +29,8 @@ "check:hosting": "node --test scripts/hosting-invariants.test.mjs scripts/deployment-gate.test.mjs scripts/trusted-app-release.test.mjs && python3 scripts/test-retain-app-assets.py", "test:hosting-runtime": "node --test scripts/hosting-runtime.test.mjs", "test:oauth-runtime": "node --test scripts/oauth-runtime.test.mjs", - "test:rollback-runtime": "node --test scripts/rollback-runtime.test.mjs" + "test:rollback-runtime": "node --test scripts/rollback-runtime.test.mjs", + "test:conditions-runtime": "node --test scripts/webhook-conditions-runtime.test.mjs" }, "engines": { "node": ">=24.12.0" diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 590680ae..dce8d6c2 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -978,7 +978,7 @@ export interface paths { patch?: never; trace?: never; }; - "/api/v1/job-handlers/test": { + "/api/v1/job-conditions/test": { parameters: { query?: never; header?: never; @@ -988,12 +988,14 @@ export interface paths { get?: never; put?: never; /** - * Test webhook handler - * @description Requires the flows:write scope. + * Test webhook conditions + * @description Evaluates supplied prepared webhook context only; does not authenticate the example, route events, verify GitHub state, or invoke jobs. + * + * Requires the flows:write scope. * * Accepts a scoped bearer token or interactive owner session. */ - post: operations["post_api_v1_job_handlers_test"]; + post: operations["post_api_v1_job_conditions_test"]; delete?: never; options?: never; head?: never; @@ -1701,7 +1703,9 @@ export interface components { /** @default true */ enabled: boolean; config: { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "linear"; projectId: string; @@ -1711,7 +1715,9 @@ export interface components { targetId: string; }[]; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "clickup"; listId: string; @@ -1721,7 +1727,9 @@ export interface components { targetId: string; }[]; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "github"; installationId: number; @@ -1734,7 +1742,9 @@ export interface components { targetId: string; }[]; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "cloudflareTail"; integrationId: string; @@ -1761,9 +1771,11 @@ export interface components { name?: string; idempotencyKey?: string; }; - JobHandlerTest: { - handlerCode: string; - payload: { + JobConditionsTest: { + conditions?: { + [key: string]: unknown; + }; + webhook: { [key: string]: unknown; }; }; @@ -1883,6 +1895,8 @@ export interface operations { /** @description Unauthenticated sessions return authenticated:false; expired, unverified, removed or revoked owners are unauthenticated. */ 200: { headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ "X-Factorize-Contract"?: "gen-2157-static-v1"; [name: string]: unknown; @@ -1942,6 +1956,8 @@ export interface operations { /** @description Success */ 200: { headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ "X-Factorize-Contract"?: "gen-2157-static-v1"; [name: string]: unknown; @@ -1985,6 +2001,8 @@ export interface operations { /** @description Success */ 202: { headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ "X-Factorize-Contract"?: "gen-2157-static-v1"; [name: string]: unknown; @@ -2026,6 +2044,8 @@ export interface operations { /** @description Success */ 200: { headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ "X-Factorize-Contract"?: "gen-2157-static-v1"; [name: string]: unknown; @@ -2066,6 +2086,8 @@ export interface operations { /** @description Success */ 200: { headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ "X-Factorize-Contract"?: "gen-2157-static-v1"; [name: string]: unknown; @@ -2107,6 +2129,8 @@ export interface operations { /** @description Success */ 200: { headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ "X-Factorize-Contract"?: "gen-2157-static-v1"; [name: string]: unknown; @@ -2148,6 +2172,8 @@ export interface operations { /** @description Success */ 200: { headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ "X-Factorize-Contract"?: "gen-2157-static-v1"; [name: string]: unknown; @@ -2189,6 +2215,8 @@ export interface operations { /** @description Success */ 200: { headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ "X-Factorize-Contract"?: "gen-2157-static-v1"; [name: string]: unknown; @@ -2223,6 +2251,8 @@ export interface operations { /** @description Success */ 200: { headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ "X-Factorize-Contract"?: "gen-2157-static-v1"; [name: string]: unknown; @@ -3807,7 +3837,9 @@ export interface operations { /** @default true */ enabled: boolean; config: { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "linear"; projectId: string; @@ -3818,7 +3850,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "clickup"; listId: string; @@ -3829,7 +3863,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "github"; installationId: number; @@ -3843,7 +3879,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "cloudflareTail"; integrationId: string; @@ -3967,7 +4005,9 @@ export interface operations { /** @default true */ enabled: boolean; config: { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "linear"; projectId: string; @@ -3978,7 +4018,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "clickup"; listId: string; @@ -3989,7 +4031,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "github"; installationId: number; @@ -4003,7 +4047,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "cloudflareTail"; integrationId: string; @@ -4047,7 +4093,7 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; - post_api_v1_job_handlers_test: { + post_api_v1_job_conditions_test: { parameters: { query?: never; header?: never; @@ -4056,7 +4102,7 @@ export interface operations { }; requestBody: { content: { - "application/json": components["schemas"]["JobHandlerTest"]; + "application/json": components["schemas"]["JobConditionsTest"]; }; }; responses: { @@ -4067,16 +4113,12 @@ export interface operations { }; content: { "application/json": { - /** @constant */ - ok: true; - decision: boolean | { - [key: string]: unknown; - }; - } | { - /** @constant */ - ok: false; /** @enum {string} */ - category: "handler_error" | "invalid_return" | "timeout" | "platform_error"; + decision: "match" | "no-match" | "error"; + error?: string; + details: { + [key: string]: unknown; + }[]; }; }; }; @@ -4303,7 +4345,9 @@ export interface operations { /** @default true */ enabled: boolean; config: { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "linear"; projectId: string; @@ -4314,7 +4358,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "clickup"; listId: string; @@ -4325,7 +4371,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "github"; installationId: number; @@ -4339,7 +4387,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "cloudflareTail"; integrationId: string; @@ -4432,7 +4482,9 @@ export interface operations { /** @default true */ enabled?: boolean; config: { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "linear"; projectId: string; @@ -4442,7 +4494,9 @@ export interface operations { targetId: string; }[]; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "clickup"; listId: string; @@ -4452,7 +4506,9 @@ export interface operations { targetId: string; }[]; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "github"; installationId: number; @@ -4465,7 +4521,9 @@ export interface operations { targetId: string; }[]; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "cloudflareTail"; integrationId: string; @@ -4556,7 +4614,9 @@ export interface operations { /** @default true */ enabled: boolean; config: { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "linear"; projectId: string; @@ -4567,7 +4627,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "clickup"; listId: string; @@ -4578,7 +4640,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "github"; installationId: number; @@ -4592,7 +4656,9 @@ export interface operations { }[]; secretConfigured?: boolean; } | { - handlerCode?: string; + conditions?: { + [key: string]: unknown; + }; /** @constant */ provider: "cloudflareTail"; integrationId: string; diff --git a/packages/api/migrations/0013_webhook_conditions.sql b/packages/api/migrations/0013_webhook_conditions.sql new file mode 100644 index 00000000..f44d961f --- /dev/null +++ b/packages/api/migrations/0013_webhook_conditions.sql @@ -0,0 +1,43 @@ +-- GEN-2158: explicit reviewed cutover. The deploy must restore only after +-- the conditions Worker is deployed and verified. Unknown handlers abort. +LOCK TABLE app.triggers IN SHARE ROW EXCLUSIVE MODE; +CREATE TABLE app.webhook_conditions_cutover ( + tenant_id uuid NOT NULL, trigger_id uuid NOT NULL, was_enabled boolean NOT NULL, + conditions jsonb NOT NULL, restored_at timestamptz, + PRIMARY KEY (tenant_id, trigger_id), + FOREIGN KEY (tenant_id, trigger_id) REFERENCES app.triggers(tenant_id, id) ON DELETE CASCADE +); +DO $cutover$ +DECLARE legacy record; +BEGIN + FOR legacy IN SELECT * FROM app.triggers WHERE config ? 'handlerCode' LOOP + IF legacy.job_id <> '0bf608ba-e2f3-4c75-ac1d-42971bcd1cc4'::uuid + OR legacy.slug <> 'trigger-2' OR legacy.kind <> 'webhook' + OR legacy.config->>'provider' IS DISTINCT FROM 'github' + OR legacy.config->>'event' IS DISTINCT FROM 'check_suite' + OR legacy.config->>'action' IS DISTINCT FROM 'completed' + OR legacy.config->>'handlerCode' IS DISTINCT FROM $reviewed$function handler(webhook) { + const suite = webhook.check_suite; + if (webhook.action !== "completed" || !suite) return true; + const branch = typeof suite.head_branch === "string" ? suite.head_branch : ""; + if (suite.conclusion === "success" && branch.startsWith("gh-readonly-queue/")) return false; + if (suite.conclusion === "success" && branch === "main" && webhook.sender?.login === "github-merge-queue[bot]") return false; + if (suite.conclusion === "skipped" && suite.app?.slug === "mintlify") return false; + return true; +}$reviewed$ + OR legacy.config ? 'conditions' THEN + RAISE EXCEPTION 'GEN-2158 migration blocker: unreviewed handler on trigger %', legacy.id; + END IF; + INSERT INTO app.webhook_conditions_cutover(tenant_id,trigger_id,was_enabled,conditions) + VALUES (legacy.tenant_id,legacy.id,legacy.enabled,$conditions${"not": {"any": [{"all": [{"fact": "webhook", "path": "$.check_suite.conclusion", "operator": "equal", "value": "success"}, {"fact": "webhook", "path": "$.check_suite.head_branch", "operator": "startsWith", "value": "gh-readonly-queue/"}]}, {"all": [{"fact": "webhook", "path": "$.check_suite.conclusion", "operator": "equal", "value": "success"}, {"fact": "webhook", "path": "$.check_suite.head_branch", "operator": "equal", "value": "main"}, {"fact": "webhook", "path": "$.sender.login", "operator": "equal", "value": "github-merge-queue[bot]"}]}, {"all": [{"fact": "webhook", "path": "$.check_suite.conclusion", "operator": "equal", "value": "skipped"}, {"fact": "webhook", "path": "$.check_suite.app.slug", "operator": "equal", "value": "mintlify"}]}]}}$conditions$::jsonb); + UPDATE app.triggers SET enabled=false, + config=(config-'handlerCode') || jsonb_build_object('conditions',$conditions${"not": {"any": [{"all": [{"fact": "webhook", "path": "$.check_suite.conclusion", "operator": "equal", "value": "success"}, {"fact": "webhook", "path": "$.check_suite.head_branch", "operator": "startsWith", "value": "gh-readonly-queue/"}]}, {"all": [{"fact": "webhook", "path": "$.check_suite.conclusion", "operator": "equal", "value": "success"}, {"fact": "webhook", "path": "$.check_suite.head_branch", "operator": "equal", "value": "main"}, {"fact": "webhook", "path": "$.sender.login", "operator": "equal", "value": "github-merge-queue[bot]"}]}, {"all": [{"fact": "webhook", "path": "$.check_suite.conclusion", "operator": "equal", "value": "skipped"}, {"fact": "webhook", "path": "$.check_suite.app.slug", "operator": "equal", "value": "mintlify"}]}]}}$conditions$::jsonb), updated_at=now() + WHERE tenant_id=legacy.tenant_id AND id=legacy.id; + UPDATE app.jobs SET updated_at=now() WHERE tenant_id=legacy.tenant_id AND id=legacy.job_id; + END LOOP; + IF EXISTS (SELECT 1 FROM app.triggers WHERE config ? 'handlerCode') THEN + RAISE EXCEPTION 'GEN-2158: stored handlers remain'; + END IF; +END $cutover$; +-- Prevent the previous Worker (or any direct writer) reintroducing a handler. +ALTER TABLE app.triggers ADD CONSTRAINT no_webhook_handler_code CHECK (NOT (config ? 'handlerCode')); diff --git a/packages/api/migrations/build-manager-conditions.json b/packages/api/migrations/build-manager-conditions.json new file mode 100644 index 00000000..a7990481 --- /dev/null +++ b/packages/api/migrations/build-manager-conditions.json @@ -0,0 +1,60 @@ +{ + "not": { + "any": [ + { + "all": [ + { + "fact": "webhook", + "path": "$.check_suite.conclusion", + "operator": "equal", + "value": "success" + }, + { + "fact": "webhook", + "path": "$.check_suite.head_branch", + "operator": "startsWith", + "value": "gh-readonly-queue/" + } + ] + }, + { + "all": [ + { + "fact": "webhook", + "path": "$.check_suite.conclusion", + "operator": "equal", + "value": "success" + }, + { + "fact": "webhook", + "path": "$.check_suite.head_branch", + "operator": "equal", + "value": "main" + }, + { + "fact": "webhook", + "path": "$.sender.login", + "operator": "equal", + "value": "github-merge-queue[bot]" + } + ] + }, + { + "all": [ + { + "fact": "webhook", + "path": "$.check_suite.conclusion", + "operator": "equal", + "value": "skipped" + }, + { + "fact": "webhook", + "path": "$.check_suite.app.slug", + "operator": "equal", + "value": "mintlify" + } + ] + } + ] + } +} diff --git a/packages/api/package.json b/packages/api/package.json index 77bacab4..c1bcab28 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -27,6 +27,8 @@ "cron-parser": "^5.10.1", "drizzle-orm": "^0.45.2", "hono": "^4.11.4", + "json-rules-engine": "^7.3.1", + "jsonpath-plus": "^10.3.0", "mustache": "^4.2.0", "pg": "8.16.3", "zod": "^4.6.2" diff --git a/packages/api/scripts/restore-webhook-conditions.mjs b/packages/api/scripts/restore-webhook-conditions.mjs new file mode 100644 index 00000000..7dc1ad0c --- /dev/null +++ b/packages/api/scripts/restore-webhook-conditions.mjs @@ -0,0 +1,20 @@ +// Explicit post-deploy step. A failed release leaves affected triggers disabled. +import pg from "pg"; +import { restoreConditionsCutover } from "./webhook-conditions-cutover.mjs"; +const origin = process.argv[2]; +if (!origin || !process.env.DATABASE_URL) throw new Error("Origin and DATABASE_URL are required"); +// The OAuth envelope protects unknown routes before dispatch, so anonymous +// route status alone cannot distinguish old/new Workers. Use the public marker. +let ready = false; +for (let attempt = 0; attempt < 12; attempt++) { + const response = await fetch(new URL("/api/v1/session", origin), { redirect: "manual", cache: "no-store" }); + if (response.status === 200 && response.headers.get("x-factorize-webhook-conditions") === "v1") { ready = true; break; } + await new Promise(resolve => setTimeout(resolve, 5000)); +} +if (!ready) throw new Error("Conditions API cutover is not live; affected triggers stay disabled"); +const client = new pg.Client({ connectionString: process.env.DATABASE_URL, ssl: process.env.DATABASE_URL.includes("localhost") ? undefined : { rejectUnauthorized: false } }); +await client.connect(); +try { + console.log(JSON.stringify({ restored: await restoreConditionsCutover(client) })); +} catch (error) { await client.query("ROLLBACK"); throw error; } +finally { await client.end(); } diff --git a/packages/api/scripts/validate-webhook-conditions-cutover.ts b/packages/api/scripts/validate-webhook-conditions-cutover.ts new file mode 100644 index 00000000..8874ed98 --- /dev/null +++ b/packages/api/scripts/validate-webhook-conditions-cutover.ts @@ -0,0 +1,42 @@ +import pg from "pg"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { evaluateWebhookConditions } from "../src/webhook-conditions"; +// @ts-expect-error Standalone deployment helper has no declaration file. +import { restoreConditionsCutover } from "./webhook-conditions-cutover.mjs"; +const connection = new URL(process.env.DATABASE_URL!); +if (process.argv.includes("--neon")) { + // This exact isolated endpoint was created via the documented Neon API. + // Reuse the CI-held role credential without retrieving or printing it. + connection.hostname = "ep-patient-voice-arpjw9pa.c-4.us-west-2.aws.neon.tech"; +} else assert.ok(["localhost", "127.0.0.1"].includes(connection.hostname)); +const client = new pg.Client({ connectionString: connection.href, ssl: connection.hostname.endsWith(".neon.tech") ? { rejectUnauthorized: false } : undefined }); +await client.connect(); +try { + const sql = await readFile(new URL("../migrations/0013_webhook_conditions.sql", import.meta.url), "utf8"); + const conditions = JSON.parse(await readFile(new URL("../migrations/build-manager-conditions.json", import.meta.url), "utf8")); + const before = (await client.query("SELECT tenant_id,id,job_id,slug,kind,enabled,config,removed_at FROM app.triggers ORDER BY tenant_id,id")).rows; + const handlers = before.filter(row => Object.hasOwn(row.config, "handlerCode")); + console.log(JSON.stringify({ storedTriggers: before.length, handlers: handlers.map(row => ({ jobId: row.job_id, triggerId: row.id, slug: row.slug, enabled: row.enabled, removed: Boolean(row.removed_at) })) })); + assert.equal(handlers.length, 1, "Validation expects the re-inventoried live handler; review changed inventory"); + const original = handlers[0]; + // Unexpected handler blockers must roll back the entire migration. + await client.query("BEGIN"); + await client.query("UPDATE app.triggers SET config=jsonb_set(config,'{handlerCode}',to_jsonb('unreviewed'::text)) WHERE tenant_id=$1 AND id=$2", [original.tenant_id, original.id]); + await assert.rejects(client.query(sql), /migration blocker/); + await client.query("ROLLBACK"); + await client.query("BEGIN"); await client.query(sql); await client.query("COMMIT"); + const converted = (await client.query("SELECT * FROM app.triggers WHERE tenant_id=$1 AND id=$2", [original.tenant_id, original.id])).rows[0]; + assert.equal(converted.enabled, false); assert.deepEqual(converted.config, { ...Object.fromEntries(Object.entries(original.config).filter(([key]) => key !== "handlerCode")), conditions }); + for (const [conclusion, branch, sender, app, expected] of [["success", "gh-readonly-queue/main/a", "human", "actions", "no-match"], ["success", "main", "github-merge-queue[bot]", "actions", "no-match"], ["skipped", "feature", "human", "mintlify", "no-match"], ["failure", "feature", "human", "actions", "match"]]) { + assert.equal((await evaluateWebhookConditions(converted.config.conditions, { check_suite: { conclusion, head_branch: branch, app: { slug: app } }, sender: { login: sender } })).decision, expected); + } + assert.equal((await evaluateWebhookConditions(converted.config.conditions, {})).decision, "match"); + await assert.rejects(client.query("UPDATE app.triggers SET config=config || '{\"handlerCode\":\"removed\"}'::jsonb WHERE tenant_id=$1 AND id=$2", [original.tenant_id, original.id]), /no_webhook_handler_code/); + await restoreConditionsCutover(client); + const after = (await client.query("SELECT tenant_id,id,job_id,slug,kind,enabled,config,removed_at FROM app.triggers ORDER BY tenant_id,id")).rows; + const expected = before.map(row => row.id === original.id && row.tenant_id === original.tenant_id ? { ...row, config: converted.config } : row); + assert.deepEqual(after, expected); + assert.equal((await client.query("SELECT count(*)::int n FROM app.triggers WHERE config ? 'handlerCode'")).rows[0].n, 0); + console.log("Isolated cutover validation passed: conversion, blocker rollback, strict rejection, restoration, unchanged identity/routing/context."); +} finally { await client.end(); } diff --git a/packages/api/scripts/webhook-conditions-cutover.mjs b/packages/api/scripts/webhook-conditions-cutover.mjs new file mode 100644 index 00000000..d2361ebd --- /dev/null +++ b/packages/api/scripts/webhook-conditions-cutover.mjs @@ -0,0 +1,15 @@ +export async function restoreConditionsCutover(client) { + try { + await client.query("BEGIN"); + await client.query("LOCK TABLE app.triggers IN SHARE ROW EXCLUSIVE MODE"); + await client.query(`DO $$ BEGIN + IF EXISTS (SELECT 1 FROM app.triggers WHERE config ? 'handlerCode') THEN RAISE EXCEPTION 'Stored handlers remain'; END IF; + IF EXISTS (SELECT 1 FROM app.webhook_conditions_cutover c JOIN app.triggers t ON t.tenant_id=c.tenant_id AND t.id=c.trigger_id WHERE c.restored_at IS NULL AND (t.enabled OR t.config->'conditions' IS DISTINCT FROM c.conditions)) THEN RAISE EXCEPTION 'Cutover configuration changed; review before restoring'; END IF; + END $$`); + const result = await client.query(`UPDATE app.triggers t SET enabled=c.was_enabled,updated_at=now() FROM app.webhook_conditions_cutover c WHERE t.tenant_id=c.tenant_id AND t.id=c.trigger_id AND c.restored_at IS NULL RETURNING t.id,t.enabled`); + await client.query(`UPDATE app.jobs j SET updated_at=now() WHERE EXISTS (SELECT 1 FROM app.triggers t JOIN app.webhook_conditions_cutover c ON c.tenant_id=t.tenant_id AND c.trigger_id=t.id WHERE t.tenant_id=j.tenant_id AND t.job_id=j.id AND c.restored_at IS NULL)`); + await client.query("UPDATE app.webhook_conditions_cutover SET restored_at=now() WHERE restored_at IS NULL"); + await client.query("COMMIT"); + return result.rows; + } catch (error) { await client.query("ROLLBACK"); throw error; } +} diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 82722e6d..1faeb517 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -9,7 +9,7 @@ import type { ApiService } from "./flow-service"; import { jobInputSchema, manualInvocationSchema, - jobHandlerTestSchema, + jobConditionsTestSchema, listRunsSchema, scopeSchema, } from "./flow-schemas"; @@ -25,6 +25,7 @@ export interface RouteContract { ownerSession: boolean; authOperation?: AuthAction; body?: z.ZodType; + maxBodyBytes?: number; query?: z.ZodObject; parameters: z.ZodObject; status: number; @@ -117,7 +118,7 @@ function route( documentation: RouteContract["documentation"], execute: RouteContract["execute"], options: Partial< - Pick + Pick > = {}, ): RouteContract { const keys = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]); @@ -157,7 +158,7 @@ function authRoute(method: string, path: string, action: AuthAction, summary: st documentation: { summary, description: "Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached.", - responses: { [status]: { description: "session" === action ? "Unauthenticated sessions return authenticated:false; expired, unverified, removed or revoked owners are unauthenticated." : "Success", headers: { "X-Factorize-Contract": { description: "Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover.", schema: { type: "string", const: "gen-2157-static-v1" } } }, content: { "application/json": { schema: jsonSchema(response, "output") } } } }, + responses: { [status]: { description: "session" === action ? "Unauthenticated sessions return authenticated:false; expired, unverified, removed or revoked owners are unauthenticated." : "Success", headers: { "X-Factorize-Webhook-Conditions": { description: "Conditions-only webhook runtime deployment marker.", schema: { type: "string", const: "v1" } }, "X-Factorize-Contract": { description: "Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover.", schema: { type: "string", const: "gen-2157-static-v1" } } }, content: { "application/json": { schema: jsonSchema(response, "output") } } } }, }, execute: async () => { throw new Error("Auth operations must use the protected API dispatcher"); }, }; @@ -667,14 +668,15 @@ export const API_ROUTES: RouteContract[] = [ ), route( "POST", - "/api/v1/job-handlers/test", + "/api/v1/job-conditions/test", "flows:write", { - summary: "Test webhook handler", - responses: { "200": { description: "Decision", content: { "application/json": { schema: jsonSchema(z.discriminatedUnion("ok", [z.object({ ok: z.literal(true), decision: z.union([z.boolean(), z.record(z.string(), z.unknown())]) }), z.object({ ok: z.literal(false), category: z.enum(["handler_error", "invalid_return", "timeout", "platform_error"]) })]), "output") } } } }, + summary: "Test webhook conditions", + description: "Evaluates supplied prepared webhook context only; does not authenticate the example, route events, verify GitHub state, or invoke jobs.", + responses: { "200": { description: "Decision", content: { "application/json": { schema: jsonSchema(z.object({ decision: z.enum(["match", "no-match", "error"]), error: z.string().optional(), details: z.array(z.record(z.string(), z.unknown())) }), "output") } } } }, }, - (service, { body }) => service.testJobHandler(body), - { body: jobHandlerTestSchema }, + (service, { body }) => service.testJobConditions(body), + { body: jobConditionsTestSchema, maxBodyBytes: 300_000 }, ), route( "POST", @@ -1041,7 +1043,7 @@ export function generateOpenApi() { const namedBodies: Record = { JobInput: jobInputSchema, ManualInvocation: manualInvocationSchema, - JobHandlerTest: jobHandlerTestSchema, + JobConditionsTest: jobConditionsTestSchema, TraceReplayRequest: traceReplaySchema, }; const schemas = { diff --git a/packages/api/src/auth-api.ts b/packages/api/src/auth-api.ts index 8df2e4d3..846a8bfe 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -48,7 +48,7 @@ export function validBrowserOrigin(request: Request, env: Env): boolean { return request.headers.get("Origin") === env.APP_ORIGIN && request.headers.get("Sec-Fetch-Site") !== "cross-site"; } export function authJson(body: unknown, status = 200): Response { - return Response.json(body, { status, headers: { "X-Factorize-Contract": "gen-2157-static-v1", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", Pragma: "no-cache" } }); + return Response.json(body, { status, headers: { "X-Factorize-Contract": "gen-2157-static-v1", "X-Factorize-Webhook-Conditions": "v1", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", Pragma: "no-cache" } }); } const failure = (status: number, message: string) => authJson({ error: { code: status === 401 ? "invalid_token" : status === 403 ? "forbidden" : "invalid_request", message } }, status); function sessionCookie(env: Env, value: string, maxAge: number): string { diff --git a/packages/api/src/custom-handler.ts b/packages/api/src/custom-handler.ts deleted file mode 100644 index 048ec37b..00000000 --- a/packages/api/src/custom-handler.ts +++ /dev/null @@ -1,70 +0,0 @@ -export const CUSTOM_HANDLER_MAX_CODE_BYTES = 16_384; -export const CUSTOM_HANDLER_MAX_PAYLOAD_BYTES = 262_144; -export const CUSTOM_HANDLER_COMPATIBILITY_DATE = "2026-09-10"; -export const CUSTOM_HANDLER_DEADLINE_MS = 250; - -export type HandlerDecision = - | { ok: true; decision: boolean | Record } - | { ok: false; category: "handler_error" | "invalid_return" | "timeout" | "platform_error" }; - -const encoder = new TextEncoder(); -export function validateHandlerCode(handlerCode: unknown): string { - if (typeof handlerCode !== "string" || encoder.encode(handlerCode).byteLength > CUSTOM_HANDLER_MAX_CODE_BYTES) throw new Error(`Handler code must be at most ${CUSTOM_HANDLER_MAX_CODE_BYTES} bytes.`); - if (!/^\s*function\s+handler\s*\(\s*webhook\s*\)\s*\{[\s\S]*\}\s*;?\s*$/.test(handlerCode)) throw new Error("Provide one complete function handler(webhook) declaration."); - return handlerCode; -} - -export function userWorkerModule(handlerCode: string): string { - return `${handlerCode}\n -const jsonCompatible = (value, seen = new Set()) => { - if (value === null || typeof value === "string" || typeof value === "boolean") return true; - if (typeof value === "number") return Number.isFinite(value); - if (typeof value !== "object" || seen.has(value)) return false; - seen.add(value); - const valid = Array.isArray(value) - ? value.every(item => jsonCompatible(item, seen)) - : (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null) && Object.values(value).every(item => jsonCompatible(item, seen)); - seen.delete(value); - return valid; -}; -export default { async fetch(request) { - if (request.method !== "POST") return Response.json({ ok: false, category: "handler_error" }, { status: 405 }); - try { - const webhook = await request.json(); - const result = handler(webhook); - if (result !== null && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") return Response.json({ ok: false, category: "invalid_return" }); - if (typeof result === "boolean") return Response.json({ ok: true, decision: result }); - if (result === null || typeof result !== "object" || Array.isArray(result) || !jsonCompatible(result)) return Response.json({ ok: false, category: "invalid_return" }); - try { - const serialized = JSON.stringify(result); - const decision = JSON.parse(serialized); - if (decision === null || typeof decision !== "object" || Array.isArray(decision)) return Response.json({ ok: false, category: "invalid_return" }); - return Response.json({ ok: true, decision }); - } catch { return Response.json({ ok: false, category: "invalid_return" }); } - } catch { return Response.json({ ok: false, category: "handler_error" }); } -} };`; -} - -export async function invokeCustomHandler(loader: WorkerLoader, source: { handlerCode: string }, payload: unknown): Promise { - const body = JSON.stringify(payload); - if (encoder.encode(body).byteLength > CUSTOM_HANDLER_MAX_PAYLOAD_BYTES) return { ok: false, category: "platform_error" }; - const controller = new AbortController(); - const deadline = setTimeout(() => controller.abort(), CUSTOM_HANDLER_DEADLINE_MS); - try { - const worker = loader.load({ - compatibilityDate: CUSTOM_HANDLER_COMPATIBILITY_DATE, - mainModule: "worker.js", - modules: { "worker.js": userWorkerModule(source.handlerCode) }, - env: {}, - globalOutbound: null, - limits: { cpuMs: 10, subRequests: 0 }, - }); - const response = await worker.getEntrypoint().fetch("https://handler.internal/", { method: "POST", headers: { "Content-Type": "application/json" }, body, signal: controller.signal }); - if (!response.ok) return { ok: false, category: "platform_error" }; - const result = await response.json() as any; - const validDecision = typeof result?.decision === "boolean" || (result?.decision !== null && typeof result?.decision === "object" && !Array.isArray(result?.decision)); - return result?.ok === true && validDecision ? result : result?.ok === false && ["handler_error", "invalid_return", "timeout", "platform_error"].includes(result.category) ? result : { ok: false, category: "platform_error" }; - } catch (error) { - return { ok: false, category: error instanceof DOMException && error.name === "AbortError" ? "timeout" : "platform_error" }; - } finally { clearTimeout(deadline); } -} diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 6524031f..f50f07f7 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { conditionsSchema, preparedWebhookSchema } from "./webhook-conditions"; export const scopeSchema = z.enum(["flows:read", "flows:write", "runs:read", "runs:write"]); export const runStateSchema = z.enum(["queued", "starting", "running", "done", "blocked", "failed", "ignored", "succeeded", "stopping", "stopped"]); @@ -13,7 +14,7 @@ export const listRunsSchema = z.object({ }); export const runIdSchema = z.object({ runId: z.string().min(1) }); -const webhookCommonSchema = z.object({ handlerCode: z.string().max(16_384).optional() }); +const webhookCommonSchema = z.object({ conditions: conditionsSchema.optional() }); export const webhookTriggerConfigSchema = z.discriminatedUnion("provider", [ webhookCommonSchema.extend({ provider: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(), webhookCommonSchema.extend({ provider: z.literal("clickup"), listId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(), @@ -50,8 +51,8 @@ export const manualInvocationSchema = z.object({ message: "idempotencyKey must not include the reserved manual: claim-key prefix", }).optional(), }).strict(); -export const jobHandlerTestSchema = z.object({ - handlerCode: z.string().max(16_384), payload: z.record(z.string(), z.unknown()), +export const jobConditionsTestSchema = z.object({ + conditions: conditionsSchema.optional(), webhook: preparedWebhookSchema, }).strict(); export type JobInput = z.infer; diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 06be04f0..da4e8862 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -23,8 +23,8 @@ import { GitHubRepository } from "./postgres/github-repository"; import { IntegrationService } from "./postgres/integration-service"; import { OperationsRepository } from "./postgres/operations-repository"; import { installedTriggerAvailability } from "./trigger-availability"; -import { invokeCustomHandler } from "./custom-handler"; -import { validateWebhookHandler } from "./webhook-trigger"; +import { evaluateWebhookConditions } from "./webhook-conditions"; +import { jobConditionsTestSchema } from "./flow-schemas"; import { ProviderCatalog } from "./postgres/provider-catalog"; import { ArtifactRepository } from "./postgres/artifact-repository"; import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken } from "./access-tokens"; @@ -185,7 +185,7 @@ export class ApiService { async listJobEvents(jobId: string, limit = 50) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).jobEvents(jobId, limit); } async listWebhookDeliveries(query: URLSearchParams) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).deliveries(query); } async getWebhookDelivery(deliveryId: string) { await this.authorize("runs:read"); const value = await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).delivery(deliveryId); if (!value) throw new ServiceError(404,"not_found","Webhook delivery not found"); return value; } - async testJobHandler(input: { handlerCode: string; payload: Record }) { await this.authorize("flows:write"); const config: any = { provider: "linear", projectId: "handler-test", matchRules: [], handlerCode: input.handlerCode }; validateWebhookHandler(config); if (!this.env.CUSTOM_HANDLER_LOADER) throw new ServiceError(503,"operation_failed","Webhook handler platform is unavailable"); return invokeCustomHandler(this.env.CUSTOM_HANDLER_LOADER, config, input.payload); } + async testJobConditions(input: unknown) { await this.authorize("flows:write"); const parsed = jobConditionsTestSchema.parse(input); return evaluateWebhookConditions(parsed.conditions, parsed.webhook); } async createJob(input: JobInput) { await this.authorize("flows:write"); const timestamp = new Date().toISOString(), id = crypto.randomUUID(); const triggers = this.normalizedTriggers(input.triggers).map(trigger => ({ ...trigger, jobId: id })); diff --git a/packages/api/src/postgres/automation-scheduler.ts b/packages/api/src/postgres/automation-scheduler.ts index eb075947..357e8ac6 100644 --- a/packages/api/src/postgres/automation-scheduler.ts +++ b/packages/api/src/postgres/automation-scheduler.ts @@ -6,7 +6,7 @@ import type { Database } from "./database"; import { PostgresJobRepository } from "./job-repository"; import { githubHeaders, installationToken } from "../github"; import { adaptWebhook, type WebhookTriggerConfig } from "../webhook-trigger"; -import { invokeCustomHandler } from "../custom-handler"; +import { evaluateWebhookConditions } from "../webhook-conditions"; function skipFullQueue(error: unknown): void { if (!(error instanceof InvocationError) || error.code !== "queue_full") throw error; @@ -74,7 +74,7 @@ export class AutomationScheduler { } private async githubVerifications() { - const pending = await this.database.pool.query(`SELECT p.*,t.slug trigger_slug,t.config trigger_config,g.state installation_state FROM app.pending_verifications p JOIN app.triggers t ON t.tenant_id=p.tenant_id AND t.id=p.trigger_id LEFT JOIN app.github_installations g ON g.tenant_id=p.tenant_id AND g.installation_id=p.installation_id WHERE p.next_attempt_at<=now() ORDER BY p.next_attempt_at LIMIT 20`); + const pending = await this.database.pool.query(`SELECT p.*,t.slug trigger_slug,t.config trigger_config,t.enabled trigger_enabled,t.removed_at,j.enabled job_enabled,g.state installation_state FROM app.pending_verifications p JOIN app.triggers t ON t.tenant_id=p.tenant_id AND t.id=p.trigger_id JOIN app.jobs j ON j.tenant_id=p.tenant_id AND j.id=p.job_id LEFT JOIN app.github_installations g ON g.tenant_id=p.tenant_id AND g.installation_id=p.installation_id WHERE p.next_attempt_at<=now() ORDER BY p.next_attempt_at LIMIT 20`); for (const row of pending.rows) { const finish = async (outcome: string, detail: string) => { await this.database.transaction(async client => { @@ -84,22 +84,21 @@ export class AutomationScheduler { if (delivery) { await client.query("INSERT INTO app.webhook_delivery_events(tenant_id,id,delivery_id,job_id,outcome,detail) VALUES ($1,$2,$3,$4,$5,$6)", [row.tenant_id, crypto.randomUUID(), delivery.id, row.job_id, outcome, detail]); await client.query("UPDATE app.webhook_deliveries SET outcome=$3,detail=$4 WHERE tenant_id=$1 AND id=$2", [row.tenant_id, delivery.id, outcome, detail]); } }); }; + if (!row.trigger_enabled || row.removed_at || !row.job_enabled) { await finish("disabled", "Trigger or job is disabled or removed."); continue; } if (row.installation_state !== "active") { await finish("verification_failed", "GitHub installation is disconnected."); continue; } try { const token = await installationToken(this.env, Number(row.installation_id)), response = await fetch(`https://api.github.com/repos/${encodeURIComponent(row.repository_owner)}/${encodeURIComponent(row.repository_name)}/pulls/${row.pull_number}`, { headers: githubHeaders(token) }); if (!response.ok) throw new Error(`GitHub verification failed (${response.status})`); const pull = await response.json() as any; if (pull.state !== "open" || pull.base?.ref !== "main" || pull.mergeable === true) { await finish("ignored", pull.mergeable === true ? "GitHub reports that the pull request is mergeable." : "Pull request is closed or no longer targets main."); continue; } - if (pull.mergeable === null) { const attempt = Number(row.attempt) + 1; if (attempt >= 8) await finish("verification_failed", "GitHub did not finish calculating mergeability."); else await this.database.pool.query("UPDATE app.pending_verifications SET attempt=$3,next_attempt_at=now()+make_interval(secs=>least(60,5*$3)) WHERE tenant_id=$1 AND id=$2", [row.tenant_id, row.id, attempt]); continue; } + if (pull.mergeable !== false) { const attempt = Number(row.attempt) + 1; if (attempt >= 8) await finish("verification_failed", "GitHub did not finish calculating mergeability."); else await this.database.pool.query("UPDATE app.pending_verifications SET attempt=$3,next_attempt_at=now()+make_interval(secs=>least(60,5*$3)) WHERE tenant_id=$1 AND id=$2", [row.tenant_id, row.id, attempt]); continue; } const config = row.trigger_config as WebhookTriggerConfig, invocation = adaptWebhook(config, "github", row.delivery_id, row.payload, "pull_request"); if (!invocation) { await finish("ignored", "Verified pull request no longer matches the trigger."); continue; } let context: Record = { ...invocation.payload, pull_request: { ...invocation.payload.pull_request as any, mergeable: false, mergeable_state: pull.mergeable_state } }; - if (config.handlerCode) { - if (!this.env.CUSTOM_HANDLER_LOADER) { await finish("platform_error", "Webhook handler platform is unavailable; no run was created."); continue; } - const decision = await invokeCustomHandler(this.env.CUSTOM_HANDLER_LOADER, { handlerCode: config.handlerCode }, context); - if (!decision.ok) { await finish(decision.category, "Webhook handler failed closed; no run was created."); continue; } - if (decision.decision === false) { await finish("rejected", "Handler returned false; no run was created."); continue; } - if (decision.decision !== true) context = decision.decision; + const decision = await evaluateWebhookConditions(config.conditions, context); + if (decision.decision !== "match") { + await finish(decision.decision === "error" ? "conditions_error" : "excluded", decision.decision === "error" ? "Webhook conditions failed; no run was created." : "Webhook conditions did not match; no run was created."); + continue; } const result = await new InvocationService(this.repository(row.tenant_id), value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)).invoke(row.job_id, { source: "webhook", triggerId: row.trigger_id, claimKey: `webhook:${row.trigger_id}:${invocation.claimKey}`, context: { [row.trigger_slug]: context }, occurrence: { ...invocation.occurrence, metadata: { ...invocation.occurrence.metadata, triggerId: row.trigger_id, mergeable: false } } }); await finish(result.duplicate ? "duplicate" : "accepted", result.duplicate ? "Verified occurrence was already claimed." : "Merge-conflicted pull request queued through canonical job invocation."); diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 7e1734c0..fc980d9f 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -43,7 +43,11 @@ export const jobs = app.table("jobs", { }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.slug), check("jobs_concurrency_limit_check", sql`${t.concurrencyLimit} >= 1`)]); export const triggers = app.table("triggers", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), kind: text("kind").$type().notNull(), slug: text("slug").notNull(), enabled: boolean("enabled").notNull().default(true), config: jsonb("config").$type>().notNull().default({}), position: integer("position").notNull().default(0), createdAt: createdAt(), updatedAt: updatedAt(), removedAt: timestamp("removed_at", { withTimezone: true }), -}, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("triggers_active_slug").on(t.tenantId, t.jobId, t.slug).where(sql`${t.removedAt} is null`), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), check("triggers_kind_check", sql`${t.kind} in ('manual','schedule','webhook','jobLifecycle')`)]); +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("triggers_active_slug").on(t.tenantId, t.jobId, t.slug).where(sql`${t.removedAt} is null`), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), check("no_webhook_handler_code", sql`NOT (${t.config} ? 'handlerCode')`), check("triggers_kind_check", sql`${t.kind} in ('manual','schedule','webhook','jobLifecycle')`)]); +// One-time cutover state; no legacy execution or configuration is retained. +export const webhookConditionsCutover = app.table("webhook_conditions_cutover", { + tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), wasEnabled: boolean("was_enabled").notNull(), conditions: jsonb("conditions").$type>().notNull(), restoredAt: timestamp("restored_at", { withTimezone: true }), +}, t => [primaryKey({ columns: [t.tenantId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade")]); export const invocations = app.table("invocations", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), source: text("source").$type().notNull(), claimKey: text("claim_key").notNull(), triggerId: uuid("trigger_id").notNull(), context: jsonb("context").$type>().notNull(), occurrence: jsonb("occurrence").$type(), createdAt: createdAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.jobId, t.claimKey), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }), check("invocations_source_check", sql`${t.source} in ('manual','schedule','webhook','jobLifecycle')`)]); @@ -114,7 +118,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, - connections, linearWorkspaces, githubInstallations, githubSetupStates, jobs, triggers, invocations, jobRuns, runs, runArtifacts, + connections, linearWorkspaces, githubInstallations, githubSetupStates, jobs, triggers, webhookConditionsCutover, invocations, jobRuns, runs, runArtifacts, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, runTraceProjections, traceReplayLimits, traceReplayOperations, diff --git a/packages/api/src/postgres/webhook-service.ts b/packages/api/src/postgres/webhook-service.ts index 9598ea32..c984664e 100644 --- a/packages/api/src/postgres/webhook-service.ts +++ b/packages/api/src/postgres/webhook-service.ts @@ -2,7 +2,7 @@ import { clickUpJson, matchingClickUpTask } from "../clickup"; import { verifyTailDelivery, sanitizeTailEvent, suppressTailEvent } from "../cloudflare-tail"; import { decrypt, equalHmac, encrypt } from "../crypto"; import { InvocationError, InvocationService, type Job } from "../job-domain"; -import { invokeCustomHandler } from "../custom-handler"; +import { evaluateWebhookConditions } from "../webhook-conditions"; import type { Env } from "../types"; import { adaptWebhook, type WebhookProvider, type WebhookTriggerConfig } from "../webhook-trigger"; import { ConnectionRepository } from "./connection-repository"; @@ -38,12 +38,10 @@ export class WebhookService { const invocation = adaptWebhook(candidate.config, provider, deliveryId, payload, eventName); if (!invocation) { await this.event(deliveryPk, candidate.job.id, provider, deliveryId, "ignored", "Webhook did not match this job trigger."); continue; } let context: Record = invocation.payload; - if (candidate.config.handlerCode) { - if (!this.env.CUSTOM_HANDLER_LOADER) { await this.event(deliveryPk, candidate.job.id, provider, deliveryId, "platform_error", "Webhook handler platform is unavailable; no run was created."); continue; } - const decision = await invokeCustomHandler(this.env.CUSTOM_HANDLER_LOADER, { handlerCode: candidate.config.handlerCode }, payload); - if (!decision.ok) { await this.event(deliveryPk, candidate.job.id, provider, deliveryId, decision.category, "Webhook handler failed closed; no run was created."); continue; } - if (decision.decision === false) { await this.event(deliveryPk, candidate.job.id, provider, deliveryId, "rejected", "Handler returned false; no run was created."); continue; } - if (decision.decision !== true) context = decision.decision; + const decision = await evaluateWebhookConditions(candidate.config.conditions, context); + if (decision.decision !== "match") { + await this.event(deliveryPk, candidate.job.id, provider, deliveryId, decision.decision === "error" ? "conditions_error" : "excluded", decision.decision === "error" ? "Webhook conditions failed; no run was created." : "Webhook conditions did not match; no run was created."); + continue; } const service = new InvocationService(this.jobs, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); try { diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index f4c94569..a2c4dd50 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -5,7 +5,7 @@ import { createMcpHandler, McpServer } from "@modelcontextprotocol/server"; import { createMcpHonoApp } from "@modelcontextprotocol/hono"; import { z } from "zod"; import { ApiService, ServiceError } from "./flow-service"; -import { jobHandlerTestSchema, jobIdSchema, jobInputSchema, listRunsSchema, manualInvocationSchema, runIdSchema } from "./flow-schemas"; +import { jobConditionsTestSchema, jobIdSchema, jobInputSchema, listRunsSchema, manualInvocationSchema, runIdSchema } from "./flow-schemas"; import type { Env, OAuthProps } from "./types"; import { executeAuth, validBrowserOrigin } from "./auth-api"; import { matchApiOperation } from "./api-contract"; @@ -64,8 +64,22 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP let body: unknown; if (route.body) { if (request.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() !== "application/json") throw new ServiceError(415, "unsupported_media_type", "Content-Type must be application/json."); - try { body = await request.json(); } - catch { throw new ServiceError(400, "invalid_request", "Request body must be valid JSON."); } + try { + if (route.maxBodyBytes) { + const reader = request.body?.getReader(); + const chunks: Uint8Array[] = []; let size = 0; + if (reader) for (;;) { + const { done, value } = await reader.read(); if (done) break; + size += value.byteLength; + if (size > route.maxBodyBytes) { await reader.cancel(); throw new ServiceError(400, "invalid_request", "Request body exceeds the byte limit."); } + chunks.push(value); + } + const data = new Uint8Array(size); let offset = 0; + for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.byteLength; } + body = JSON.parse(new TextDecoder().decode(data)); + } else body = await request.json(); + } + catch (error) { if (error instanceof ServiceError) throw error; throw new ServiceError(400, "invalid_request", "Request body must be valid JSON."); } body = route.body.parse(body); } if (route.authOperation) return timed(await executeAuth(route.authOperation, request, env, body as Record)); @@ -101,7 +115,7 @@ function createMcpServer(service: ApiService): McpServer { tool("list_job_webhook_activity", "List matching, rejected, duplicate, and accepted webhook activity for a job", z.object({ jobId: z.string().min(1), limit: z.number().int().min(1).max(100).default(50) }), ({ jobId, limit }: any) => service.listJobEvents(jobId, limit)); tool("list_webhook_deliveries", "Search tenant-scoped webhook deliveries by provider, delivery ID, event, outcome, job, time range, or safe diagnostic text. Results are newest first and cursor paginated.", z.object({ provider: z.string().optional(), deliveryId: z.string().optional(), event: z.string().optional(), action: z.string().optional(), outcome: z.string().optional(), jobId: z.string().optional(), q: z.string().optional(), from: z.string().optional(), to: z.string().optional(), limit: z.number().int().min(1).max(100).default(50), cursor: z.string().optional() }), (input: any) => service.listWebhookDeliveries(queryOf(input))); tool("get_webhook_delivery", "Get a webhook delivery and its safe processing timeline. Secrets and payloads are never returned.", z.object({ deliveryId: z.string().min(1) }), ({ deliveryId }: any) => service.getWebhookDelivery(deliveryId)); - tool("test_job_webhook_handler", "Test an isolated synchronous Job webhook handler without creating a run. Returns the decision and never accepts credentials.", jobHandlerTestSchema, (input: any) => service.testJobHandler(input)); + tool("test_job_webhook_conditions", "Evaluate conditions on supplied prepared webhook context. No authentication of the example, routing, live GitHub verification, or invocation.", jobConditionsTestSchema, (input: any) => service.testJobConditions(input)); tool("list_execution_targets", "List non-secret execution target metadata and capabilities", z.object({}), () => service.listExecutionTargets()); tool("diagnose_exe_integration", "Probe a saved exe.dev connection's permissions and a disposable tagged VM's agent/model integration. The disposable VM is deleted before the tool returns.", z.object({ connectionId: z.string().min(1) }), ({ connectionId }: any) => service.diagnoseExeIntegration(connectionId)); tool("list_cloudflare_tail_integrations", "List installed Cloudflare Tail integrations and reference counts. Signing secrets are never returned.", z.object({}), () => service.listTailIntegrations()); diff --git a/packages/api/src/trigger-context.ts b/packages/api/src/trigger-context.ts index aa939649..515aecd6 100644 --- a/packages/api/src/trigger-context.ts +++ b/packages/api/src/trigger-context.ts @@ -72,9 +72,9 @@ export const triggerContextCatalog: Record = { export function reflectTriggerContext(trigger: { slug?: unknown; kind?: unknown; config?: any }): TriggerContextReflection { const kind = String(trigger.kind ?? ""), provider = kind === "webhook" ? String(trigger.config?.provider ?? "") : undefined; - const key = provider ?? kind, handler = kind === "webhook" && typeof trigger.config?.handlerCode === "string" && trigger.config.handlerCode.trim().length > 0; + const key = provider ?? kind; return { - slug: String(trigger.slug ?? ""), kind, ...(provider ? { provider } : {}), dynamic: handler, - paths: handler ? [{ path: "*", type: "unknown", description: "The provider handler replaces context with a dynamic JSON object; inspect the handler contract." }] : (triggerContextCatalog[key] ?? [{ path: "*", type: "unknown", description: "Context shape is not known." }]), + slug: String(trigger.slug ?? ""), kind, ...(provider ? { provider } : {}), dynamic: false, + paths: (triggerContextCatalog[key] ?? [{ path: "*", type: "unknown", description: "Context shape is not known." }]), }; } diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index 2e3f0d41..8c93d5be 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -19,7 +19,6 @@ export interface Env { GITHUB_APP_SLUG?: string; GITHUB_APP_PRIVATE_KEY?: string; GITHUB_WEBHOOK_SECRET?: string; - CUSTOM_HANDLER_LOADER?: WorkerLoader; RECOVERY_TIMEOUT_MS?: string; RECOVERY_MAX_ATTEMPTS?: string; OAUTH_KV?: KVNamespace; diff --git a/packages/api/src/webhook-conditions.ts b/packages/api/src/webhook-conditions.ts new file mode 100644 index 00000000..2875e201 --- /dev/null +++ b/packages/api/src/webhook-conditions.ts @@ -0,0 +1,80 @@ +import { Engine, Operator, OperatorDecorator, type TopLevelCondition } from "json-rules-engine"; +import { JSONPath } from "jsonpath-plus"; +import { z } from "zod"; + +export const CONDITION_LIMITS = { bytes: 16_384, depth: 16, nodes: 128, contextBytes: 262_144 } as const; +type Scalar = string | number | boolean | null; +export type WebhookConditions = { all: WebhookConditions[] } | { any: WebhookConditions[] } | { not: WebhookConditions } | { fact: "webhook"; path: string; operator: string; value: Scalar | Scalar[] }; +export type ConditionDecision = { decision: "match" | "no-match" | "error"; error?: string; details: Record[] }; +const numeric = new Set(["lessThan", "lessThanInclusive", "greaterThan", "greaterThanInclusive"]); +const operators = new Set(["equal", "notEqual", "in", "notIn", "contains", "doesNotContain", "startsWith", ...numeric]); +// Deliberately excludes recursive descent, unions, slices, filters and scripts. +const pathPattern = /^\$(?:(?:\.[A-Za-z_][A-Za-z0-9_-]*)|(?:\[\d+\])|(?:\[\*\])|(?:\.\*)|(?:\['[^'\\\x00-\x1f]+'\])|(?:\["[^"\\\x00-\x1f]+"\]))*$/; +const scalar = (value: unknown): value is Scalar => value === null || typeof value === "string" || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)); +const bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).byteLength; +export function validateConditions(input: unknown): asserts input is WebhookConditions { + let count = 0; + function visit(value: unknown, depth: number): void { + if (depth > CONDITION_LIMITS.depth || ++count > CONDITION_LIMITS.nodes) throw new Error("Conditions exceed the depth or node limit."); + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Each condition must be an object."); + const node = value as Record, keys = Object.keys(node); + const group = ["all", "any", "not"].find(key => Object.hasOwn(node, key)); + if (group) { + if (keys.length !== 1) throw new Error("Boolean groups accept only all, any, or not."); + if (group === "not") visit(node.not, depth + 1); + else { + const children = node[group]; + if (!Array.isArray(children) || !children.length) throw new Error("Condition groups must not be empty."); + for (const child of children) visit(child, depth + 1); + } + return; + } + if (keys.length !== 4 || !["fact", "path", "operator", "value"].every(key => Object.hasOwn(node, key))) throw new Error("Leaf conditions require only fact, path, operator, and value."); + if (node.fact !== "webhook") throw new Error("Only the webhook fact is allowed."); + if (typeof node.path !== "string" || node.path.length > 512 || !pathPattern.test(node.path)) throw new Error("Unsupported JSONPath; use properties, indexes, and wildcards."); + if (typeof node.operator !== "string" || !operators.has(node.operator)) throw new Error("Unsupported condition operator."); + if (numeric.has(node.operator)) { + if (typeof node.value !== "number" || !Number.isFinite(node.value)) throw new Error("Numeric operators require a finite number."); + } else if (node.operator === "startsWith") { + if (typeof node.value !== "string") throw new Error("startsWith requires a string."); + } else if (["in", "notIn"].includes(node.operator)) { + if (!Array.isArray(node.value) || !node.value.every(scalar)) throw new Error("in and notIn require an array of scalar values."); + } else if (!scalar(node.value)) throw new Error("This operator requires a scalar value."); + } + visit(input, 1); + if (bytes(input) > CONDITION_LIMITS.bytes) throw new Error("Conditions exceed the 16384 byte limit."); +} +export const conditionsSchema = z.record(z.string(), z.unknown()).superRefine((value, ctx) => { + try { validateConditions(value); } catch (error) { ctx.addIssue({ code: "custom", message: (error as Error).message }); } +}); +export const preparedWebhookSchema = z.record(z.string(), z.unknown()).superRefine((value, ctx) => { + if (bytes(value) > CONDITION_LIMITS.contextBytes) ctx.addIssue({ code: "custom", message: "Prepared webhook exceeds the 262144 byte limit." }); +}); +function engineConditions(node: WebhookConditions): TopLevelCondition { + function convert(value: WebhookConditions): any { + if ("all" in value) return { all: value.all.map(convert) }; + if ("any" in value) return { any: value.any.map(convert) }; + if ("not" in value) return { not: convert(value.not) }; + return { ...value, operator: numeric.has(value.operator) ? `finiteNumber:${value.operator}` : value.operator }; + } + const converted = convert(node); + return "fact" in node ? { all: [converted] } : converted; +} +/** A fresh engine with one supplied fact. No callbacks, network facts, or invocation. */ +export async function evaluateWebhookConditions(conditions: unknown, webhook: Record): Promise { + try { + if (conditions === undefined) return { decision: "match", details: [] }; + validateConditions(conditions); + const engine = new Engine([], { pathResolver: (json, path) => JSONPath({ path, json, eval: false, wrap: /\.\*|\[\*\]/.test(path) }) }); + engine.addOperator(new Operator("startsWith", (a, b) => typeof a === "string" && typeof b === "string" && a.startsWith(b))); + // Constrain runtime operands while preserving the library's comparison semantics. + engine.addOperatorDecorator(new OperatorDecorator("finiteNumber", (a, b, next) => typeof a === "number" && Number.isFinite(a) && typeof b === "number" && Number.isFinite(b) && next(a, b))); + engine.addRule({ conditions: engineConditions(conditions), event: { type: "factorize-match" } }); + const result = await engine.run({ webhook }); + const details = [...result.results, ...result.failureResults].map(rule => rule.toJSON(false) as unknown as Record); + return { decision: result.events.length ? "match" : "no-match", details }; + } catch { + // Never persist arbitrary payloads or library exceptions in runtime diagnostics. + return { decision: "error", error: "Invalid webhook conditions or evaluation failure.", details: [] }; + } +} diff --git a/packages/api/src/webhook-trigger.ts b/packages/api/src/webhook-trigger.ts index c9b4c32f..b910d42c 100644 --- a/packages/api/src/webhook-trigger.ts +++ b/packages/api/src/webhook-trigger.ts @@ -1,13 +1,12 @@ import { matchingIssue } from "./matcher"; import type { MatchRule } from "./types"; -import { validateHandlerCode } from "./custom-handler"; import { matchingGitHubIssue } from "./github-issue-matcher"; export type WebhookProvider = "linear" | "clickup" | "github" | "cloudflareTail"; export type WebhookTriggerConfig = { provider: WebhookProvider; projectId?: string; listId?: string; matchRules?: MatchRule[]; installationId?: number; repositoryId?: number; - event?: string; action?: string; integrationId?: string; signingSecret?: string; secret?: string; handlerCode?: string; + event?: string; action?: string; integrationId?: string; signingSecret?: string; secret?: string; conditions?: Record; }; export interface WebhookInvocation { claimKey: string; payload: Record; @@ -43,7 +42,3 @@ export function publicWebhookConfig(config: WebhookTriggerConfig): Record { await expect(verifyTailDelivery(secret, String(Date.now() - 61_000), delivery, body, signature)).resolves.toBe("stale"); }); - it("removes sensitive data recursively before handlers, activity, or prompts", () => { + it("removes sensitive data recursively before conditions, activity, or prompts", () => { const event = sanitizeTailEvent({ scriptName: "producer", event: { request: { headers: { authorization: "Bearer x", cookie: "x=y", accept: "json" }, body: "raw" } }, token: "secret", logs: [{ level: "error", message: "safe" }] }); expect(JSON.stringify(event)).not.toContain("Bearer x"); expect(JSON.stringify(event)).not.toContain("x=y"); diff --git a/packages/api/test/conditions-api.test.ts b/packages/api/test/conditions-api.test.ts new file mode 100644 index 00000000..7d642299 --- /dev/null +++ b/packages/api/test/conditions-api.test.ts @@ -0,0 +1,58 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { protectedApiFetch } from "../src/protected-api"; +import { ApiService } from "../src/flow-service"; +import { InvocationService } from "../src/job-domain"; +import { evaluateWebhookConditions } from "../src/webhook-conditions"; +import { matchApiOperation } from "../src/api-contract"; +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {} })); +afterEach(() => vi.restoreAllMocks()); +const condition = { fact: "webhook", path: "$.provider", operator: "equal", value: "github" }; +function fixture(scopes = ["flows:write"], member = true) { + const query = vi.fn().mockResolvedValue({ rows: member ? [{ user_id: "owner", role: "owner", session_version: 1 }] : [] }); + const env = { APP_ORIGIN: "https://example.com", DATABASE: { pool: { query } } } as any; + const auth = { tenantId: "tenant", userId: "owner", sessionVersion: 1, authMethod: "bearer", scopes } as any; + async function send(transport: string, input: unknown, tool = "test_job_webhook_conditions") { + return protectedApiFetch(new Request(env.APP_ORIGIN + (transport === "MCP" ? "/mcp" : "/api/v1/job-conditions/test"), { method: "POST", headers: { Origin: env.APP_ORIGIN, Host: "example.com", "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, body: JSON.stringify(transport === "MCP" ? { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: input } } : input) }), env, auth, {} as any); + } + return { send, query, env, auth }; +} +async function message(response: Response) { + const text = await response.text(); + return JSON.parse(text.startsWith("event:") ? text.split("\n").find(line => line.startsWith("data:"))!.slice(5) : text); +} +describe("conditions REST/MCP boundaries", () => { + it.each(["REST", "MCP"])("%s uses the evaluator, authorizes, and never invokes or verifies GitHub", async transport => { + const f = fixture(), invoke = vi.spyOn(InvocationService.prototype, "invoke"), fetch = vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("No network allowed")); + for (const webhook of [{ provider: "github" }, { provider: "linear" }]) { + const response = await f.send(transport, { conditions: condition, webhook }); expect(response.status).toBe(200); + const body = await message(response), output = transport === "MCP" ? body.result.structuredContent : body; + expect(output).toEqual(await evaluateWebhookConditions(condition, webhook)); + } + expect(f.query).toHaveBeenCalledTimes(2); expect(invoke).not.toHaveBeenCalled(); expect(fetch).not.toHaveBeenCalled(); + }); + it.each(["REST", "MCP"])("%s rejects insufficient scopes and revoked/removed owners", async transport => { + for (const f of [fixture(["flows:read"]), fixture(["flows:write"], false)]) { + const response = await f.send(transport, { conditions: condition, webhook: {} }); + if (transport === "REST") expect([401, 403]).toContain(response.status); + else { const body = await message(response); expect(body.result?.isError || body.error).toBeTruthy(); } + } + }); + it.each(["REST", "MCP"])("%s rejects invalid shape, oversized examples and legacy fields", async transport => { + for (const input of [{ conditions: { all: [] }, webhook: {} }, { conditions: condition, webhook: [] }, { conditions: condition, webhook: { value: "x".repeat(262145) } }, { handlerCode: "removed", payload: {} }]) { + const response = await fixture().send(transport, input); + if (transport === "REST") expect(response.status).toBe(400); + else { const body = await message(response); expect(body.result?.isError || body.error).toBeTruthy(); } + } + }); + it("removes legacy endpoint/tool and bounds the raw HTTP request", async () => { + expect(matchApiOperation("POST", "/api/v1/job-handlers/test")).toBeUndefined(); + const body = await message(await fixture().send("MCP", {}, "test_job_webhook_handler")); expect(body.error || body.result?.isError).toBeTruthy(); + const f = fixture(); + const response = await protectedApiFetch(new Request(f.env.APP_ORIGIN + "/api/v1/job-conditions/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: " ".repeat(300001) + "{}" }), f.env, f.auth, {} as any); + expect(response.status).toBe(400); expect(f.query).not.toHaveBeenCalled(); + const anonymous = await protectedApiFetch(new Request(f.env.APP_ORIGIN + "/api/v1/job-conditions/test", { method: "POST" }), f.env, null, {} as any); expect(anonymous.status).toBe(401); + }); + it("service validates even when called directly", async () => { + const f = fixture(); await expect(new ApiService(f.env, f.auth).testJobConditions({ conditions: { all: [] }, webhook: {} })).rejects.toThrow(); + }); +}); diff --git a/packages/api/test/conditions-runtime-paths.test.ts b/packages/api/test/conditions-runtime-paths.test.ts new file mode 100644 index 00000000..b51185e6 --- /dev/null +++ b/packages/api/test/conditions-runtime-paths.test.ts @@ -0,0 +1,92 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { readFileSync } from "node:fs"; +import { AutomationScheduler } from "../src/postgres/automation-scheduler"; +import { WebhookService } from "../src/postgres/webhook-service"; +import { InvocationError, InvocationService } from "../src/job-domain"; +import { adaptWebhook } from "../src/webhook-trigger"; +import { evaluateWebhookConditions } from "../src/webhook-conditions"; +vi.mock("../src/github", () => ({ installationToken: vi.fn(async () => "fixture-token"), githubHeaders: () => ({}) })); +afterEach(() => vi.restoreAllMocks()); +const build = JSON.parse(readFileSync(new URL("../migrations/build-manager-conditions.json", import.meta.url), "utf8")); +const leaf = (path: string, value: unknown) => ({ fact: "webhook", path, operator: "equal", value }); +function fixture(conditions: unknown = build) { + const config: any = { provider: "github", installationId: 1, repositoryId: 2, event: "pull_request", action: "dequeued", conditions }; + const payload = { installation: { id: 1 }, repository: { id: 2 }, action: "dequeued", pull_request: { number: 3, state: "open", base: { ref: "main" } } }; + const row: any = { id: "verification", tenant_id: "tenant", job_id: "job", trigger_id: "trigger-id", trigger_slug: "trigger-2", trigger_config: config, trigger_enabled: true, job_enabled: true, removed_at: null, installation_state: "active", payload, delivery_id: "delivery", attempt: 0 }; + const query = vi.fn(async (sql: string) => ({ rows: sql.includes("SELECT p.*") ? [row] : [] })); + const database: any = { pool: { query }, transaction: async (fn: any) => fn({ query }) }; + const env: any = {}; + const scheduler = new AutomationScheduler(database, env), ordinary = new WebhookService(database, env, "tenant"); + vi.spyOn(ordinary as any, "candidates").mockImplementation(async () => [{ job: { id: "job" }, triggerId: "trigger-id", triggerSlug: "trigger-2", config }]); + vi.spyOn(ordinary as any, "ensure").mockResolvedValue("delivery-pk"); + const event = vi.spyOn(ordinary as any, "event").mockResolvedValue(undefined); + const invoke = vi.spyOn(InvocationService.prototype, "invoke").mockResolvedValue({ duplicate: false } as any); + const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({ state: "open", base: { ref: "main" }, mergeable: false, mergeable_state: "dirty" })); + return { config, payload, row, query, scheduler, ordinary, event, invoke, fetch }; +} +describe("condition execution contract", () => { + it.each([ + ["success", "gh-readonly-queue/main/x", "human", "actions"], + ["success", "main", "github-merge-queue[bot]", "actions"], + ["skipped", "feature", "human", "mintlify"], + ["failure", "feature", "human", "actions"], + [undefined, undefined, undefined, undefined], + ])("preview and both paths agree and keep prepared context for %s/%s", async (conclusion, branch, sender, app) => { + const f = fixture(); + Object.assign(f.payload, { check_suite: { conclusion, head_branch: branch, app: { slug: app } }, sender: { login: sender } }); + const prepared = adaptWebhook(f.config, "github", "delivery", f.payload, "pull_request")!.payload; + const verified = { ...prepared, pull_request: { ...f.payload.pull_request, mergeable: false, mergeable_state: "dirty" } }; + const preview = await evaluateWebhookConditions(build, prepared), delayedPreview = await evaluateWebhookConditions(build, verified); + expect(preview.decision).toBe(delayedPreview.decision); + await (f.ordinary as any).invoke("github", "delivery", f.payload, "pull_request"); + expect(f.invoke).toHaveBeenCalledTimes(preview.decision === "match" ? 1 : 0); + if (preview.decision === "match") expect(f.invoke.mock.calls[0][1]).toMatchObject({ claimKey: "webhook:trigger-id:webhook:github:delivery", context: { "trigger-2": prepared } }); + f.invoke.mockClear(); + await (f.scheduler as any).githubVerifications(); + expect(f.invoke).toHaveBeenCalledTimes(preview.decision === "match" ? 1 : 0); + if (preview.decision === "match") expect(f.invoke.mock.calls[0][1]).toMatchObject({ context: { "trigger-2": verified } }); + else expect(f.query.mock.calls.some(([sql, values]: any) => sql.includes("INSERT INTO app.job_events") && values.includes("excluded"))).toBe(true); + }); + it("continues after invalid candidates and keeps duplicate/queue_full distinct", async () => { + const f = fixture(); + vi.spyOn(f.ordinary as any, "candidates").mockResolvedValue([ + { job: { id: "invalid" }, triggerId: "invalid", triggerSlug: "hook", config: { ...f.config, conditions: { all: [] } } }, + { job: { id: "excluded" }, triggerId: "excluded", triggerSlug: "hook", config: { ...f.config, conditions: leaf("$.action", "other") } }, + ...["duplicate", "full", "accepted"].map(id => ({ job: { id }, triggerId: id, triggerSlug: "hook", config: f.config })), + ]); + f.invoke.mockResolvedValueOnce({ duplicate: true } as any).mockRejectedValueOnce(new InvocationError("queue_full", "full")).mockResolvedValueOnce({ duplicate: false } as any); + await (f.ordinary as any).invoke("github", "delivery", f.payload, "pull_request"); + expect(f.event.mock.calls.map(call => call[4])).toEqual(["conditions_error", "excluded", "duplicate", "queue_full", "accepted"]); + }); + it("checks scope before conditions and queues GitHub verification before filtering", async () => { + const f = fixture({ all: [] }); + await (f.ordinary as any).invoke("github", "delivery", { ...f.payload, repository: { id: 99 } }, "pull_request"); + expect(f.event.mock.calls[0][4]).toBe("ignored"); expect(f.invoke).not.toHaveBeenCalled(); + await f.ordinary.github(f.payload, "delivery", "pull_request"); + expect(f.query.mock.calls.some(([sql]) => sql.includes("INSERT INTO app.pending_verifications"))).toBe(true); expect(f.fetch).not.toHaveBeenCalled(); + }); + it("uses latest conditions when a pending verification is evaluated", async () => { + const f = fixture(leaf("$.pull_request.mergeable", true)); + f.row.trigger_config = { ...f.config, conditions: leaf("$.pull_request.mergeable", false) }; + await (f.scheduler as any).githubVerifications(); expect(f.invoke).toHaveBeenCalledOnce(); + }); + it("never invokes on evaluation error or disabled/removed triggers", async () => { + for (const update of [{ trigger_config: { ...fixture().config, conditions: { all: [] } } }, { trigger_enabled: false }, { job_enabled: false }, { removed_at: new Date() }]) { + vi.restoreAllMocks(); const f = fixture(); Object.assign(f.row, update); + await (f.scheduler as any).githubVerifications(); expect(f.invoke).not.toHaveBeenCalled(); + if (!("trigger_config" in update)) expect(f.fetch).not.toHaveBeenCalled(); + } + }); + it("preserves unresolved mergeability retries, open/main gates and queue outcomes", async () => { + for (const pull of [{ state: "closed", base: { ref: "main" }, mergeable: false }, { state: "open", base: { ref: "feature" }, mergeable: false }, { state: "open", base: { ref: "main" }, mergeable: true }, { state: "open", base: { ref: "main" }, mergeable: null }, { state: "open", base: { ref: "main" }, mergeable: undefined }]) { + vi.restoreAllMocks(); const f = fixture(); f.fetch.mockResolvedValue(Response.json(pull)); await (f.scheduler as any).githubVerifications(); expect(f.invoke).not.toHaveBeenCalled(); + if (pull.mergeable === null || pull.mergeable === undefined) expect(f.query.mock.calls.some(([sql]) => sql.includes("UPDATE app.pending_verifications SET attempt"))).toBe(true); + } + for (const outcome of ["duplicate", "queue_full"]) { + vi.restoreAllMocks(); const f = fixture(); + if (outcome === "duplicate") f.invoke.mockResolvedValue({ duplicate: true } as any); else f.invoke.mockRejectedValue(new InvocationError("queue_full", "full")); + await (f.scheduler as any).githubVerifications(); + expect(f.query.mock.calls.some(([sql, values]: any) => sql.includes("INSERT INTO app.job_events") && values.includes(outcome))).toBe(true); + } + }); +}); diff --git a/packages/api/test/custom-handler.test.ts b/packages/api/test/custom-handler.test.ts deleted file mode 100644 index 35a1d527..00000000 --- a/packages/api/test/custom-handler.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { invokeCustomHandler, userWorkerModule, validateHandlerCode } from "../src/custom-handler"; - -describe("custom handlers", () => { - const runAdapter = async (body: string) => { - const source = userWorkerModule(`function handler(webhook) { ${body} }`); - const module = await import(`data:text/javascript;base64,${Buffer.from(source).toString("base64")}#${crypto.randomUUID()}`); - const response = await module.default.fetch(new Request("https://handler.internal", { method: "POST", body: "{}" })); - return response.json(); - }; - - it("accepts only the complete synchronous function contract", () => { - expect(validateHandlerCode("function handler(webhook) { return webhook.type === 'Issue'; }")).toContain("function handler"); - for (const code of ["return true", "const handler = () => true", "async function handler(webhook) { return true; }", "function other(webhook) { return true; }"]) { - expect(() => validateHandlerCode(code)).toThrow("complete function handler(webhook)"); - } - }); - - it("pins an adapter that rejects thenables and invalid return types without exposing errors", () => { - const module = userWorkerModule("function handler(webhook) { return true; }"); - expect(module).toContain('typeof result.then === "function"'); - expect(module).toContain('typeof result === "boolean"'); - expect(module).toContain("Array.isArray(result)"); - expect(module).not.toContain("error.stack"); - }); - - it("loads handlers without bindings or outbound network access", async () => { - let loaded: WorkerLoaderWorkerCode | undefined; - const loader = { - load(code: WorkerLoaderWorkerCode) { - loaded = code; - return { - getEntrypoint: () => ({ - fetch: async () => Response.json({ ok: true, decision: true }), - }), - }; - }, - } as unknown as WorkerLoader; - const source = { handlerCode: "function handler(webhook) { return true; }" }; - - await expect(invokeCustomHandler(loader, source, {})).resolves.toEqual({ ok: true, decision: true }); - expect(loaded?.env).toEqual({}); - expect(loaded?.globalOutbound).toBeNull(); - expect(loaded?.limits).toEqual({ cpuMs: 10, subRequests: 0 }); - }); - - it("admits literal booleans and fails closed on invalid synchronous results", async () => { - await expect(runAdapter("return true;")).resolves.toEqual({ ok: true, decision: true }); - await expect(runAdapter("return false;")).resolves.toEqual({ ok: true, decision: false }); - await expect(runAdapter("return 1;")).resolves.toEqual({ ok: false, category: "invalid_return" }); - await expect(runAdapter("return Promise.resolve(true);")).resolves.toEqual({ ok: false, category: "invalid_return" }); - await expect(runAdapter("return { then() {} };")).resolves.toEqual({ ok: false, category: "invalid_return" }); - await expect(runAdapter("return { issue: { id: 'i1' } };")).resolves.toEqual({ ok: true, decision: { issue: { id: "i1" } } }); - await expect(runAdapter("return [1, 2];")).resolves.toEqual({ ok: false, category: "invalid_return" }); - await expect(runAdapter("return null;")).resolves.toEqual({ ok: false, category: "invalid_return" }); - await expect(runAdapter("return { missing: undefined };")).resolves.toEqual({ ok: false, category: "invalid_return" }); - await expect(runAdapter("return { value: NaN };")).resolves.toEqual({ ok: false, category: "invalid_return" }); - await expect(runAdapter("return { value: 1n };")).resolves.toEqual({ ok: false, category: "invalid_return" }); - await expect(runAdapter("throw new Error('secret');")).resolves.toEqual({ ok: false, category: "handler_error" }); - }); -}); diff --git a/packages/api/test/trigger-context.test.ts b/packages/api/test/trigger-context.test.ts index 2a4bd12a..35dc70be 100644 --- a/packages/api/test/trigger-context.test.ts +++ b/packages/api/test/trigger-context.test.ts @@ -14,9 +14,9 @@ describe("trigger context reflection", () => { expect(triggerContextCatalog.github).toContainEqual(expect.objectContaining({ path: "issue.title", type: "string" })); }); - it("preserves the slug and explicitly marks unknown handler output", () => { - const reflected = reflectTriggerContext({ slug: "trigger-7", kind: "webhook", config: { provider: "linear", handlerCode: "function handler() { return {}; }" } }); - expect(reflected).toMatchObject({ slug: "trigger-7", provider: "linear", dynamic: true }); - expect(reflected.paths).toEqual([{ path: "*", type: "unknown", description: expect.any(String) }]); + it("preserves the slug and retains provider context with conditions", () => { + const reflected = reflectTriggerContext({ slug: "trigger-7", kind: "webhook", config: { provider: "linear", conditions: { all: [] } } }); + expect(reflected).toMatchObject({ slug: "trigger-7", provider: "linear", dynamic: false }); + expect(reflected.paths).toEqual(triggerContextCatalog.linear); }); }); diff --git a/packages/api/test/webhook-conditions.test.ts b/packages/api/test/webhook-conditions.test.ts new file mode 100644 index 00000000..de89614c --- /dev/null +++ b/packages/api/test/webhook-conditions.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import { readFileSync } from "node:fs"; +import { CONDITION_LIMITS, evaluateWebhookConditions, validateConditions } from "../src/webhook-conditions"; +import { webhookTriggerConfigSchema } from "../src/flow-schemas"; +const build = JSON.parse(readFileSync(new URL("../migrations/build-manager-conditions.json", import.meta.url), "utf8")); +export const leaf = (path: string, operator: string, value: unknown) => ({ fact: "webhook", path, operator, value }); +const decision = async (conditions: unknown, webhook: Record) => (await evaluateWebhookConditions(conditions, webhook)).decision; +describe("shared webhook conditions", () => { + it("preserves all Build Manager exclusions and accepted/missing/null/wrong-type cases", async () => { + for (const conclusion of [undefined, null, "success", "skipped", "failure"]) + for (const branch of [undefined, null, 123, "main", "feature", "gh-readonly-queue/main/test"]) + for (const sender of [undefined, null, "github-merge-queue[bot]", "human"]) + for (const app of [undefined, null, "mintlify", "github-actions"]) { + const excluded = (conclusion === "success" && typeof branch === "string" && branch.startsWith("gh-readonly-queue/")) || (conclusion === "success" && branch === "main" && sender === "github-merge-queue[bot]") || (conclusion === "skipped" && app === "mintlify"); + expect(await decision(build, { action: "completed", check_suite: { conclusion, head_branch: branch, app: { slug: app } }, sender: { login: sender } })).toBe(excluded ? "no-match" : "match"); + } + for (const check_suite of [undefined, null, false, "invalid"]) + expect(await decision(build, { action: "completed", check_suite })).toBe("match"); + }); + it("uses strict equality and documented missing-field semantics", async () => { + expect(await decision(undefined, {})).toBe("match"); + expect(await decision(leaf("$.missing", "notEqual", "x"), {})).toBe("match"); + expect(await decision(leaf("$.missing", "equal", null), {})).toBe("no-match"); + expect(await decision(leaf("$.id", "equal", 42), { id: "42" })).toBe("no-match"); + expect(await decision(leaf("$.id", "equal", null), { id: null })).toBe("match"); + for (const value of [undefined, null, 1, [], {}]) expect(await decision(leaf("$.branch", "startsWith", "gh-"), { branch: value })).toBe("no-match"); + }); + it("supports scalar/index/quoted property and wildcard paths with Boolean nesting", async () => { + const context = { items: [{ tag: "a" }, { tag: "b" }], tags: ["a", "b"], "quoted-key": "yes" }; + for (const path of ["$.items[0].tag", "$['items'][0].tag", '$["items"][0].tag']) expect(await decision(leaf(path, "equal", "a"), context)).toBe("match"); + for (const path of ["$.items[*].tag", "$.tags", "$.items.*.tag"]) expect(await decision(leaf(path, "contains", "b"), context)).toBe("match"); + expect(await decision({ not: { any: [{ all: [leaf("$.tags", "doesNotContain", "b"), leaf("$.items[0].tag", "in", ["a", "c"])] }, leaf("$.items[0].tag", "notIn", ["a"])] } }, context)).toBe("match"); + expect(await decision(leaf("$.items[*].missing", "contains", "x"), context)).toBe("no-match"); + expect(await decision(leaf("$.text", "contains", "x"), { text: "xxx" })).toBe("no-match"); + }); + it("requires finite numeric operands rather than lexical/coerced comparison", async () => { + for (const operator of ["lessThan", "lessThanInclusive", "greaterThan", "greaterThanInclusive"]) { + expect(() => validateConditions(leaf("$.n", operator, "10"))).toThrow(); + expect(await decision(leaf("$.n", operator, 10), { n: "2" })).toBe("no-match"); + expect(await decision(leaf("$.n", operator, 10), { n: null })).toBe("no-match"); + } + expect(await decision(leaf("$.n", "lessThan", 10), { n: 2 })).toBe("match"); + }); + it("rejects executable paths, unknown operators/facts, mixed groups and user engine options", async () => { + const invalid = [null, {}, [], { all: [] }, { any: [] }, { not: {} }, { all: [leaf("$.x", "equal", true)], any: [] }, { ...leaf("$.x", "equal", true), priority: 2 }, { ...leaf("$.x", "equal", true), fact: "network" }, leaf("$.x", "unknown", true), leaf("$.x", "in", "abc"), leaf("$.x", "equal", { fact: "network" }), leaf("$.x", "startsWith", 1)]; + for (const path of ["x", "$..x", "$.a[?(@.x)]", "$.a[(@.length-1)]", "$.a[0:2]", "$.a[0,1]", "$.a[", "$.a()"] ) invalid.push(leaf(path, "equal", true)); + for (const value of invalid) { expect(() => validateConditions(value)).toThrow(); expect(await decision(value, {})).toBe("error"); } + }); + it("bounds byte size, depth and nodes", async () => { + expect(() => validateConditions(leaf("$.x", "equal", "x".repeat(CONDITION_LIMITS.bytes)))).toThrow("byte"); + expect(() => validateConditions({ all: Array.from({ length: CONDITION_LIMITS.nodes }, () => leaf("$.x", "equal", true)) })).toThrow("node"); + let nested: unknown = leaf("$.x", "equal", true); + for (let i = 0; i < CONDITION_LIMITS.depth; i++) nested = { not: nested }; + expect(() => validateConditions(nested)).toThrow("depth"); + expect(() => validateConditions({ all: Array.from({ length: CONDITION_LIMITS.nodes - 1 }, () => leaf("$.x", "equal", true)) })).not.toThrow(); + }); + it("returns plain result objects and leaves context intact", async () => { + const webhook = { id: "a", payload: { x: 1 } }, original = structuredClone(webhook); + const result = await evaluateWebhookConditions({ any: [leaf("$.id", "equal", "a"), leaf("$.id", "equal", "b")] }, webhook); + expect(result.decision).toBe("match"); expect(typeof result.details[0]).toBe("object"); + expect(typeof result.details[0].conditions).toBe("object"); + expect(JSON.parse(JSON.stringify(result))).toEqual(result); expect(webhook).toEqual(original); + }); + it("validates conditions for every provider and rejects legacy requests", () => { + const configs = [{ provider: "linear", projectId: "p", matchRules: [{ type: "status", targetId: "done" }] }, { provider: "clickup", listId: "l", matchRules: [{ type: "status", targetId: "done" }] }, { provider: "github", installationId: 1, repositoryId: 2, event: "check_suite", action: "completed" }, { provider: "cloudflareTail", integrationId: "tail" }]; + for (const config of configs) { + expect(webhookTriggerConfigSchema.parse({ ...config, conditions: build })).toEqual({ ...config, conditions: build }); + expect(() => webhookTriggerConfigSchema.parse({ ...config, handlerCode: "removed" })).toThrow(); + } + }); +}); diff --git a/packages/api/test/webhook-trigger.test.ts b/packages/api/test/webhook-trigger.test.ts index 75adb2d2..5cfae632 100644 --- a/packages/api/test/webhook-trigger.test.ts +++ b/packages/api/test/webhook-trigger.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { adaptWebhook, publicWebhookConfig, validateWebhookHandler } from "../src/webhook-trigger"; +import { adaptWebhook, publicWebhookConfig } from "../src/webhook-trigger"; describe("webhook Job trigger adapters", () => { it("matches Linear and derives a stable claim plus string invocation inputs", () => { @@ -29,13 +29,7 @@ describe("webhook Job trigger adapters", () => { }); it("never exposes webhook secrets", () => { - expect(publicWebhookConfig({ provider: "cloudflareTail", signingSecret: "super-secret-value", handlerCode: "function handler(webhook) { return true; }" })).toEqual({ provider: "cloudflareTail", handlerCode: "function handler(webhook) { return true; }", secretConfigured: true }); + expect(publicWebhookConfig({ provider: "cloudflareTail", signingSecret: "super-secret-value", conditions: { all: [{ fact: "webhook", path: "$.outcome", operator: "equal", value: "exception" }] } })).toEqual({ provider: "cloudflareTail", conditions: { all: [{ fact: "webhook", path: "$.outcome", operator: "equal", value: "exception" }] }, secretConfigured: true }); }); - it("validates optional handlers for every provider", () => { - for (const provider of ["linear", "clickup", "github", "cloudflareTail"] as const) { - expect(() => validateWebhookHandler({ provider, handlerCode: "function handler(webhook) { return { id: webhook.id }; }" })).not.toThrow(); - } - expect(() => validateWebhookHandler({ provider: "linear", handlerCode: "return true" })).toThrow("complete function handler(webhook)"); - }); }); diff --git a/packages/api/wrangler.jsonc b/packages/api/wrangler.jsonc index e509c05f..27a29fd2 100644 --- a/packages/api/wrangler.jsonc +++ b/packages/api/wrangler.jsonc @@ -8,7 +8,6 @@ "kv_namespaces": [{ "binding": "OAUTH_KV", "id": "cacbf744337747ffbb9c0153329aad4f" }], "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "9b6c8a09921d4ee18cdf3723135c82ad" }], "r2_buckets": [{ "binding": "RUN_ARTIFACTS", "bucket_name": "factorize-run-artifacts" }], - "worker_loaders": [{ "binding": "CUSTOM_HANDLER_LOADER" }], "durable_objects": { "bindings": [{ "name": "SCHEDULER", "class_name": "AlarmCoordinator" }] }, diff --git a/packages/app/src/features/jobs/conditions-editor.tsx b/packages/app/src/features/jobs/conditions-editor.tsx new file mode 100644 index 00000000..4cf63543 --- /dev/null +++ b/packages/app/src/features/jobs/conditions-editor.tsx @@ -0,0 +1,28 @@ +import { useEffect, useState } from "react"; +import { useMutation } from "@tanstack/react-query"; +import { api } from "factorize-api-client"; +import { messageOf } from "../auth/session"; +import type { Trigger } from "./editor-state"; +type Conditions = Extract["config"]["conditions"]; +export function ConditionsEditor({ conditions, onChange }: { conditions: Conditions; onChange: (value: Conditions) => void }) { + const [text, setText] = useState(() => conditions === undefined ? "" : JSON.stringify(conditions, null, 2)); + const [webhook, setWebhook] = useState("{}"), [invalid, setInvalid] = useState(""); + useEffect(() => { setText(conditions === undefined ? "" : JSON.stringify(conditions, null, 2)); setInvalid(""); }, [conditions]); + const test = useMutation({ retry: false, mutationFn: async () => { + const example: unknown = JSON.parse(webhook); + if (!example || typeof example !== "object" || Array.isArray(example)) throw new Error("Example webhook must be a JSON object."); + const { data, error } = await api.POST("/api/v1/job-conditions/test", { body: { conditions: text.trim() ? JSON.parse(text) : undefined, webhook: example as Record } }); + if (!data || error) throw new Error(messageOf(error)); return data; + } }); + return