Guides

Webhooks: Capture & Replay

Send an inbound callback to the agent's capture endpoint to retain a specimen. The endpoint returns 200 after a successful file write and sync; it does not forward the callback to your application. An authenticated member can later replay one stored capture through the control-plane API to an approved receiver.

Two halves: capture vs. replay

Capture — admitted requests

The agent appends the admitted callback to a service-scoped JSONL file and returns 200 after write and sync succeed. A full queue or failed write/sync returns 503; inspect the outcome before repeating.

Replay — an explicit outbound call

The API mirrors supported records from the shared store. A member explicitly selects a capture and target for each replay. Capture and sync do not send the event to the application.

Three separate observations

Check the capture response, the stored record and the receiver's business effect separately. A capture 200 confirms the sink write and sync, not API import or consumer processing. A 503, timeout or lost response does not establish absence; a replay response does not prove the application processed the event once.

Capturing inbound webhooks

The capture sink accepts HTTP methods at /webhook/{tenant}/{service_id}, typically POST. Admitted captures pass through a shared file sink under WEBHOOK_DIR, one JSONL file per service. Agent and API must share that mounted directory; the intended container path is /data/webhooks. The API mirrors supported records in the background, by default every 30 seconds, rather than delivering them to a consumer.

Authored generic text-event specimen, shown expanded for readability; the file stores one compact JSON record per line:

{
  "id": "wh_a1b2c3d4e5f60718",
  "received_at": "2026-10-27T09:14:22Z",
  "tenant": "default",
  "service_id": "svc_5f2c9e1a7b3d4c6e8f0a1b2c3d4e5f60",
  "method": "POST",
  "uri": "/webhook/default/svc_5f2c9e1a7b3d4c6e8f0a1b2c3d4e5f60",
  "headers": { "content-type": "application/json" },
  "body": "{\"event_id\":\"evt_example_A\",\"type\":\"order.updated\",\"order_id\":\"order_A\"}",
  "signature_kind": "generic"
}

After a successful write and sync, capture returns 200 with { received: true, id: "wh_…" }. A write_failed outcome returns 503 with Retry-After: 30; queue_full returns 503 with Retry-After: 1. Retry-After does not guarantee redelivery: the sender must have a policy that retries that outcome. A failed sync can leave a complete source record or an already-imported API row, so a failure response does not prove nothing was stored. Inspect retained captures before resubmitting.

Event identity is not capture identity

Each admitted delivery gets a new wh_<16 hex> capture ID. For example, captures wh_a1b2c3d4e5f60718 and wh_b1b2c3d4e5f60718 can both have event_id: evt_example_A in their parsed text bodies. The API avoids reimporting the same capture ID. received_at is capture time, not the event's creation time or a replay-order contract.

Recognized, non-null provider delivery IDs can also deduplicate API rows within the same tenant and service. This extraction does not authenticate the sender. A conflict keeps the existing row without comparing or updating its payload; a reused ID with changed content may not appear as a new row. Missing, redacted or invalid IDs do not merge, and older rows are not backfilled. This rule does not deduplicate the local file. Your consumer still chooses the logical-event key, its source/account scope and the intended business-effect policy.

Header lookup prefers webhook-id, then svix-id, X-GitHub-Delivery and I-Twilio-Idempotency-Token. Eligibility depends on retained values and length checks; an overlong higher-priority value can prevent use of a later header. A Stripe fallback checks a retained stripe-signature and a JSON object id starting evt_. This is delivery-ID extraction, not signature verification.

Which webhooks are captured

Traffic and webhook capture are separate service settings, on by default. After the agent receives its routing table, webhook admission requires an active routed service with webhook capture enabled:

  • An unknown, archived or deleted service is refused with 404 and reason unknown_service.
  • A routed service with capture off is refused with 403 and reason capture_disabled. Refusal counts reset when the agent restarts.
  • Active license access, valid 1–64-character ASCII alphanumeric/underscore/hyphen path slugs, the configured capture token and body limits also apply. Oversized bodies receive 413.

Set WEBHOOK_CAPTURE_TOKEN in the agent environment to require a matching capture credential. Send it in X-Gostly-Capture-Token; a token query credential is also accepted, with a nonempty header preferred. Without a configured token, capture does not require that credential. It is separate from API authentication and does not verify a sender's signature.

Service, credential, path and body-limit refusals do not write a capture. Before the first routing table arrives, slug-valid service IDs may be admitted subject to the other checks. Admitted requests still wait for the sink write and sync before a 200 acknowledgement.

Provider detection

signature_kind classifies recognized header sets as stripe, github, standard or generic. A parsed-signature view is descriptive metadata. Classification, parsed fields and retained headers do not verify authenticity; the capture/replay surface does not verify or re-sign signatures.

Binary and non-UTF-8 bodies

