Leaf and Kettle's warehouse tells the shop when stock changes by calling a webhook, POST /api/webhooks/stock, with a JSON body like { "id": "evt_101", "updates": [{ "tea": "mint", "count": 0 }] }. Anyone on the internet can call that URL, so the warehouse signs every call, and your handler in app/api/webhooks/stock/route.ts must check the signature before it trusts a word of it.
Each call has two headers. Warehouse-Timestamp is when it was sent, in whole seconds since 1970. Warehouse-Signature is sha256= followed by the HMAC-SHA256, in hex, of the timestamp, a dot, and the body exactly as sent, signed with STOCK_WEBHOOK_SECRET from @/lib/env. @/lib/signing gives you hmacSha256Hex(secret, message), which is async like Web Crypto's, and safeEqual(a, b), a comparison whose time doesn't depend on where the two strings differ.
Check these in order, and answer 401 with the error of the first that fails: both headers are there ({ error: "Missing signature" }); the timestamp is a whole number of seconds no more than 5 minutes before or after now ({ error: "Stale timestamp" }), so a call someone recorded can't be replayed later; the signature is right ({ error: "Bad signature" }).
Only then read the body as JSON. It must be an object with a string id and a list of updates, each with a string tea and a whole count of 0 or more. Otherwise answer 400 with { error: "Bad payload" }, and change nothing.
The warehouse sends a call again when it doesn't hear back in time, so the same event can arrive twice. If its id is already in handledEvents from @/lib/stock, answer 200 with { received: true, duplicate: true } and do nothing else. Otherwise, for each update call setStock(tea, count) and revalidateTag("tea:<slug>", "max"), the tag each tea's page caches its stock under. Then add the id to handledEvents and answer 200 with { received: true }.
// How the warehouse signs a call:
const body = '{"id":"evt_101","updates":[{"tea":"mint","count":0}]}';
const timestamp = "1763430000";
const signature = "sha256=" + (await hmacSha256Hex(STOCK_WEBHOOK_SECRET, timestamp + "." + body));
// → headers Warehouse-Timestamp: 1763430000 and Warehouse-Signature: sha256=…
lib/signing.ts, read-only. Import it as @/lib/signing.
// HMAC-SHA256 in plain TypeScript, so it runs everywhere the tests do. It gives the same answer as
// Web Crypto's crypto.subtle.sign("HMAC", ...) and Node.js's createHmac("sha256", ...), which a
// real app would use.
const encoder = new TextEncoder();
// SHA-256's constants: the first 32 bits of the fractional parts of the cube roots (K) and the
// square roots (H) of the first 64 and 8 primes.
const primes: number[] = [];
for (let n = 2; primes.length < 64; n++) if (primes.every((p) => n % p !== 0)) primes.push(n);
const fraction = (x: number) => ((x - Math.floor(x)) * 2 ** 32) >>> 0;
const K = primes.map((p) => fraction(Math.cbrt(p)));
const H = primes.slice(0, 8).map((p) => fraction(Math.sqrt(p)));
function sha256(data: Uint8Array): Uint8Array {
const blocks = new Uint8Array(Math.ceil((data.length + 9) / 64) * 64);
blocks.set(data);
blocks[data.length] = 0x80;
const view = new DataView(blocks.buffer);
view.setUint32(blocks.length - 8, Math.floor(data.length / 2 ** 29));
view.setUint32(blocks.length - 4, (data.length * 8) >>> 0);
const hash = H.slice();
const w = new Uint32Array(64);
const rotate = (x: number, n: number) => (x >>> n) | (x << (32 - n));
for (let offset = 0; offset < blocks.length; offset += 64) {
for (let i = 0; i < 64; i++) {
w[i] = i < 16 ? view.getUint32(offset + i * 4) : w[i - 16] + (rotate(w[i - 15], 7) ^ rotate(w[i - 15], 18) ^ (w[i - 15] >>> 3)) + w[i - 7] + (rotate(w[i - 2], 17) ^ rotate(w[i - 2], 19) ^ (w[i - 2] >>> 10));
}
let [a, b, c, d, e, f, g, h] = hash;
for (let i = 0; i < 64; i++) {
const t1 = (h + (rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0;
const t2 = ((rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
[h, g, f, e, d, c, b, a] = [g, f, e, (d + t1) | 0, c, b, a, (t1 + t2) | 0];
}
[a, b, c, d, e, f, g, h].forEach((value, i) => (hash[i] = (hash[i] + value) | 0));
}
const digest = new Uint8Array(32);
hash.forEach((value, i) => new DataView(digest.buffer).setUint32(i * 4, value >>> 0));
return digest;
}
/** The HMAC-SHA256 of `message` with `secret`, as 64 lowercase hex digits. Async, like Web Crypto's. */
export async function hmacSha256Hex(secret: string, message: string): Promise<string> {
let key = encoder.encode(secret);
if (key.length > 64) key = sha256(key);
const pad = (byte: number) => Uint8Array.from({ length: 64 }, (_, i) => (key[i] ?? 0) ^ byte);
const join = (first: Uint8Array, second: Uint8Array) => {
const both = new Uint8Array(first.length + second.length);
both.set(first);
both.set(second, first.length);
return both;
};
const mac = sha256(join(pad(0x5c), sha256(join(pad(0x36), encoder.encode(message)))));
return Array.from(mac, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
/** Whether `a` and `b` are the same text, in the same time wherever they differ. */
export function safeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let difference = 0;
for (let i = 0; i < a.length; i++) difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
return difference === 0;
}
lib/env.ts, read-only. Import it as @/lib/env.
/** The secret the warehouse signs its webhooks with. A real app reads it from process.env, on the server only. */
export const STOCK_WEBHOOK_SECRET = "leaf-and-kettle-warehouse-secret";
lib/stock.ts, read-only. Import it as @/lib/stock.
/** How many tins of each tea are left. */
export const stock: Record<string, number> = { green: 12, mint: 4, oolong: 3 };
/** The ids of the webhook events already applied. */
export const handledEvents: string[] = [];
/** Sets how many tins of a tea are left. */
export async function setStock(tea: string, count: number) {
stock[tea] = count;
}
useFakeTimers();
const body = JSON.stringify({ id: "evt_101", updates: [{ tea: "mint", count: 0 }, { tea: "green", count: 20 }] });
const timestamp = String(Math.floor(Date.now() / 1000));
const signature = "sha256=" + (await hmacSha256Hex(STOCK_WEBHOOK_SECRET, timestamp + "." + body));
const response = await POST(
request("/api/webhooks/stock", {
method: "POST",
body,
headers: { "content-type": "application/json", "warehouse-timestamp": timestamp, "warehouse-signature": signature },
}),
);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ received: true });
expect(stock).toEqual({ green: 20, mint: 0, oolong: 3 });
expect(cache.calls).toEqual([
{ name: "revalidateTag", args: ["tea:mint", "max"] },
{ name: "revalidateTag", args: ["tea:green", "max"] },
]);
expect(handledEvents).toEqual(["evt_101"]);
useFakeTimers();
const body = JSON.stringify({ id: "evt_102", updates: [{ tea: "oolong", count: 9 }] }, null, 2) + "\n";
const timestamp = String(Math.floor(Date.now() / 1000));
const signature = "sha256=" + (await hmacSha256Hex(STOCK_WEBHOOK_SECRET, timestamp + "." + body));
const response = await POST(
request("/api/webhooks/stock", {
method: "POST",
body,
headers: { "content-type": "application/json", "warehouse-timestamp": timestamp, "warehouse-signature": signature },
}),
);
expect(response.status).toBe(200);
expect(stock.oolong).toBe(9);
useFakeTimers();
const body = JSON.stringify({ id: "evt_103", updates: [{ tea: "mint", count: 50 }] });
const timestamp = String(Math.floor(Date.now() / 1000));
const signature = "sha256=" + (await hmacSha256Hex(STOCK_WEBHOOK_SECRET, timestamp + "." + body));
for (const headers of [{ "warehouse-timestamp": timestamp }, { "warehouse-signature": signature }, {}]) {
const response = await POST(request("/api/webhooks/stock", { method: "POST", body, headers: { "content-type": "application/json", ...headers } }));
expect(response.status).toBe(401);
expect(await response.json()).toEqual({ error: "Missing signature" });
}
expect(stock.mint).toBe(4);
expect(cache.calls).toEqual([]);
useFakeTimers();
const body = JSON.stringify({ id: "evt_104", updates: [{ tea: "mint", count: 0 }] });
const timestamp = String(Math.floor(Date.now() / 1000));
const sign = async (message, secret = STOCK_WEBHOOK_SECRET) => "sha256=" + (await hmacSha256Hex(secret, message));
const attempts = [
// The body was changed after it was signed.
[body.replace('"count":0', '"count":999'), await sign(timestamp + "." + body)],
// Signed with a guessed secret.
[body, await sign(timestamp + "." + body, "guessed-secret")],
// Signed without the timestamp.
[body, await sign(body)],
// The right signature without its sha256= prefix.
[body, (await sign(timestamp + "." + body)).slice("sha256=".length)],
];
for (const [sent, signature] of attempts) {
const response = await POST(
request("/api/webhooks/stock", {
method: "POST",
body: sent,
headers: { "content-type": "application/json", "warehouse-timestamp": timestamp, "warehouse-signature": signature },
}),
);
expect(response.status).toBe(401);
expect(await response.json()).toEqual({ error: "Bad signature" });
}
expect(stock.mint).toBe(4);
expect(cache.calls).toEqual([]);
expect(handledEvents).toEqual([]);
const clock = useFakeTimers();
const sentAt = Math.floor(Date.now() / 1000);
const call = async (id, timestamp) => {
const body = JSON.stringify({ id, updates: [{ tea: "green", count: 1 }] });
const signature = "sha256=" + (await hmacSha256Hex(STOCK_WEBHOOK_SECRET, timestamp + "." + body));
return POST(
request("/api/webhooks/stock", {
method: "POST",
body,
headers: { "content-type": "application/json", "warehouse-timestamp": timestamp, "warehouse-signature": signature },
}),
);
};
expect((await call("evt_105", String(sentAt + 300))).status).toBe(200);
expect((await call("evt_106", String(sentAt + 301))).status).toBe(401);
clock.tick(300_000);
expect((await call("evt_107", String(sentAt))).status).toBe(200);
clock.tick(1_000);
const replayed = await call("evt_108", String(sentAt));
expect(replayed.status).toBe(401);
expect(await replayed.json()).toEqual({ error: "Stale timestamp" });
expect((await call("evt_109", "soon")).status).toBe(401);
expect(handledEvents).toEqual(["evt_105", "evt_107"]);
useFakeTimers();
const timestamp = String(Math.floor(Date.now() / 1000));
const bodies = [
"stock changed",
"null",
JSON.stringify({ updates: [{ tea: "mint", count: 1 }] }),
JSON.stringify({ id: "evt_110", updates: "mint" }),
JSON.stringify({ id: "evt_111", updates: [{ tea: "mint", count: -1 }] }),
JSON.stringify({ id: "evt_112", updates: [{ tea: "mint", count: 1 }, { tea: "green", count: "lots" }] }),
];
for (const body of bodies) {
const signature = "sha256=" + (await hmacSha256Hex(STOCK_WEBHOOK_SECRET, timestamp + "." + body));
const response = await POST(
request("/api/webhooks/stock", {
method: "POST",
body,
headers: { "content-type": "application/json", "warehouse-timestamp": timestamp, "warehouse-signature": signature },
}),
);
expect(response.status).toBe(400);
expect(await response.json()).toEqual({ error: "Bad payload" });
}
expect(stock).toEqual({ green: 12, mint: 4, oolong: 3 });
expect(cache.calls).toEqual([]);
expect(handledEvents).toEqual([]);
useFakeTimers();
const timestamp = String(Math.floor(Date.now() / 1000));
const deliver = async (body) => {
const signature = "sha256=" + (await hmacSha256Hex(STOCK_WEBHOOK_SECRET, timestamp + "." + body));
return POST(
request("/api/webhooks/stock", {
method: "POST",
body,
headers: { "content-type": "application/json", "warehouse-timestamp": timestamp, "warehouse-signature": signature },
}),
);
};
const event = JSON.stringify({ id: "evt_113", updates: [{ tea: "mint", count: 2 }] });
expect(await (await deliver(event)).json()).toEqual({ received: true });
const again = await deliver(event);
expect(again.status).toBe(200);
expect(await again.json()).toEqual({ received: true, duplicate: true });
expect(cache.calls.length).toBe(1);
await deliver(JSON.stringify({ id: "evt_114", updates: [{ tea: "mint", count: 7 }] }));
expect(stock.mint).toBe(7);
expect(handledEvents).toEqual(["evt_113", "evt_114"]);
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with A signed stock webhook that revalidates. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.