A Cloudflare Worker signs its requests to a legacy origin with HMAC and verifies the origin's webhooks; how do you build both safely with crypto.subtle?
answer
- import the key once per use
- sign the canonical string, not the object
- let the runtime compare
- equal lengths or an exception
- redirects carry headers
basics
~20 sImport the secret with crypto.subtle.importKey as a non-extractable HMAC SHA-256 key, sign a canonical string with a timestamp, and check incoming signatures with crypto.subtle.verify on the raw body, never ===. Use redirect: 'manual' so signed headers never follow a redirect.
solid answer
~50 sKeep the shared secret as a Worker secret and turn it into a `CryptoKey` with `crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"])`. To sign, build one canonical string (timestamp, method, path and query, plus a body hash where the payload matters), call `crypto.subtle.sign("HMAC", key, data)` and send it in a header beside the timestamp. To verify a webhook, read the raw body once with `text()` or `arrayBuffer()`, decode the received MAC to bytes, and call `crypto.subtle.verify()`, which does the comparison for you, then reject stale timestamps. Never compare hex strings with `===`, which can stop at the first mismatch. For other secret comparisons there is the non-standard `crypto.subtle.timingSafeEqual()`, which throws a `TypeError` when lengths differ. Finally, subrequests follow redirects by default and carry custom headers such as the signature to the new host, so send signed requests with `redirect: "manual"`.
code
javascript · 45 linesconst enc = new TextEncoder();
const toHex = (buf) =>
[...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
function fromHex(hex) {
if (!/^(?:[0-9a-f]{2})+$/.test(hex)) return null;
return new Uint8Array(hex.match(/../g).map((h) => parseInt(h, 16)));
}
export default {
async fetch(request, env) {
const key = await crypto.subtle.importKey(
"raw",
enc.encode(env.ORIGIN_HMAC_SECRET),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign", "verify"],
);
const url = new URL(request.url);
if (url.pathname === "/hooks/legacy") {
const ts = Number(request.headers.get("X-Timestamp"));
const body = await request.text();
const mac = fromHex(request.headers.get("X-Signature") ?? "");
const fresh = Math.abs(Date.now() / 1000 - ts) <= 300;
const valid =
fresh && mac !== null && (await crypto.subtle.verify("HMAC", key, mac, enc.encode(`${ts}\n${body}`)));
return valid ? new Response("accepted") : new Response("invalid signature", { status: 401 });
}
const ts = Math.floor(Date.now() / 1000).toString();
const signed = `${ts}\n${request.method}\n${url.pathname}${url.search}`;
const headers = new Headers(request.headers);
headers.set("X-Timestamp", ts);
headers.set("X-Signature", toHex(await crypto.subtle.sign("HMAC", key, enc.encode(signed))));
return fetch(`https://legacy.example.com${url.pathname}${url.search}`, {
method: request.method,
headers,
body: request.body,
redirect: "manual",
});
},
};go deeper
Recall that crypto.subtle provides importKey, sign and verify, that HMAC needs a shared secret, and that the secret belongs in a Worker secret.
Explain the canonical string, signing a timestamp, verifying raw body bytes, and why verify() replaces a string comparison.
Review a signing Worker for the real gaps: === comparisons, timingSafeEqual's length TypeError, replay windows, and redirect: 'manual' on signed subrequests.
Decide where signing lives: a shared helper module or one gateway Worker, with one key rotation procedure and one replay window across every service that verifies.
## The building blocks in Workers Workers implements the **Web Crypto API** as `crypto.subtle`, backed by native code, which the documentation notes is significantly faster than cryptography written in JavaScript. HMAC is supported for `sign()`, `verify()`, `importKey()`, `exportKey()` and `generateKey()`. Workers adds two non-standard helpers: `crypto.subtle.timingSafeEqual(a, b)` and `crypto.DigestStream`, a writable stream that hashes data as it flows. An HMAC is a keyed hash: both sides share a secret, the sender computes `HMAC(secret, message)`, and the receiver recomputes it. Anyone without the secret can neither forge a valid MAC nor learn the secret from one. It authenticates the message; it does not encrypt it. ## Signing outgoing requests 1. Store the shared secret as an encrypted Worker secret, never as a plaintext var or in code, and read it from `env`. 2. Import it: `crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"])`. `false` makes the key non-extractable, so no code path can export it. 3. Build a **canonical string** both sides can rebuild byte for byte, such as `timestamp`, method, path and query separated by newlines. Include a hash of the body when the origin must trust the payload. 4. `await crypto.subtle.sign("HMAC", key, encoded)` returns an `ArrayBuffer`; encode it as hex or base64 and send it with the timestamp in headers. 5. Use `headers.set()` on a header set you built, so a client cannot inject its own signature header. ## Verifying incoming webhooks - **Read the raw body once.** The MAC covers bytes, so verify the body as received, before `JSON.parse`. A body is a one-use stream; read it with `text()` or `arrayBuffer()` and work from that value. - **Let `verify()` compare.** `crypto.subtle.verify("HMAC", key, receivedMacBytes, data)` recomputes and compares inside the runtime and returns a boolean. The Workers signing example uses it precisely because a string comparison can bail out at the first differing character and leak, through timing, how much of a forged MAC was right. - **Reject malformed input early.** Decode the header strictly (even-length hex, or valid base64) and treat a decode failure as invalid. - **Bound replay.** Check the signed timestamp against a short window and reject anything older. | Need | Use | Watch out for | |---|---|---| | Check an HMAC | `crypto.subtle.verify()` | decode the MAC to bytes first | | Compare two secrets, such as API tokens | `crypto.subtle.timingSafeEqual()` | throws `TypeError` if byte lengths differ | | Hash a large body | `crypto.DigestStream` with `tee()` | await its `digest` promise | `timingSafeEqual()` requires equal byte lengths and otherwise throws `TypeError: Input buffers must have the same byte length.` Returning early on a length mismatch would leak the secret's length, so the documentation's Basic Auth example compares the input against itself and negates the result when lengths differ. ## The redirect trap A `fetch()` subrequest defaults to `redirect: "follow"`, and the runtime then forwards your headers to the redirect target, even on another host: cookies and custom headers such as your signature go along. Only `Authorization` is dropped on a cross-origin redirect, for compatibility dates from 2025-09-01 on (the `strip_authorization_on_cross_origin_redirect` flag, undone by `retain_authorization_on_cross_origin_redirect`). A signed request should use `redirect: "manual"`, so a `3xx` comes back to your code to inspect. Requests proxied from the client already default to `manual`; the risk is in requests your Worker creates. ## Choosing Web Crypto over Node's crypto module With Node.js compatibility enabled, Workers also offers `node:crypto` for libraries that need it. New Worker code that only needs HMAC, hashing or random values is simplest on `crypto.subtle`, which needs no flag and is the same API in browsers. ## A review checklist 1. Is the key material a secret, imported with `extractable` set to `false`? 2. Does the signed string cover everything the receiver acts on: method, path, query, timestamp and, where it matters, the body? 3. Is every comparison done by `verify()` or `timingSafeEqual()`, with the length case handled? 4. Is the timestamp window enforced on the receiving side? 5. Do signed subrequests use `redirect: "manual"`? 6. Are client-supplied headers with the same names overwritten rather than forwarded?
- Why mark the imported HMAC key non-extractable?Passing `false` as the `extractable` argument of `importKey()` means `exportKey()` refuses to return the raw bytes. Code that later handles the `CryptoKey`, including a dependency or a logging helper, cannot leak the secret through it. The secret still exists in `env`, so keep that variable's use to the one import.
- The origin returns 302 to a host you do not control. What does your Worker do with redirect: 'manual'?`fetch()` returns the `302` response itself instead of following it, with the target in the `Location` header. Your code decides: follow only to an allow-listed host, re-signing for that request, or pass the redirect back to the client. With the default `follow`, the runtime would have sent the signature header to the new host; only `Authorization` is dropped cross-origin.
- How do you compare an API token from a header with the expected token safely?Encode both with `TextEncoder` and call `crypto.subtle.timingSafeEqual(a, b)`. It throws a `TypeError` when byte lengths differ, so check lengths first and, on a mismatch, compare the input with itself and return the negation. That keeps timing independent of where the strings differ.
- Comparing the computed and received HMAC hex strings with === is fine.
- crypto.subtle.timingSafeEqual() returns false when the inputs differ in length.
- HMAC-SHA256 encrypts the request so the origin's traffic stays private.
- fetch() strips custom headers when it follows a redirect to another host.
- Parse the webhook JSON first, then verify the signature of the re-serialised object.