@blamejs/core 0.7.18 → 0.7.20

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.
Files changed (169) hide show
  1. package/CHANGELOG.md +427 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +350 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +399 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/fetch-metadata.js +129 -0
  86. package/lib/middleware/health.js +392 -392
  87. package/lib/middleware/index.js +85 -79
  88. package/lib/middleware/rate-limit.js +358 -358
  89. package/lib/middleware/request-id.js +61 -61
  90. package/lib/middleware/request-log.js +168 -168
  91. package/lib/middleware/require-auth.js +104 -104
  92. package/lib/middleware/security-headers.js +121 -116
  93. package/lib/middleware/sse.js +166 -166
  94. package/lib/migrations.js +383 -383
  95. package/lib/mtls-ca.js +518 -518
  96. package/lib/mtls-engine-default.js +481 -481
  97. package/lib/network-dns.js +632 -632
  98. package/lib/network-heartbeat.js +290 -290
  99. package/lib/network-nts.js +574 -574
  100. package/lib/network-proxy.js +265 -265
  101. package/lib/network-tls.js +328 -328
  102. package/lib/network.js +233 -233
  103. package/lib/notify.js +612 -612
  104. package/lib/ntp-check.js +229 -229
  105. package/lib/numeric-bounds.js +111 -111
  106. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  107. package/lib/object-store/azure-blob.js +488 -488
  108. package/lib/object-store/gcs-bucket-ops.js +351 -351
  109. package/lib/object-store/gcs.js +519 -519
  110. package/lib/object-store/http-put.js +153 -153
  111. package/lib/object-store/index.js +197 -197
  112. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  113. package/lib/object-store/sigv4.js +903 -903
  114. package/lib/observability.js +151 -151
  115. package/lib/otel-export.js +269 -269
  116. package/lib/pagination.js +464 -464
  117. package/lib/parsers/index.js +80 -80
  118. package/lib/parsers/safe-env.js +642 -642
  119. package/lib/parsers/safe-ini.js +292 -292
  120. package/lib/parsers/safe-toml.js +784 -784
  121. package/lib/parsers/safe-xml.js +390 -390
  122. package/lib/parsers/safe-yaml.js +1015 -1015
  123. package/lib/permissions.js +708 -708
  124. package/lib/pqc-agent.js +87 -87
  125. package/lib/pqc-gate.js +279 -279
  126. package/lib/protobuf-encoder.js +190 -190
  127. package/lib/protocol-dispatcher.js +161 -161
  128. package/lib/pubsub-redis.js +167 -167
  129. package/lib/pubsub.js +429 -429
  130. package/lib/queue-local.js +476 -476
  131. package/lib/queue-redis.js +745 -745
  132. package/lib/queue-sqs.js +319 -319
  133. package/lib/queue.js +695 -695
  134. package/lib/redis-client.js +519 -519
  135. package/lib/request-helpers.js +340 -340
  136. package/lib/restore-bundle.js +237 -237
  137. package/lib/restore-rollback.js +259 -259
  138. package/lib/restore.js +409 -409
  139. package/lib/retry.js +376 -376
  140. package/lib/router.js +748 -748
  141. package/lib/safe-async.js +735 -735
  142. package/lib/safe-buffer.js +237 -237
  143. package/lib/safe-json.js +541 -541
  144. package/lib/safe-schema.js +1266 -1266
  145. package/lib/safe-url.js +159 -159
  146. package/lib/scheduler.js +706 -706
  147. package/lib/security-assert.js +373 -373
  148. package/lib/seeders.js +618 -618
  149. package/lib/session.js +535 -478
  150. package/lib/slug.js +269 -269
  151. package/lib/ssrf-guard.js +401 -401
  152. package/lib/static.js +7 -5
  153. package/lib/storage.js +471 -471
  154. package/lib/subject.js +281 -281
  155. package/lib/template.js +791 -791
  156. package/lib/testing.js +798 -798
  157. package/lib/time.js +310 -310
  158. package/lib/totp.js +302 -302
  159. package/lib/tracing.js +494 -494
  160. package/lib/uuid.js +132 -132
  161. package/lib/validate-opts.js +340 -340
  162. package/lib/vault/index.js +308 -308
  163. package/lib/vault/rotate.js +784 -784
  164. package/lib/vault/wrap.js +296 -296
  165. package/lib/vendor/noble-ciphers.cjs +9 -9
  166. package/lib/webhook.js +595 -595
  167. package/lib/websocket.js +1048 -1048
  168. package/package.json +77 -77
  169. package/sbom.cyclonedx.json +7 -7