Valid UTF-8 bodies are strings in the local JSONL, including JSON text as the escaped string above. Non-UTF-8 bodies use a local { b64: "…", size_bytes: N } envelope. During API sync, a non-string body is serialized to JSON text; replay sends that stored text and does not decode the envelope back into the original binary bytes. Local base64 encoding is not end-to-end binary replay fidelity.

Headers and bodies have different boundaries

Capture removes the reserved capture-token header and token query parameters. Other URI/query data is retained. Header names become lowercase, repeated values are joined and unrepresentable values can become empty strings. By default, the 16-header credential floor plus configured extra headers replace values with [REDACTED]. WEBHOOK_PERSIST_VERBATIM=true opts out of that header redaction; it does not retain the reserved capture credential. Extra redaction can also change signature headers. Webhook sync validates storable text but does not scrub body secrets or personal data: both local and API-stored text need review. See the header redaction reference.

Shared capture sink and WebSocket frames

WebSocket frame capture is a separate observability surface with transport, connection, direction and frame-kind metadata. The replay API below operates on HTTP webhook captures, not frame playback. Use the WebSocket capture controls to configure that surface.

HTTP captures and both WebSocket frame lanes share a bounded queue for each service file within one agent process. A full queue immediately refuses HTTP capture with queue_full; frame producers wait for room. This does not establish ordering across agents, files or providers. A disconnected caller does not prove already-batched writes stopped.

Use an authenticated session or permitted API key to read GET /v1/services/{service_id}/webhook-sink for the tenant-scoped service sink state. Acknowledged and failed counts include frame records; queue-full counts describe refused HTTP capture admission. Counts are process-local, reset on agent restart and cover retained service entries rather than a durable history. Unavailable counts are unknown, not zero. Use capture responses and sender logs for actual HTTP outcomes, not a shared failed-count total. For operation-level failure reports, read the capture-sink metrics.

  1. Inspect the capture 200, 503 or missing answer, then verify the retained text and capture/event identity. Do not infer absence from a failed or lost response.
  2. Investigate write_failed volume/access findings or queue_full pressure. Check the sender's retry policy and logs before repeating; stop while sink state or capture outcome is unresolved.
  3. Only then explicitly replay an inspected capture to an owned, admitted test consumer and check its durable effect. Stop on changed content under a reused ID, unsuitable body/signature material or an unexpected effect.

Operator-triggered replay

Each explicit replay call selects one stored capture and one target. Delivery uses the captured method, the stored body string and filtered headers. The destination is the exact caller-supplied target_url; the captured URI/query is not appended. The API POST starts replay but does not change the captured target method to POST.

These routes require an authenticated session or permitted API key and a resolved tenant. Replay and DELETE additionally require the member role floor; read access alone does not authorize them.

GET
/v1/webhooks/{service_id}

List capture summaries, newest capture time first: limit 1–500 (default 50), offset >= 0 and optional signature_kind filter. This is not an ordered replay queue.

GET
/v1/webhooks/{service_id}/{webhook_id}

Read one capture, including its string body, retained headers and descriptive signature metadata.

POST
/v1/webhooks/{service_id}/{webhook_id}/replay

Explicitly replay the selected stored capture. Returns the target status, headers, body, elapsed time and delivery evidence.

DELETE
/v1/webhooks/{service_id}/{webhook_id}

Remove the database row; retained source content can be imported again while it remains within any configured capture-age policy.

For this authored generic text case, replace the target placeholder below with an owned nonproduction receiver that is reachable from the API and admitted by its outbound policy. The .example address is a placeholder, not a configured endpoint. Inspect the stored capture first and use its actual IDs.

curl -X POST \
  http://localhost:8000/v1/webhooks/svc_5f2c9e1a7b3d4c6e8f0a1b2c3d4e5f60/wh_a1b2c3d4e5f60718/replay \
  -H "X-API-Key: $GHOST_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "target_url": "https://webhook-test.example/receive",
    "preserve_signature": false,
    "timeout_seconds": 10
  }'

# Inspect the embedded status_code and the receiver's effect record.

Replay options

target_url

The complete destination, starting with lowercase http:// or https://. Schema validation can return 422; destination safety checks can return 400. Use an approved API-reachable nonproduction receiver.

preserve_signature

Default true keeps eligible captured signature headers after filtering; it does not restore redacted values or verify them. False removes recognized signature-family headers, including webhook-id and webhook-timestamp. Host, Content-Length and hop-by-hop headers are always removed. Other retained headers, including [REDACTED] values, can be forwarded.

timeout_seconds

Total delivery budget greater than 0 and at most 60 seconds, default 10; fractional values are accepted. Response bodies are bounded to 1 MiB and redirects are not followed.

Forwarding is not signature verification

