All blocks

AI Chat Conversation

Transcript of alternating turns carrying mixed rich content inline (prose, code blocks, collapsible tool-call output) beside a resizable artifact panel that collapses to a full-screen dialog on narrow screens.

Chat

Today
webhooks/verify.tswebhooks/route.ts
@AgentCan you audit our billing webhook verification? Replayed deliveries from last week still seem to pass the HMAC check.
2:08 PM
Checking the webhook handler and signature helper now to see how the timestamp header is validated.
readwebhooks/verify.ts
29ms
readwebhooks/route.ts
34ms
bashrg "X-Webhook-Timestamp" src/
worker:edge-dev92ms

Found it. In webhooks/verify.ts, the HMAC digest is computed over the raw body alone, and X-Webhook-Timestamp is never checked for freshness.

Here's what happens on a replay:

  1. An old signed delivery arrives hours later
  2. hmacSha256Hex() matches the body digest
  3. The route returns 200 and re-processes the invoice event

We should bind the timestamp into the signed payload, enforce a 300-second window, and compare in constant time:

webhooks/verify.ts
export async function verifyWebhookSignature(
  rawBody: string,
  headerSig: string | null,
  timestampHeader: string | null,
  secret: string,
): Promise<boolean> {
  if (!headerSig || !timestampHeader) return false;

  const sentAt = Number(timestampHeader);
  const skewSeconds = Math.abs(Date.now() / 1000 - sentAt);
  if (!Number.isFinite(sentAt) || skewSeconds > 300) {
    return false;
  }

  const expected = await hmacSha256Hex(secret, `${sentAt}.${rawBody}`);
  return timingSafeEqualHex(headerSig, expected);
}
Assistant · 2:09 PM
Good catch — signing the timestamp fixes both issues.
Can you add unit tests for stale timestamps and bad digests?
2:10 PM · Delivered
readwebhooks/verify.test.ts
24ms
editwebhooks/verify.test.ts
+22-088ms
bashbun test webhooks/verify.test.ts
worker:edge-dev1.4s

Added replay and tamper coverage. All 4 specs pass:

SpecResult
Accepts fresh signed deliveryPass
Rejects valid signature older than 5 minPass
Deduplicates repeated delivery IDsPass
Rejects tampered payload bodyPass
webhooks/verify.test.ts
describe("verifyWebhookSignature", () => {
  it("rejects valid signatures outside the 5-minute replay window", async () => {
    const body = JSON.stringify({ event: "invoice.paid", id: "evt_918" });
    const staleTs = String(Math.floor(Date.now() / 1000) - 600);
    const sig = await hmacSha256Hex(TEST_SECRET, `${staleTs}.${body}`);

    const ok = await verifyWebhookSignature(body, sig, staleTs, TEST_SECRET);
    expect(ok).toBe(false);
  });

  it("accepts a fresh signed payload", async () => {
    const body = JSON.stringify({ event: "invoice.paid", id: "evt_919" });
    const nowTs = String(Math.floor(Date.now() / 1000));
    const sig = await hmacSha256Hex(TEST_SECRET, `${nowTs}.${body}`);

    const ok = await verifyWebhookSignature(body, sig, nowTs, TEST_SECRET);
    expect(ok).toBe(true);
  });
});
2:11 PM

Workspace synced · 2 files updated

Before we ship this, can you put together a short RFC with the rollout plan for the billing team?
2:13 PM

Drafted an RFC covering the root cause, the timestamped signature change, and the verification matrix.

Open it below to inspect or copy for the PR description.

2:14 PM
Nice. Can you include a dry-run logging phase before hard rejections?
2:15 PM · Delivered
Adding a 48-hour dry-run phase under webhook_replay_guard and the skew alert thresholds to the RFC now.
2:15 PM

Webhook Replay Protection: RFC & Rollout

Context

Our billing webhook receiver verifies HMAC-SHA256 signatures, but previously ignored the signed timestamp header. A captured delivery could be replayed indefinitely and still pass verification.

Root Cause

Signature checking compared the raw digest without checking delivery age or using constant-time equality:

  1. verifyWebhookSignature() hashed the raw payload body only
  2. X-Webhook-Timestamp was never bound into the signed message
  3. Replayed payloads older than 5 minutes returned 200

Implementation

The verifier now signs ${timestamp}.${rawBody}, rejects timestamps outside a 300-second skew window, and compares digests with timingSafeEqual.

  • Replay-safe — stale deliveries fail fast with 401
  • Timing-safe — constant-time buffer comparison avoids side-channel leaks
  • Idempotent — delivery IDs are cached in KV for 10 minutes

Verification Matrix

Every replay and signature edge case is tested:

CaseStatus
Valid signature within 5 min window200
Valid signature older than 5 min401
Duplicate delivery ID200 (no-op)
Tampered payload or bad digest401

Rollout Plan

  1. Enable webhook_replay_guard in dry-run logging mode for 48 hours
  2. Track webhooks.verify.stale and webhooks.verify.invalid counters
  3. Enforce hard rejections once clock-skew false positives stay below 0.1%
  4. Remove the legacy body-only verifier after one billing cycle

    Install

    Source

    components/blocks/ui-sdk/ai-chat.tsx

    Inspired by the AI Chat Conversation template from Astryx (MIT License · Copyright (c) 2026 Meta Platforms, Inc.).