@hookieai/node 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/README.md +161 -2
- package/admin.d.ts +159 -0
- package/admin.mjs +179 -0
- package/errors.d.ts +50 -0
- package/errors.mjs +113 -0
- package/express.d.ts +8 -0
- package/express.mjs +17 -0
- package/hono.d.ts +6 -0
- package/hono.mjs +6 -0
- package/http.mjs +103 -0
- package/index.d.ts +26 -0
- package/index.mjs +41 -0
- package/ingest.d.ts +58 -0
- package/ingest.mjs +112 -0
- package/next.d.ts +6 -0
- package/next.mjs +1 -0
- package/package.json +85 -4
- package/receiver.d.ts +10 -0
- package/receiver.mjs +66 -0
- package/verify.d.ts +57 -0
- package/verify.mjs +309 -0
package/receiver.mjs
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Shared by the three JSON webhook route handlers. Keep framework packages
|
|
2
|
+
// out of the runtime and keep all authentication decisions in verifyWebhook.
|
|
3
|
+
import { safeVerifyWebhook } from "./verify.mjs";
|
|
4
|
+
|
|
5
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
6
|
+
|
|
7
|
+
export function createReceiver(secret, onEvent, options = {}) {
|
|
8
|
+
const { maxBodyBytes = 1024 * 1024, scheme = "standard", ...verifyOptions } = options;
|
|
9
|
+
if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) throw new TypeError("maxBodyBytes must be a positive safe integer.");
|
|
10
|
+
if (typeof onEvent !== "function") throw new TypeError("onEvent must be a function.");
|
|
11
|
+
|
|
12
|
+
async function receive(bytes, headers) {
|
|
13
|
+
if (bytes.byteLength > maxBodyBytes) return 413;
|
|
14
|
+
const verified = await safeVerifyWebhook(bytes, headers, secret, { ...verifyOptions, scheme });
|
|
15
|
+
if (!verified.ok) return 401;
|
|
16
|
+
|
|
17
|
+
let event;
|
|
18
|
+
try {
|
|
19
|
+
event = JSON.parse(decoder.decode(bytes));
|
|
20
|
+
} catch {
|
|
21
|
+
return 400;
|
|
22
|
+
}
|
|
23
|
+
await onEvent(event, verified);
|
|
24
|
+
return 204;
|
|
25
|
+
}
|
|
26
|
+
return { maxBodyBytes, receive };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Do not trust Content-Length: a chunked request can exceed it or omit it.
|
|
30
|
+
async function readBody(request, maxBytes) {
|
|
31
|
+
if (request.bodyUsed) throw new TypeError("The webhook handler needs an unread request body.");
|
|
32
|
+
if (!request.body) return new Uint8Array();
|
|
33
|
+
const reader = request.body.getReader();
|
|
34
|
+
const chunks = [];
|
|
35
|
+
let length = 0;
|
|
36
|
+
try {
|
|
37
|
+
for (;;) {
|
|
38
|
+
const { done, value } = await reader.read();
|
|
39
|
+
if (done) break;
|
|
40
|
+
length += value.byteLength;
|
|
41
|
+
if (length > maxBytes) {
|
|
42
|
+
void reader.cancel().catch(() => {});
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
if (value.byteLength) chunks.push(value);
|
|
46
|
+
}
|
|
47
|
+
} finally {
|
|
48
|
+
reader.releaseLock();
|
|
49
|
+
}
|
|
50
|
+
const body = new Uint8Array(length);
|
|
51
|
+
let offset = 0;
|
|
52
|
+
for (const chunk of chunks) {
|
|
53
|
+
body.set(chunk, offset);
|
|
54
|
+
offset += chunk.byteLength;
|
|
55
|
+
}
|
|
56
|
+
return body;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function createFetchHandler(secret, onEvent, options) {
|
|
60
|
+
const { maxBodyBytes, receive } = createReceiver(secret, onEvent, options);
|
|
61
|
+
return async request => {
|
|
62
|
+
const bytes = await readBody(request, maxBodyBytes);
|
|
63
|
+
const status = bytes === null ? 413 : await receive(bytes, request.headers);
|
|
64
|
+
return new Response(null, { status });
|
|
65
|
+
};
|
|
66
|
+
}
|
package/verify.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { HookieSignatureError } from "./errors.js";
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_TOLERANCE_SECONDS: 300;
|
|
4
|
+
|
|
5
|
+
export interface ReplayStore {
|
|
6
|
+
/** Has this opaque authenticated replay key been accepted already? */
|
|
7
|
+
has(id: string): boolean | Promise<boolean>;
|
|
8
|
+
/** Remember it for `ttlSeconds`. */
|
|
9
|
+
add(id: string, ttlSeconds: number): void | Promise<void>;
|
|
10
|
+
/** Atomically remember an unseen key for `ttlSeconds`; true only for the first claimant. Required for safety across processes/isolates. Without it, has/add are serialized only within this SDK instance and store object. */
|
|
11
|
+
claim?(id: string, ttlSeconds: number): boolean | Promise<boolean>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface VerifyOptions {
|
|
15
|
+
/** Which signature to check. Default "auto": Standard Webhooks when its headers are present, else Hookie-Signature (and the other if the first fails). */
|
|
16
|
+
scheme?: "auto" | "standard" | "hookie";
|
|
17
|
+
/** Accept a timestamp this far from now, either side. Default 300. Infinity switches the check off (do not, without a replay store). */
|
|
18
|
+
toleranceSeconds?: number;
|
|
19
|
+
/** Unix seconds; for tests. Default: now. */
|
|
20
|
+
now?: number;
|
|
21
|
+
/** Refuse a signed delivery id (Standard Webhooks) or signed content fingerprint (Hookie) seen before. */
|
|
22
|
+
replayStore?: ReplayStore;
|
|
23
|
+
/** "auto" (default) claims the replay key as soon as the signature verifies; "manual" leaves it to `result.commitReplay()` after your handler succeeds. Manual verification does not reserve a key: use transactional business deduplication if concurrent processing must be prevented. */
|
|
24
|
+
commitReplay?: "auto" | "manual";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface VerifiedWebhook {
|
|
28
|
+
scheme: "standard" | "hookie";
|
|
29
|
+
/** webhook-id is signed in Standard Webhooks mode. Hookie-Delivery-Id is unsigned metadata; never use it for security decisions. */
|
|
30
|
+
id: string;
|
|
31
|
+
/** The signed unix timestamp. */
|
|
32
|
+
timestamp: number;
|
|
33
|
+
/** Hookie-Event-Id is unsigned metadata. Use authenticated body data for business deduplication. */
|
|
34
|
+
eventId?: string;
|
|
35
|
+
/** Atomically claims the key, rejecting with reason `replayed` if another request claimed it. Repeated calls on this result share the same promise. */
|
|
36
|
+
commitReplay(): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type Headerish = Headers | { get(name: string): string | null } | Record<string, string | string[] | undefined>;
|
|
40
|
+
|
|
41
|
+
/** Verify a received webhook against the RAW body. Throws HookieSignatureError. */
|
|
42
|
+
export function verifyWebhook(payload: string | Uint8Array | ArrayBuffer, headers: Headerish, secret: string | readonly string[], opts?: VerifyOptions): Promise<VerifiedWebhook>;
|
|
43
|
+
|
|
44
|
+
export function safeVerifyWebhook(
|
|
45
|
+
payload: string | Uint8Array | ArrayBuffer,
|
|
46
|
+
headers: Headerish,
|
|
47
|
+
secret: string | readonly string[],
|
|
48
|
+
opts?: VerifyOptions
|
|
49
|
+
): Promise<({ ok: true } & VerifiedWebhook) | { ok: false; error: HookieSignatureError }>;
|
|
50
|
+
|
|
51
|
+
export function createMemoryReplayStore(opts?: { max?: number; now?: () => number }): ReplayStore & { claim(id: string, ttlSeconds: number): boolean; readonly size: number };
|
|
52
|
+
|
|
53
|
+
/** `t=<unix>,v1=<hex>`: the X-Hookie-Signature value for a body. */
|
|
54
|
+
export function signHookieBody(secret: string, body: string | Uint8Array | ArrayBuffer, unixSeconds?: number): Promise<string>;
|
|
55
|
+
|
|
56
|
+
/** The HMAC key Standard Webhooks derives from a secret, or null if it is not valid base64. */
|
|
57
|
+
export function standardWebhooksKey(secret: string): Uint8Array | null;
|
package/verify.mjs
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// @hookieai/node/verify: check a webhook Hookie sent you (#471).
|
|
2
|
+
//
|
|
3
|
+
// Hookie signs every delivery twice over one timestamp (apps/api/src/outbound.ts):
|
|
4
|
+
//
|
|
5
|
+
// Hookie-Signature: t=<unix>,v1=<hex>[,v1=<hex>]
|
|
6
|
+
// HMAC-SHA256 over `${t}.${body}`, key = the UTF-8 bytes of the WHOLE
|
|
7
|
+
// `whsec_...` secret string. A second v1 is present for a day after a
|
|
8
|
+
// secret rotation (signed with the previous secret).
|
|
9
|
+
// webhook-id / webhook-timestamp / webhook-signature (Standard Webhooks)
|
|
10
|
+
// `v1,<base64>` (space-separated when rotating), HMAC-SHA256 over
|
|
11
|
+
// `${id}.${timestamp}.${body}`, key = the base64-DECODED bytes after
|
|
12
|
+
// `whsec_`. A different key from the same secret, as that spec says.
|
|
13
|
+
//
|
|
14
|
+
// Pure WebCrypto (crypto.subtle): Node 22+, Workers, Deno and Bun. Comparison is
|
|
15
|
+
// crypto.subtle.verify, which is constant time, and every candidate signature is
|
|
16
|
+
// checked whether or not an earlier one matched. `payload` MUST be the raw body
|
|
17
|
+
// exactly as received: a parsed-and-reserialised body will not verify.
|
|
18
|
+
|
|
19
|
+
import { HookieSignatureError } from "./errors.mjs";
|
|
20
|
+
|
|
21
|
+
export const DEFAULT_TOLERANCE_SECONDS = 300;
|
|
22
|
+
|
|
23
|
+
const enc = new TextEncoder();
|
|
24
|
+
|
|
25
|
+
// Older stores expose separate reads/writes. Serialize those operations for
|
|
26
|
+
// each replay key within this SDK instance. Distributed stores must implement
|
|
27
|
+
// claim() atomically at the storage layer; a local lock cannot coordinate hosts.
|
|
28
|
+
const replayLocks = new WeakMap();
|
|
29
|
+
async function claimReplay(store, id, ttl) {
|
|
30
|
+
if (typeof store.claim === "function") return (await store.claim(id, ttl)) === true;
|
|
31
|
+
let locks = replayLocks.get(store);
|
|
32
|
+
if (!locks) replayLocks.set(store, (locks = new Map()));
|
|
33
|
+
const previous = locks.get(id);
|
|
34
|
+
let release;
|
|
35
|
+
const current = new Promise((resolve) => { release = resolve; });
|
|
36
|
+
locks.set(id, current);
|
|
37
|
+
try {
|
|
38
|
+
await previous;
|
|
39
|
+
if (await store.has(id)) return false;
|
|
40
|
+
await store.add(id, ttl);
|
|
41
|
+
return true;
|
|
42
|
+
} finally {
|
|
43
|
+
release();
|
|
44
|
+
if (locks.get(id) === current) locks.delete(id);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function header(headers, name) {
|
|
49
|
+
if (!headers) return null;
|
|
50
|
+
if (typeof headers.get === "function") return headers.get(name);
|
|
51
|
+
const lower = name.toLowerCase();
|
|
52
|
+
for (const k of Object.keys(headers)) {
|
|
53
|
+
if (k.toLowerCase() === lower) {
|
|
54
|
+
const v = headers[k];
|
|
55
|
+
return Array.isArray(v) ? v.join(",") : v == null ? null : String(v);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function payloadBytes(payload) {
|
|
62
|
+
if (typeof payload === "string") return enc.encode(payload);
|
|
63
|
+
if (payload instanceof Uint8Array) return payload;
|
|
64
|
+
if (payload instanceof ArrayBuffer) return new Uint8Array(payload);
|
|
65
|
+
throw new TypeError("payload must be the raw request body: a string, Uint8Array or ArrayBuffer (not a parsed object).");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function concat(...parts) {
|
|
69
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
70
|
+
let o = 0;
|
|
71
|
+
for (const p of parts) {
|
|
72
|
+
out.set(p, o);
|
|
73
|
+
o += p.length;
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function hexToBytes(hex) {
|
|
79
|
+
if (hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) return null;
|
|
80
|
+
const out = new Uint8Array(hex.length / 2);
|
|
81
|
+
for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Strict standard-alphabet base64, as Standard Webhooks libraries and Hookie's signer both require. */
|
|
86
|
+
function b64ToBytes(b64) {
|
|
87
|
+
if (!b64 || b64.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(b64)) return null;
|
|
88
|
+
const bin = atob(b64);
|
|
89
|
+
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The HMAC key Standard Webhooks derives from a secret, or null if it is not valid base64. */
|
|
93
|
+
export function standardWebhooksKey(secret) {
|
|
94
|
+
const raw = b64ToBytes(secret.startsWith("whsec_") ? secret.slice(6) : secret);
|
|
95
|
+
return raw && raw.length ? raw : null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const hmacKey = (raw, usage) => crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, [usage]);
|
|
99
|
+
|
|
100
|
+
/** Does any (key, signature) pair verify? Every pair is checked; there is no early exit. */
|
|
101
|
+
async function anyMatch(keys, signatures, data) {
|
|
102
|
+
let ok = false;
|
|
103
|
+
let matched = null;
|
|
104
|
+
for (const key of keys) {
|
|
105
|
+
for (const sig of signatures) {
|
|
106
|
+
if (sig.length !== 32) continue;
|
|
107
|
+
const good = await crypto.subtle.verify("HMAC", key, sig, data);
|
|
108
|
+
if (good && !ok) matched = sig;
|
|
109
|
+
ok = good || ok;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return ok ? matched : null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function checkTimestamp(tsText, now, tolerance) {
|
|
116
|
+
if (!/^\d{1,12}$/.test(tsText ?? "")) throw new HookieSignatureError("bad_timestamp", "The signature timestamp is not a unix time in seconds.");
|
|
117
|
+
const ts = Number(tsText);
|
|
118
|
+
if (tolerance !== Infinity) {
|
|
119
|
+
if (now - ts > tolerance) throw new HookieSignatureError("timestamp_too_old", `The signature is more than ${tolerance} seconds old: possible replay, or a clock out of step.`);
|
|
120
|
+
if (ts - now > tolerance) throw new HookieSignatureError("timestamp_too_new", `The signature timestamp is more than ${tolerance} seconds in the future.`);
|
|
121
|
+
}
|
|
122
|
+
return ts;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Verify one received webhook. Returns what was proven; throws HookieSignatureError otherwise.
|
|
127
|
+
* @param {string | Uint8Array | ArrayBuffer} payload the RAW body
|
|
128
|
+
* @param {Headers | Record<string, string | string[] | undefined>} headers
|
|
129
|
+
* @param {string | string[]} secret `whsec_...`; pass the current and previous secret while you rotate
|
|
130
|
+
* @param {import("./verify.d.ts").VerifyOptions} [opts]
|
|
131
|
+
*/
|
|
132
|
+
export async function verifyWebhook(payload, headers, secret, opts = {}) {
|
|
133
|
+
const secrets = (Array.isArray(secret) ? secret : [secret]).filter((s) => typeof s === "string" && s.length > 0);
|
|
134
|
+
if (!secrets.length) throw new HookieSignatureError("bad_secret", "No signing secret was given.");
|
|
135
|
+
const tolerance = opts.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
|
|
136
|
+
if (!(tolerance > 0)) throw new TypeError("toleranceSeconds must be a positive number (or Infinity to switch the check off).");
|
|
137
|
+
const now = opts.now ?? Math.floor(Date.now() / 1000);
|
|
138
|
+
const body = payloadBytes(payload);
|
|
139
|
+
const scheme = opts.scheme ?? "auto";
|
|
140
|
+
|
|
141
|
+
const stdId = header(headers, "webhook-id");
|
|
142
|
+
const stdTs = header(headers, "webhook-timestamp");
|
|
143
|
+
const stdSig = header(headers, "webhook-signature");
|
|
144
|
+
const hookieSig = header(headers, "Hookie-Signature");
|
|
145
|
+
const haveStd = Boolean(stdId && stdTs && stdSig);
|
|
146
|
+
const wantStd = scheme === "standard" || (scheme === "auto" && haveStd);
|
|
147
|
+
const wantHookie = scheme === "hookie" || (scheme === "auto" && Boolean(hookieSig));
|
|
148
|
+
if ((scheme === "standard" && !haveStd) || (scheme === "hookie" && !hookieSig) || (!wantStd && !wantHookie)) {
|
|
149
|
+
throw new HookieSignatureError("missing_headers", "The request carries no Hookie-Signature or complete webhook-id / webhook-timestamp / webhook-signature headers.");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let failure = null;
|
|
153
|
+
/** @type {{ scheme: "standard" | "hookie", id: string, timestamp: number, sig: Uint8Array } | null} */
|
|
154
|
+
let proven = null;
|
|
155
|
+
|
|
156
|
+
if (wantStd) {
|
|
157
|
+
try {
|
|
158
|
+
const ts = checkTimestamp(stdTs, now, tolerance);
|
|
159
|
+
const keys = [];
|
|
160
|
+
for (const s of secrets) {
|
|
161
|
+
const raw = standardWebhooksKey(s);
|
|
162
|
+
if (raw) keys.push(await hmacKey(raw, "verify"));
|
|
163
|
+
}
|
|
164
|
+
if (!keys.length) throw new HookieSignatureError("bad_secret", "None of the secrets is a valid base64 Standard Webhooks secret (whsec_ + base64).");
|
|
165
|
+
const sigs = [];
|
|
166
|
+
for (const part of stdSig.split(" ")) {
|
|
167
|
+
const [version, value] = part.split(",");
|
|
168
|
+
const bytes = version === "v1" && value ? b64ToBytes(value) : null;
|
|
169
|
+
if (bytes) sigs.push(bytes);
|
|
170
|
+
}
|
|
171
|
+
if (!sigs.length) throw new HookieSignatureError("malformed_signature", "webhook-signature has no v1 signature.");
|
|
172
|
+
const matched = await anyMatch(keys, sigs, concat(enc.encode(`${stdId}.${stdTs}.`), body));
|
|
173
|
+
if (matched) proven = { scheme: "standard", id: stdId, timestamp: ts, sig: matched };
|
|
174
|
+
else failure = new HookieSignatureError("no_valid_signature", "No webhook-signature matches this body and secret.");
|
|
175
|
+
} catch (err) {
|
|
176
|
+
if (!(err instanceof HookieSignatureError)) throw err;
|
|
177
|
+
failure = err;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (!proven && wantHookie) {
|
|
182
|
+
try {
|
|
183
|
+
let t = null;
|
|
184
|
+
const candidates = [];
|
|
185
|
+
for (const part of hookieSig.split(",")) {
|
|
186
|
+
const eq = part.indexOf("=");
|
|
187
|
+
if (eq < 1) continue;
|
|
188
|
+
const k = part.slice(0, eq).trim();
|
|
189
|
+
const v = part.slice(eq + 1).trim();
|
|
190
|
+
if (k === "t" && t === null) t = v;
|
|
191
|
+
else if (k === "v1") {
|
|
192
|
+
const bytes = hexToBytes(v);
|
|
193
|
+
if (bytes) candidates.push(bytes);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (t === null || !candidates.length) throw new HookieSignatureError("malformed_signature", "Hookie-Signature must look like t=<unix>,v1=<hex>.");
|
|
197
|
+
const ts = checkTimestamp(t, now, tolerance);
|
|
198
|
+
const keys = await Promise.all(secrets.map((s) => hmacKey(enc.encode(s), "verify")));
|
|
199
|
+
const matched = await anyMatch(keys, candidates, concat(enc.encode(`${t}.`), body));
|
|
200
|
+
if (matched) proven = { scheme: "hookie", id: header(headers, "Hookie-Delivery-Id") ?? toHex(matched), timestamp: ts, sig: matched };
|
|
201
|
+
else throw new HookieSignatureError("no_valid_signature", "No Hookie-Signature v1 matches this body and secret.");
|
|
202
|
+
} catch (err) {
|
|
203
|
+
if (!(err instanceof HookieSignatureError)) throw err;
|
|
204
|
+
failure ??= err;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (!proven) throw failure ?? new HookieSignatureError("no_valid_signature", "The signature did not verify.");
|
|
209
|
+
|
|
210
|
+
const result = {
|
|
211
|
+
scheme: proven.scheme,
|
|
212
|
+
/** Delivery metadata. Only Standard Webhooks signs its id; Hookie-Delivery-Id is unsigned. */
|
|
213
|
+
id: proven.id,
|
|
214
|
+
timestamp: proven.timestamp,
|
|
215
|
+
/** `Hookie-Event-Id` is unsigned metadata, not an authenticated deduplication key. */
|
|
216
|
+
eventId: header(headers, "Hookie-Event-Id") ?? undefined,
|
|
217
|
+
commitReplay: async () => {},
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
const store = opts.replayStore;
|
|
221
|
+
if (store) {
|
|
222
|
+
// Hookie-Signature authenticates only timestamp + body. Its delivery-id
|
|
223
|
+
// header is unsigned and must never control replay protection. Hash the
|
|
224
|
+
// signed content so rotating keys and reordered signatures share one key.
|
|
225
|
+
const replayId = proven.scheme === "hookie"
|
|
226
|
+
? `hookie:${toHex(new Uint8Array(await crypto.subtle.digest("SHA-256", concat(enc.encode(`${proven.timestamp}.`), body))))}`
|
|
227
|
+
: `standard:${proven.id}`;
|
|
228
|
+
const ttl = tolerance === Infinity ? 24 * 3600 : tolerance * 2;
|
|
229
|
+
const replayed = () => new HookieSignatureError("replayed", "This signed webhook was already accepted.");
|
|
230
|
+
let commitment;
|
|
231
|
+
result.commitReplay = () => (commitment ??= (async () => {
|
|
232
|
+
if (!(await claimReplay(store, replayId, ttl))) throw replayed();
|
|
233
|
+
})());
|
|
234
|
+
// Only a request that VERIFIED is remembered, so a forger cannot fill the store.
|
|
235
|
+
if ((opts.commitReplay ?? "auto") === "auto") await result.commitReplay();
|
|
236
|
+
else if (await store.has(replayId)) throw replayed();
|
|
237
|
+
}
|
|
238
|
+
return result;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Like verifyWebhook, but answers `{ ok: false, error }` instead of throwing a signature failure. */
|
|
242
|
+
export async function safeVerifyWebhook(payload, headers, secret, opts) {
|
|
243
|
+
try {
|
|
244
|
+
return { ok: true, ...(await verifyWebhook(payload, headers, secret, opts)) };
|
|
245
|
+
} catch (error) {
|
|
246
|
+
if (error instanceof HookieSignatureError) return { ok: false, error };
|
|
247
|
+
throw error;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function toHex(bytes) {
|
|
252
|
+
return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* An in-memory replay store for ONE process or isolate: bounded, expiring.
|
|
257
|
+
* Behind several instances (Workers, serverless), use a store with an atomic
|
|
258
|
+
* claim, such as a Durable Object, Redis SET NX or a database unique insert.
|
|
259
|
+
* @param {{ max?: number, now?: () => number }} [opts]
|
|
260
|
+
*/
|
|
261
|
+
export function createMemoryReplayStore(opts = {}) {
|
|
262
|
+
const max = opts.max ?? 10_000;
|
|
263
|
+
if (!Number.isSafeInteger(max) || max < 1) throw new TypeError("max must be a positive safe integer.");
|
|
264
|
+
const clock = opts.now ?? (() => Date.now());
|
|
265
|
+
const seen = new Map();
|
|
266
|
+
const sweep = () => {
|
|
267
|
+
const t = clock();
|
|
268
|
+
for (const [id, exp] of seen) if (exp <= t) seen.delete(id);
|
|
269
|
+
while (seen.size > max) seen.delete(seen.keys().next().value);
|
|
270
|
+
};
|
|
271
|
+
return {
|
|
272
|
+
has(id) {
|
|
273
|
+
const exp = seen.get(id);
|
|
274
|
+
if (exp === undefined) return false;
|
|
275
|
+
if (exp <= clock()) {
|
|
276
|
+
seen.delete(id);
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
return true;
|
|
280
|
+
},
|
|
281
|
+
add(id, ttlSeconds) {
|
|
282
|
+
seen.set(id, clock() + ttlSeconds * 1000);
|
|
283
|
+
sweep();
|
|
284
|
+
},
|
|
285
|
+
claim(id, ttlSeconds) {
|
|
286
|
+
const now = clock();
|
|
287
|
+
const exp = seen.get(id);
|
|
288
|
+
if (exp !== undefined && exp > now) return false;
|
|
289
|
+
seen.set(id, now + ttlSeconds * 1000);
|
|
290
|
+
sweep();
|
|
291
|
+
return true;
|
|
292
|
+
},
|
|
293
|
+
get size() {
|
|
294
|
+
return seen.size;
|
|
295
|
+
},
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Sign a body the way Hookie's inbound `X-Hookie-Signature` check expects:
|
|
301
|
+
* `t=<unix>,v1=<hex hmac-sha256 of "<t>.<body>">` (same grammar as Hookie-Signature).
|
|
302
|
+
* Used by the ingest client for an ingest key that requires signed requests, and
|
|
303
|
+
* handy for testing a receiver.
|
|
304
|
+
*/
|
|
305
|
+
export async function signHookieBody(secret, body, unixSeconds = Math.floor(Date.now() / 1000)) {
|
|
306
|
+
const key = await hmacKey(enc.encode(secret), "sign");
|
|
307
|
+
const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, concat(enc.encode(`${unixSeconds}.`), payloadBytes(body))));
|
|
308
|
+
return `t=${unixSeconds},v1=${toHex(sig)}`;
|
|
309
|
+
}
|