Files
OmniRoute/docs/frameworks/WEBHOOKS.md
Diego Rodrigues de Sa e Souza 5ac4637816 docs: reorganize docs/ + accuracy audit + drop Node 20 (rebased onto current release tip) (#5262)
* docs: move superpowers/research artifacts to isolated _tasks repo + docs tree cleanup

- Move docs/superpowers/{plans,specs} and docs/research/* into the gitignored,
  separately-versioned _tasks/ repo; untrack the two tracked research design docs.
- Add CLAUDE.md "Planning & Research Artifacts" section overriding the superpowers
  default save paths (docs/... -> _tasks/...); align REPOSITORY_MAP and
  DOCUMENTATION_OVERHAUL_PLAN with the new convention.
- Drop 4 now-obsolete /api/discovery/* entries from check-docs-symbols allowlist
  (stale-enforcement) and refresh code/spec path comments to _tasks/...
- Sweeps in concurrent docs-tree restructuring (root-level provider/guide docs,
  compression spec cleanup, .mcp.json.example removal).

* docs: reorganize docs/ tree + fix stale facts across ~26 docs

Phase A — reorganization:
- Move 7 orphan root docs into subfolders (providers/ created; TIERS+USAGE_QUOTA→guides/;
  plugins+PLUGIN_SDK→frameworks/); delete 8 obsolete/redundant docs (SUBMIT_PR superseded
  by CONTRIBUTING; DOCUMENTATION_OVERHAUL_PLAN; INCIDENT_RESPONSE/PERF_BUDGETS/THREAT_MODEL;
  3 ops snapshots). Rebuild README index (was missing ~40 files) + per-folder meta.json nav.
- Clean 14 dangling doc-path references in bin/ ops scripts, scripts/, workflow, tests;
  fix the dockerignore-docs-coverage required-docs path (PROVIDERS→providers/CLAUDE_WEB).

Phase B — content accuracy (verified against code, not the audit summary):
- Functional: ENVIRONMENT flag defaults (INPUT_SANITIZER/MCP_ENFORCE_SCOPES=true,
  COMPRESS_DESCRIPTIONS=false, dynamic heap); MCP-SERVER notion tool names (omniroute_*→
  notion_*) + counts 87→94; coverage gate 75/70→60/60/60/60 (RELEASE_CHECKLIST, COVERAGE_PLAN,
  ERROR_SANITIZATION, CONTRIBUTING); pre-push hook description; regenerate PROVIDER_REFERENCE (237).
- Count drift: providers 237, executors 70, migrations 106, db modules 94, oauth 19,
  strategies 17, MCP 94, flags 38, TS 6.0, open-sse ~900/services 294 across architecture/
  frameworks/ops docs; AUTO-COMBO 9→12 factors w/ correct DEFAULT_WEIGHTS; REASONING +2
  patterns; STEALTH UA defaults; AGENT_PROTOCOLS +cursor-cloud/list-capabilities;
  LANGUAGE_PACKS +id pack.
- Kept Node 20 (runtime guard accepts 20.20.2+; only engines is stricter) and MCP scopes=13
  (mcpScopes.ts) — both were correct in the docs; corrected only the attribution.

* docs: finish content refresh — compression engines, CLI_TOKEN merge, metadata sweep

- Compression: document the additional built-in engines (CCR, headroom, ionizer,
  session-dedup) in COMPRESSION_ENGINES; clarify LLMLingua-2 is the ultra-mode SLM
  backend + cross-ref the extra engines in EXTENDING_COMPRESSION; add the id
  (Indonesian) language pack to LANGUAGE_PACKS.
- AUTO-COMBO: replace the orphan 'How tiers fit' weight table (stale weights) with a
  pointer to the canonical 12-factor DEFAULT_WEIGHTS table.
- Security: merge CLI_TOKEN_AUTH.md (legacy 32-char SHA-256 format) into CLI_TOKEN.md
  as a 'Legacy format — still accepted' section (server accepts both HMAC + legacy),
  delete CLI_TOKEN_AUTH.md, drop it from the index + security nav.
- Metadata: bump stale frontmatter (version/lastUpdated) to 3.8.40/2026-06-28 across the
  doc set audited this pass, and normalize the in-body 'Last updated' header lines to match.

* fix(runtime): drop Node 20 from supported range + align all docs/diagrams/counts

- Node minimum is now 22 (aligned with package.json engines). SUPPORTED_NODE_RANGE in
  src/shared/utils/nodeRuntimeSupport.ts (and the bin/ mirror) drops the 20.x line →
  '>=22.22.2 <23 || >=24.0.0 <27'; getNodeRuntimeSupport now rejects Node 20 as
  unsupported-major. Test updated (TDD): node-runtime-support.test.ts asserts Node 20
  rejected. Docs aligned (TROUBLESHOOTING ×2, TERMUX, RELEASE_CHECKLIST, CODEBASE,
  CLI-TOOLS, README, llm.txt + 42 i18n llm.txt mirrors, skills/cli-serve).
- Diagrams regenerated: mcp-tools-87 -> mcp-tools-94 (34 base + pool 6 = 94) and
  auto-combo-9factor -> auto-combo-12factor (correct DEFAULT_WEIGHTS); SVGs re-rendered
  via mermaid-cli; doc refs + diagrams/README updated; fixed a pre-existing broken
  resilience-3layers image path.
- CLAUDE.md + AGENTS.md aligned to real counts (237 providers, 94 MCP tools / 34 base,
  106 migrations, 94 db modules, 12-factor auto-combo, 17 strategies); README provider
  count 231 -> 237; executor count corrected to 68 (provider executors, excl base/index)
  and OAuth to 18 across architecture docs. check:docs-all now passes (0 strict drift,
  0 broken links); removed dead .mcp.json.example doc link.

* fix(services): update installer Node hint to >=22.22.2 (aligned with dropped Node 20)

* docs: realign counts to current release tip after rebase

The release tip advanced while this work was in flight (Gemini CLI provider/executor
removed by #5246, plus other PRs). Re-counted against the current code and updated:
providers 237->236, executors 68->67, OAuth modules 18->17, open-sse services 294->298;
regenerated PROVIDER_REFERENCE.md (236). check:docs-all passes (0 strict drift).

* docs(changelog) + i18n: record Node 20 drop + fix nodeIncompatibleHint

- CHANGELOG: add [3.8.40] entries for the Node 20.x removal (runtime) and the docs
  reorganization/accuracy audit.
- i18n: nodeIncompatibleHint across all 42 locales no longer lists Node 20.x as
  supported (ASCII + CJK full-width variants), aligned with the dropped Node 20.

* fix(docs): repair CI breakages from the doc moves

- test: cli-plugin-system asserted docs/dev/plugins.md exists; the file moved to
  docs/frameworks/PLUGINS.md — point the test at the new path (Unit fast-path 2/2 fix).
- frontmatter: PLUGINS.md and PLUGIN_SDK.md moved into the fumadocs-indexed
  docs/frameworks/ which requires a 'title' frontmatter; the missing frontmatter
  failed the Next.js MDX build (dast-smoke 'invalid frontmatter'). Added frontmatter
  to both, plus the providers/ docs (consistency; that folder is not indexed).
2026-06-28 22:07:18 -03:00

9.3 KiB

title, version, lastUpdated
title version lastUpdated
Webhooks 3.8.40 2026-06-28

Webhooks

Source of truth: src/lib/webhookDispatcher.ts, src/lib/db/webhooks.ts, src/app/api/webhooks/ Last updated: 2026-06-28 — v3.8.40

OmniRoute can fire HTTP webhooks on platform events. Use them to integrate with Slack, PagerDuty, Datadog, internal alerting services, or any HTTP receiver.

The dispatcher signs each delivery with HMAC-SHA256, retries on transient failures, tracks delivery health per webhook, and auto-disables endpoints that keep failing.

Supported Events

The WebhookEvent type (src/lib/webhookDispatcher.ts) currently models:

Event Fires when
request.completed A proxied request completes successfully
request.failed A proxied request fails after all retries/fallback
provider.error A provider returns an error eligible for circuit-breaking
provider.recovered A previously failing provider returns to a healthy state
quota.exceeded An API key crosses a budget/quota threshold
combo.switched A combo strategy switches its primary target
test.ping Synthetic event used by the test endpoint

Subscriptions accept the literal "*" to receive every event. Unknown event names in events are ignored at dispatch time.

Note: the dispatcher API is wired, but production call sites for some of the non-test.ping events are still landing. Check grep dispatchEvent to see which paths currently invoke the dispatcher in your release.

Architecture

Caller (handler, service, monitor)
  dispatchEvent(event, data)            [src/lib/webhookDispatcher.ts]
    -> getEnabledWebhooks()             [src/lib/db/webhooks.ts]
    -> filter by webhook.events
    -> for each match (in parallel):
       deliverWebhook(url, payload, secret)
         build payload { event, timestamp, data }
         sign body with HMAC-SHA256 (if secret present)
         POST with 10s timeout
         retry up to 3 times on 5xx / network error
       recordWebhookDelivery(id, status, success)
    -> disableWebhooksWithHighFailures(10)

Dispatch is fire-and-forget for the caller: Promise.allSettled swallows per-webhook errors so one bad receiver cannot block the others.

HMAC Signing

When a webhook has a secret, OmniRoute signs the JSON body and sends:

Content-Type: application/json
User-Agent: OmniRoute-Webhook/1.0
X-Webhook-Event: <event>
X-Webhook-Timestamp: <ISO-8601>
X-Webhook-Signature: sha256=<hex HMAC-SHA256(secret, body)>

Header names use the X-Webhook-* prefix (not X-OmniRoute-*). The signature value is sha256=<hex> — verify the full prefix.

If createWebhook is called without a secret, the DB module generates one (whsec_<48 hex>) so all webhooks are signed by default.

Verifying on the receiver

import { createHmac, timingSafeEqual } from "node:crypto";

function verify(rawBody: string, signature: string, secret: string) {
  const expected = "sha256=" + createHmac("sha256", secret).update(rawBody).digest("hex");
  const a = Buffer.from(expected);
  const b = Buffer.from(signature);
  return a.length === b.length && timingSafeEqual(a, b);
}

Always verify against the raw request body, before any JSON parsing.

Retry & Failure Policy

deliverWebhook(url, payload, secret, maxRetries = 3):

  • 10 second timeout per attempt (AbortController).
  • HTTP 2xx counts as success.
  • HTTP 3xx/4xx counts as a non-retryable final status — recorded as delivered with success = res.ok.
  • HTTP 5xx and network errors are retried with exponential backoff: 2^attempt * 1000 ms (1s, 2s, 4s).
  • After maxRetries, the delivery is recorded as failed.
  • Each delivery updates last_triggered_at, last_status, and either resets or increments failure_count.
  • The dispatcher calls disableWebhooksWithHighFailures(10) after each fan-out, so any webhook with failure_count >= 10 is automatically disabled.

Database

Table webhooks (migration 011_webhooks.sql):

Column Type Notes
id TEXT PK UUID
url TEXT Destination URL
events TEXT JSON array; default ["*"]
secret TEXT HMAC secret (auto-generated if not given)
enabled INT 0/1; defaults to 1
description TEXT Optional human label
created_at TEXT datetime('now')
last_triggered_at TEXT Updated on every delivery attempt
last_status INT HTTP status of the last attempt (0 = network)
failure_count INT Resets to 0 on success, +1 on failure

There is no separate webhook_deliveries table in the current schema — delivery history is aggregated on the webhooks row. If you need full audit history, consume request.completed / audit style events from a downstream log store.

REST API

All endpoints require management auth (requireManagementAuth).

Endpoint Method Description
/api/webhooks GET List webhooks (secrets masked)
/api/webhooks POST Create webhook
/api/webhooks/[id] GET Webhook detail (full secret)
/api/webhooks/[id] PUT Update fields
/api/webhooks/[id] DELETE Remove
/api/webhooks/[id]/test POST Fire a test.ping (no retries)

GET /api/webhooks masks the secret to <first 10 chars>... to avoid leaking on listing pages. Use the [id] GET when you actually need the secret.

Create webhook

curl -X POST http://localhost:20128/api/webhooks \
  -H "Cookie: auth_token=..." \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://hooks.slack.com/services/...",
    "secret": "whsec_my_shared_secret",
    "events": ["quota.exceeded", "provider.error"],
    "description": "Slack alerts"
  }'

If secret is omitted, the server generates a whsec_<hex> secret and returns it in the response.

Test webhook

curl -X POST http://localhost:20128/api/webhooks/<id>/test \
  -H "Cookie: auth_token=..."

Returns { delivered, status, error }. No retries are attempted — useful for quickly validating that the receiver accepts the payload and signature.

Dashboard

The dashboard page at /dashboard/webhooks (see src/app/(dashboard)/dashboard/webhooks/page.tsx) provides:

  • Create/edit webhooks with an event picker
  • Status indicator (active / inactive / errored) based on enabled, failure_count, and last_status
  • One-click test delivery
  • Manual enable/disable toggle

Payload Examples

request.completed

{
  "event": "request.completed",
  "timestamp": "2026-05-13T20:30:00.123Z",
  "data": {
    "trace_id": "...",
    "api_key_id": "...",
    "provider": "openai",
    "model": "gpt-5",
    "status": 200,
    "tokens_in": 142,
    "tokens_out": 350,
    "cost_usd": 0.0042
  }
}

provider.error

{
  "event": "provider.error",
  "timestamp": "2026-05-13T20:31:00.000Z",
  "data": {
    "provider": "anthropic",
    "status": 503,
    "consecutive_failures": 5,
    "circuit_state": "open"
  }
}

test.ping

{
  "event": "test.ping",
  "timestamp": "2026-05-13T20:32:00.000Z",
  "data": {
    "message": "Test webhook delivery from OmniRoute",
    "webhookId": "<uuid>"
  }
}

Field shapes for non-test.ping events are defined by the call sites that emit them; treat the data object as forward-compatible (add fields, don't depend on absence).

Best Practices

  • Verify the signature on every delivery against the raw body — prevents spoofed POSTs from anyone who guesses your webhook URL.
  • Respond 2xx within ~5 seconds — the dispatcher times out at 10 s. Slow receivers will eat retries and inflate failure_count.
  • Make handlers idempotent — retries and at-least-once delivery semantics mean duplicates are possible.
  • Subscribe minimally — list only events you actually consume; "*" will add cost on receivers you do not control.
  • Watch failure_count — endpoints are auto-disabled at 10 consecutive failures; reset by calling PUT /api/webhooks/[id] with enabled: true after fixing the receiver.
  • Rotate secrets periodicallyPUT a new secret, deploy the new value to the receiver, and confirm via the test endpoint.

See Also

  • API_REFERENCE.md — full management API surface
  • RESILIENCE_GUIDE.md — circuit breaker / cooldown semantics that drive provider.error / provider.recovered
  • Source: src/lib/webhookDispatcher.ts, src/lib/db/webhooks.ts