package/lib/webhook.js CHANGED
@@ -1,595 +1,595 @@
1
- "use strict";
2
- /**
3
- * b.webhook — outbound webhook signing + inbound verification.
4
- *
5
- * var signer = b.webhook.signer({
6
- * algo: "hmac-sha3-512",
7
- * keys: { v1: secretBytes },
8
- * defaultKid: "v1",
9
- * });
10
- *
11
- * await signer.send({ url: "https://example.com/hook", body: jsonString });
12
- * // POSTs with:
13
- * // Webhook-Signature: t=<unix-seconds>,id=<uuid>,v1=<sig-hex>
14
- *
15
- * var verifier = b.webhook.verifier({
16
- * algo: "hmac-sha3-512",
17
- * keys: { v1: secret, v0: oldSecret }, // multi-key for rotation
18
- * toleranceMs: b.constants.TIME.minutes(5),
19
- * nonceStore: b.nonceStore.create({ ... }), // optional replay defense
20
- * });
21
- *
22
- * router.use(b.middleware.bodyParser({ keepRawBody: true })); // REQUIRED
23
- * router.post("/inbound-webhook", verifier.middleware(), function (req, res) {
24
- * // req.webhook = { algo, kid, timestamp, id }
25
- * });
26
- *
27
- * Algorithms:
28
- * "hmac-sha3-512" — symmetric. keys: { kid → Buffer/string secret }
29
- * "pqc-pem" — asymmetric. keys map for signer:
30
- * { kid → { privateKey, publicKey } } (PEM)
31
- * keys map for verifier:
32
- * { kid → publicKey } (PEM)
33
- * Algorithm (SLH-DSA-SHAKE-256f / ML-DSA-87) is
34
- * auto-detected by Node from the PEM. No classical
35
- * (Ed25519, RSA, ECDSA) signature scheme is exposed.
36
- *
37
- * Signed string (deterministic, prefix-bound to defend against algorithm-
38
- * substitution and key-substitution attacks):
39
- *
40
- * <algo>.<kid>.<timestamp>.<id>.<body>
41
- *
42
- * Header format (single combined header, Stripe-shape):
43
- *
44
- * Webhook-Signature: t=<unix-seconds>,id=<uuid>,<kid>=<sig-hex>
45
- *
46
- * `t` and `id` are reserved segment names; every other `<name>=<value>`
47
- * pair is treated as a kid → signature mapping. Multiple kid pairs are
48
- * accepted on the verifier side; the signer emits exactly one. Operators
49
- * rotating keys point the verifier at both old + new keys and migrate
50
- * signers progressively.
51
- *
52
- * Replay defense:
53
- * - `id` is included in the signed string, so a captured signature
54
- * cannot be reused with a fresh id.
55
- * - Optional `nonceStore` records seen ids; second delivery with the
56
- * same id rejects with REPLAY. The framework's b.nonceStore is the
57
- * reference impl; operators plug in Redis/SQL by passing any object
58
- * with `checkAndInsert(nonce, expireAt) → bool/Promise<bool>`.
59
- *
60
- * Validation policy:
61
- *
62
- * - signer/verifier creation opts → throw at config time
63
- * - signer.sign body type → throw at call site
64
- * - signer.send url shape → throw at call site (via safeUrl)
65
- * - verifier.verify input shape → throw WebhookError at call site
66
- * - nonceStore.checkAndInsert err → propagates (fail-closed)
67
- */
68
-
69
- var crypto = require("./crypto");
70
- var httpClient = require("./http-client");
71
- var safeBuffer = require("./safe-buffer");
72
- var safeUrl = require("./safe-url");
73
- var retry = require("./retry");
74
- var C = require("./constants");
75
- var lazyRequire = require("./lazy-require");
76
- var numericChecks = require("./numeric-checks");
77
- var requestHelpers = require("./request-helpers");
78
- var validateOpts = require("./validate-opts");
79
- var { WebhookError } = require("./framework-error");
80
-
81
- var observability = lazyRequire(function () { return require("./observability"); });
82
-
83
- function _emitEvent(n, v, l) { observability().safeEvent(n, v, l || {}); }
84
-
85
- var _err = WebhookError.factory;
86
-
87
- // ---- Constants ----
88
-
89
- var ALGOS = Object.freeze({
90
- HMAC_SHA3_512: "hmac-sha3-512",
91
- PQC_PEM: "pqc-pem",
92
- });
93
-
94
- var HEADER = Object.freeze({
95
- SIGNATURE: "Webhook-Signature",
96
- });
97
-
98
- var DEFAULTS = Object.freeze({
99
- toleranceMs: C.TIME.minutes(5),
100
- clockSkewMs: C.TIME.minutes(1),
101
- signatureHeader: HEADER.SIGNATURE,
102
- // Audit defaults: BOTH success and failure default ON. The webhook
103
- // verify is the framework boundary where an inbound message gets
104
- // accepted — that acceptance IS the audit-worthy event, not a
105
- // precursor to one. "Inbound webhook id <X> verified from kid <Y>
106
- // at time T" is the compliance trail. The send side mirrors:
107
- // outbound delivery success/failure to a partner is also a
108
- // standalone audit event. Operators with extreme volume opt out
109
- // via auditSuccess: false; failures remain on regardless.
110
- auditFailures: true,
111
- auditSuccess: true,
112
- });
113
-
114
- // ---- Call-site validation helpers (throw on bad input) ----
115
-
116
- var _isPositiveInt = numericChecks.isPositiveInt;
117
- var _isNonNegFinite = numericChecks.isFiniteNonNegative;
118
- function _hasOwn(obj, k) { return Object.prototype.hasOwnProperty.call(obj, k); }
119
- function _objectKeys(obj) { return Object.keys(obj); }
120
-
121
- function _validateAlgo(algo) {
122
- if (algo !== ALGOS.HMAC_SHA3_512 && algo !== ALGOS.PQC_PEM) {
123
- throw _err("BAD_OPT", "webhook: algo must be one of " +
124
- JSON.stringify([ALGOS.HMAC_SHA3_512, ALGOS.PQC_PEM]) + ", got " + JSON.stringify(algo));
125
- }
126
- }
127
-
128
- function _validateKeysShape(name, algo, keys, side) {
129
- if (!keys || typeof keys !== "object" || Array.isArray(keys)) {
130
- throw _err("BAD_OPT", name + ": keys must be a non-empty object map of kid → key, got " +
131
- typeof keys);
132
- }
133
- var kids = _objectKeys(keys);
134
- if (kids.length === 0) {
135
- throw _err("BAD_OPT", name + ": keys must have at least one kid entry");
136
- }
137
- for (var i = 0; i < kids.length; i++) {
138
- var kid = kids[i];
139
- if (kid.length === 0 || /[,=\s]/.test(kid)) {
140
- throw _err("BAD_OPT", name + ": kid must be non-empty and contain no comma/equals/whitespace, got " +
141
- JSON.stringify(kid));
142
- }
143
- if (kid === "t" || kid === "id") {
144
- throw _err("BAD_OPT", name + ": kid '" + kid + "' is reserved (collides with header field)");
145
- }
146
- var k = keys[kid];
147
- if (algo === ALGOS.HMAC_SHA3_512) {
148
- if (!Buffer.isBuffer(k) && typeof k !== "string") {
149
- throw _err("BAD_OPT", name + ": HMAC key for kid '" + kid +
150
- "' must be a Buffer or string, got " + typeof k);
151
- }
152
- if (k.length === 0) {
153
- throw _err("BAD_OPT", name + ": HMAC key for kid '" + kid + "' must be non-empty");
154
- }
155
- } else if (algo === ALGOS.PQC_PEM) {
156
- if (side === "signer") {
157
- if (!k || typeof k !== "object" || Array.isArray(k) ||
158
- (typeof k.privateKey !== "string" && !Buffer.isBuffer(k.privateKey)) ||
159
- (typeof k.publicKey !== "string" && !Buffer.isBuffer(k.publicKey))) {
160
- throw _err("BAD_OPT", name + ": PQC signer key for kid '" + kid +
161
- "' must be { privateKey, publicKey } as PEM strings/Buffers");
162
- }
163
- } else {
164
- if (typeof k !== "string" && !Buffer.isBuffer(k)) {
165
- throw _err("BAD_OPT", name + ": PQC verifier key for kid '" + kid +
166
- "' must be a PEM string/Buffer (public key)");
167
- }
168
- }
169
- }
170
- }
171
- }
172
-
173
- function _validateBody(body) {
174
- if (typeof body !== "string" && !Buffer.isBuffer(body)) {
175
- throw _err("BAD_BODY", "webhook: body must be a string or Buffer, got " + typeof body);
176
- }
177
- }
178
-
179
- // ---- Signed-string composition ----
180
-
181
- function _composeSignedString(algo, kid, timestamp, id, body) {
182
- var prefix = algo + "." + kid + "." + timestamp + "." + id + ".";
183
- if (Buffer.isBuffer(body)) {
184
- return Buffer.concat([Buffer.from(prefix, "utf8"), body]);
185
- }
186
- return Buffer.from(prefix + body, "utf8");
187
- }
188
-
189
- // ---- Sign / verify primitives ----
190
-
191
- function _hmacSign(key, data) {
192
- return crypto.hmacSha3(key, data); // hex string
193
- }
194
-
195
- function _hmacVerify(key, data, expectedHex) {
196
- if (!safeBuffer.isHex(expectedHex)) return false;
197
- var actualHex = crypto.hmacSha3(key, data);
198
- return crypto.timingSafeEqual(actualHex, expectedHex);
199
- }
200
-
201
- function _pqcSign(privateKeyPem, data) {
202
- return crypto.sign(data, privateKeyPem).toString("hex");
203
- }
204
-
205
- function _pqcVerify(publicKeyPem, data, expectedHex) {
206
- if (!safeBuffer.isHex(expectedHex) || (expectedHex.length % 2) !== 0) {
207
- return false;
208
- }
209
- var sigBuf;
210
- try { sigBuf = Buffer.from(expectedHex, "hex"); }
211
- catch (_e) { return false; }
212
- try { return crypto.verify(data, sigBuf, publicKeyPem); }
213
- catch (_e) { return false; }
214
- }
215
-
216
- // ---- Header parsing ----
217
- //
218
- // Format: t=<seconds>,id=<uuid>,<kid>=<hex>[,<kid>=<hex>]*
219
- // `t` and `id` are reserved segment names; everything else is treated as
220
- // a kid → signature pair. Whitespace tolerated around commas.
221
-
222
- function _parseSignatureHeader(headerValue) {
223
- var segs = requestHelpers.parseListHeader(headerValue);
224
- var t = null, id = null, sigs = {};
225
- for (var i = 0; i < segs.length; i++) {
226
- var seg = segs[i];
227
- var eq = seg.indexOf("=");
228
- if (eq <= 0) continue; // skip malformed segments rather than failing whole header
229
- var name = seg.slice(0, eq);
230
- var value = seg.slice(eq + 1);
231
- if (name === "t") t = value;
232
- else if (name === "id") id = value;
233
- else if (name.length > 0) sigs[name] = value; // kid → sig hex
234
- }
235
- return { t: t, id: id, sigs: sigs };
236
- }
237
-
238
- // ---- Signer ----
239
-
240
- function _validateSignerOpts(opts) {
241
- validateOpts.requireObject(opts, "webhook.signer", WebhookError);
242
- _validateAlgo(opts.algo);
243
- _validateKeysShape("webhook.signer", opts.algo, opts.keys, "signer");
244
- var kids = _objectKeys(opts.keys);
245
- if (opts.defaultKid !== undefined) {
246
- if (!_hasOwn(opts.keys, opts.defaultKid)) {
247
- throw _err("BAD_OPT", "webhook.signer: defaultKid '" + opts.defaultKid +
248
- "' not present in keys (have: " + JSON.stringify(kids) + ")");
249
- }
250
- } else if (kids.length > 1) {
251
- throw _err("BAD_OPT", "webhook.signer: defaultKid required when keys has " +
252
- kids.length + " entries");
253
- }
254
- validateOpts.optionalNonEmptyString(opts.signatureHeader, "webhook.signer: signatureHeader", WebhookError);
255
- validateOpts.optionalFunction(opts.idGenerator, "webhook.signer: idGenerator", WebhookError);
256
- validateOpts.optionalFunction(opts.now, "webhook.signer: now", WebhookError);
257
- validateOpts.auditShape(opts.audit, "webhook.signer", WebhookError);
258
- }
259
-
260
- function signer(opts) {
261
- _validateSignerOpts(opts);
262
- var algo = opts.algo;
263
- var cfg = validateOpts.applyDefaults(opts, DEFAULTS);
264
- var keys = opts.keys;
265
- var kids = _objectKeys(keys);
266
- var defaultKid = opts.defaultKid || kids[0];
267
- var sigHeader = cfg.signatureHeader;
268
- var idGen = opts.idGenerator || function () { return crypto.generateToken(C.BYTES.bytes(16)); };
269
- var nowFn = opts.now || function () { return Date.now(); };
270
- var retryOpts = opts.retry || retry.DEFAULT_RETRY;
271
- var httpOpts = opts.http || {};
272
- var audit = opts.audit || null;
273
- var auditFailures = cfg.auditFailures;
274
- var auditSuccess = cfg.auditSuccess;
275
-
276
- var _auditEmit = validateOpts.makeAuditEmitter(audit);
277
-
278
- function _signOne(body, kid) {
279
- _validateBody(body);
280
- var keyForKid = kids.indexOf(kid) === -1 ? null : keys[kid];
281
- if (keyForKid == null) {
282
- throw _err("BAD_OPT", "webhook.signer: unknown kid '" + kid + "'");
283
- }
284
- var timestamp = Math.floor(nowFn() / C.TIME.seconds(1));
285
- var id = idGen();
286
- if (typeof id !== "string" || id.length === 0 || /[,=\s]/.test(id)) {
287
- throw _err("BAD_OPT", "webhook.signer: idGenerator must return a non-empty string with no comma/equals/whitespace, got " + JSON.stringify(id));
288
- }
289
- var signed = _composeSignedString(algo, kid, timestamp, id, body);
290
- var sigHex;
291
- if (algo === ALGOS.HMAC_SHA3_512) {
292
- sigHex = _hmacSign(keyForKid, signed);
293
- } else {
294
- sigHex = _pqcSign(keyForKid.privateKey, signed);
295
- }
296
- return { kid: kid, timestamp: timestamp, id: id, signature: sigHex };
297
- }
298
-
299
- function sign(body, callOpts) {
300
- var kid = (callOpts && callOpts.kid) || defaultKid;
301
- var s = _signOne(body, kid);
302
- var headerValue = "t=" + s.timestamp + ",id=" + s.id + "," + s.kid + "=" + s.signature;
303
- var headers = {};
304
- headers[sigHeader] = headerValue;
305
- return {
306
- headers: headers,
307
- timestamp: s.timestamp,
308
- id: s.id,
309
- kid: s.kid,
310
- signature: s.signature,
311
- };
312
- }
313
-
314
- function headers(body, callOpts) {
315
- return sign(body, callOpts).headers;
316
- }
317
-
318
- async function send(input) {
319
- if (!input || typeof input !== "object") {
320
- throw _err("BAD_OPT", "webhook.signer.send: input must be { url, body, headers? }");
321
- }
322
- var url = input.url;
323
- var body = input.body;
324
- safeUrl.parse(url, {
325
- allowedProtocols: httpOpts.allowedProtocols || safeUrl.ALLOW_HTTP_TLS,
326
- errorClass: WebhookError,
327
- });
328
- _validateBody(body);
329
- var signed = sign(body, { kid: input.kid });
330
- var mergedHeaders = Object.assign({}, input.headers || {}, signed.headers);
331
- if (!mergedHeaders["Content-Type"] && !mergedHeaders["content-type"]) {
332
- mergedHeaders["Content-Type"] = Buffer.isBuffer(body)
333
- ? "application/octet-stream"
334
- : "application/json";
335
- }
336
- var requestOpts = Object.assign({
337
- method: "POST",
338
- url: url,
339
- headers: mergedHeaders,
340
- body: body,
341
- allowedProtocols: safeUrl.ALLOW_HTTP_TLS,
342
- errorClass: WebhookError,
343
- }, httpOpts);
344
- requestOpts.headers = mergedHeaders;
345
- requestOpts.url = url;
346
- requestOpts.body = body;
347
- requestOpts.method = "POST";
348
- var hostLabel = "";
349
- try {
350
- hostLabel = safeUrl.parse(url, {
351
- allowedProtocols: httpOpts.allowedProtocols || safeUrl.ALLOW_HTTP_TLS,
352
- errorClass: WebhookError,
353
- }).host;
354
- } catch (_e) { hostLabel = ""; }
355
- try {
356
- var res = await retry.withRetry(function () {
357
- return httpClient.request(requestOpts);
358
- }, retryOpts);
359
- var statusCode = (res && (res.statusCode || res.status)) || 0;
360
- _emitEvent("webhook.send", 1, {
361
- outcome: statusCode >= 200 && statusCode < 300 ? "success" : "failure",
362
- status: statusCode,
363
- host: hostLabel,
364
- });
365
- if (auditSuccess && statusCode >= 200 && statusCode < 300) {
366
- _auditEmit("webhook.send", {
367
- resource: { kind: "webhook", id: hostLabel },
368
- outcome: "success",
369
- metadata: { status: statusCode },
370
- });
371
- }
372
- if (auditFailures && (statusCode < 200 || statusCode >= 300)) {
373
- _auditEmit("webhook.send", {
374
- resource: { kind: "webhook", id: hostLabel },
375
- outcome: "failure",
376
- reason: "http-" + statusCode,
377
- });
378
- }
379
- return res;
380
- } catch (err) {
381
- _emitEvent("webhook.send", 1, {
382
- outcome: "failure", reason: "transport-error", host: hostLabel,
383
- });
384
- if (auditFailures) {
385
- _auditEmit("webhook.send", {
386
- resource: { kind: "webhook", id: hostLabel },
387
- outcome: "failure",
388
- reason: (err && err.code) || "transport-error",
389
- });
390
- }
391
- throw err;
392
- }
393
- }
394
-
395
- return {
396
- sign: sign,
397
- headers: headers,
398
- send: send,
399
- };
400
- }
401
-
402
- // ---- Verifier ----
403
-
404
- function _validateVerifierOpts(opts) {
405
- validateOpts.requireObject(opts, "webhook.verifier", WebhookError);
406
- _validateAlgo(opts.algo);
407
- _validateKeysShape("webhook.verifier", opts.algo, opts.keys, "verifier");
408
- validateOpts.optionalFiniteNonNegative(opts.toleranceMs, "webhook.verifier: toleranceMs", WebhookError);
409
- validateOpts.optionalFiniteNonNegative(opts.clockSkewMs, "webhook.verifier: clockSkewMs", WebhookError);
410
- validateOpts.optionalNonEmptyString(opts.signatureHeader, "webhook.verifier: signatureHeader", WebhookError);
411
- validateOpts.optionalObjectWithMethod(opts.nonceStore, "checkAndInsert",
412
- "webhook.verifier: nonceStore", WebhookError, "BAD_OPT",
413
- "must implement checkAndInsert(nonce, expireAt)");
414
- validateOpts.optionalFunction(opts.now, "webhook.verifier: now", WebhookError);
415
- validateOpts.auditShape(opts.audit, "webhook.verifier", WebhookError);
416
- validateOpts.optionalBoolean(opts.auditFailures, "webhook.verifier: auditFailures", WebhookError);
417
- validateOpts.optionalBoolean(opts.auditSuccess, "webhook.verifier: auditSuccess", WebhookError);
418
- }
419
-
420
- function verifier(opts) {
421
- _validateVerifierOpts(opts);
422
- var cfg = validateOpts.applyDefaults(opts, DEFAULTS);
423
- var algo = opts.algo;
424
- var keys = opts.keys;
425
- var toleranceMs = cfg.toleranceMs;
426
- var clockSkewMs = cfg.clockSkewMs;
427
- var sigHeader = cfg.signatureHeader.toLowerCase();
428
- var nonceStore = opts.nonceStore || null;
429
- var nowFn = opts.now || function () { return Date.now(); };
430
- var audit = opts.audit || null;
431
- var auditFailures = cfg.auditFailures;
432
- var auditSuccess = cfg.auditSuccess;
433
-
434
- function _auditEmit(outcome, reason, info, req) {
435
- if (!audit) return;
436
- if (outcome === "success" && !auditSuccess) return;
437
- if (outcome === "failure" && !auditFailures) return;
438
- try {
439
- audit.safeEmit({
440
- action: "webhook.verify",
441
- actor: requestHelpers.extractActorContext(req),
442
- resource: { kind: "webhook" },
443
- outcome: outcome,
444
- reason: reason || null,
445
- metadata: info || null,
446
- });
447
- } catch (_e) { /* audit best-effort */ }
448
- }
449
-
450
- function _failure(code, message, reason, req) {
451
- _emitEvent("webhook.verify", 1, { outcome: "failure", reason: reason || code });
452
- _auditEmit("failure", reason || code, null, req);
453
- return _err(code, message);
454
- }
455
-
456
- async function verify(input) {
457
- if (!input || typeof input !== "object") {
458
- throw _err("BAD_OPT", "webhook.verifier.verify: input must be { body, headers }");
459
- }
460
- var headers = input.headers;
461
- if (!headers || typeof headers !== "object") {
462
- throw _err("BAD_OPT", "webhook.verifier.verify: headers must be an object");
463
- }
464
- var body = input.body;
465
- _validateBody(body);
466
- var ctxReq = input.req || null;
467
-
468
- // Headers may be node-style (lowercased keys) or operator-supplied
469
- // (mixed case). Resolve case-insensitively.
470
- var headerValue = null;
471
- var headerKeys = Object.keys(headers);
472
- for (var i = 0; i < headerKeys.length; i++) {
473
- if (headerKeys[i].toLowerCase() === sigHeader) {
474
- headerValue = headers[headerKeys[i]];
475
- break;
476
- }
477
- }
478
- if (typeof headerValue !== "string" || headerValue.length === 0) {
479
- throw _failure("MISSING_HEADER",
480
- "webhook: " + (opts.signatureHeader || HEADER.SIGNATURE) + " header missing",
481
- "missing-header", ctxReq);
482
- }
483
-
484
- var parsed = _parseSignatureHeader(headerValue);
485
- if (parsed.t === null && parsed.id === null && Object.keys(parsed.sigs).length === 0) {
486
- throw _failure("BAD_HEADER_FORMAT", "webhook: signature header could not be parsed", "bad-header-format", ctxReq);
487
- }
488
- if (parsed.t === null) {
489
- throw _failure("MISSING_TIMESTAMP", "webhook: t= field missing from signature header", "missing-timestamp", ctxReq);
490
- }
491
- var ts = Number(parsed.t);
492
- if (!isFinite(ts) || ts < 0 || Math.floor(ts) !== ts) {
493
- throw _failure("BAD_TIMESTAMP", "webhook: t= field is not a non-negative integer, got " + JSON.stringify(parsed.t), "bad-timestamp", ctxReq);
494
- }
495
- if (parsed.id === null || parsed.id.length === 0) {
496
- throw _failure("MISSING_ID", "webhook: id= field missing from signature header", "missing-id", ctxReq);
497
- }
498
- var sigKids = Object.keys(parsed.sigs);
499
- if (sigKids.length === 0) {
500
- throw _failure("MISSING_SIGNATURE", "webhook: no v<kid>= segment found in signature header", "missing-signature", ctxReq);
501
- }
502
-
503
- // Timestamp window: signed in seconds, compare to ms clock.
504
- var nowMs = nowFn();
505
- var ageMs = nowMs - C.TIME.seconds(ts);
506
- if (ageMs > toleranceMs) {
507
- throw _failure("EXPIRED", "webhook: timestamp older than toleranceMs (age=" + ageMs + "ms)", "expired", ctxReq);
508
- }
509
- if (-ageMs > clockSkewMs) {
510
- throw _failure("FUTURE", "webhook: timestamp in the future beyond clockSkewMs (skew=" + (-ageMs) + "ms)", "future", ctxReq);
511
- }
512
-
513
- // Find the first kid the verifier holds a key for.
514
- var matchedKid = null;
515
- for (var j = 0; j < sigKids.length; j++) {
516
- if (_hasOwn(keys, sigKids[j])) { matchedKid = sigKids[j]; break; }
517
- }
518
- if (matchedKid === null) {
519
- throw _failure("UNKNOWN_KID",
520
- "webhook: no registered key matches signed kids " + JSON.stringify(sigKids),
521
- "unknown-kid", ctxReq);
522
- }
523
-
524
- var signed = _composeSignedString(algo, matchedKid, ts, parsed.id, body);
525
- var ok;
526
- if (algo === ALGOS.HMAC_SHA3_512) {
527
- ok = _hmacVerify(keys[matchedKid], signed, parsed.sigs[matchedKid]);
528
- } else {
529
- ok = _pqcVerify(keys[matchedKid], signed, parsed.sigs[matchedKid]);
530
- }
531
- if (!ok) {
532
- throw _failure("BAD_SIGNATURE", "webhook: cryptographic verification failed", "bad-signature", ctxReq);
533
- }
534
-
535
- if (nonceStore) {
536
- var expireAt = C.TIME.seconds(ts) + toleranceMs;
537
- var fresh = await nonceStore.checkAndInsert(parsed.id, expireAt);
538
- if (!fresh) {
539
- throw _failure("REPLAY", "webhook: id '" + parsed.id + "' has been seen before", "replay", ctxReq);
540
- }
541
- }
542
-
543
- _emitEvent("webhook.verify", 1, { outcome: "success", kid: matchedKid });
544
- _auditEmit("success", null, { kid: matchedKid }, ctxReq);
545
- return { algo: algo, kid: matchedKid, timestamp: ts, id: parsed.id };
546
- }
547
-
548
- function middleware() {
549
- return function (req, res, next) {
550
- var raw = req.bodyRaw;
551
- if (raw === undefined) {
552
- if (Buffer.isBuffer(req.body)) raw = req.body;
553
- else if (typeof req.body === "string") raw = req.body;
554
- }
555
- if (raw === undefined) {
556
- return _writeError(res, 401, "MISSING_RAW_BODY",
557
- "webhook verifier middleware requires bodyParser({ keepRawBody: true })");
558
- }
559
- verify({ body: raw, headers: req.headers, req: req }).then(
560
- function (info) {
561
- req.webhook = info;
562
- next();
563
- },
564
- function (err) {
565
- if (err && err.isWebhookError) {
566
- _writeError(res, 401, err.code, err.message);
567
- } else {
568
- _writeError(res, 500, "VERIFY_ERROR", "webhook verification error");
569
- }
570
- }
571
- );
572
- };
573
- }
574
-
575
- return {
576
- verify: verify,
577
- middleware: middleware,
578
- };
579
- }
580
-
581
- function _writeError(res, status, code, message) {
582
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
583
- res.end(JSON.stringify({ error: code, message: message }));
584
- }
585
-
586
- // ---- Public surface ----
587
-
588
- module.exports = {
589
- signer: signer,
590
- verifier: verifier,
591
- ALGOS: ALGOS,
592
- HEADER: HEADER,
593
- DEFAULTS: DEFAULTS,
594
- WebhookError: WebhookError,
595
- };
1
+ "use strict";
2
+ /**
3
+ * b.webhook — outbound webhook signing + inbound verification.
4
+ *
5
+ * var signer = b.webhook.signer({
6
+ * algo: "hmac-sha3-512",
7
+ * keys: { v1: secretBytes },
8
+ * defaultKid: "v1",
9
+ * });
10
+ *
11
+ * await signer.send({ url: "https://example.com/hook", body: jsonString });
12
+ * // POSTs with:
13
+ * // Webhook-Signature: t=<unix-seconds>,id=<uuid>,v1=<sig-hex>
14
+ *
15
+ * var verifier = b.webhook.verifier({
16
+ * algo: "hmac-sha3-512",
17
+ * keys: { v1: secret, v0: oldSecret }, // multi-key for rotation
18
+ * toleranceMs: b.constants.TIME.minutes(5),
19
+ * nonceStore: b.nonceStore.create({ ... }), // optional replay defense
20
+ * });
21
+ *
22
+ * router.use(b.middleware.bodyParser({ keepRawBody: true })); // REQUIRED
23
+ * router.post("/inbound-webhook", verifier.middleware(), function (req, res) {
24
+ * // req.webhook = { algo, kid, timestamp, id }
25
+ * });
26
+ *
27
+ * Algorithms:
28
+ * "hmac-sha3-512" — symmetric. keys: { kid → Buffer/string secret }
29
+ * "pqc-pem" — asymmetric. keys map for signer:
30
+ * { kid → { privateKey, publicKey } } (PEM)
31
+ * keys map for verifier:
32
+ * { kid → publicKey } (PEM)
33
+ * Algorithm (SLH-DSA-SHAKE-256f / ML-DSA-87) is
34
+ * auto-detected by Node from the PEM. No classical
35
+ * (Ed25519, RSA, ECDSA) signature scheme is exposed.
36
+ *
37
+ * Signed string (deterministic, prefix-bound to defend against algorithm-
38
+ * substitution and key-substitution attacks):
39
+ *
40
+ * <algo>.<kid>.<timestamp>.<id>.<body>
41
+ *
42
+ * Header format (single combined header, Stripe-shape):
43
+ *
44
+ * Webhook-Signature: t=<unix-seconds>,id=<uuid>,<kid>=<sig-hex>
45
+ *
46
+ * `t` and `id` are reserved segment names; every other `<name>=<value>`
47
+ * pair is treated as a kid → signature mapping. Multiple kid pairs are
48
+ * accepted on the verifier side; the signer emits exactly one. Operators
49
+ * rotating keys point the verifier at both old + new keys and migrate
50
+ * signers progressively.
51
+ *
52
+ * Replay defense:
53
+ * - `id` is included in the signed string, so a captured signature
54
+ * cannot be reused with a fresh id.
55
+ * - Optional `nonceStore` records seen ids; second delivery with the
56
+ * same id rejects with REPLAY. The framework's b.nonceStore is the
57
+ * reference impl; operators plug in Redis/SQL by passing any object
58
+ * with `checkAndInsert(nonce, expireAt) → bool/Promise<bool>`.
59
+ *
60
+ * Validation policy:
61
+ *
62
+ * - signer/verifier creation opts → throw at config time
63
+ * - signer.sign body type → throw at call site
64
+ * - signer.send url shape → throw at call site (via safeUrl)
65
+ * - verifier.verify input shape → throw WebhookError at call site
66
+ * - nonceStore.checkAndInsert err → propagates (fail-closed)
67
+ */
68
+
69
+ var crypto = require("./crypto");
70
+ var httpClient = require("./http-client");
71
+ var safeBuffer = require("./safe-buffer");
72
+ var safeUrl = require("./safe-url");
73
+ var retry = require("./retry");
74
+ var C = require("./constants");
75
+ var lazyRequire = require("./lazy-require");
76
+ var numericChecks = require("./numeric-checks");
77
+ var requestHelpers = require("./request-helpers");
78
+ var validateOpts = require("./validate-opts");
79
+ var { WebhookError } = require("./framework-error");
80
+
81
+ var observability = lazyRequire(function () { return require("./observability"); });
82
+
83
+ function _emitEvent(n, v, l) { observability().safeEvent(n, v, l || {}); }
84
+
85
+ var _err = WebhookError.factory;
86
+
87
+ // ---- Constants ----
88
+
89
+ var ALGOS = Object.freeze({
90
+ HMAC_SHA3_512: "hmac-sha3-512",
91
+ PQC_PEM: "pqc-pem",
92
+ });
93
+
94
+ var HEADER = Object.freeze({
95
+ SIGNATURE: "Webhook-Signature",
96
+ });
97
+
98
+ var DEFAULTS = Object.freeze({
99
+ toleranceMs: C.TIME.minutes(5),
100
+ clockSkewMs: C.TIME.minutes(1),
101
+ signatureHeader: HEADER.SIGNATURE,
102
+ // Audit defaults: BOTH success and failure default ON. The webhook
103
+ // verify is the framework boundary where an inbound message gets
104
+ // accepted — that acceptance IS the audit-worthy event, not a
105
+ // precursor to one. "Inbound webhook id <X> verified from kid <Y>
106
+ // at time T" is the compliance trail. The send side mirrors:
107
+ // outbound delivery success/failure to a partner is also a
108
+ // standalone audit event. Operators with extreme volume opt out
109
+ // via auditSuccess: false; failures remain on regardless.
110
+ auditFailures: true,
111
+ auditSuccess: true,
112
+ });
113
+
114
+ // ---- Call-site validation helpers (throw on bad input) ----
115
+
116
+ var _isPositiveInt = numericChecks.isPositiveInt;
117
+ var _isNonNegFinite = numericChecks.isFiniteNonNegative;
118
+ function _hasOwn(obj, k) { return Object.prototype.hasOwnProperty.call(obj, k); }
119
+ function _objectKeys(obj) { return Object.keys(obj); }
120
+
121
+ function _validateAlgo(algo) {
122
+ if (algo !== ALGOS.HMAC_SHA3_512 && algo !== ALGOS.PQC_PEM) {
123
+ throw _err("BAD_OPT", "webhook: algo must be one of " +
124
+ JSON.stringify([ALGOS.HMAC_SHA3_512, ALGOS.PQC_PEM]) + ", got " + JSON.stringify(algo));
125
+ }
126
+ }
127
+
128
+ function _validateKeysShape(name, algo, keys, side) {
129
+ if (!keys || typeof keys !== "object" || Array.isArray(keys)) {
130
+ throw _err("BAD_OPT", name + ": keys must be a non-empty object map of kid → key, got " +
131
+ typeof keys);
132
+ }
133
+ var kids = _objectKeys(keys);
134
+ if (kids.length === 0) {
135
+ throw _err("BAD_OPT", name + ": keys must have at least one kid entry");
136
+ }
137
+ for (var i = 0; i < kids.length; i++) {
138
+ var kid = kids[i];
139
+ if (kid.length === 0 || /[,=\s]/.test(kid)) {
140
+ throw _err("BAD_OPT", name + ": kid must be non-empty and contain no comma/equals/whitespace, got " +
141
+ JSON.stringify(kid));
142
+ }
143
+ if (kid === "t" || kid === "id") {
144
+ throw _err("BAD_OPT", name + ": kid '" + kid + "' is reserved (collides with header field)");
145
+ }
146
+ var k = keys[kid];
147
+ if (algo === ALGOS.HMAC_SHA3_512) {
148
+ if (!Buffer.isBuffer(k) && typeof k !== "string") {
149
+ throw _err("BAD_OPT", name + ": HMAC key for kid '" + kid +
150
+ "' must be a Buffer or string, got " + typeof k);
151
+ }
152
+ if (k.length === 0) {
153
+ throw _err("BAD_OPT", name + ": HMAC key for kid '" + kid + "' must be non-empty");
154
+ }
155
+ } else if (algo === ALGOS.PQC_PEM) {
156
+ if (side === "signer") {
157
+ if (!k || typeof k !== "object" || Array.isArray(k) ||
158
+ (typeof k.privateKey !== "string" && !Buffer.isBuffer(k.privateKey)) ||
159
+ (typeof k.publicKey !== "string" && !Buffer.isBuffer(k.publicKey))) {
160
+ throw _err("BAD_OPT", name + ": PQC signer key for kid '" + kid +
161
+ "' must be { privateKey, publicKey } as PEM strings/Buffers");
162
+ }
163
+ } else {
164
+ if (typeof k !== "string" && !Buffer.isBuffer(k)) {
165
+ throw _err("BAD_OPT", name + ": PQC verifier key for kid '" + kid +
166
+ "' must be a PEM string/Buffer (public key)");
167
+ }
168
+ }
169
+ }
170
+ }
171
+ }
172
+
173
+ function _validateBody(body) {
174
+ if (typeof body !== "string" && !Buffer.isBuffer(body)) {
175
+ throw _err("BAD_BODY", "webhook: body must be a string or Buffer, got " + typeof body);
176
+ }
177
+ }
178
+
179
+ // ---- Signed-string composition ----
180
+
181
+ function _composeSignedString(algo, kid, timestamp, id, body) {
182
+ var prefix = algo + "." + kid + "." + timestamp + "." + id + ".";
183
+ if (Buffer.isBuffer(body)) {
184
+ return Buffer.concat([Buffer.from(prefix, "utf8"), body]);
185
+ }
186
+ return Buffer.from(prefix + body, "utf8");
187
+ }
188
+
189
+ // ---- Sign / verify primitives ----
190
+
191
+ function _hmacSign(key, data) {
192
+ return crypto.hmacSha3(key, data); // hex string
193
+ }
194
+
195
+ function _hmacVerify(key, data, expectedHex) {
196
+ if (!safeBuffer.isHex(expectedHex)) return false;
197
+ var actualHex = crypto.hmacSha3(key, data);
198
+ return crypto.timingSafeEqual(actualHex, expectedHex);
199
+ }
200
+
201
+ function _pqcSign(privateKeyPem, data) {
202
+ return crypto.sign(data, privateKeyPem).toString("hex");
203
+ }
204
+
205
+ function _pqcVerify(publicKeyPem, data, expectedHex) {
206
+ if (!safeBuffer.isHex(expectedHex) || (expectedHex.length % 2) !== 0) {
207
+ return false;
208
+ }
209
+ var sigBuf;
210
+ try { sigBuf = Buffer.from(expectedHex, "hex"); }
211
+ catch (_e) { return false; }
212
+ try { return crypto.verify(data, sigBuf, publicKeyPem); }
213
+ catch (_e) { return false; }
214
+ }
215
+
216
+ // ---- Header parsing ----
217
+ //
218
+ // Format: t=<seconds>,id=<uuid>,<kid>=<hex>[,<kid>=<hex>]*
219
+ // `t` and `id` are reserved segment names; everything else is treated as
220
+ // a kid → signature pair. Whitespace tolerated around commas.
221
+
222
+ function _parseSignatureHeader(headerValue) {
223
+ var segs = requestHelpers.parseListHeader(headerValue);
224
+ var t = null, id = null, sigs = {};
225
+ for (var i = 0; i < segs.length; i++) {
226
+ var seg = segs[i];
227
+ var eq = seg.indexOf("=");
228
+ if (eq <= 0) continue; // skip malformed segments rather than failing whole header
229
+ var name = seg.slice(0, eq);
230
+ var value = seg.slice(eq + 1);
231
+ if (name === "t") t = value;
232
+ else if (name === "id") id = value;
233
+ else if (name.length > 0) sigs[name] = value; // kid → sig hex
234
+ }
235
+ return { t: t, id: id, sigs: sigs };
236
+ }
237
+
238
+ // ---- Signer ----
239
+
240
+ function _validateSignerOpts(opts) {
241
+ validateOpts.requireObject(opts, "webhook.signer", WebhookError);
242
+ _validateAlgo(opts.algo);
243
+ _validateKeysShape("webhook.signer", opts.algo, opts.keys, "signer");
244
+ var kids = _objectKeys(opts.keys);
245
+ if (opts.defaultKid !== undefined) {
246
+ if (!_hasOwn(opts.keys, opts.defaultKid)) {
247
+ throw _err("BAD_OPT", "webhook.signer: defaultKid '" + opts.defaultKid +
248
+ "' not present in keys (have: " + JSON.stringify(kids) + ")");
249
+ }
250
+ } else if (kids.length > 1) {
251
+ throw _err("BAD_OPT", "webhook.signer: defaultKid required when keys has " +
252
+ kids.length + " entries");
253
+ }
254
+ validateOpts.optionalNonEmptyString(opts.signatureHeader, "webhook.signer: signatureHeader", WebhookError);
255
+ validateOpts.optionalFunction(opts.idGenerator, "webhook.signer: idGenerator", WebhookError);
256
+ validateOpts.optionalFunction(opts.now, "webhook.signer: now", WebhookError);
257
+ validateOpts.auditShape(opts.audit, "webhook.signer", WebhookError);
258
+ }
259
+
260
+ function signer(opts) {
261
+ _validateSignerOpts(opts);
262
+ var algo = opts.algo;
263
+ var cfg = validateOpts.applyDefaults(opts, DEFAULTS);
264
+ var keys = opts.keys;
265
+ var kids = _objectKeys(keys);
266
+ var defaultKid = opts.defaultKid || kids[0];
267
+ var sigHeader = cfg.signatureHeader;
268
+ var idGen = opts.idGenerator || function () { return crypto.generateToken(C.BYTES.bytes(16)); };
269
+ var nowFn = opts.now || function () { return Date.now(); };
270
+ var retryOpts = opts.retry || retry.DEFAULT_RETRY;
271
+ var httpOpts = opts.http || {};
272
+ var audit = opts.audit || null;
273
+ var auditFailures = cfg.auditFailures;
274
+ var auditSuccess = cfg.auditSuccess;
275
+
276
+ var _auditEmit = validateOpts.makeAuditEmitter(audit);
277
+
278
+ function _signOne(body, kid) {
279
+ _validateBody(body);
280
+ var keyForKid = kids.indexOf(kid) === -1 ? null : keys[kid];
281
+ if (keyForKid == null) {
282
+ throw _err("BAD_OPT", "webhook.signer: unknown kid '" + kid + "'");
283
+ }
284
+ var timestamp = Math.floor(nowFn() / C.TIME.seconds(1));
285
+ var id = idGen();
286
+ if (typeof id !== "string" || id.length === 0 || /[,=\s]/.test(id)) {
287
+ throw _err("BAD_OPT", "webhook.signer: idGenerator must return a non-empty string with no comma/equals/whitespace, got " + JSON.stringify(id));
288
+ }
289
+ var signed = _composeSignedString(algo, kid, timestamp, id, body);
290
+ var sigHex;
291
+ if (algo === ALGOS.HMAC_SHA3_512) {
292
+ sigHex = _hmacSign(keyForKid, signed);
293
+ } else {
294
+ sigHex = _pqcSign(keyForKid.privateKey, signed);
295
+ }
296
+ return { kid: kid, timestamp: timestamp, id: id, signature: sigHex };
297
+ }
298
+
299
+ function sign(body, callOpts) {
300
+ var kid = (callOpts && callOpts.kid) || defaultKid;
301
+ var s = _signOne(body, kid);
302
+ var headerValue = "t=" + s.timestamp + ",id=" + s.id + "," + s.kid + "=" + s.signature;
303
+ var headers = {};
304
+ headers[sigHeader] = headerValue;
305
+ return {
306
+ headers: headers,
307
+ timestamp: s.timestamp,
308
+ id: s.id,
309
+ kid: s.kid,
310
+ signature: s.signature,
311
+ };
312
+ }
313
+
314
+ function headers(body, callOpts) {
315
+ return sign(body, callOpts).headers;
316
+ }
317
+
318
+ async function send(input) {
319
+ if (!input || typeof input !== "object") {
320
+ throw _err("BAD_OPT", "webhook.signer.send: input must be { url, body, headers? }");
321
+ }
322
+ var url = input.url;
323
+ var body = input.body;
324
+ safeUrl.parse(url, {
325
+ allowedProtocols: httpOpts.allowedProtocols || safeUrl.ALLOW_HTTP_TLS,
326
+ errorClass: WebhookError,
327
+ });
328
+ _validateBody(body);
329
+ var signed = sign(body, { kid: input.kid });
330
+ var mergedHeaders = Object.assign({}, input.headers || {}, signed.headers);
331
+ if (!mergedHeaders["Content-Type"] && !mergedHeaders["content-type"]) {
332
+ mergedHeaders["Content-Type"] = Buffer.isBuffer(body)
333
+ ? "application/octet-stream"
334
+ : "application/json";
335
+ }
336
+ var requestOpts = Object.assign({
337
+ method: "POST",
338
+ url: url,
339
+ headers: mergedHeaders,
340
+ body: body,
341
+ allowedProtocols: safeUrl.ALLOW_HTTP_TLS,
342
+ errorClass: WebhookError,
343
+ }, httpOpts);
344
+ requestOpts.headers = mergedHeaders;
345
+ requestOpts.url = url;
346
+ requestOpts.body = body;
347
+ requestOpts.method = "POST";
348
+ var hostLabel = "";
349
+ try {
350
+ hostLabel = safeUrl.parse(url, {
351
+ allowedProtocols: httpOpts.allowedProtocols || safeUrl.ALLOW_HTTP_TLS,
352
+ errorClass: WebhookError,
353
+ }).host;
354
+ } catch (_e) { hostLabel = ""; }
355
+ try {
356
+ var res = await retry.withRetry(function () {
357
+ return httpClient.request(requestOpts);
358
+ }, retryOpts);
359
+ var statusCode = (res && (res.statusCode || res.status)) || 0;
360
+ _emitEvent("webhook.send", 1, {
361
+ outcome: statusCode >= 200 && statusCode < 300 ? "success" : "failure",
362
+ status: statusCode,
363
+ host: hostLabel,
364
+ });
365
+ if (auditSuccess && statusCode >= 200 && statusCode < 300) {
366
+ _auditEmit("webhook.send", {
367
+ resource: { kind: "webhook", id: hostLabel },
368
+ outcome: "success",
369
+ metadata: { status: statusCode },
370
+ });
371
+ }
372
+ if (auditFailures && (statusCode < 200 || statusCode >= 300)) {
373
+ _auditEmit("webhook.send", {
374
+ resource: { kind: "webhook", id: hostLabel },
375
+ outcome: "failure",
376
+ reason: "http-" + statusCode,
377
+ });
378
+ }
379
+ return res;
380
+ } catch (err) {
381
+ _emitEvent("webhook.send", 1, {
382
+ outcome: "failure", reason: "transport-error", host: hostLabel,
383
+ });
384
+ if (auditFailures) {
385
+ _auditEmit("webhook.send", {
386
+ resource: { kind: "webhook", id: hostLabel },
387
+ outcome: "failure",
388
+ reason: (err && err.code) || "transport-error",
389
+ });
390
+ }
391
+ throw err;
392
+ }
393
+ }
394
+
395
+ return {
396
+ sign: sign,
397
+ headers: headers,
398
+ send: send,
399
+ };
400
+ }
401
+
402
+ // ---- Verifier ----
403
+
404
+ function _validateVerifierOpts(opts) {
405
+ validateOpts.requireObject(opts, "webhook.verifier", WebhookError);
406
+ _validateAlgo(opts.algo);
407
+ _validateKeysShape("webhook.verifier", opts.algo, opts.keys, "verifier");
408
+ validateOpts.optionalFiniteNonNegative(opts.toleranceMs, "webhook.verifier: toleranceMs", WebhookError);
409
+ validateOpts.optionalFiniteNonNegative(opts.clockSkewMs, "webhook.verifier: clockSkewMs", WebhookError);
410
+ validateOpts.optionalNonEmptyString(opts.signatureHeader, "webhook.verifier: signatureHeader", WebhookError);
411
+ validateOpts.optionalObjectWithMethod(opts.nonceStore, "checkAndInsert",
412
+ "webhook.verifier: nonceStore", WebhookError, "BAD_OPT",
413
+ "must implement checkAndInsert(nonce, expireAt)");
414
+ validateOpts.optionalFunction(opts.now, "webhook.verifier: now", WebhookError);
415
+ validateOpts.auditShape(opts.audit, "webhook.verifier", WebhookError);
416
+ validateOpts.optionalBoolean(opts.auditFailures, "webhook.verifier: auditFailures", WebhookError);
417
+ validateOpts.optionalBoolean(opts.auditSuccess, "webhook.verifier: auditSuccess", WebhookError);
418
+ }
419
+
420
+ function verifier(opts) {
421
+ _validateVerifierOpts(opts);
422
+ var cfg = validateOpts.applyDefaults(opts, DEFAULTS);
423
+ var algo = opts.algo;
424
+ var keys = opts.keys;
425
+ var toleranceMs = cfg.toleranceMs;
426
+ var clockSkewMs = cfg.clockSkewMs;
427
+ var sigHeader = cfg.signatureHeader.toLowerCase();
428
+ var nonceStore = opts.nonceStore || null;
429
+ var nowFn = opts.now || function () { return Date.now(); };
430
+ var audit = opts.audit || null;
431
+ var auditFailures = cfg.auditFailures;
432
+ var auditSuccess = cfg.auditSuccess;
433
+
434
+ function _auditEmit(outcome, reason, info, req) {
435
+ if (!audit) return;
436
+ if (outcome === "success" && !auditSuccess) return;
437
+ if (outcome === "failure" && !auditFailures) return;
438
+ try {
439
+ audit.safeEmit({
440
+ action: "webhook.verify",
441
+ actor: requestHelpers.extractActorContext(req),
442
+ resource: { kind: "webhook" },
443
+ outcome: outcome,
444
+ reason: reason || null,
445
+ metadata: info || null,
446
+ });
447
+ } catch (_e) { /* audit best-effort */ }
448
+ }
449
+
450
+ function _failure(code, message, reason, req) {
451
+ _emitEvent("webhook.verify", 1, { outcome: "failure", reason: reason || code });
452
+ _auditEmit("failure", reason || code, null, req);
453
+ return _err(code, message);
454
+ }
455
+
456
+ async function verify(input) {
457
+ if (!input || typeof input !== "object") {
458
+ throw _err("BAD_OPT", "webhook.verifier.verify: input must be { body, headers }");
459
+ }
460
+ var headers = input.headers;
461
+ if (!headers || typeof headers !== "object") {
462
+ throw _err("BAD_OPT", "webhook.verifier.verify: headers must be an object");
463
+ }
464
+ var body = input.body;
465
+ _validateBody(body);
466
+ var ctxReq = input.req || null;
467
+
468
+ // Headers may be node-style (lowercased keys) or operator-supplied
469
+ // (mixed case). Resolve case-insensitively.
470
+ var headerValue = null;
471
+ var headerKeys = Object.keys(headers);
472
+ for (var i = 0; i < headerKeys.length; i++) {
473
+ if (headerKeys[i].toLowerCase() === sigHeader) {
474
+ headerValue = headers[headerKeys[i]];
475
+ break;
476
+ }
477
+ }
478
+ if (typeof headerValue !== "string" || headerValue.length === 0) {
479
+ throw _failure("MISSING_HEADER",
480
+ "webhook: " + (opts.signatureHeader || HEADER.SIGNATURE) + " header missing",
481
+ "missing-header", ctxReq);
482
+ }
483
+
484
+ var parsed = _parseSignatureHeader(headerValue);
485
+ if (parsed.t === null && parsed.id === null && Object.keys(parsed.sigs).length === 0) {
486
+ throw _failure("BAD_HEADER_FORMAT", "webhook: signature header could not be parsed", "bad-header-format", ctxReq);
487
+ }
488
+ if (parsed.t === null) {
489
+ throw _failure("MISSING_TIMESTAMP", "webhook: t= field missing from signature header", "missing-timestamp", ctxReq);
490
+ }
491
+ var ts = Number(parsed.t);
492
+ if (!isFinite(ts) || ts < 0 || Math.floor(ts) !== ts) {
493
+ throw _failure("BAD_TIMESTAMP", "webhook: t= field is not a non-negative integer, got " + JSON.stringify(parsed.t), "bad-timestamp", ctxReq);
494
+ }
495
+ if (parsed.id === null || parsed.id.length === 0) {
496
+ throw _failure("MISSING_ID", "webhook: id= field missing from signature header", "missing-id", ctxReq);
497
+ }
498
+ var sigKids = Object.keys(parsed.sigs);
499
+ if (sigKids.length === 0) {
500
+ throw _failure("MISSING_SIGNATURE", "webhook: no v<kid>= segment found in signature header", "missing-signature", ctxReq);
501
+ }
502
+
503
+ // Timestamp window: signed in seconds, compare to ms clock.
504
+ var nowMs = nowFn();
505
+ var ageMs = nowMs - C.TIME.seconds(ts);
506
+ if (ageMs > toleranceMs) {
507
+ throw _failure("EXPIRED", "webhook: timestamp older than toleranceMs (age=" + ageMs + "ms)", "expired", ctxReq);
508
+ }
509
+ if (-ageMs > clockSkewMs) {
510
+ throw _failure("FUTURE", "webhook: timestamp in the future beyond clockSkewMs (skew=" + (-ageMs) + "ms)", "future", ctxReq);
511
+ }
512
+
513
+ // Find the first kid the verifier holds a key for.
514
+ var matchedKid = null;
515
+ for (var j = 0; j < sigKids.length; j++) {
516
+ if (_hasOwn(keys, sigKids[j])) { matchedKid = sigKids[j]; break; }
517
+ }
518
+ if (matchedKid === null) {
519
+ throw _failure("UNKNOWN_KID",
520
+ "webhook: no registered key matches signed kids " + JSON.stringify(sigKids),
521
+ "unknown-kid", ctxReq);
522
+ }
523
+
524
+ var signed = _composeSignedString(algo, matchedKid, ts, parsed.id, body);
525
+ var ok;
526
+ if (algo === ALGOS.HMAC_SHA3_512) {
527
+ ok = _hmacVerify(keys[matchedKid], signed, parsed.sigs[matchedKid]);
528
+ } else {
529
+ ok = _pqcVerify(keys[matchedKid], signed, parsed.sigs[matchedKid]);
530
+ }
531
+ if (!ok) {
532
+ throw _failure("BAD_SIGNATURE", "webhook: cryptographic verification failed", "bad-signature", ctxReq);
533
+ }
534
+
535
+ if (nonceStore) {
536
+ var expireAt = C.TIME.seconds(ts) + toleranceMs;
537
+ var fresh = await nonceStore.checkAndInsert(parsed.id, expireAt);
538
+ if (!fresh) {
539
+ throw _failure("REPLAY", "webhook: id '" + parsed.id + "' has been seen before", "replay", ctxReq);
540
+ }
541
+ }
542
+
543
+ _emitEvent("webhook.verify", 1, { outcome: "success", kid: matchedKid });
544
+ _auditEmit("success", null, { kid: matchedKid }, ctxReq);
545
+ return { algo: algo, kid: matchedKid, timestamp: ts, id: parsed.id };
546
+ }
547
+
548
+ function middleware() {
549
+ return function (req, res, next) {
550
+ var raw = req.bodyRaw;
551
+ if (raw === undefined) {
552
+ if (Buffer.isBuffer(req.body)) raw = req.body;
553
+ else if (typeof req.body === "string") raw = req.body;
554
+ }
555
+ if (raw === undefined) {
556
+ return _writeError(res, 401, "MISSING_RAW_BODY",
557
+ "webhook verifier middleware requires bodyParser({ keepRawBody: true })");
558
+ }
559
+ verify({ body: raw, headers: req.headers, req: req }).then(
560
+ function (info) {
561
+ req.webhook = info;
562
+ next();
563
+ },
564
+ function (err) {
565
+ if (err && err.isWebhookError) {
566
+ _writeError(res, 401, err.code, err.message);
567
+ } else {
568
+ _writeError(res, 500, "VERIFY_ERROR", "webhook verification error");
569
+ }
570
+ }
571
+ );
572
+ };
573
+ }
574
+
575
+ return {
576
+ verify: verify,
577
+ middleware: middleware,
578
+ };
579
+ }
580
+
581
+ function _writeError(res, status, code, message) {
582
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
583
+ res.end(JSON.stringify({ error: code, message: message }));
584
+ }
585
+
586
+ // ---- Public surface ----
587
+
588
+ module.exports = {
589
+ signer: signer,
590
+ verifier: verifier,
591
+ ALGOS: ALGOS,
592
+ HEADER: HEADER,
593
+ DEFAULTS: DEFAULTS,
594
+ WebhookError: WebhookError,
595
+ };