{"name":"webhook-receiver","title":"Webhook receiver","description":"Receives webhooks, verifies their HMAC signature (Stripe, GitHub or generic), stores each delivery in /data and lists recent ones.","runtime":"Python 3.11, standard library","size":"small","env":[{"name":"WEBHOOK_SECRET","required":true,"description":"The signing secret shared with the sender (Stripe's whsec_..., GitHub's webhook secret, or your own). Deliveries are refused until it is set; the service boots without it."},{"name":"READ_TOKEN","required":false,"description":"Bearer token for GET /events. Defaults to WEBHOOK_SECRET."}],"tags":["webhooks","stripe","github","hmac","python"],"next":"Set WEBHOOK_SECRET (oa env set {slug} WEBHOOK_SECRET=..., or PUT /v1/artifacts/{slug}/env), then point the sender at {url}/webhook. Read deliveries with curl {url}/events -H 'Authorization: Bearer <WEBHOOK_SECRET>'.","oa_json":{"type":"service","start":"python3 app.py"},"files":[{"path":"README.md","content":"# Webhook receiver\n\nAn endpoint for webhooks that checks each delivery's HMAC signature, stores\nthe ones that verify in `/data`, and lists them back to you. It understands\nStripe's and GitHub's signature headers and a generic one, in Python with\nonly the standard library.\n\n## Call it\n\nPoint the sender at `<url>/webhook` (or `<url>/webhook/<label>`; the label is\nstored with each event, e.g. `/webhook/stripe`). The signature header picks\nthe scheme, and every scheme is keyed with `WEBHOOK_SECRET`:\n\n| Header | Sender | Signed bytes |\n| --- | --- | --- |\n| `Stripe-Signature: t=<unix>,v1=<hex>` | Stripe | `<t>.<raw body>`; `t` must be within 5 minutes |\n| `X-Hub-Signature-256: sha256=<hex>` | GitHub | the raw body |\n| `X-Signature: sha256=<hex>` | anything else | the raw body |\n\nA verified delivery answers `200 {\"ok\":true,\"id\":\"...\"}`; a missing or wrong\nsignature answers `401 bad_signature` and is not stored. To send a test\ndelivery yourself:\n\n```bash\nbody='{\"type\":\"ping\"}'\nsig=$(printf %s \"$body\" | openssl dgst -sha256 -hmac \"$WEBHOOK_SECRET\" -r | cut -d' ' -f1)\ncurl -s -X POST <url>/webhook -H \"X-Signature: sha256=$sig\" -d \"$body\"\n```\n\nRead what arrived (newest first) with the secret as a bearer token:\n\n```bash\ncurl -s \"<url>/events?limit=20\" -H \"Authorization: Bearer $WEBHOOK_SECRET\"\ncurl -s <url>/events/<id> -H \"Authorization: Bearer $WEBHOOK_SECRET\"   # one event, with its body\n```\n\n## Environment\n\n| Variable | Required | What it does |\n| --- | --- | --- |\n| `WEBHOOK_SECRET` | yes | The secret shared with the sender: Stripe's `whsec_...` signing secret, the secret you typed into GitHub, or your own. Without it the service still boots, but every delivery is refused with 503. |\n| `READ_TOKEN` | no | The bearer token for `GET /events`. Defaults to `WEBHOOK_SECRET`. |\n| `KEEP_EVENTS` | no | How many deliveries to keep. Default 500. |\n\nSet them with `oa env set <slug> WEBHOOK_SECRET=...` or\n`PUT /v1/artifacts/<slug>/env {\"env\":{\"WEBHOOK_SECRET\":\"...\"}}`.\n\n## Durability\n\nEach delivery is written whole, as its own file\n(`/data/events/<ms>-<id>.json`), before the 200 goes back, and never modified\nafterwards. A sender that gets no 2xx (the service crashed, or was asleep and\nthe wake took too long) retries, so nothing acknowledged is lost. The oldest\nfiles are pruned past `KEEP_EVENTS`.\n\n## Extend it\n\n- Act on an event: after `store(event)` in `do_POST`, look at\n  `event[\"event_type\"]` (`checkout.session.completed`, `push`, ...) and do the\n  work. Keep it short, or queue it: senders time out after about 10 seconds.\n- Deduplicate: Stripe and GitHub retry with the same event id\n  (`event[\"delivery_id\"]`); skip one you have already stored.\n- Another signature scheme: add a branch to `verify()`.\n\n## What it costs\n\nPrices for `small`, the size this template needs (current prices on\n[openartifacts.sh](https://openartifacts.sh/#cost)):\n\n- **Asleep:** no runtime charge. The bundle and `/data` are stored at $0.05 per GB-month.\n- **Awake:** $0.03 per awake hour, billed per minute, plus $0.216 per vCPU-hour of CPU actually used. A delivery wakes it and it stays awake 600 seconds (`sleep_after_s`) after the last one, so an occasional delivery costs about $0.005 plus a little CPU.\n- **Busy all day:** awake around the clock is $0.72 a day plus CPU.\n\nStarting it needs an hour of awake time in credit ($0.03), and an account runs\none service per $1 of balance.\n"},{"path":"app.py","content":"\"\"\"Receives webhooks, checks their HMAC signature, and keeps them in /data.\nPython standard library only.\n\n    POST /webhook             a delivery (also /webhook/<label>, e.g. /webhook/stripe)\n    GET  /events              recent deliveries, newest first (?limit=20)\n    GET  /events/<id>         one delivery, with its body\n    GET  /                    status, and how to sign a test delivery\n\nThree signature styles, chosen by the header the sender uses:\n\n  Stripe-Signature: t=<unix>,v1=<hex>   HMAC-SHA256 of \"<t>.<body>\", t within 5 minutes\n  X-Hub-Signature-256: sha256=<hex>     GitHub: HMAC-SHA256 of the body\n  X-Signature: sha256=<hex> (or <hex>)  anything else: HMAC-SHA256 of the body\n\nall keyed with WEBHOOK_SECRET. A delivery is stored before it is acknowledged:\neach one is written whole as its own file, /data/events/<ms>-<id>.json, and\nnever modified (files on /data should be written whole; it is object\nstorage). A sender that gets no 2xx retries, so nothing acknowledged is lost.\n\"\"\"\n\nimport hashlib\nimport hmac\nimport json\nimport os\nimport re\nimport secrets\nimport sys\nimport threading\nimport time\nfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer\nfrom urllib.parse import parse_qs, urlsplit\n\nPORT = int(os.environ.get(\"PORT\", \"8080\"))\nSECRET = os.environ.get(\"WEBHOOK_SECRET\", \"\")\n# Reading events needs `Authorization: Bearer <READ_TOKEN>`; without READ_TOKEN, the WEBHOOK_SECRET itself.\nREAD_TOKEN = os.environ.get(\"READ_TOKEN\", \"\") or SECRET\nPUBLIC_URL = os.environ.get(\"OA_URL\", f\"http://localhost:{PORT}\").rstrip(\"/\")\nDATA_DIR = os.environ.get(\"DATA_DIR\") or (\"/data\" if os.path.isdir(\"/data\") else os.path.join(os.getcwd(), \"data\"))\nEVENTS = os.path.join(DATA_DIR, \"events\")\nKEEP = int(os.environ.get(\"KEEP_EVENTS\", \"500\"))\nSTRIPE_TOLERANCE_S = 300\nMAX_BODY = 1_000_000\n# Request headers kept with each event (never Authorization or cookies).\nKEPT_HEADERS = (\n    \"content-type\", \"user-agent\", \"x-github-event\", \"x-github-delivery\", \"x-event-type\",\n    \"x-request-id\", \"stripe-signature\", \"x-hub-signature-256\", \"x-signature\",\n)\n\nlock = threading.Lock()\nstats = {\"accepted\": 0, \"rejected\": 0}\n\n\ndef now_iso():\n    return time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime())\n\n\ndef hmac_hex(message: bytes) -> str:\n    return hmac.new(SECRET.encode(), message, hashlib.sha256).hexdigest()\n\n\ndef verify(headers, body: bytes):\n    \"\"\"(source, None) when the signature checks out, else (source, why).\"\"\"\n    stripe = headers.get(\"stripe-signature\")\n    if stripe:\n        parts = [p.split(\"=\", 1) for p in stripe.split(\",\") if \"=\" in p]\n        stamp = next((v for k, v in parts if k.strip() == \"t\"), \"\")\n        candidates = [v for k, v in parts if k.strip() == \"v1\"]\n        if not stamp.isdigit() or not candidates:\n            return \"stripe\", \"Stripe-Signature needs t=<unix seconds> and at least one v1=<hex>.\"\n        if abs(time.time() - int(stamp)) > STRIPE_TOLERANCE_S:\n            return \"stripe\", f\"Stripe-Signature timestamp is more than {STRIPE_TOLERANCE_S}s from now (a replay, or a clock off).\"\n        expected = hmac_hex(stamp.encode() + b\".\" + body)\n        ok = any(hmac.compare_digest(expected, c.strip()) for c in candidates)\n        return \"stripe\", None if ok else \"Stripe-Signature does not match the body and WEBHOOK_SECRET.\"\n    github = headers.get(\"x-hub-signature-256\")\n    if github:\n        ok = hmac.compare_digest(f\"sha256={hmac_hex(body)}\", github.strip())\n        return \"github\", None if ok else \"X-Hub-Signature-256 does not match the body and WEBHOOK_SECRET.\"\n    generic = headers.get(\"x-signature\") or headers.get(\"x-signature-256\") or headers.get(\"x-webhook-signature\")\n    if generic:\n        given = generic.strip()\n        given = given[7:] if given.startswith(\"sha256=\") else given\n        ok = hmac.compare_digest(hmac_hex(body), given.lower())\n        return \"generic\", None if ok else \"X-Signature does not match HMAC-SHA256(WEBHOOK_SECRET, body).\"\n    return \"unknown\", \"No signature header: send Stripe-Signature, X-Hub-Signature-256 or X-Signature.\"\n\n\ndef event_type(source, headers, parsed):\n    if source == \"github\":\n        return headers.get(\"x-github-event\")\n    if headers.get(\"x-event-type\"):\n        return headers.get(\"x-event-type\")\n    if isinstance(parsed, dict):\n        for key in (\"type\", \"event\", \"event_type\", \"action\"):\n            if isinstance(parsed.get(key), str):\n                return parsed[key]\n    return None\n\n\ndef store(event):\n    \"\"\"Write the event as its own file, whole: a sibling first, then a rename.\"\"\"\n    os.makedirs(EVENTS, exist_ok=True)\n    final = os.path.join(EVENTS, f\"{event['id']}.json\")\n    tmp = final + \".tmp\"\n    with open(tmp, \"w\") as f:\n        json.dump(event, f)\n    os.replace(tmp, final)\n\n\ndef event_files():\n    try:\n        return sorted(n for n in os.listdir(EVENTS) if n.endswith(\".json\"))\n    except FileNotFoundError:\n        return []\n\n\ndef prune():\n    \"\"\"Keep the newest KEEP events. Ids sort by time, so the oldest come first.\"\"\"\n    names = event_files()\n    for name in names[: max(0, len(names) - KEEP)]:\n        try:\n            os.remove(os.path.join(EVENTS, name))\n        except FileNotFoundError:\n            pass\n\n\ndef summary(event):\n    body = event.get(\"body\")\n    preview = body if isinstance(body, str) else json.dumps(body)\n    return {k: event.get(k) for k in (\"id\", \"received_at\", \"source\", \"label\", \"event_type\", \"bytes\")} | {\n        \"preview\": preview[:200]\n    }\n\n\nEVENT_PATH = re.compile(r\"^/events/([0-9]+-[0-9a-f]+)$\")\n\n\nclass Handler(BaseHTTPRequestHandler):\n    server_version = \"webhook-receiver/1\"\n\n    def send_json(self, status, payload):\n        body = json.dumps(payload).encode()\n        self.send_response(status)\n        self.send_header(\"content-type\", \"application/json\")\n        self.send_header(\"content-length\", str(len(body)))\n        self.end_headers()\n        self.wfile.write(body)\n\n    def can_read(self):\n        given = self.headers.get(\"authorization\", \"\")\n        return bool(READ_TOKEN) and hmac.compare_digest(given, f\"Bearer {READ_TOKEN}\")\n\n    def do_GET(self):\n        url = urlsplit(self.path)\n        path = url.path.rstrip(\"/\") or \"/\"\n        if path in (\"/\", \"/health\"):\n            return self.send_json(200, {\n                \"name\": \"webhook-receiver\",\n                \"status\": \"ready\" if SECRET else \"needs_secret\",\n                \"message\": (\n                    f\"POST deliveries to {PUBLIC_URL}/webhook\"\n                    if SECRET\n                    else \"WEBHOOK_SECRET is not set, so every delivery is refused. Set it (oa env set <slug> WEBHOOK_SECRET=<secret>, or PUT /v1/artifacts/<slug>/env), using the same secret as the sender.\"\n                ),\n                \"endpoint\": f\"{PUBLIC_URL}/webhook\",\n                \"signatures\": [\"Stripe-Signature\", \"X-Hub-Signature-256\", \"X-Signature: sha256=<hex>\"],\n                \"events_stored\": len(event_files()),\n                \"since_boot\": stats,\n                \"test\": (\n                    \"body='{\\\"type\\\":\\\"ping\\\"}'; sig=$(printf %s \\\"$body\\\" | openssl dgst -sha256 -hmac \\\"$WEBHOOK_SECRET\\\" -r | cut -d' ' -f1); \"\n                    f\"curl -X POST {PUBLIC_URL}/webhook -H \\\"X-Signature: sha256=$sig\\\" -d \\\"$body\\\"\"\n                ),\n            })\n        if path == \"/events\" or EVENT_PATH.match(path):\n            if not self.can_read():\n                return self.send_json(401, {\n                    \"code\": \"unauthorized\",\n                    \"message\": \"Send Authorization: Bearer <READ_TOKEN> (or the WEBHOOK_SECRET when READ_TOKEN is unset) to read events.\",\n                })\n            match = EVENT_PATH.match(path)\n            if match:\n                try:\n                    with open(os.path.join(EVENTS, f\"{match.group(1)}.json\")) as f:\n                        return self.send_json(200, json.load(f))\n                except FileNotFoundError:\n                    return self.send_json(404, {\"code\": \"not_found\", \"message\": f\"No event {match.group(1)}.\"})\n            limit = max(1, min(int((parse_qs(url.query).get(\"limit\") or [\"20\"])[0] or 20), 200))\n            names = event_files()[-limit:][::-1]\n            events = []\n            for name in names:\n                try:\n                    with open(os.path.join(EVENTS, name)) as f:\n                        events.append(summary(json.load(f)))\n                except (FileNotFoundError, ValueError):\n                    continue\n            return self.send_json(200, {\"events\": events, \"total\": len(event_files())})\n        self.send_json(404, {\"code\": \"not_found\", \"message\": f\"No route GET {path}.\"})\n\n    def do_POST(self):\n        path = urlsplit(self.path).path.rstrip(\"/\")\n        if path != \"/webhook\" and not path.startswith(\"/webhook/\"):\n            return self.send_json(404, {\"code\": \"not_found\", \"message\": \"Deliveries go to POST /webhook (or /webhook/<label>).\"})\n        if not SECRET:\n            return self.send_json(503, {\n                \"code\": \"not_configured\",\n                \"message\": \"WEBHOOK_SECRET is not set; refusing deliveries that cannot be verified. Set it with oa env set <slug> WEBHOOK_SECRET=<secret>.\",\n            })\n        length = int(self.headers.get(\"content-length\") or 0)\n        if length > MAX_BODY:\n            return self.send_json(413, {\"code\": \"too_large\", \"message\": f\"Deliveries are limited to {MAX_BODY} bytes.\"})\n        body = self.rfile.read(length)\n        source, problem = verify(self.headers, body)\n        if problem:\n            stats[\"rejected\"] += 1\n            print(f\"rejected {source} delivery: {problem}\", file=sys.stderr, flush=True)\n            return self.send_json(401, {\"code\": \"bad_signature\", \"message\": problem})\n        text = body.decode(\"utf-8\", \"replace\")\n        try:\n            parsed = json.loads(text)\n        except ValueError:\n            parsed = text\n        label = path[len(\"/webhook/\"):] if path.startswith(\"/webhook/\") else None\n        event = {\n            \"id\": f\"{int(time.time() * 1000)}-{secrets.token_hex(4)}\",\n            \"received_at\": now_iso(),\n            \"source\": source,\n            \"label\": label,\n            \"event_type\": event_type(source, self.headers, parsed),\n            \"delivery_id\": self.headers.get(\"x-github-delivery\") or (parsed.get(\"id\") if isinstance(parsed, dict) else None),\n            \"bytes\": len(body),\n            \"headers\": {h: self.headers.get(h) for h in KEPT_HEADERS if self.headers.get(h) is not None},\n            \"body\": parsed,\n        }\n        with lock:\n            store(event)\n            stats[\"accepted\"] += 1\n            if stats[\"accepted\"] % 50 == 0:\n                prune()\n        print(f\"accepted {source} {event['event_type'] or '-'} {event['id']}\", flush=True)\n        self.send_json(200, {\"ok\": True, \"id\": event[\"id\"]})\n\n    def log_message(self, fmt, *args):\n        sys.stderr.write(\"%s %s\\n\" % (self.address_string(), fmt % args))\n\n\nif __name__ == \"__main__\":\n    prune()\n    state = \"WEBHOOK_SECRET set\" if SECRET else \"WEBHOOK_SECRET not set: deliveries are refused until it is\"\n    print(f\"webhook-receiver listening on 0.0.0.0:{PORT}; {state}\", flush=True)\n    server = ThreadingHTTPServer((\"0.0.0.0\", PORT), Handler)\n    server.daemon_threads = True\n    server.serve_forever()\n"},{"path":"oa.json","content":"{\n  \"type\": \"service\",\n  \"start\": \"python3 app.py\"\n}\n"}],"file_count":3,"bytes":14667,"page":"https://openartifacts.sh/templates/webhook-receiver","publish":{"curl":"curl -sX POST https://openartifacts.sh/v1/publish -H \"Authorization: Bearer $OA_TOKEN\" -F type=service -F template=webhook-receiver -F slug=my-hooks","mcp":{"tool":"publish_artifact","arguments":{"type":"service","template":"webhook-receiver","slug":"my-hooks"}},"cli":"oa deploy --template webhook-receiver --slug my-hooks"},"hint":"files is in the shape publish_artifact takes. To publish it unchanged: POST /v1/publish -F type=service -F template=webhook-receiver. To publish an edited copy: send your changed files alongside -F template=webhook-receiver (they replace the files of the same path), or publish the whole edited set without it (type=service; oa.json is among the files)."}