The receiver applies its own authentication and replay policy. Retained signature values may have been redacted or transformed, and replay does not mint a new signature. Delivery evidence hashes and byte counts describe selected values passed to the HTTP client boundary; they do not prove signature validity, socket delivery or a business effect.

Read the target result and check the effect

A successful API wrapper means the replay call returned a result. Inspect its embedded status_code: a target redirect, 4xx or 5xx can appear there without an API failure or automatic status retry. A timeout or response error may occur after the consumer committed an effect. Before repeating a call, inspect the consumer's durable result and apply its event-idempotency policy; a manual repeat can create duplicates.

Replay does not recreate original delivery timing or impose capture-wide ordering on concurrent manual calls. A connect failure may try another already-admitted address; this is not a target-status retry policy or an exactly-once guarantee.

Replay target safety

Choose a receiver you own for nonproduction work. The API checks scheme, host, port and resolved addresses, then pins delivery to an admitted address while retaining the logical host for HTTP/TLS. Redirects do not expand the destination. Loopback, private and CGNAT addresses are refused by default; metadata, link-local, multicast, unspecified and reserved destinations remain blocked even when private replay is allowed.

For a private test receiver, an operator can set GOSTLY_OUTBOUND_ALLOWED_PRIVATE_ORIGINS in the API environment to exact approved origins, such as http://webhook-receiver:4000. Each comma-separated entry is scheme://host[:port], with no userinfo, path, query or fragment; an optional trailing slash is accepted. A malformed entry invalidates the list. Configure the actual test-service DNS name, port and network shared with the API; the replay target can then be http://webhook-receiver:4000/receive if that receiver is reachable there. Scheme and blocked-port restrictions still apply. If GOSTLY_OUTBOUND_ALLOWED_ORIGINS is configured, it must also list the target origin; see the destination-list configuration.

The Full Compose file forwards GOSTLY_OUTBOUND_ALLOWED_PRIVATE_ORIGINS from .env to the API. Set the exact approved origins there and recreate ghost-web for the change to take effect. Lite does not forward this setting; a custom Lite setup needs an explicit API environment mapping. Allowlisting an origin does not create network reachability.

In a containerized deployment, localhost means the API container, not your host application. Setting a target URL does not create reachability or bypass policy. Prefer an exact approved origin over broadly enabling local replay.

Behind an egress proxy, replay uses HTTPS_PROXY (https targets), HTTP_PROXY (http targets) and NO_PROXY from the API container's environment; it does not use ALL_PROXY. The API still resolves and checks the target itself, then asks the proxy for a CONNECT tunnel to the checked address, never to the hostname, and TLS inside the tunnel still verifies the hostname. The API host must therefore resolve the receiver's name, and a proxy that matches CONNECT targets only by hostname refuses the tunnel. A CA bundle in SSL_CERT_FILE or SSL_CERT_DIR replaces the default roots, so include the public roots if you also replay to public receivers. Logs record the target's origin, never its path or query.

400

Destination safety refusal or DNS failure. Target admission can fail before capture lookup.

403

The configured outbound-origin filter refused the target (outbound_origin_not_allowed).

404

Capture not found in the requesting tenant.

422

Request schema or header validation failed, including signature-header size or unsupported header text.

502

Delivery timed out, was unreachable, the egress proxy refused the tunnel, or the response exceeded size/decoding bounds. The consumer effect may still need inspection.

DELETE removes the database row, not the source capture

DELETE leaves the agent's service JSONL unchanged. A retained source line can be imported again on a reread while it remains within any configured capture-age policy, so this is not permanent erasure. With capture-age cleanup enabled, sync skips source records already past the cutoff; see the capture-age configuration. Review the recorded-data retention boundary for related copies and limits.

Tenancy

API reads and mutations apply the resolved tenant to capture queries; another tenant's capture reads as 404. Sync binds records to the deployment's resolved tenant, not an arbitrary tenant named in the capture URL. With the supported migrations applied and the request connection using the non-owner, NOBYPASSRLS gostly_app role, PostgreSQL also enforces the webhook table's tenant policy under FORCE ROW LEVEL SECURITY. Keep application tenant filters and follow the runtime and maintenance role separation; a privileged maintenance connection has a different boundary.

What is not shipped yet

This surface provides admitted capture and explicit manual replay. It does not provide:

  • Scheduled replay — the agent does not re-fire captures on a timer or trigger.
  • Fan-out — one selected capture has one target per API call, not a broadcast.
  • Re-signing — replay does not mint a fresh signature.
  • WebSocket replay — frame capture is for observability.
  • Logical-event deduplication or exactly-once processing — the consumer must define and verify its own effect policy.

Test duplicate deliveries

Run the authored local Python/SQLite inbox and outbox-intent exercise. Compare a scoped event key with wrong attempt-ID and resource-ID controls, then inspect conflicts and restart boundaries. These local intents do not establish provider delivery or external exactly-once effects. Read the worked example.

Next steps