[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M74F7481EBD7G5471ZC4S9YB":3,"skill-same:01M74F7481EBD7G5471ZC4S9YB":52},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":29,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M74F7481EBD7G5471ZC4S9YB","webhook-idempotency",null,"Defend against double-processing of webhook events across every provider (Stripe, GitHub, Slack, Twilio, SendGrid). Idempotency-key pattern + replay-window enforcement + dedupe-storage strategy. Triggers on any webhook handler authoring (route matching \u002Fwebhook(s)?\u002F, Stripe-Signature \u002F X-Hub-Signature-256 header references). Defense against OWASP ASI02 (Tool Misuse) -- a replayed webhook that re-triggers a destructive tool is the canonical control-flow-level replay attack. Universal across providers; stack-specific signature verification lives in stack-specific skills.","MILTONADINA\u002FDevOPs","MILTONADINA","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106546372?v=4","01M74F3R2PP4Z04DQMMBHSQAT1","Milton Adina","01M74F3R3CHTKPXJV4RP7RR3W8",0,"MIT","https:\u002F\u002Fgithub.com\u002FMILTONADINA\u002FDevOPs\u002Fblob\u002Fmain\u002Fskills\u002Funiversal\u002Fsecurity\u002Fwebhook-idempotency\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: webhook-idempotency\ndescription: Defend against double-processing of webhook events across every provider (Stripe, GitHub, Slack, Twilio, SendGrid). Idempotency-key pattern + replay-window enforcement + dedupe-storage strategy. Triggers on any webhook handler authoring (route matching \u002Fwebhook(s)?\u002F, Stripe-Signature \u002F X-Hub-Signature-256 header references). Defense against OWASP ASI02 (Tool Misuse) -- a replayed webhook that re-triggers a destructive tool is the canonical control-flow-level replay attack. Universal across providers; stack-specific signature verification lives in stack-specific skills.\n---\n\n# Webhook Idempotency\n\n> Defends against **OWASP ASI02 (Tool Misuse)** -- specifically, the control-flow\n> replay path where a webhook delivery retries (legitimately or maliciously) and\n> the receiver double-processes the event, triggering a side effect (charge,\n> deploy, notification, inventory mutation) more than once.\n\n**Tradeoff:** Adds a dedupe-store dependency (Redis \u002F DB unique constraint \u002F etc.)\nplus a per-event read-before-act. Worth it: webhook double-processing is a\nrecurring production-critical defect across every provider that emits HTTP\nwebhooks. The cost of NOT having this is a charge billed twice, an email sent\ntwice, a deploy re-run mid-flight.\n\n---\n\n## The threat\n\nWebhook delivery is retried on transient failures (network blip, 5xx response,\ntimeout). Most providers retry aggressively -- Stripe retries on a backoff\nschedule for up to 3 days; GitHub retries 3-8 times depending on the delivery\ntype. Every retry that lands AFTER the receiver successfully processed (but\nbefore the response made it back to the provider) is a duplicate.\n\nMapping to **ASI02 (Tool Misuse)**: if the webhook handler invokes a\ndestructive tool (charge a card, send a notification, deploy an environment,\nmutate inventory), a replayed delivery re-invokes that tool. The agent layer's\nprompt-injection-defense (ASI01) does not protect against this -- the replay\nis a legitimate-looking webhook from the legitimate provider, just delivered\nmultiple times. The control-flow-level defense is structural idempotency on\nthe receiver, NOT content-level sanitization.\n\n---\n\n## Idempotency key\n\nThe **idempotency key** is a stable, per-event identifier the provider assigns.\nA correctly designed receiver:\n\n1. Reads the idempotency key from the incoming request (NOT computed from\n   the body content -- see anti-patterns).\n2. Looks up the key in a dedupe store.\n3. If the key is already present and marked \"processed\", returns the prior\n   response without re-invoking the handler logic.\n4. If the key is absent or marked \"in-flight\", records the key (with TTL),\n   runs the handler, then marks the key \"processed\".\n\nThe key field name differs per provider but the pattern is constant:\n\n| Provider | Idempotency key source |\n|----------|------------------------|\n| Stripe | `event.id` (in the webhook payload body) |\n| GitHub | `X-GitHub-Delivery` header (UUID per delivery) |\n| Slack | `event_id` in the payload + `X-Slack-Request-Timestamp` |\n| Twilio | `MessageSid` in the payload |\n| SendGrid | `sg_event_id` per event in the batch |\n\nThe key is what makes idempotency idempotency: same key arriving twice means\nthe same event arriving twice, regardless of what the body or headers look\nlike otherwise.\n\n---\n\n## Replay window\n\nThe idempotency key stops a second processing of an event already handled.\nThe **replay window** stops a captured delivery from being re-sent later: it\nis a configurable time-bound on the provider's signed per-delivery timestamp\n(for Stripe, the `t=` value in the `Stripe-Signature` header), and a request\nwhose signed timestamp falls outside it is rejected. Legitimate retries pass,\nbecause Stripe generates a new signature and timestamp for every delivery\nattempt. The event's own creation time (`event.created`) is signed too, but\nit stays the same across retries, so it is not a replay clock: windowing on\nit rejects every retry that arrives after the window.\n\nTypical recommendation: **5 minutes (300 seconds)** of skew tolerance. Stripe's\nofficial libraries default to a 300-second tolerance on the signature\ntimestamp; this matches HMAC-signed-request best practice across most\nproviders.\n\nThe replay-window check is independent of the idempotency-key check:\n\n- **Idempotency-key check** -- \"have I already processed *this specific*\n  event?\"\n- **Replay-window check** -- \"is *this delivery's* signed timestamp recent\n  enough to accept?\"\n\nReject deliveries whose signed timestamp is more than 300 seconds (or your\nconfigured window) before the current server time. This defends against\nstored-and-replayed deliveries where an attacker who captured a webhook\npayload tries to replay it later. Note that the replay-window depends on a\nverified signed timestamp from the provider; raw payload timestamps without\nsignature verification are not trustable inputs. If a provider signs no\ntimestamp, there is no replay window to apply: GitHub's `X-Hub-Signature-256`\ncovers only the payload, and GitHub documents deduplication on\n`X-GitHub-Delivery` (which a redelivery reuses) as its replay defense.\n\n---\n\n## Storage strategies\n\nThree storage backends are common for the idempotency-key dedupe set. Each\nhas a \"fails when\" caveat -- pick the one that fails least disastrously for\nyour throughput and reliability profile.\n\n### Strategy 1 -- Redis with TTL\n\nUse `SETNX key value EX 86400` (set-if-not-exists with 24h TTL) as the\natomic \"have I seen this key?\" primitive.\n\n- **Pros**: O(1) check + write; battle-tested for high throughput; the TTL\n  bounds memory growth automatically.\n- **Fails when**: Redis is unavailable (network partition, memory eviction\n  policy kicks in, the operator forgot to enable persistence). The TTL also\n  means events delivered MORE than 24h after their first processing\n  (extremely-delayed retries) will be re-processed. For Stripe's 3-day\n  retry schedule, set TTL >= 4 days.\n\n### Strategy 2 -- Database unique constraint\n\nAdd a `processed_events` table with a `UNIQUE` constraint on the\nidempotency-key column. INSERT inside the handler transaction; rely on the\nDB's constraint violation as the dedupe signal.\n\n- **Pros**: Atomic with the handler's own writes (same transaction);\n  durable beyond Redis evictions; queryable for audit.\n- **Fails when**: High webhook throughput hits write contention on the\n  unique index; long-running handler transactions hold locks. Mitigated by\n  inserting the key FIRST in a small transaction, then doing the actual\n  side-effect work after. Also fails when the DB's isolation level allows\n  phantom reads between the SELECT and INSERT -- use the constraint as\n  the single source of truth, not a check-then-insert pattern.\n\n### Strategy 3 -- In-memory LRU (low-volume only)\n\nA bounded LRU cache (e.g., 10000 most-recent keys) in process memory.\n\n- **Pros**: Zero infrastructure dependency; lowest latency; appropriate for\n  low-volume single-instance receivers.\n- **Fails when**: The process restarts (deploy, crash, scale-out) -- all\n  remembered keys are gone, and the NEXT retry of any in-flight event\n  re-processes. Also fails when traffic scales beyond LRU capacity; older\n  keys evict and re-processing risk reappears for those. Strictly NOT\n  acceptable for multi-instance receivers without sticky routing.\n\nFor PCI-scoped or financial-side-effect handlers, Strategy 2 (DB unique\nconstraint) is the conservative default. For mid-throughput notification\nor sync handlers, Strategy 1 (Redis TTL) is the typical pick. Strategy 3\nis rarely the right answer outside dev\u002Ftest environments.\n\n---\n\n## Worked examples\n\n### Stripe (TypeScript \u002F Node.js)\n\n```ts\n\u002F\u002F webhook-stripe.ts -- synthetic example, no live network, PII redacted\nimport Stripe from 'stripe';\nimport { createClient } from 'redis';\n\nconst redis = createClient({ url: process.env.REDIS_URL });\nconst stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\nconst SIGNING_SECRET = process.env.STRIPE_WEBHOOK_SECRET!;\nconst REPLAY_WINDOW_SECONDS = 300;\n\nasync function handleStripeWebhook(rawBody: string, signatureHeader: string) {\n  \u002F\u002F 1. Verify signature (provider-specific; verification + idempotency are\n  \u002F\u002F    orthogonal concerns -- both required).\n  let event: Stripe.Event;\n  try {\n    event = stripe.webhooks.constructEvent(\n      rawBody, signatureHeader, SIGNING_SECRET, REPLAY_WINDOW_SECONDS);\n  } catch {\n    return { status: 400, body: 'invalid signature' };\n  }\n\n  \u002F\u002F 2. Replay window: constructEvent has already rejected any delivery whose\n  \u002F\u002F    signed `t=` timestamp in the Stripe-Signature header is more than\n  \u002F\u002F    REPLAY_WINDOW_SECONDS old (never pass 0, which turns that check off).\n  \u002F\u002F    Stripe signs each delivery attempt afresh, so legitimate retries pass.\n  \u002F\u002F    Do not window on event.created: it stays the same across retries, so\n  \u002F\u002F    it would reject every retry that arrives more than five minutes after\n  \u002F\u002F    the event.\n\n  \u002F\u002F 3. Idempotency-key check (Redis SETNX with 4-day TTL covering Stripe's\n  \u002F\u002F    72-hour retry schedule plus headroom).\n  const dedupeKey = `stripe:event:${event.id}`;\n  const claimed = await redis.set(dedupeKey, 'processing', { NX: true, EX: 86400 * 4 });\n  if (claimed !== 'OK') {\n    \u002F\u002F Already processed (or in-flight by another worker); replay-safe no-op.\n    return { status: 200, body: 'duplicate (idempotent)' };\n  }\n\n  \u002F\u002F 4. Run handler. Synthetic event.data.object with PII redacted.\n  \u002F\u002F Example shape: { customer_email: \"redacted@example.test\", amount: 1999 }\n  await runStripeEventHandler(event);\n\n  await redis.set(dedupeKey, 'processed', { EX: 86400 * 4 });\n  return { status: 200, body: 'ok' };\n}\n\nasync function runStripeEventHandler(_event: Stripe.Event) {\n  \u002F\u002F Side-effect implementation lives here -- charge ledger, fulfillment, etc.\n  \u002F\u002F Synthetic placeholder: no live network in this example.\n}\n```\n\n### GitHub (Python \u002F FastAPI)\n\n```python\n# webhook_github.py -- synthetic example, no live network, PII redacted\nimport hmac\nimport hashlib\nimport time\nfrom fastapi import FastAPI, Request, HTTPException\nfrom sqlalchemy import Column, String, DateTime, create_engine\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm import declarative_base, sessionmaker\nfrom datetime import datetime, timezone\n\napp = FastAPI()\nBase = declarative_base()\nengine = create_engine(\"postgresql+psycopg:\u002F\u002Flocalhost\u002Fapp\")  # placeholder\nSession = sessionmaker(bind=engine)\n\nclass ProcessedEvent(Base):\n    __tablename__ = \"processed_events\"\n    delivery_id = Column(String, primary_key=True)  # UNIQUE by virtue of PK\n    received_at = Column(DateTime(timezone=True), nullable=False)\n\n@app.post(\"\u002Fapi\u002Fwebhook\u002Fgithub\")\nasync def handle_github_webhook(req: Request):\n    raw_body = await req.body()\n    signature = req.headers.get(\"X-Hub-Signature-256\", \"\")\n    delivery_id = req.headers.get(\"X-GitHub-Delivery\", \"\")\n\n    # 1. Verify signature (HMAC-SHA256 with shared secret).\n    secret = b\"placeholder-secret-redacted\"  # in prod: load from vault\n    expected = \"sha256=\" + hmac.new(secret, raw_body, hashlib.sha256).hexdigest()\n    if not hmac.compare_digest(expected, signature):\n        raise HTTPException(status_code=400, detail=\"invalid signature\")\n\n    # 2. No replay window: X-Hub-Signature-256 covers only the body and\n    #    GitHub signs no delivery timestamp. A body timestamp such as\n    #    \"created_at\" is not a per-delivery clock and would reject\n    #    redeliveries. The delivery-id check in step 3 is the replay defense\n    #    GitHub documents; a redelivery reuses the same X-GitHub-Delivery.\n    payload = await req.json()\n\n    # 3. Idempotency-key check via DB unique constraint on delivery_id.\n    session = Session()\n    try:\n        session.add(ProcessedEvent(delivery_id=delivery_id, received_at=datetime.now(timezone.utc)))\n        session.commit()\n    except IntegrityError:\n        session.rollback()\n        return {\"status\": \"duplicate (idempotent)\"}\n    finally:\n        session.close()\n\n    # 4. Run handler. Synthetic payload with PII redacted -- e.g.\n    #    { \"sender\": { \"login\": \"REDACTED\" }, \"repository\": { \"name\": \"REDACTED\" } }\n    run_github_event_handler(payload)\n    return {\"status\": \"ok\"}\n\ndef run_github_event_handler(_payload: dict) -> None:\n    # Side-effect implementation lives here. Synthetic placeholder.\n    pass\n```\n\nBoth examples are self-contained, deterministic (no live network), and use\nsynthetic payloads with PII fields explicitly redacted to `redacted@example.test`,\n`REDACTED`, or placeholder secrets. Adapt to your own infrastructure\n(connection strings, dedupe-store choice per the Strategy 1\u002F2\u002F3 tradeoff\nabove).\n\n---\n\n## Anti-patterns\n\nThe following patterns SHALL NOT appear in production webhook handlers. Each\nfails for the reason given.\n\n1. **Body-hash as idempotency key.** Computing `sha256(request.body)` and\n   using THAT as the dedupe key. **Fails when** the provider's retry includes\n   a legitimate body change (e.g., GitHub adds a retry counter to the body;\n   Stripe re-serializes JSON with different key ordering). Same logical event,\n   different hash, re-processed. Use the provider's explicit event id, not\n   the body content.\n\n2. **In-memory dedupe store without persistence.** A `Set\u003Cstring>` in process\n   memory holding the seen keys. **Fails when** the process restarts -- every\n   in-flight retry that lands post-restart is treated as new. Common on\n   serverless platforms where containers are recycled aggressively. Use a\n   shared dedupe store (Redis \u002F DB) for any multi-instance or restart-prone\n   deployment.\n\n3. **Silent re-process on dedupe-store unavailability.** If Redis is down,\n   skip the dedupe check and \"fail open\" to processing the event. **Fails when**\n   it most matters -- precisely during the dedupe-store outage, the receiver\n   processes EVERY retry. Fail closed instead: return 503 if the dedupe store\n   is unavailable, let the provider retry later when the store is back.\n\n---\n\n## Provider-specific extensions\n\nFor providers with distinctive primitives that go beyond the universal\npattern, see the stack-specific skills:\n\n- **Stripe-specific** -- `skills\u002Fstack-specific\u002Fstripe\u002Fwebhook-idempotency`\n  (signature verification, fulfillment guards, payment-intent state)\n- (others to be added as patterns surface)\n\nThis universal skill stays provider-agnostic on purpose: idempotency-key +\nreplay-window + dedupe storage are the load-bearing primitives across every\nprovider. Stack-specific quirks layer on top.\n\n---\n\n## Testing\n\nAuthor replay tests in your handler test suite:\n\n```ts\ntest(\"duplicate Stripe webhook delivery is idempotent\", async () => {\n  const payload = stripeSyntheticEvent({ id: \"evt_test_replay_1\" });\n  const res1 = await handler(payload, validSignature);\n  const res2 = await handler(payload, validSignature);\n  expect(res1.status).toBe(200);\n  expect(res2.status).toBe(200);\n  expect(res2.body).toContain(\"duplicate\");\n  \u002F\u002F Side effect (e.g., DB row, ledger entry) ran exactly ONCE.\n  expect(await countLedgerEntries({ event_id: \"evt_test_replay_1\" })).toBe(1);\n});\n```\n\nA successful idempotency suite has the property: same event delivered N\ntimes → 1 side effect, N - 1 \"duplicate\" responses.\n\n---\n\n## When this skill is working\n\n- OWASP ASI02 red-team probes that include webhook-replay vectors return 0\n  successful double-processing.\n- Production incident reports stop mentioning \"billed twice\", \"email\n  sent twice\", \"deploy ran twice from the same trigger\".\n- Webhook-handler PRs include a duplicate-delivery test as a standard part\n  of the review checklist.\n\n---\n\n## See also\n\n- `governance\u002Fowasp-asi-2026\u002Fthreats.md` -- ASI02 (Tool Misuse) full reference\n- `skills\u002Fstack-specific\u002Fstripe\u002Fwebhook-idempotency` -- Stripe-specific\n  extension\n- Renovate \u002F Dependabot webhook noise: out of scope; this skill is about\n  webhooks that trigger application side effects, not DevOps platform\n  notifications.\n","# Webhook Idempotency\n\n> Defends against **OWASP ASI02 (Tool Misuse)** -- specifically, the control-flow\n> replay path where a webhook delivery retries (legitimately or maliciously) and\n> the receiver double-processes the event, triggering a side effect (charge,\n> deploy, notification, inventory mutation) more than once.\n\n**Tradeoff:** Adds a dedupe-store dependency (Redis \u002F DB unique constraint \u002F etc.)\nplus a per-event read-before-act. Worth it: webhook double-processing is a\nrecurring production-critical defect across every provider that emits HTTP\nwebhooks. The cost of NOT having this is a charge billed twice, an email sent\ntwice, a deploy re-run mid-flight.\n\n---\n\n## The threat\n\nWebhook delivery is retried on transient failures (network blip, 5xx response,\ntimeout). Most providers retry aggressively -- Stripe retries on a backoff\nschedule for up to 3 days; GitHub retries 3-8 times depending on the delivery\ntype. Every retry that lands AFTER the receiver successfully processed (but\nbefore the response made it back to the provider) is a duplicate.\n\nMapping to **ASI02 (Tool Misuse)**: if the webhook handler invokes a\ndestructive tool (charge a card, send a notification, deploy an environment,\nmutate inventory), a replayed delivery re-invokes that tool. The agent layer's\nprompt-injection-defense (ASI01) does not protect against this -- the replay\nis a legitimate-looking webhook from the legitimate provider, just delivered\nmultiple times. The control-flow-level defense is structural idempotency on\nthe receiver, NOT content-level sanitization.\n\n---\n\n## Idempotency key\n\nThe **idempotency key** is a stable, per-event identifier the provider assigns.\nA correctly designed receiver:\n\n1. Reads the idempotency key from the incoming request (NOT computed from\n   the body content -- see anti-patterns).\n2. Looks up the key in a dedupe store.\n3. If the key is already present and marked \"processed\", returns the prior\n   response without re-invoking the handler logic.\n4. If the key is absent or marked \"in-flight\", records the key (with TTL),\n   runs the handler, then marks the key \"processed\".\n\nThe key field name differs per provider but the pattern is constant:\n\n| Provider | Idempotency key source |\n|----------|------------------------|\n| Stripe | `event.id` (in the webhook payload body) |\n| GitHub | `X-GitHub-Delivery` header (UUID per delivery) |\n| Slack | `event_id` in the payload + `X-Slack-Request-Timestamp` |\n| Twilio | `MessageSid` in the payload |\n| SendGrid | `sg_event_id` per event in the batch |\n\nThe key is what makes idempotency idempotency: same key arriving twice means\nthe same event arriving twice, regardless of what the body or headers look\nlike otherwise.\n\n---\n\n## Replay window\n\nThe idempotency key stops a second processing of an event already handled.\nThe **replay window** stops a captured delivery from being re-sent later: it\nis a configurable time-bound on the provider's signed per-delivery timestamp\n(for Stripe, the `t=` value in the `Stripe-Signature` header), and a request\nwhose signed timestamp falls outside it is rejected. Legitimate retries pass,\nbecause Stripe generates a new signature and timestamp for every delivery\nattempt. The event's own creation time (`event.created`) is signed too, but\nit stays the same across retries, so it is not a replay clock: windowing on\nit rejects every retry that arrives after the window.\n\nTypical recommendation: **5 minutes (300 seconds)** of skew tolerance. Stripe's\nofficial libraries default to a 300-second tolerance on the signature\ntimestamp; this matches HMAC-signed-request best practice across most\nproviders.\n\nThe replay-window check is independent of the idempotency-key check:\n\n- **Idempotency-key check** -- \"have I already processed *this specific*\n  event?\"\n- **Replay-window check** -- \"is *this delivery's* signed timestamp recent\n  enough to accept?\"\n\nReject deliveries whose signed timestamp is more than 300 seconds (or your\nconfigured window) before the current server time. This defends against\nstored-and-replayed deliveries where an attacker who captured a webhook\npayload tries to replay it later. Note that the replay-window depends on a\nverified signed timestamp from the provider; raw payload timestamps without\nsignature verification are not trustable inputs. If a provider signs no\ntimestamp, there is no replay window to apply: GitHub's `X-Hub-Signature-256`\ncovers only the payload, and GitHub documents deduplication on\n`X-GitHub-Delivery` (which a redelivery reuses) as its replay defense.\n\n---\n\n## Storage strategies\n\nThree storage backends are common for the idempotency-key dedupe set. Each\nhas a \"fails when\" caveat -- pick the one that fails least disastrously for\nyour throughput and reliability profile.\n\n### Strategy 1 -- Redis with TTL\n\nUse `SETNX key value EX 86400` (set-if-not-exists with 24h TTL) as the\natomic \"have I seen this key?\" primitive.\n\n- **Pros**: O(1) check + write; battle-tested for high throughput; the TTL\n  bounds memory growth automatically.\n- **Fails when**: Redis is unavailable (network partition, memory eviction\n  policy kicks in, the operator forgot to enable persistence). The TTL also\n  means events delivered MORE than 24h after their first processing\n  (extremely-delayed retries) will be re-processed. For Stripe's 3-day\n  retry schedule, set TTL >= 4 days.\n\n### Strategy 2 -- Database unique constraint\n\nAdd a `processed_events` table with a `UNIQUE` constraint on the\nidempotency-key column. INSERT inside the handler transaction; rely on the\nDB's constraint violation as the dedupe signal.\n\n- **Pros**: Atomic with the handler's own writes (same transaction);\n  durable beyond Redis evictions; queryable for audit.\n- **Fails when**: High webhook throughput hits write contention on the\n  unique index; long-running handler transactions hold locks. Mitigated by\n  inserting the key FIRST in a small transaction, then doing the actual\n  side-effect work after. Also fails when the DB's isolation level allows\n  phantom reads between the SELECT and INSERT -- use the constraint as\n  the single source of truth, not a check-then-insert pattern.\n\n### Strategy 3 -- In-memory LRU (low-volume only)\n\nA bounded LRU cache (e.g., 10000 most-recent keys) in process memory.\n\n- **Pros**: Zero infrastructure dependency; lowest latency; appropriate for\n  low-volume single-instance receivers.\n- **Fails when**: The process restarts (deploy, crash, scale-out) -- all\n  remembered keys are gone, and the NEXT retry of any in-flight event\n  re-processes. Also fails when traffic scales beyond LRU capacity; older\n  keys evict and re-processing risk reappears for those. Strictly NOT\n  acceptable for multi-instance receivers without sticky routing.\n\nFor PCI-scoped or financial-side-effect handlers, Strategy 2 (DB unique\nconstraint) is the conservative default. For mid-throughput notification\nor sync handlers, Strategy 1 (Redis TTL) is the typical pick. Strategy 3\nis rarely the right answer outside dev\u002Ftest environments.\n\n---\n\n## Worked examples\n\n### Stripe (TypeScript \u002F Node.js)\n\n```ts\n\u002F\u002F webhook-stripe.ts -- synthetic example, no live network, PII redacted\nimport Stripe from 'stripe';\nimport { createClient } from 'redis';\n\nconst redis = createClient({ url: process.env.REDIS_URL });\nconst stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\nconst SIGNING_SECRET = process.env.STRIPE_WEBHOOK_SECRET!;\nconst REPLAY_WINDOW_SECONDS = 300;\n\nasync function handleStripeWebhook(rawBody: string, signatureHeader: string) {\n  \u002F\u002F 1. Verify signature (provider-specific; verification + idempotency are\n  \u002F\u002F    orthogonal concerns -- both required).\n  let event: Stripe.Event;\n  try {\n    event = stripe.webhooks.constructEvent(\n      rawBody, signatureHeader, SIGNING_SECRET, REPLAY_WINDOW_SECONDS);\n  } catch {\n    return { status: 400, body: 'invalid signature' };\n  }\n\n  \u002F\u002F 2. Replay window: constructEvent has already rejected any delivery whose\n  \u002F\u002F    signed `t=` timestamp in the Stripe-Signature header is more than\n  \u002F\u002F    REPLAY_WINDOW_SECONDS old (never pass 0, which turns that check off).\n  \u002F\u002F    Stripe signs each delivery attempt afresh, so legitimate retries pass.\n  \u002F\u002F    Do not window on event.created: it stays the same across retries, so\n  \u002F\u002F    it would reject every retry that arrives more than five minutes after\n  \u002F\u002F    the event.\n\n  \u002F\u002F 3. Idempotency-key check (Redis SETNX with 4-day TTL covering Stripe's\n  \u002F\u002F    72-hour retry schedule plus headroom).\n  const dedupeKey = `stripe:event:${event.id}`;\n  const claimed = await redis.set(dedupeKey, 'processing', { NX: true, EX: 86400 * 4 });\n  if (claimed !== 'OK') {\n    \u002F\u002F Already processed (or in-flight by another worker); replay-safe no-op.\n    return { status: 200, body: 'duplicate (idempotent)' };\n  }\n\n  \u002F\u002F 4. Run handler. Synthetic event.data.object with PII redacted.\n  \u002F\u002F Example shape: { customer_email: \"redacted@example.test\", amount: 1999 }\n  await runStripeEventHandler(event);\n\n  await redis.set(dedupeKey, 'processed', { EX: 86400 * 4 });\n  return { status: 200, body: 'ok' };\n}\n\nasync function runStripeEventHandler(_event: Stripe.Event) {\n  \u002F\u002F Side-effect implementation lives here -- charge ledger, fulfillment, etc.\n  \u002F\u002F Synthetic placeholder: no live network in this example.\n}\n```\n\n### GitHub (Python \u002F FastAPI)\n\n```python\n# webhook_github.py -- synthetic example, no live network, PII redacted\nimport hmac\nimport hashlib\nimport time\nfrom fastapi import FastAPI, Request, HTTPException\nfrom sqlalchemy import Column, String, DateTime, create_engine\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm import declarative_base, sessionmaker\nfrom datetime import datetime, timezone\n\napp = FastAPI()\nBase = declarative_base()\nengine = create_engine(\"postgresql+psycopg:\u002F\u002Flocalhost\u002Fapp\")  # placeholder\nSession = sessionmaker(bind=engine)\n\nclass ProcessedEvent(Base):\n    __tablename__ = \"processed_events\"\n    delivery_id = Column(String, primary_key=True)  # UNIQUE by virtue of PK\n    received_at = Column(DateTime(timezone=True), nullable=False)\n\n@app.post(\"\u002Fapi\u002Fwebhook\u002Fgithub\")\nasync def handle_github_webhook(req: Request):\n    raw_body = await req.body()\n    signature = req.headers.get(\"X-Hub-Signature-256\", \"\")\n    delivery_id = req.headers.get(\"X-GitHub-Delivery\", \"\")\n\n    # 1. Verify signature (HMAC-SHA256 with shared secret).\n    secret = b\"placeholder-secret-redacted\"  # in prod: load from vault\n    expected = \"sha256=\" + hmac.new(secret, raw_body, hashlib.sha256).hexdigest()\n    if not hmac.compare_digest(expected, signature):\n        raise HTTPException(status_code=400, detail=\"invalid signature\")\n\n    # 2. No replay window: X-Hub-Signature-256 covers only the body and\n    #    GitHub signs no delivery timestamp. A body timestamp such as\n    #    \"created_at\" is not a per-delivery clock and would reject\n    #    redeliveries. The delivery-id check in step 3 is the replay defense\n    #    GitHub documents; a redelivery reuses the same X-GitHub-Delivery.\n    payload = await req.json()\n\n    # 3. Idempotency-key check via DB unique constraint on delivery_id.\n    session = Session()\n    try:\n        session.add(ProcessedEvent(delivery_id=delivery_id, received_at=datetime.now(timezone.utc)))\n        session.commit()\n    except IntegrityError:\n        session.rollback()\n        return {\"status\": \"duplicate (idempotent)\"}\n    finally:\n        session.close()\n\n    # 4. Run handler. Synthetic payload with PII redacted -- e.g.\n    #    { \"sender\": { \"login\": \"REDACTED\" }, \"repository\": { \"name\": \"REDACTED\" } }\n    run_github_event_handler(payload)\n    return {\"status\": \"ok\"}\n\ndef run_github_event_handler(_payload: dict) -> None:\n    # Side-effect implementation lives here. Synthetic placeholder.\n    pass\n```\n\nBoth examples are self-contained, deterministic (no live network), and use\nsynthetic payloads with PII fields explicitly redacted to `redacted@example.test`,\n`REDACTED`, or placeholder secrets. Adapt to your own infrastructure\n(connection strings, dedupe-store choice per the Strategy 1\u002F2\u002F3 tradeoff\nabove).\n\n---\n\n## Anti-patterns\n\nThe following patterns SHALL NOT appear in production webhook handlers. Each\nfails for the reason given.\n\n1. **Body-hash as idempotency key.** Computing `sha256(request.body)` and\n   using THAT as the dedupe key. **Fails when** the provider's retry includes\n   a legitimate body change (e.g., GitHub adds a retry counter to the body;\n   Stripe re-serializes JSON with different key ordering). Same logical event,\n   different hash, re-processed. Use the provider's explicit event id, not\n   the body content.\n\n2. **In-memory dedupe store without persistence.** A `Set\u003Cstring>` in process\n   memory holding the seen keys. **Fails when** the process restarts -- every\n   in-flight retry that lands post-restart is treated as new. Common on\n   serverless platforms where containers are recycled aggressively. Use a\n   shared dedupe store (Redis \u002F DB) for any multi-instance or restart-prone\n   deployment.\n\n3. **Silent re-process on dedupe-store unavailability.** If Redis is down,\n   skip the dedupe check and \"fail open\" to processing the event. **Fails when**\n   it most matters -- precisely during the dedupe-store outage, the receiver\n   processes EVERY retry. Fail closed instead: return 503 if the dedupe store\n   is unavailable, let the provider retry later when the store is back.\n\n---\n\n## Provider-specific extensions\n\nFor providers with distinctive primitives that go beyond the universal\npattern, see the stack-specific skills:\n\n- **Stripe-specific** -- `skills\u002Fstack-specific\u002Fstripe\u002Fwebhook-idempotency`\n  (signature verification, fulfillment guards, payment-intent state)\n- (others to be added as patterns surface)\n\nThis universal skill stays provider-agnostic on purpose: idempotency-key +\nreplay-window + dedupe storage are the load-bearing primitives across every\nprovider. Stack-specific quirks layer on top.\n\n---\n\n## Testing\n\nAuthor replay tests in your handler test suite:\n\n```ts\ntest(\"duplicate Stripe webhook delivery is idempotent\", async () => {\n  const payload = stripeSyntheticEvent({ id: \"evt_test_replay_1\" });\n  const res1 = await handler(payload, validSignature);\n  const res2 = await handler(payload, validSignature);\n  expect(res1.status).toBe(200);\n  expect(res2.status).toBe(200);\n  expect(res2.body).toContain(\"duplicate\");\n  \u002F\u002F Side effect (e.g., DB row, ledger entry) ran exactly ONCE.\n  expect(await countLedgerEntries({ event_id: \"evt_test_replay_1\" })).toBe(1);\n});\n```\n\nA successful idempotency suite has the property: same event delivered N\ntimes → 1 side effect, N - 1 \"duplicate\" responses.\n\n---\n\n## When this skill is working\n\n- OWASP ASI02 red-team probes that include webhook-replay vectors return 0\n  successful double-processing.\n- Production incident reports stop mentioning \"billed twice\", \"email\n  sent twice\", \"deploy ran twice from the same trigger\".\n- Webhook-handler PRs include a duplicate-delivery test as a standard part\n  of the review checklist.\n\n---\n\n## See also\n\n- `governance\u002Fowasp-asi-2026\u002Fthreats.md` -- ASI02 (Tool Misuse) full reference\n- `skills\u002Fstack-specific\u002Fstripe\u002Fwebhook-idempotency` -- Stripe-specific\n  extension\n- Renovate \u002F Dependabot webhook noise: out of scope; this skill is about\n  webhooks that trigger application side effects, not DevOps platform\n  notifications.\n",{"name":5,"description":7},"main","5a590e92c8f62b54c96a6928215ac2145b671e03","skills\u002Funiversal\u002Fsecurity\u002Fwebhook-idempotency","https:\u002F\u002Fgithub.com\u002FMILTONADINA\u002FDevOPs","https:\u002F\u002Fgithub.com\u002FMILTONADINA","https:\u002F\u002Fwww.linkedin.com\u002Fin\u002Fmiltonadina","CS\u002FCybersecurity SWE & former Epidemiologist. Building secure, test-driven full-stack & mobile apps (TS\u002FReact\u002FNode, Java\u002FSpring, Flutter).","2026-11-14 20:03:36",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add MILTONADINA\u002FDevOPs --skill webhook-idempotency",{"tool":38,"command":39},"bunx","bunx skills add MILTONADINA\u002FDevOPs --skill webhook-idempotency",{"tool":41,"command":42},"pnpm","pnpm dlx skills add MILTONADINA\u002FDevOPs --skill webhook-idempotency","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMILTONADINA\u002FDevOPs\u002Fblob\u002Fmain\u002Fskills\u002Funiversal\u002Fsecurity\u002Fwebhook-idempotency\u002FSKILL.md",true,[46],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"SKILL.md.bundle","OTHER","其他",9503,"https:\u002F\u002Fgithub.com\u002FMILTONADINA\u002FDevOPs\u002Fblob\u002Fmain\u002Fskills\u002Funiversal\u002Fsecurity\u002Fwebhook-idempotency\u002FSKILL.md.bundle",[53,60,67,74,79,86],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M74F7F3HN6J7CSFHBVQAE9S5","karpathy-guidelines","Behavioral guidelines that reduce common LLM coding mistakes. Apply whenever writing, modifying, or reviewing code. Don't assume requirements, don't overcomplicate, don't refactor unrelated code, and define success criteria before implementing. Use this skill on every non-trivial coding task to avoid bloat, silent assumptions, and completion-bias.","https:\u002F\u002Fgithub.com\u002FMILTONADINA\u002FDevOPs\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fsecurity\u002Fmodified-skill\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M74F7D60N9FRWWWHCGZMMB41","unsigned-missing-sig-fixture","Test fixture (F.09) — SKILL.md without an accompanying .sig file. Default install rejects with exit 2; --allow-unsigned --rationale=\"...\" proceeds.","https:\u002F\u002Fgithub.com\u002FMILTONADINA\u002FDevOPs\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Finstall\u002Fsource-skills\u002Funsigned-missing-sig\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M74F7BKGX67Q606QPKZV7TQV","unsigned-mismatched-sig-fixture","Test fixture (F.09) — SKILL.md whose accompanying .sig signs different content. NFR-F3 hash check catches this even with --allow-unsigned.","https:\u002F\u002Fgithub.com\u002FMILTONADINA\u002FDevOPs\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Finstall\u002Fsource-skills\u002Funsigned-mismatched-sig\u002FSKILL.md",[],[],{"skillNo":75,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M74F793BYMX98EQC5XP4CDZK","https:\u002F\u002Fgithub.com\u002FMILTONADINA\u002FDevOPs\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Finstall\u002Fsource-skills\u002Fsigned\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M74F71Q6JKRFJ66G5T98KE8H","semgrep-scan","Run Semgrep static analysis to detect insecure code patterns - SQL injection, XSS, path traversal, weak crypto, broken auth, OWASP Top 10 issues. Use on every file change touching security-sensitive code and as part of the tiered security gate. Complements gitleaks (which catches secrets) by catching insecure logic.","https:\u002F\u002Fgithub.com\u002FMILTONADINA\u002FDevOPs\u002Fblob\u002Fmain\u002Fskills\u002Funiversal\u002Fsecurity\u002Fsemgrep-scan\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M74F6Z08PK2X7THG17YBNNCR","prompt-injection-defense","Sanitize all external content before it enters the agent's context window. Use whenever the agent ingests documents, web pages, RAG results, tool outputs, file contents, emails, or any data from outside the user's direct typed input. Defense against OWASP ASI01 (Goal Hijacking) and ASI04 (Indirect Prompt Injection) - the","https:\u002F\u002Fgithub.com\u002FMILTONADINA\u002FDevOPs\u002Fblob\u002Fmain\u002Fskills\u002Funiversal\u002Fsecurity\u002Fprompt-injection-defense\u002FSKILL.md",[],[]]