@aarivbuildz/hookverify 0.0.0-stage → 1.0.1

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.
@@ -0,0 +1,916 @@
1
+ 'use strict';
2
+
3
+ // hookverify: zero-dependency webhook signature verification engine.
4
+ // One implementation shared by the ESM and CommonJS public surfaces.
5
+
6
+ const crypto = require('node:crypto');
7
+
8
+ const ERROR_CODES = Object.freeze({
9
+ INVALID_ARGUMENT: 'INVALID_ARGUMENT',
10
+ INVALID_BODY: 'INVALID_BODY',
11
+ MISSING_HEADER: 'MISSING_HEADER',
12
+ INVALID_HEADER: 'INVALID_HEADER',
13
+ INVALID_SECRET: 'INVALID_SECRET',
14
+ INVALID_SIGNATURE: 'INVALID_SIGNATURE',
15
+ SIGNATURE_MISMATCH: 'SIGNATURE_MISMATCH',
16
+ TIMESTAMP_MISSING: 'TIMESTAMP_MISSING',
17
+ TIMESTAMP_INVALID: 'TIMESTAMP_INVALID',
18
+ TIMESTAMP_OUT_OF_TOLERANCE: 'TIMESTAMP_OUT_OF_TOLERANCE',
19
+ REPLAYED_DELIVERY: 'REPLAYED_DELIVERY',
20
+ UNKNOWN_PROVIDER: 'UNKNOWN_PROVIDER',
21
+ PROVIDER_ERROR: 'PROVIDER_ERROR',
22
+ });
23
+
24
+ class HookVerifyError extends Error {
25
+ constructor(code, message, details) {
26
+ super(message);
27
+ this.name = 'HookVerifyError';
28
+ this.code = code;
29
+ if (details !== undefined) this.details = details;
30
+ if (typeof Error.captureStackTrace === 'function') {
31
+ Error.captureStackTrace(this, HookVerifyError);
32
+ }
33
+ }
34
+
35
+ toJSON() {
36
+ const out = { name: this.name, code: this.code, message: this.message };
37
+ if (this.details !== undefined) out.details = this.details;
38
+ return out;
39
+ }
40
+ }
41
+
42
+ function fail(code, message, details) {
43
+ throw new HookVerifyError(code, message, details);
44
+ }
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // Strict encoding and constant-time comparison
48
+ // ---------------------------------------------------------------------------
49
+
50
+ const HEX_RE = /^(?:[0-9a-fA-F]{2})+$/;
51
+ const BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
52
+ const TIMESTAMP_RE = /^(?:0|[1-9][0-9]{0,11})$/;
53
+
54
+ function decodeHex(value, label = 'signature') {
55
+ if (typeof value !== 'string' || value.length === 0 || value.length % 2 !== 0 || !HEX_RE.test(value)) {
56
+ fail('INVALID_SIGNATURE', `${label} must be an even-length, non-empty hex string`);
57
+ }
58
+ return Buffer.from(value, 'hex');
59
+ }
60
+
61
+ function decodeBase64(value, label = 'signature') {
62
+ if (typeof value !== 'string' || value.length === 0 || value.length % 4 !== 0 || !BASE64_RE.test(value)) {
63
+ fail('INVALID_SIGNATURE', `${label} must be canonical padded base64`);
64
+ }
65
+ const decoded = Buffer.from(value, 'base64');
66
+ if (decoded.length === 0 || decoded.toString('base64') !== value) {
67
+ fail('INVALID_SIGNATURE', `${label} is not canonical base64 (bad padding or non-zero pad bits)`);
68
+ }
69
+ return decoded;
70
+ }
71
+
72
+ function decodeHexOfLength(value, bytes, label) {
73
+ const decoded = decodeHex(value, label);
74
+ if (decoded.length !== bytes) {
75
+ fail('INVALID_SIGNATURE', `${label} must decode to exactly ${bytes} bytes`);
76
+ }
77
+ return decoded;
78
+ }
79
+
80
+ // Both operands are always passed to timingSafeEqual when non-empty. A length
81
+ // mismatch is reported only after the comparison, and never by throwing from
82
+ // timingSafeEqual itself.
83
+ function constantTimeEqual(a, b) {
84
+ if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
85
+ fail('INVALID_ARGUMENT', 'constantTimeEqual expects two Buffers');
86
+ }
87
+ if (a.length === 0 || b.length === 0) return a.length === b.length;
88
+ const other = a.length === b.length ? b : Buffer.alloc(a.length);
89
+ const equal = crypto.timingSafeEqual(a, other);
90
+ return a.length === b.length && equal;
91
+ }
92
+
93
+ function hmac(secret, payload, algorithm = 'sha256') {
94
+ return crypto.createHmac(algorithm, secret).update(payload).digest();
95
+ }
96
+
97
+ function deliveryKey(provider, identifier) {
98
+ const digest = crypto.createHash('sha256').update(String(identifier), 'utf8').digest('hex');
99
+ return `${provider}:${digest}`;
100
+ }
101
+
102
+ function signatureKey(provider, secretIndex, signature) {
103
+ const hash = crypto.createHash('sha256')
104
+ .update(provider, 'utf8')
105
+ .update('\0', 'utf8')
106
+ .update(String(secretIndex), 'utf8')
107
+ .update('\0', 'utf8')
108
+ .update(signature);
109
+ return `${provider}:${hash.digest('hex')}`;
110
+ }
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // Raw body and header normalization
114
+ // ---------------------------------------------------------------------------
115
+
116
+ function normalizeBody(body) {
117
+ if (Buffer.isBuffer(body)) return body;
118
+ if (body instanceof Uint8Array) return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
119
+ if (typeof body === 'string') return Buffer.from(body, 'utf8');
120
+ fail('INVALID_BODY', 'Raw body must be a Buffer, Uint8Array, or string. Pass the exact bytes received; never pass parsed JSON.');
121
+ }
122
+
123
+ function addHeader(target, key, value, arrayKeys) {
124
+ if (typeof key !== 'string') fail('INVALID_ARGUMENT', 'Header names must be strings');
125
+ const normalized = key.toLowerCase();
126
+ let list = target.get(normalized);
127
+ if (!list) {
128
+ list = [];
129
+ target.set(normalized, list);
130
+ }
131
+ const isArray = Array.isArray(value);
132
+ if (isArray) arrayKeys.add(normalized);
133
+ const values = isArray ? value : [value];
134
+ for (const item of values) {
135
+ if (item === null || item === undefined) {
136
+ list.push(null);
137
+ } else if (typeof item === 'string') {
138
+ list.push(item);
139
+ } else {
140
+ fail('INVALID_HEADER', `Header "${normalized}" has a non-string value`);
141
+ }
142
+ }
143
+ }
144
+
145
+ function normalizeHeaders(headers) {
146
+ const out = new Map();
147
+ const arrayKeys = new Set();
148
+ if (headers instanceof Map) {
149
+ headers.forEach((value, key) => addHeader(out, key, value, arrayKeys));
150
+ } else if (headers && typeof headers.get === 'function' && typeof headers.forEach === 'function') {
151
+ headers.forEach((value, key) => addHeader(out, key, value, arrayKeys));
152
+ } else if (headers && typeof headers === 'object') {
153
+ for (const key of Object.keys(headers)) addHeader(out, key, headers[key], arrayKeys);
154
+ } else {
155
+ fail('INVALID_ARGUMENT', 'headers must be an object, Map, or Headers instance');
156
+ }
157
+ return { headers: out, arrayKeys };
158
+ }
159
+
160
+ function getHeader(ctx, name) {
161
+ const key = name.toLowerCase();
162
+ const values = ctx.headers.get(key);
163
+ if (!values || values.length === 0 || values.every((value) => value === null)) {
164
+ fail('MISSING_HEADER', `Required header "${key}" is missing`, { header: key });
165
+ }
166
+ if (values.length !== 1 || values[0] === null || ctx.headerArrays.has(key)) {
167
+ fail('INVALID_HEADER', `Header "${key}" must appear exactly once as a single string value`, { header: key });
168
+ }
169
+ return values[0];
170
+ }
171
+
172
+ function getOptionalHeader(ctx, name) {
173
+ const key = name.toLowerCase();
174
+ const values = ctx.headers.get(key);
175
+ if (!values || values.length === 0 || values.every((value) => value === null)) return null;
176
+ if (values.length !== 1 || ctx.headerArrays.has(key)) {
177
+ fail('INVALID_HEADER', `Header "${key}" must appear exactly once as a single string value`, { header: key });
178
+ }
179
+ return values[0];
180
+ }
181
+
182
+ function parseTimestampSeconds(value) {
183
+ if (typeof value !== 'string' || !TIMESTAMP_RE.test(value)) {
184
+ fail('TIMESTAMP_INVALID', 'Timestamp must be a canonical positive integer number of seconds');
185
+ }
186
+ const seconds = Number(value);
187
+ if (!Number.isSafeInteger(seconds) || seconds <= 0) {
188
+ fail('TIMESTAMP_INVALID', 'Timestamp is outside the supported range');
189
+ }
190
+ return seconds * 1000;
191
+ }
192
+
193
+ function enforceTimestamp(ctx, timestampMs) {
194
+ if (typeof timestampMs !== 'number' || !Number.isFinite(timestampMs)) {
195
+ fail('TIMESTAMP_INVALID', 'Provider returned an invalid timestamp');
196
+ }
197
+ const delta = Math.abs(ctx.nowMs - timestampMs);
198
+ if (delta > ctx.toleranceSeconds * 1000) {
199
+ fail('TIMESTAMP_OUT_OF_TOLERANCE', 'Timestamp is outside the configured replay window', {
200
+ deltaSeconds: Math.floor(delta / 1000),
201
+ toleranceSeconds: ctx.toleranceSeconds,
202
+ });
203
+ }
204
+ }
205
+
206
+ // ---------------------------------------------------------------------------
207
+ // Verification helpers used by provider adapters
208
+ // ---------------------------------------------------------------------------
209
+
210
+ const MAX_SIGNATURE_CANDIDATES = 32;
211
+ const MAX_SECRETS = 32;
212
+
213
+ function assertUsableSecret(secret) {
214
+ if (typeof secret === 'string') {
215
+ if (secret.length === 0 || secret.trim().length === 0) {
216
+ fail('INVALID_SECRET', 'Secrets must be non-empty strings');
217
+ }
218
+ return;
219
+ }
220
+ if (Buffer.isBuffer(secret)) {
221
+ if (secret.length === 0) {
222
+ fail('INVALID_SECRET', 'Secret buffers must not be empty');
223
+ }
224
+ return;
225
+ }
226
+ fail('INVALID_SECRET', 'Secrets must be non-empty strings or buffers');
227
+ }
228
+
229
+ function verifyHmacWithSecrets(secrets, provided, payload) {
230
+ if (!Array.isArray(secrets)) {
231
+ fail('INVALID_ARGUMENT', 'verifyHmacWithSecrets expects an array of secrets');
232
+ }
233
+ const candidates = Array.isArray(provided) ? provided : [provided];
234
+ if (candidates.length === 0) fail('INVALID_SIGNATURE', 'No signature was supplied');
235
+ if (candidates.length > MAX_SIGNATURE_CANDIDATES) {
236
+ fail('INVALID_SIGNATURE', `Too many signature candidates (limit ${MAX_SIGNATURE_CANDIDATES})`);
237
+ }
238
+ if (secrets.length > MAX_SECRETS) {
239
+ fail('INVALID_SECRET', `Too many secrets (limit ${MAX_SECRETS})`);
240
+ }
241
+ for (const secret of secrets) assertUsableSecret(secret);
242
+ let matchedIndex = -1;
243
+ let matchedSignature = null;
244
+ // Every matching pair is reported. A rotation header can carry one valid
245
+ // signature per configured secret, and a delivery keyed only on the highest
246
+ // matching secret could be replayed by resubmitting the same header with
247
+ // that signature removed. The engine records a replay key for each pair.
248
+ const matchedSignatures = [];
249
+ for (let i = 0; i < secrets.length; i += 1) {
250
+ const expected = hmac(secrets[i], payload);
251
+ for (let j = 0; j < candidates.length; j += 1) {
252
+ if (constantTimeEqual(candidates[j], expected)) {
253
+ matchedIndex = i;
254
+ matchedSignature = candidates[j];
255
+ matchedSignatures.push({ secretIndex: i, signature: candidates[j] });
256
+ }
257
+ }
258
+ }
259
+ if (matchedIndex === -1) {
260
+ fail('SIGNATURE_MISMATCH', 'Signature does not match any configured secret');
261
+ }
262
+ // The primary replay key must bind to a candidate that actually matched.
263
+ // Binding to candidates[0] lets an attacker prepend a decoy signature to a
264
+ // captured header and obtain a fresh replay key for the same delivery.
265
+ return { secretIndex: matchedIndex, signature: matchedSignature, matchedSignatures };
266
+ }
267
+
268
+ function verifyHmac(ctx, provided, payload = ctx.body) {
269
+ return verifyHmacWithSecrets(ctx.secrets, provided, payload);
270
+ }
271
+
272
+ const helpers = Object.freeze({
273
+ decodeHex,
274
+ decodeBase64,
275
+ decodeHexOfLength,
276
+ constantTimeEqual,
277
+ hmac,
278
+ deliveryKey,
279
+ signatureKey,
280
+ getHeader,
281
+ getOptionalHeader,
282
+ parseTimestampSeconds,
283
+ verifyHmac,
284
+ verifyHmacWithSecrets,
285
+ fail,
286
+ HookVerifyError,
287
+ });
288
+
289
+ // ---------------------------------------------------------------------------
290
+ // Replay store
291
+ // ---------------------------------------------------------------------------
292
+
293
+ class MemoryReplayStore {
294
+ constructor(options = {}) {
295
+ if (options === null || typeof options !== 'object') {
296
+ fail('INVALID_ARGUMENT', 'MemoryReplayStore options must be an object');
297
+ }
298
+ const maxEntries = options.maxEntries === undefined ? 10000 : options.maxEntries;
299
+ const ttlSeconds = options.ttlSeconds === undefined ? 600 : options.ttlSeconds;
300
+ if (!Number.isSafeInteger(maxEntries) || maxEntries < 1 || maxEntries > 1000000) {
301
+ fail('INVALID_ARGUMENT', 'maxEntries must be an integer between 1 and 1000000');
302
+ }
303
+ if (!Number.isSafeInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > 31536000) {
304
+ fail('INVALID_ARGUMENT', 'ttlSeconds must be an integer between 1 and 31536000');
305
+ }
306
+ this.maxEntries = maxEntries;
307
+ this.ttlSeconds = ttlSeconds;
308
+ this._entries = new Map();
309
+ }
310
+
311
+ get size() {
312
+ return this._entries.size;
313
+ }
314
+
315
+ _now(nowMs) {
316
+ if (nowMs === undefined) return Date.now();
317
+ if (typeof nowMs !== 'number' || !Number.isFinite(nowMs)) {
318
+ fail('INVALID_ARGUMENT', 'nowMs must be a finite millisecond timestamp');
319
+ }
320
+ return nowMs;
321
+ }
322
+
323
+ checkAndRecord(key, nowMs) {
324
+ if (typeof key !== 'string' || key.length === 0) {
325
+ fail('INVALID_ARGUMENT', 'Replay key must be a non-empty string');
326
+ }
327
+ const now = this._now(nowMs);
328
+ const existing = this._entries.get(key);
329
+ if (existing !== undefined) {
330
+ if (existing > now) {
331
+ // Refresh recency so bounded eviction is a true LRU.
332
+ this._entries.delete(key);
333
+ this._entries.set(key, existing);
334
+ return false;
335
+ }
336
+ this._entries.delete(key);
337
+ }
338
+ this._evict(now);
339
+ this._entries.set(key, now + this.ttlSeconds * 1000);
340
+ return true;
341
+ }
342
+
343
+ _evict(now) {
344
+ if (this._entries.size < this.maxEntries) return;
345
+ for (const [key, expiresAt] of this._entries) {
346
+ if (expiresAt <= now) this._entries.delete(key);
347
+ }
348
+ while (this._entries.size >= this.maxEntries) {
349
+ const oldest = this._entries.keys().next().value;
350
+ if (oldest === undefined) break;
351
+ this._entries.delete(oldest);
352
+ }
353
+ }
354
+
355
+ has(key, nowMs) {
356
+ if (typeof key !== 'string') fail('INVALID_ARGUMENT', 'Replay key must be a string');
357
+ const now = this._now(nowMs);
358
+ const expiresAt = this._entries.get(key);
359
+ if (expiresAt === undefined) return false;
360
+ if (expiresAt <= now) {
361
+ this._entries.delete(key);
362
+ return false;
363
+ }
364
+ return true;
365
+ }
366
+
367
+ prune(nowMs) {
368
+ const now = this._now(nowMs);
369
+ let removed = 0;
370
+ for (const [key, expiresAt] of this._entries) {
371
+ if (expiresAt <= now) {
372
+ this._entries.delete(key);
373
+ removed += 1;
374
+ }
375
+ }
376
+ return removed;
377
+ }
378
+
379
+ clear() {
380
+ this._entries.clear();
381
+ }
382
+ }
383
+
384
+ // ---------------------------------------------------------------------------
385
+ // Provider registry
386
+ // ---------------------------------------------------------------------------
387
+
388
+ function defineProvider(definition) {
389
+ if (!definition || typeof definition !== 'object' || Array.isArray(definition)) {
390
+ fail('INVALID_ARGUMENT', 'Provider definition must be an object');
391
+ }
392
+ const { name, verify: verifyFn, description, requiredHeaders, secretOptional } = definition;
393
+ if (typeof name !== 'string' || !/^[a-z][a-z0-9-]{0,39}$/.test(name)) {
394
+ fail('INVALID_ARGUMENT', 'Provider name must be lowercase alphanumeric with dashes');
395
+ }
396
+ if (typeof verifyFn !== 'function') {
397
+ fail('INVALID_ARGUMENT', 'Provider definition requires a verify function');
398
+ }
399
+ if (requiredHeaders !== undefined && (!Array.isArray(requiredHeaders) || requiredHeaders.some((h) => typeof h !== 'string'))) {
400
+ fail('INVALID_ARGUMENT', 'requiredHeaders must be an array of strings');
401
+ }
402
+ return Object.freeze({
403
+ name,
404
+ description: typeof description === 'string' ? description : '',
405
+ requiredHeaders: Object.freeze(requiredHeaders ? [...requiredHeaders] : []),
406
+ secretOptional: secretOptional === true,
407
+ verify: verifyFn,
408
+ });
409
+ }
410
+
411
+ const registry = new Map();
412
+
413
+ function registerProvider(provider) {
414
+ if (!provider || typeof provider.verify !== 'function' || typeof provider.name !== 'string') {
415
+ fail('INVALID_ARGUMENT', 'Provider must define a name and a verify function');
416
+ }
417
+ if (registry.has(provider.name)) {
418
+ fail('INVALID_ARGUMENT', `Provider "${provider.name}" is already registered`);
419
+ }
420
+ registry.set(provider.name, provider);
421
+ return provider;
422
+ }
423
+
424
+ function resolveProvider(input) {
425
+ if (typeof input === 'string') {
426
+ const provider = registry.get(input);
427
+ if (!provider) fail('UNKNOWN_PROVIDER', `Unknown provider "${input}"`);
428
+ return provider;
429
+ }
430
+ if (input && typeof input === 'object' && typeof input.verify === 'function' && typeof input.name === 'string') {
431
+ return input;
432
+ }
433
+ fail('INVALID_ARGUMENT', 'provider must be a registered name or a provider object');
434
+ }
435
+
436
+ function listProviders() {
437
+ return Object.freeze([...registry.keys()].sort());
438
+ }
439
+
440
+ function getProvider(name) {
441
+ return resolveProvider(name);
442
+ }
443
+
444
+ // ---------------------------------------------------------------------------
445
+ // Built-in provider adapters
446
+ // ---------------------------------------------------------------------------
447
+
448
+ const github = defineProvider({
449
+ name: 'github',
450
+ description: 'GitHub X-Hub-Signature-256, sha256=<hex>',
451
+ requiredHeaders: ['x-hub-signature-256'],
452
+ verify(ctx) {
453
+ const header = getHeader(ctx, 'x-hub-signature-256');
454
+ const match = /^sha256=([0-9a-fA-F]{64})$/.exec(header);
455
+ if (!match) fail('INVALID_SIGNATURE', 'GitHub signature must be sha256=<64 hex characters>');
456
+ return verifyHmac(ctx, decodeHex(match[1], 'GitHub signature'));
457
+ },
458
+ });
459
+
460
+ const stripe = defineProvider({
461
+ name: 'stripe',
462
+ description: 'Stripe-Signature with t= and one or more v1= values',
463
+ requiredHeaders: ['stripe-signature'],
464
+ verify(ctx) {
465
+ const header = getHeader(ctx, 'stripe-signature');
466
+ let timestamp = null;
467
+ const signatures = [];
468
+ for (const part of header.split(',')) {
469
+ const token = part.trim();
470
+ if (token.length === 0) fail('INVALID_HEADER', 'Stripe-Signature contains an empty field');
471
+ const equals = token.indexOf('=');
472
+ if (equals <= 0 || equals === token.length - 1) {
473
+ fail('INVALID_HEADER', 'Stripe-Signature fields must be key=value');
474
+ }
475
+ const key = token.slice(0, equals);
476
+ const value = token.slice(equals + 1);
477
+ if (key === 't') {
478
+ if (timestamp !== null) fail('INVALID_HEADER', 'Stripe-Signature contains more than one t value');
479
+ timestamp = value;
480
+ } else if (key === 'v1') {
481
+ if (signatures.length >= MAX_SIGNATURE_CANDIDATES) {
482
+ fail('INVALID_SIGNATURE', `Too many signature candidates (limit ${MAX_SIGNATURE_CANDIDATES})`);
483
+ }
484
+ signatures.push(decodeHex(value, 'Stripe v1 signature'));
485
+ }
486
+ }
487
+ if (timestamp === null || signatures.length === 0) {
488
+ fail('INVALID_HEADER', 'Stripe-Signature requires one t value and at least one v1 value');
489
+ }
490
+ const timestampMs = parseTimestampSeconds(timestamp);
491
+ const payload = Buffer.concat([Buffer.from(timestamp, 'ascii'), Buffer.from('.'), ctx.body]);
492
+ const result = verifyHmac(ctx, signatures, payload);
493
+ return { ...result, timestampMs };
494
+ },
495
+ });
496
+
497
+ const slack = defineProvider({
498
+ name: 'slack',
499
+ description: 'Slack v0 signature and X-Slack-Request-Timestamp',
500
+ requiredHeaders: ['x-slack-signature', 'x-slack-request-timestamp'],
501
+ verify(ctx) {
502
+ const signature = getHeader(ctx, 'x-slack-signature');
503
+ const timestamp = getHeader(ctx, 'x-slack-request-timestamp');
504
+ const match = /^v0=([0-9a-fA-F]{64})$/.exec(signature);
505
+ if (!match) fail('INVALID_SIGNATURE', 'Slack signature must be v0=<64 hex characters>');
506
+ const timestampMs = parseTimestampSeconds(timestamp);
507
+ const payload = Buffer.concat([Buffer.from(`v0:${timestamp}:`, 'ascii'), ctx.body]);
508
+ const result = verifyHmac(ctx, decodeHex(match[1], 'Slack signature'), payload);
509
+ return { ...result, timestampMs };
510
+ },
511
+ });
512
+
513
+ const shopify = defineProvider({
514
+ name: 'shopify',
515
+ description: 'Shopify X-Shopify-Hmac-Sha256, canonical base64',
516
+ requiredHeaders: ['x-shopify-hmac-sha256'],
517
+ verify(ctx) {
518
+ const header = getHeader(ctx, 'x-shopify-hmac-sha256');
519
+ return verifyHmac(ctx, decodeBase64(header, 'Shopify signature'));
520
+ },
521
+ });
522
+
523
+ const linear = defineProvider({
524
+ name: 'linear',
525
+ description: 'Linear-Signature, hex HMAC-SHA256',
526
+ requiredHeaders: ['linear-signature'],
527
+ verify(ctx) {
528
+ const header = getHeader(ctx, 'linear-signature');
529
+ return verifyHmac(ctx, decodeHex(header, 'Linear signature'));
530
+ },
531
+ });
532
+
533
+ const standardWebhooks = defineProvider({
534
+ name: 'standard-webhooks',
535
+ description: 'Standard Webhooks / Svix with whsec_ secrets and multi v1 signatures',
536
+ requiredHeaders: ['webhook-id', 'webhook-timestamp', 'webhook-signature'],
537
+ verify(ctx) {
538
+ const messageId = getHeader(ctx, 'webhook-id');
539
+ const timestamp = getHeader(ctx, 'webhook-timestamp');
540
+ const header = getHeader(ctx, 'webhook-signature');
541
+ if (!/^[A-Za-z0-9_-]{1,200}$/.test(messageId)) {
542
+ fail('INVALID_HEADER', 'webhook-id contains unsupported characters');
543
+ }
544
+ if (header.trim() !== header || /\s{2,}/.test(header)) {
545
+ fail('INVALID_HEADER', 'webhook-signature has invalid whitespace');
546
+ }
547
+ const signatures = [];
548
+ for (const token of header.split(' ')) {
549
+ if (!token.startsWith('v1,')) fail('INVALID_HEADER', 'webhook-signature entries must use v1');
550
+ if (signatures.length >= MAX_SIGNATURE_CANDIDATES) {
551
+ fail('INVALID_SIGNATURE', `Too many signature candidates (limit ${MAX_SIGNATURE_CANDIDATES})`);
552
+ }
553
+ signatures.push(decodeBase64(token.slice(3), 'Standard Webhooks signature'));
554
+ }
555
+ if (signatures.length === 0) fail('INVALID_HEADER', 'webhook-signature is empty');
556
+ const keys = ctx.secrets.map((secret) => {
557
+ if (typeof secret !== 'string' || !secret.startsWith('whsec_')) {
558
+ fail('INVALID_SECRET', 'Standard Webhooks secrets must be strings beginning with whsec_');
559
+ }
560
+ return decodeBase64(secret.slice(6), 'whsec secret');
561
+ });
562
+ const timestampMs = parseTimestampSeconds(timestamp);
563
+ const payload = Buffer.concat([Buffer.from(`${messageId}.${timestamp}.`, 'utf8'), ctx.body]);
564
+ const result = verifyHmacWithSecrets(keys, signatures, payload);
565
+ return { ...result, timestampMs, replayKey: deliveryKey('standard-webhooks', messageId) };
566
+ },
567
+ });
568
+
569
+ const discord = defineProvider({
570
+ name: 'discord',
571
+ description: 'Discord Ed25519 interaction signature verification',
572
+ requiredHeaders: ['x-signature-ed25519', 'x-signature-timestamp'],
573
+ // The Ed25519 public key may be supplied through publicKey instead of secret,
574
+ // so a placeholder secret must not be required to reach verify().
575
+ secretOptional: true,
576
+ verify(ctx) {
577
+ const signatureHeader = getHeader(ctx, 'x-signature-ed25519');
578
+ const timestamp = getHeader(ctx, 'x-signature-timestamp');
579
+ const publicKey = ctx.options.publicKey !== undefined ? ctx.options.publicKey : ctx.secrets[0];
580
+ if (typeof publicKey !== 'string') {
581
+ fail('INVALID_SECRET', 'Discord requires an Ed25519 public key via publicKey or secret');
582
+ }
583
+ const publicKeyBytes = decodeHexOfLength(publicKey, 32, 'Discord public key');
584
+ const signature = decodeHexOfLength(signatureHeader, 64, 'Discord signature');
585
+ const timestampMs = parseTimestampSeconds(timestamp);
586
+ const payload = Buffer.concat([Buffer.from(timestamp, 'ascii'), ctx.body]);
587
+ let valid = false;
588
+ try {
589
+ const der = Buffer.concat([Buffer.from('302a300506032b6570032100', 'hex'), publicKeyBytes]);
590
+ const keyObject = crypto.createPublicKey({ key: der, format: 'der', type: 'spki' });
591
+ valid = crypto.verify(null, payload, keyObject, signature);
592
+ } catch (error) {
593
+ fail('INVALID_SIGNATURE', 'Discord Ed25519 verification could not be performed');
594
+ }
595
+ if (!valid) fail('SIGNATURE_MISMATCH', 'Discord Ed25519 signature does not match the public key');
596
+ return { timestampMs, secretIndex: 0, signature };
597
+ },
598
+ });
599
+
600
+ for (const provider of [github, stripe, slack, shopify, linear, standardWebhooks, discord]) {
601
+ registerProvider(provider);
602
+ }
603
+
604
+ // "svix" is an alias for the same verification logic, reporting the canonical name.
605
+ const svixAlias = Object.freeze({
606
+ name: 'svix',
607
+ description: 'Alias for standard-webhooks',
608
+ requiredHeaders: standardWebhooks.requiredHeaders,
609
+ verify: standardWebhooks.verify,
610
+ canonicalName: 'standard-webhooks',
611
+ });
612
+ registerProvider(svixAlias);
613
+
614
+ const providerAliases = Object.freeze({
615
+ github,
616
+ stripe,
617
+ slack,
618
+ shopify,
619
+ linear,
620
+ svix: standardWebhooks,
621
+ standardWebhooks,
622
+ 'standard-webhooks': standardWebhooks,
623
+ discord,
624
+ });
625
+
626
+ const providers = Object.freeze(providerAliases);
627
+
628
+ // ---------------------------------------------------------------------------
629
+ // Verification engine
630
+ // ---------------------------------------------------------------------------
631
+
632
+ function normalizeTolerance(value) {
633
+ const tolerance = value === undefined ? 300 : value;
634
+ if (!Number.isSafeInteger(tolerance) || tolerance < 0) {
635
+ fail('INVALID_ARGUMENT', 'toleranceSeconds must be a non-negative safe integer');
636
+ }
637
+ return tolerance;
638
+ }
639
+
640
+ function resolveNow(value) {
641
+ if (value === undefined) return Date.now();
642
+ if (typeof value !== 'function') fail('INVALID_ARGUMENT', 'now must be a function returning milliseconds');
643
+ const result = value();
644
+ if (typeof result !== 'number' || !Number.isFinite(result)) {
645
+ fail('INVALID_ARGUMENT', 'now() must return a finite millisecond timestamp');
646
+ }
647
+ return result;
648
+ }
649
+
650
+ function normalizeSecrets(options, provider) {
651
+ const configured = options.secrets !== undefined ? options.secrets : options.secret;
652
+ // Providers such as Discord accept a public key instead of a shared secret.
653
+ if (configured === undefined && provider.secretOptional === true) return [];
654
+ const list = Array.isArray(configured) ? configured : [configured];
655
+ if (list.length === 0 || list.some((secret) => typeof secret !== 'string' || secret.length === 0 || secret.trim().length === 0)) {
656
+ fail('INVALID_SECRET', 'Provide at least one non-empty secret via secret or secrets');
657
+ }
658
+ return list;
659
+ }
660
+
661
+ function isThenable(value) {
662
+ if (value === null || (typeof value !== 'object' && typeof value !== 'function')) return false;
663
+ try {
664
+ return typeof value.then === 'function';
665
+ } catch {
666
+ // An accessor that throws is not a usable result object either. Treat it
667
+ // as a thenable so the caller fails closed instead of leaking the error.
668
+ return true;
669
+ }
670
+ }
671
+
672
+ // A rejected promise from a provider or from a synchronous replay-store call
673
+ // must not survive as an unhandled rejection after this path has already
674
+ // failed closed; an unhandled rejection terminates Node by default.
675
+ function discardRejection(value) {
676
+ Promise.resolve(value).catch(() => {});
677
+ }
678
+
679
+ function buildContext(provider, body, headers, options) {
680
+ if (options === null || typeof options !== 'object' || Array.isArray(options)) {
681
+ fail('INVALID_ARGUMENT', 'options must be an object');
682
+ }
683
+ const normalized = normalizeHeaders(headers);
684
+ return Object.freeze({
685
+ provider: provider.name,
686
+ body: normalizeBody(body),
687
+ headers: normalized.headers,
688
+ headerArrays: normalized.arrayKeys,
689
+ secrets: normalizeSecrets(options, provider),
690
+ toleranceSeconds: normalizeTolerance(options.toleranceSeconds),
691
+ nowMs: resolveNow(options.now),
692
+ options: Object.freeze({ ...options }),
693
+ helpers,
694
+ });
695
+ }
696
+
697
+ function isSignatureValue(value) {
698
+ return Buffer.isBuffer(value) || value instanceof Uint8Array || typeof value === 'string';
699
+ }
700
+
701
+ function replayKeyFor(provider, secretIndex, material) {
702
+ return deliveryKey(provider.name, signatureKey(provider.name, secretIndex, material));
703
+ }
704
+
705
+ function finish(provider, ctx, result, replayStore, asyncMode) {
706
+ // A provider that forgets to be synchronous returns a promise here. Treating
707
+ // it as a result object would report valid: true before any comparison ran.
708
+ if (isThenable(result)) {
709
+ discardRejection(result);
710
+ fail('PROVIDER_ERROR', `${provider.name} verify() returned a promise; provider verify functions must be synchronous`);
711
+ }
712
+ if (!result || typeof result !== 'object') fail('PROVIDER_ERROR', `${provider.name} verify() must return a result object`);
713
+ if (result.timestampMs !== undefined && result.timestampMs !== null) enforceTimestamp(ctx, result.timestampMs);
714
+ if (result.secretIndex !== undefined && result.secretIndex !== null &&
715
+ (!Number.isSafeInteger(result.secretIndex) || result.secretIndex < 0)) {
716
+ fail('PROVIDER_ERROR', `${provider.name} verify() returned an invalid secretIndex`);
717
+ }
718
+
719
+ const keys = [];
720
+ let replayKey = result.replayKey;
721
+ if (replayKey === undefined || replayKey === null) {
722
+ const signature = result.signature;
723
+ if (signature !== undefined && signature !== null && !isSignatureValue(signature)) {
724
+ fail('PROVIDER_ERROR', `${provider.name} verify() returned an unsupported signature value`);
725
+ }
726
+ const matched = result.matchedSignatures;
727
+ if (matched !== undefined && matched !== null) {
728
+ if (!Array.isArray(matched) || matched.length > MAX_SIGNATURE_CANDIDATES) {
729
+ fail('PROVIDER_ERROR', `${provider.name} verify() returned an invalid matched signature list`);
730
+ }
731
+ for (const entry of matched) {
732
+ if (!entry || typeof entry !== 'object' ||
733
+ !Number.isSafeInteger(entry.secretIndex) || entry.secretIndex < 0 ||
734
+ !isSignatureValue(entry.signature) || entry.signature.length === 0) {
735
+ fail('PROVIDER_ERROR', `${provider.name} verify() returned an invalid matched signature entry`);
736
+ }
737
+ keys.push(replayKeyFor(provider, entry.secretIndex, entry.signature));
738
+ }
739
+ }
740
+ // An empty signature would collapse every delivery to one replay key.
741
+ const material = signature !== undefined && signature !== null && signature.length > 0 ? signature : ctx.body;
742
+ const secretIndex = result.secretIndex === undefined || result.secretIndex === null ? 0 : result.secretIndex;
743
+ replayKey = replayKeyFor(provider, secretIndex, material);
744
+ }
745
+ if (typeof replayKey !== 'string' || replayKey.length === 0) {
746
+ fail('INVALID_ARGUMENT', 'Replay key must be a non-empty string');
747
+ }
748
+ // The primary key is recorded first, then every other signature that matched
749
+ // so a rotation delivery cannot be replayed by dropping one of them.
750
+ keys.unshift(replayKey);
751
+
752
+ const output = Object.freeze({
753
+ provider: provider.canonicalName || provider.name,
754
+ valid: true,
755
+ timestamp: result.timestampMs === undefined || result.timestampMs === null ? null : new Date(result.timestampMs),
756
+ secretIndex: result.secretIndex === undefined ? null : result.secretIndex,
757
+ replayKey,
758
+ });
759
+
760
+ const applyStore = (seen, key) => {
761
+ if (seen === false) fail('REPLAYED_DELIVERY', 'This delivery has already been verified', { replayKey: key });
762
+ if (seen !== true) {
763
+ fail('INVALID_ARGUMENT', 'Replay store checkAndRecord must return true for a new delivery or false for a replay');
764
+ }
765
+ };
766
+
767
+ const complete = () => (asyncMode ? Promise.resolve(output) : output);
768
+
769
+ if (ctx.options.replayStore === undefined) return complete();
770
+
771
+ if (!replayStore || typeof replayStore.checkAndRecord !== 'function') {
772
+ fail('INVALID_ARGUMENT', 'replayStore must implement checkAndRecord(key, nowMs)');
773
+ }
774
+ const check = replayStore.checkAndRecord;
775
+ // Refuse an async store before calling it: the synchronous entry point
776
+ // cannot honor a promise, and the call itself may already have persisted
777
+ // the delivery key, which would burn a legitimate delivery id.
778
+ if (!asyncMode && check.constructor && check.constructor.name === 'AsyncFunction') {
779
+ fail('INVALID_ARGUMENT', 'This replay store is asynchronous; use verifyAsync instead');
780
+ }
781
+
782
+ const uniqueKeys = [...new Set(keys)];
783
+ let index = 0;
784
+ const recordNext = () => {
785
+ while (index < uniqueKeys.length) {
786
+ const key = uniqueKeys[index];
787
+ index += 1;
788
+ const seen = check.call(replayStore, key, ctx.nowMs);
789
+ if (isThenable(seen)) {
790
+ if (!asyncMode) {
791
+ discardRejection(seen);
792
+ fail('INVALID_ARGUMENT', 'This replay store is asynchronous; use verifyAsync instead');
793
+ }
794
+ return Promise.resolve(seen).then((value) => {
795
+ applyStore(value, key);
796
+ return recordNext();
797
+ });
798
+ }
799
+ applyStore(seen, key);
800
+ }
801
+ return complete();
802
+ };
803
+ return recordNext();
804
+ }
805
+
806
+ function unpack(args) {
807
+ if (args.length === 1 && args[0] && typeof args[0] === 'object' && !Array.isArray(args[0])) {
808
+ const single = args[0];
809
+ const options = { ...single };
810
+ delete options.provider;
811
+ delete options.body;
812
+ delete options.headers;
813
+ return [single.provider, single.body, single.headers, options];
814
+ }
815
+ return [args[0], args[1], args[2], args.length > 3 && args[3] !== undefined ? args[3] : {}];
816
+ }
817
+
818
+ function runVerify(providerInput, body, headers, options) {
819
+ const provider = resolveProvider(providerInput);
820
+ const ctx = buildContext(provider, body, headers, options);
821
+ let result;
822
+ try {
823
+ result = provider.verify(ctx);
824
+ } catch (error) {
825
+ if (error instanceof HookVerifyError) throw error;
826
+ fail('PROVIDER_ERROR', `${provider.name} verification failed`, { message: String(error && error.message ? error.message : error) });
827
+ }
828
+ return finish(provider, ctx, result, ctx.options.replayStore, false);
829
+ }
830
+
831
+ function verify(...args) {
832
+ return runVerify(...unpack(args));
833
+ }
834
+
835
+ // Declared async so argument, provider, and replay-store failures surface as a
836
+ // rejected promise rather than a synchronous throw that callers cannot catch
837
+ // with .catch().
838
+ async function verifyAsync(...args) {
839
+ const [providerInput, body, headers, options] = unpack(args);
840
+ const provider = resolveProvider(providerInput);
841
+ const ctx = buildContext(provider, body, headers, options);
842
+ let result;
843
+ try {
844
+ result = provider.verify(ctx);
845
+ } catch (error) {
846
+ if (error instanceof HookVerifyError) throw error;
847
+ fail('PROVIDER_ERROR', `${provider.name} verification failed`, { message: String(error && error.message ? error.message : error) });
848
+ }
849
+ return finish(provider, ctx, result, ctx.options.replayStore, true);
850
+ }
851
+
852
+ function isValid(...args) {
853
+ try {
854
+ verify(...args);
855
+ return true;
856
+ } catch (error) {
857
+ if (error instanceof HookVerifyError) return false;
858
+ throw error;
859
+ }
860
+ }
861
+
862
+ function createVerifier(defaults = {}) {
863
+ if (!defaults || typeof defaults !== 'object' || Array.isArray(defaults)) {
864
+ fail('INVALID_ARGUMENT', 'createVerifier expects an options object');
865
+ }
866
+ const merge = (overrides) => {
867
+ if (overrides === undefined || overrides === null) return { ...defaults };
868
+ if (typeof overrides !== 'object' || Array.isArray(overrides)) {
869
+ fail('INVALID_ARGUMENT', 'createVerifier overrides must be an options object');
870
+ }
871
+ return { ...defaults, ...overrides };
872
+ };
873
+ return Object.freeze({
874
+ verify(provider, body, headers, overrides) {
875
+ return verify(provider, body, headers, merge(overrides));
876
+ },
877
+ verifyAsync(provider, body, headers, overrides) {
878
+ return verifyAsync(provider, body, headers, merge(overrides));
879
+ },
880
+ isValid(provider, body, headers, overrides) {
881
+ return isValid(provider, body, headers, merge(overrides));
882
+ },
883
+ });
884
+ }
885
+
886
+ module.exports = Object.freeze({
887
+ HookVerifyError,
888
+ ERROR_CODES,
889
+ MemoryReplayStore,
890
+ defineProvider,
891
+ registerProvider,
892
+ getProvider,
893
+ listProviders,
894
+ verify,
895
+ verifyAsync,
896
+ isValid,
897
+ createVerifier,
898
+ providers,
899
+ github,
900
+ stripe,
901
+ slack,
902
+ shopify,
903
+ linear,
904
+ svix: standardWebhooks,
905
+ standardWebhooks,
906
+ discord,
907
+ helpers: Object.freeze({
908
+ decodeHex,
909
+ decodeBase64,
910
+ constantTimeEqual,
911
+ deliveryKey,
912
+ normalizeBody,
913
+ normalizeHeaders: (headers) => normalizeHeaders(headers).headers,
914
+ parseTimestampSeconds,
915
+ }),
916
+ });