[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-117272":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":12,"contributorsCount":12,"subscribersCount":12,"size":12,"stars1d":12,"stars7d":12,"stars30d":12,"stars90d":12,"forks30d":12,"starsTrendScore":12,"compositeScore":14,"rankGlobal":9,"rankLanguage":9,"license":9,"archived":15,"fork":15,"defaultBranch":16,"hasWiki":17,"hasPages":15,"topics":18,"createdAt":9,"pushedAt":19,"updatedAt":20,"readmeContent":21,"aiSummary":9,"trendingCount":12,"starSnapshotCount":12,"syncStatus":22,"lastSyncTime":23,"discoverSource":24},117272,"Relay","swarn007-byte\u002FRelay","swarn007-byte","A reliable, self-hosted webhook delivery service built in Go, featuring durable event storage, concurrent workers, automatic retries, HMAC signing, and dead-letter handling.",null,"Go",47,0,51,37,false,"main",true,[],"2026-11-17 20:30:12","2026-11-22 15:54:45","> **API service:** The website and dashboard have been removed. See [SAAS.md](SAAS.md) for the account\u002Fproject API. The single-owner API examples below require `RELAY_LEGACY_MODE=true`.\n\n# Relay\n\nRelay is a self-hosted webhook delivery service written in Go.\n\nApplications submit events to Relay over HTTP. Relay durably stores each event together with a\ndelivery job in SQLite, schedules due jobs, performs signed HTTP POST requests to the configured\ntarget endpoint, retries transient failures with bounded exponential backoff, records every\ndelivery attempt, and exposes an authenticated API for inspecting and replaying failed deliveries.\n\nRelay is **not** a tunnel, message broker replacement, or generic distributed task framework. It is\na focused, reliable webhook delivery backend.\n\n## Why Relay\n\nSending webhooks looks trivial until you ask the questions that matter in production:\n\n- What happens if the receiver is down when the event fires?\n- What happens if Relay crashes in the middle of a delivery?\n- How do I know which deliveries failed and why?\n- How does the receiver know the webhook really came from me?\n- What happens when an attacker makes my server send requests to internal infrastructure?\n\nRelay answers all of these: durable jobs with an atomic claim protocol, lease-based crash\nrecovery, per-attempt history, HMAC-SHA256 request signing with replay protection, and SSRF\nprotection that validates every actual dial target.\n\n## Architecture\n\n```text\nExternal Application\n        |\n        | POST \u002Fevents\n        v\n    Relay HTTP API (internal\u002Fapi)\n        |\n        | validate event + destination (internal\u002Fsecurity)\n        v\n    SQLite (internal\u002Fstorage)\n        |\n        | atomic event + delivery job insert (WAL mode)\n        v\n    Job Scheduler (internal\u002Fworker\u002Fscheduler.go)\n        |\n        | fetch due pending jobs, recover expired leases,\n        | atomically claim with a lease token\n        v\n    Bounded Worker Pool (internal\u002Fworker\u002Fpool.go)\n        |\n        | renew lease, execute delivery\n        v\n    HTTP Delivery Client (internal\u002Fworker\u002Fdelivery.go)\n        |\n        | guarded dialer, signed POST, fixed timeout\n        v\n    Target Webhook Endpoint\n        |\n        | response\n        v\n    Delivery State Manager (internal\u002Fstorage)\n        |\n        +--- 2xx -----------> delivered\n        |\n        +--- retryable ------> pending (future next_attempt_at)\n        |\n        +--- exhausted -------> dead\n        |\n        +--- non-retryable ---> dead (immediately)\n```\n\n### Project layout\n\n```text\nmain.go                      wiring: config, DB, API, pool, scheduler, shutdown\ninternal\u002F\n  config\u002Fconfig.go           environment configuration and validation\n  security\u002Fssrf.go           URL validation, IP range blocking, guarded dialer\n  storage\u002F\n    schema.sql               schema (embedded)\n    sqlite.go                connection setup, pragmas, schema bootstrap\n    events.go                atomic event + job persistence\n    jobs.go                  claims, leases, state transitions, queries, replay\n    migrate.go               automatic legacy schema migration\n  worker\u002F\n    scheduler.go             due-job dispatch loop + lease recovery\n    pool.go                  bounded workers and state machine execution\n    delivery.go              outbound HTTP client and failure classification\n    retry.go                 bounded exponential backoff with jitter\n    signature.go             HMAC-SHA256 signing and verification helper\n  api\u002Fserver.go              HTTP handlers, routing, admin authentication\n```\n\n## Tech stack\n\n- **Go 1.26+**, standard library only for HTTP, crypto, signal handling, and routing\n- **modernc.org\u002Fsqlite** — pure-Go SQLite driver (no CGO)\n- **github.com\u002Fgoogle\u002Fuuid** — identifier generation\n- SQLite **WAL mode** with busy timeout and foreign-key enforcement\n\n## Features\n\n- `POST \u002Fevents` accepting JSON events, `202 Accepted` after durable persistence\n- Atomic event + delivery-job insert in a single transaction\n- Continuously running scheduler with atomic job claiming\n- Bounded worker pool (no goroutine-per-delivery)\n- Signed outgoing webhooks: HMAC-SHA256 over `timestamp.payload` with replay-window verification\n- Exponential backoff with jitter, capped at a maximum delay\n- Attempt counter semantics: first success is attempt 1, fifth failure is attempt 5\n- Dead-letter state after exhausted retries or permanent failures\n- Persistent per-attempt history (status code, duration, sanitized error, scheduled retry)\n- Lease-based crash recovery for jobs abandoned by crashed workers\n- Manual replay of dead deliveries without concurrent duplicates\n- Authenticated inspection API (`GET \u002Fdeliveries`, attempts, replay)\n- SSRF protection: scheme\u002Fport\u002FIP-range validation at ingest **and** at dial time, no redirects,\n  no proxy bypass\n- Graceful shutdown on SIGINT\u002FSIGTERM with job release and bounded drain\n- Automatic migration of the legacy TEXT-timestamp schema (no data loss)\n\n## Installation\n\nRequires Go 1.26 or newer.\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fswarn007-byte\u002FRelay.git\ncd Relay\ngo build .\u002F...\n```\n\n## Configuration\n\nAll configuration is read from environment variables. Values are validated at startup; the\nprocess refuses to start with an invalid configuration.\n\n| Variable | Default | Description |\n|---|---|---|\n| `RELAY_PORT` | `8081` | HTTP listen port |\n| `RELAY_DB_PATH` | `data\u002Frelay.db` | SQLite database file (directory is created) |\n| `RELAY_WORKER_COUNT` | `4` | Number of delivery workers (1–1024) |\n| `RELAY_SCHEDULER_INTERVAL` | `1s` | Scheduler tick interval (min `100ms`) |\n| `RELAY_SCHEDULER_BATCH_SIZE` | `20` | Max jobs claimed per tick |\n| `RELAY_HTTP_TIMEOUT` | `10s` | Per-delivery HTTP timeout (min `1s`) |\n| `RELAY_MAX_ATTEMPTS` | `5` | Max delivery attempts before dead-letter (min `1`) |\n| `RELAY_RETRY_BASE_DELAY` | `5s` | First retry delay |\n| `RELAY_RETRY_MAX_DELAY` | `60s` | Retry delay cap (must be ≥ base delay) |\n| `RELAY_LEASE_TTL` | `60s` | Claim lease duration (must be > HTTP timeout) |\n| `RELAY_WEBHOOK_SECRET` | — | **Required**, ≥ 32 bytes. HMAC signing secret |\n| `RELAY_ADMIN_TOKEN` | — | Bearer token for the management API. If unset, the management API is disabled |\n| `RELAY_ALLOW_PRIVATE_DESTINATIONS` | `false` | Dev-only: allow private\u002Floopback destinations |\n| `RELAY_ALLOWED_PORTS` | `80,443` | Allowed destination ports (ignored in dev mode) |\n| `RELAY_SHUTDOWN_TIMEOUT` | `15s` | Graceful shutdown deadline |\n| `RELAY_MAX_BODY_BYTES` | `1048576` | Max request body size for `POST \u002Fevents` |\n\nSee [`.env.example`](.env.example) for a complete template. Never commit real secrets.\n\n## Running\n\n```bash\nexport RELAY_WEBHOOK_SECRET=\"$(openssl rand -hex 32)\"\nexport RELAY_ADMIN_TOKEN=\"$(openssl rand -hex 16)\"\ngo run .\n```\n\nFor local development against `127.0.0.1` receivers, also set:\n\n```bash\nexport RELAY_ALLOW_PRIVATE_DESTINATIONS=true\n```\n\n**Never enable `RELAY_ALLOW_PRIVATE_DESTINATIONS` in production.** It disables the SSRF guard.\n\nExpected startup output:\n\n```text\nDatabase initialized\nRelay server running on port 8081\n```\n\nStop with `Ctrl-C` or `SIGTERM`; Relay drains gracefully:\n\n```text\nShutdown signal received\nScheduler stopped\nShutdown complete\n```\n\n## Submitting an event\n\n```bash\ncurl -i -X POST http:\u002F\u002Flocalhost:8081\u002Fevents \\\n  -H 'Content-Type: application\u002Fjson' \\\n  -d '{\n    \"event\": \"payment.success\",\n    \"target_url\": \"https:\u002F\u002Fexample.com\u002Fwebhook\",\n    \"payload\": {\"payment_id\": \"pay_123\", \"amount\": 500}\n  }'\n```\n\nResponse (`202 Accepted` — the event is durable, the webhook has **not** been sent yet):\n\n```json\n{\n  \"event_id\": \"6a36fb5f-7e5c-487e-8eaf-f6ff5aec7261\",\n  \"delivery_id\": \"a0fe45e6-95a0-40f5-b4c0-3127c602c1e2\",\n  \"status\": \"accepted\"\n}\n```\n\nValidation failures return `400` with `{\"error\": \"...\"}`. Wrong or missing `Content-Type` returns\n`415`; bodies larger than `RELAY_MAX_BODY_BYTES` return `413`. Destinations that fail SSRF\nvalidation are rejected at ingest time.\n\n## Delivery lifecycle\n\n```text\npending --> processing --> delivered\n                |\n                +-------> pending   (retryable failure, future next_attempt_at)\n                |\n                +-------> dead      (attempts exhausted OR non-retryable failure)\n```\n\nEvery transition is enforced by a conditional `UPDATE` guarded by the job's lease token, plus a\n`CHECK` constraint on the status column — silent invalid transitions are impossible.\n\n1. A new event creates a `pending` job with `next_attempt_at = now`.\n2. The scheduler fetches due pending jobs, recovers expired leases, and atomically claims each job\n   (`pending → processing`, assigning `lease_owner` and `lease_expires_at`).\n3. Before sending, the worker renews the lease. If the lease was lost (recovered elsewhere), the\n   worker skips the job without touching it.\n4. The worker performs a signed HTTP POST with a fixed timeout.\n5. The outcome is persisted **in one transaction**: an `delivery_attempts` row plus the job\n   transition.\n\n### Attempt accounting\n\n`attempts` counts completed delivery attempts:\n\n| Scenario | status | attempts |\n|---|---|---|\n| First delivery succeeds | `delivered` | `1` |\n| Fifth delivery fails (retryable) | `dead` | `5` |\n| First delivery hits a permanent failure (e.g. HTTP 404) | `dead` | `1` |\n| Delivery canceled by shutdown | `pending` | unchanged (no attempt recorded) |\n\n### Retry policy\n\n| Attempt | Nominal delay | Jittered range |\n|---|---|---|\n| 1 | 5s | 4–6s |\n| 2 | 10s | 8–12s |\n| 3 | 20s | 16–24s |\n| 4 | 40s | 32–48s |\n| 5+ | 60s (cap) | 48–60s |\n\nJitter is uniform over ±20% of the nominal delay, capped at `RELAY_RETRY_MAX_DELAY`, and the\ncomputation is overflow-safe. The next attempt time is persisted in SQLite, so **restarting Relay\ndoes not lose retry schedules**.\n\n**Failure classification:**\n\n- **Retryable:** connection\u002FDNS errors, timeouts, HTTP `408`, `425`, `429`, and all `5xx`\n- **Permanent (dead immediately):** other `3xx`\u002F`4xx` responses, SSRF-blocked destinations,\n  malformed requests\n\nRedirects are **never followed** (`CheckRedirect` returns the last response), so a `3xx` is treated\nas a permanent misconfiguration rather than an open redirect vector.\n\n## HMAC-SHA256 webhook verification\n\nEvery outgoing request carries:\n\n```http\nPOST \u002Fwebhook HTTP\u002F1.1\nContent-Type: application\u002Fjson\nX-Relay-Event-ID: 6a36fb5f-7e5c-487e-8eaf-f6ff5aec7261\nX-Relay-Delivery-ID: a0fe45e6-95a0-40f5-b4c0-3127c602c1e2\nX-Relay-Event-Type: payment.success\nX-Relay-Timestamp: 1794934774\nX-Relay-Signature: sha256=d97dc8ed42fa935d6eb6d440cfa4e0580f647a7154d72a89f9d5cbade6edba7d\n```\n\n**Canonical signing format (exact):**\n\n```text\nsigned_payload = unix_seconds + \".\" + exact_request_body_bytes\nsignature      = \"sha256=\" + hex(HMAC_SHA256(RELAY_WEBHOOK_SECRET, signed_payload))\n```\n\n`unix_seconds` is the integer value of `X-Relay-Timestamp`. The signature covers the **exact bytes\ntransmitted** — the payload is never re-serialized.\n\n### Verifying in Go\n\n```go\nfunc verifyRelay(body []byte, secret []byte, tsHeader, sigHeader string, now time.Time, window time.Duration) error {\n\tseconds, err := strconv.ParseInt(tsHeader, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsentAt := time.Unix(seconds, 0)\n\tif skew := now.Sub(sentAt); skew > window || skew \u003C -window {\n\t\treturn errors.New(\"timestamp outside replay window\")\n\t}\n\n\tmac := hmac.New(sha256.New, secret)\n\tmac.Write([]byte(tsHeader))\n\tmac.Write([]byte(\".\"))\n\tmac.Write(body)\n\texpected, _ := hex.DecodeString(strings.TrimPrefix(sigHeader, \"sha256=\"))\n\n\tif !hmac.Equal(expected, mac.Sum(nil)) {\n\t\treturn errors.New(\"signature mismatch\")\n\t}\n\treturn nil\n}\n```\n\nRules for consumers:\n\n1. Reject requests whose `X-Relay-Timestamp` is outside your replay window (e.g. ±5 minutes).\n2. Compare with a **constant-time** comparison (`hmac.Equal`).\n3. Compute the signature over the **raw body bytes**, before any JSON parsing.\n4. A valid signature proves origin and integrity — it does **not** prevent replay outside the\n   window, so still make your handlers idempotent.\n\n**Secret scope:** Relay currently uses a single global `RELAY_WEBHOOK_SECRET`. It does **not**\nprovide per-destination isolation — every destination sees the same secret. Rotate it by updating\nthe environment variable and restarting Relay. Per-destination secrets are listed under future\nimprovements.\n\n## Dead-letter handling\n\nA job becomes `dead` when:\n\n- `attempts` reaches `RELAY_MAX_ATTEMPTS`, or\n- the failure is non-retryable (permanent `3xx`\u002F`4xx`, blocked destination).\n\nDead jobs are excluded from automatic scheduling. The last failure reason stays in\n`last_error`, and the full attempt history is preserved in `delivery_attempts`.\n\n```bash\ncurl -H \"Authorization: Bearer $RELAY_ADMIN_TOKEN\" \\\n  \"http:\u002F\u002Flocalhost:8081\u002Fdeliveries?status=dead\"\n```\n\n## Manual replay\n\nReplay creates a **new** `pending` delivery job for the same event:\n\n- The original dead job is never modified — its history stays intact.\n- Replay is rejected with `409 Conflict` if the event already has a `pending` or `processing`\n  job, so a replay can never create two concurrent active deliveries for one event.\n- Only `dead` jobs can be replayed (`409` otherwise).\n- The replayed job starts with `attempts = 0` and gets its own attempt history.\n\n```bash\ncurl -X POST -H \"Authorization: Bearer $RELAY_ADMIN_TOKEN\" \\\n  http:\u002F\u002Flocalhost:8081\u002Fdeliveries\u002F\u003Cdelivery-id>\u002Freplay\n```\n\n```json\n{\"delivery_id\": \"\u003Cnew-id>\", \"status\": \"pending\", \"replayed\": \"\u003Cold-id>\"}\n```\n\n## API reference\n\nAll `\u002Fdeliveries*` endpoints require `Authorization: Bearer $RELAY_ADMIN_TOKEN`. If\n`RELAY_ADMIN_TOKEN` is unset they return `403` (management API disabled). Unknown endpoints\nreturn JSON `404`.\n\n### `GET \u002Fhealth`\n\n```json\n{\"status\": \"ok\"}\n```\n\n### `POST \u002Fevents`\n\nBody: `{\"event\": string, \"target_url\": string, \"payload\": \u003Cany JSON value>}` → `202` with\n`{\"event_id\", \"delivery_id\", \"status\"}`.\n\n### `GET \u002Fdeliveries?status=\u003Cpending|processing|delivered|dead>&limit=\u003C1-200>`\n\n```json\n{\"deliveries\": [ { \"delivery_id\": \"...\", \"status\": \"delivered\", \"attempts\": 1, ... } ]}\n```\n\n### `GET \u002Fdeliveries\u002F{id}`\n\nFull detail including `event_type`, `target_url`, `next_attempt_at`, `last_error`, and `payload`.\n`404` if unknown, `400` if the id is not a UUID.\n\n### `GET \u002Fdeliveries\u002F{id}\u002Fattempts`\n\n```json\n{\"attempts\": [{\n  \"id\": \"...\",\n  \"attempt_number\": 1,\n  \"started_at\": \"2026-11-17T16:59:34.818Z\",\n  \"finished_at\": \"2026-11-17T16:59:34.82Z\",\n  \"duration_ms\": 1,\n  \"status_code\": 200,\n  \"success\": true,\n  \"next_attempt_at\": null\n}]}\n```\n\n### `POST \u002Fdeliveries\u002F{id}\u002Freplay`\n\n`202` on success, `404` unknown id, `409` if not dead or if an active delivery already exists.\n\n## Crash recovery\n\nIf Relay crashes after claiming a job (`processing`) but before recording the outcome, the job\nwould be stuck forever. Relay prevents this with **leases**:\n\n- Every claim writes `lease_owner` (a unique token) and `lease_expires_at = now + RELAY_LEASE_TTL`.\n- Expired `processing` jobs are reset to `pending` **on startup and on every scheduler tick**.\n- Every state transition is guarded by `WHERE lease_owner = \u003Ctoken>`; a stale worker whose lease\n  was reclaimed gets `ErrLeaseLost` and cannot overwrite the newer state.\n- Workers renew the lease immediately before sending, so a job queued longer than the TTL is not\n  delivered by a worker that no longer owns it.\n- A `processing` row with no lease (e.g. migrated from the legacy schema) is recovered on startup.\n\n**At-least-once semantics.** Relay guarantees at-least-once delivery, never exactly-once. If Relay\ncrashes after the target accepted a request but before SQLite recorded the success, the job will be\nretried and the target may receive a duplicate. **Webhook consumers must be idempotent.**\n\n## Graceful shutdown\n\nOn `SIGINT`\u002F`SIGTERM`:\n\n1. The HTTP server stops accepting new requests (`Server.Shutdown`).\n2. The scheduler stops claiming new jobs and exits.\n3. The jobs channel is closed; queued jobs that were claimed but not dispatched are **released\n   back to `pending`** (not counted as attempts).\n4. In-flight deliveries are canceled by context and released back to `pending`.\n5. Workers are awaited with a `RELAY_SHUTDOWN_TIMEOUT` deadline.\n6. The database is closed only after dependent goroutines stop.\n\nCanceled deliveries are never recorded as ordinary failures.\n\n## SQLite reliability\n\n- `journal_mode=WAL`, `busy_timeout=5000`, `foreign_keys=ON`, `synchronous=NORMAL`\n- Connection pool capped (`MaxOpenConns=16`)\n- All timestamps are **integer Unix milliseconds** — sorting and comparison are exact\n- Parameterized SQL everywhere; atomic multi-statement transactions for every lifecycle change\n- Indexes: `(status, next_attempt_at)` for dispatch, `(status, lease_expires_at)` for recovery,\n  `(event_id)` for replay checks, `(delivery_id, attempt_number)` for history\n- Legacy databases that still use TEXT\u002FRFC3339 timestamps are migrated automatically inside a\n  transaction on first start; existing rows are preserved\n\n## Testing\n\n```bash\ngofmt -l .\ngo vet .\u002F...\ngo build .\u002F...\ngo test .\u002F...\ngo test -race .\u002F...\n```\n\nThe suite covers, without any external network access:\n\n- event validation and atomic event+job persistence\n- due-job fetching, atomic claiming, concurrent dispatch without duplicate claims\n- successful HTTP delivery, exact payload bytes, response classification (2xx\u002F3xx\u002F4xx\u002F5xx)\n- retry scheduling, backoff and jitter bounds, maximum attempts, dead-letter transitions\n- HMAC generation\u002Fverification, tampered payload\u002Fsecret rejection, replay-window enforcement\n- crash recovery, stale-worker protection, lease expiry\n- graceful shutdown: queued-job release, canceled delivery not counted as attempt\n- manual replay semantics and conflicts\n- SSRF defense: private\u002Floopback\u002Flink-local\u002Fmulticast\u002Fmetadata ranges (IPv4 + IPv6), credential\n  URLs, port restrictions, redirect non-following, DNS rebinding at dial time, proxy bypass\n- configuration validation and legacy schema migration\n\n## Security notes and limitations\n\nImplemented:\n\n- SSRF validation at ingest **and** at dial time; the dialer resolves the host, checks every\n  address, then dials the validated IP directly (no TOCTOU\u002Frebinding window)\n- Only `http`\u002F`https`; no credentials in URLs; default port allowlist (`80,443`)\n- Blocked ranges include loopback, RFC1918, CGNAT, link-local\u002F`169.254.169.254` metadata, ULA,\n  multicast, unspecified, documentation, NAT64\u002F6to4\u002FTeredo prefixes\n- `Proxy: nil` on the delivery transport — `HTTP_PROXY` cannot bypass the guard\n- Redirects are never followed\n- Request body limits, strict `Content-Type`, single-JSON-value enforcement\n- HTTP server read\u002Fwrite\u002Fidle timeouts\n- Admin API with constant-time token comparison; disabled when unconfigured\n- Secrets are never logged; stored errors are truncated to 512 characters and never contain\n  credentials\n\nLimitations (be aware before production use):\n\n- **Single global signing secret** — no per-destination isolation or rotation without restart\n- **No rate limiting or TLS** on the management API — put Relay behind a reverse proxy\n- **At-least-once** — duplicates are possible; consumers must be idempotent\n- **Ingest-time DNS resolution** — an event whose host fails to resolve right now is rejected with\n  `400` (the dial-time check still applies on every attempt)\n- **Single node** — SQLite and one process; no clustering or HA\n- The management API has no pagination cursors (bounded `limit` only)\n\n## Future improvements\n\n- Per-destination signing secrets and rotation\n- Rate limiting and TLS termination for the management API\n- Metrics endpoint (Prometheus) and structured logging\n- Delivery dashboard\n- Pagination cursors for listing endpoints\n- Multi-node scheduling on top of the existing lease protocol\n",2,"2026-11-24 04:55:15","CREATED_QUERY"]