@blamejs/core 0.4.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.
Files changed (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
package/lib/webhook.js ADDED
@@ -0,0 +1,632 @@
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 tiers:
61
+ *
62
+ * - signer/verifier creation opts → Tier A (throw)
63
+ * - signer.sign body type → Tier A (throw)
64
+ * - signer.send url shape → Tier A (throw via safeUrl)
65
+ * - verifier.verify input shape → Tier A (throw WebhookError)
66
+ * - nonceStore.checkAndInsert err → propagates (fail-closed)
67
+ */
68
+
69
+ var crypto = require("./crypto");
70
+ var httpClient = require("./http-client");
71
+ var safeUrl = require("./safe-url");
72
+ var retry = require("./retry");
73
+ var C = require("./constants");
74
+ var lazyRequire = require("./lazy-require");
75
+ var requestHelpers = require("./request-helpers");
76
+ var { WebhookError } = require("./framework-error");
77
+
78
+ var observability = lazyRequire(function () { return require("./observability"); });
79
+
80
+ function _emitEvent(name, value, labels) {
81
+ try { observability().event(name, value, labels || {}); }
82
+ catch (_e) { /* Tier B: hot-path observability sink */ }
83
+ }
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
+ // ---- Tier-A validation helpers ----
115
+
116
+ function _isPositiveInt(n) {
117
+ return typeof n === "number" && isFinite(n) && n >= 1 && Math.floor(n) === n;
118
+ }
119
+ function _isNonNegFinite(n) {
120
+ return typeof n === "number" && isFinite(n) && n >= 0;
121
+ }
122
+ function _hasOwn(obj, k) { return Object.prototype.hasOwnProperty.call(obj, k); }
123
+ function _objectKeys(obj) { return Object.keys(obj); }
124
+
125
+ function _validateAlgo(algo) {
126
+ if (algo !== ALGOS.HMAC_SHA3_512 && algo !== ALGOS.PQC_PEM) {
127
+ throw _err("BAD_OPT", "webhook: algo must be one of " +
128
+ JSON.stringify([ALGOS.HMAC_SHA3_512, ALGOS.PQC_PEM]) + ", got " + JSON.stringify(algo));
129
+ }
130
+ }
131
+
132
+ function _validateKeysShape(name, algo, keys, side) {
133
+ if (!keys || typeof keys !== "object" || Array.isArray(keys)) {
134
+ throw _err("BAD_OPT", name + ": keys must be a non-empty object map of kid → key, got " +
135
+ typeof keys);
136
+ }
137
+ var kids = _objectKeys(keys);
138
+ if (kids.length === 0) {
139
+ throw _err("BAD_OPT", name + ": keys must have at least one kid entry");
140
+ }
141
+ for (var i = 0; i < kids.length; i++) {
142
+ var kid = kids[i];
143
+ if (kid.length === 0 || /[,=\s]/.test(kid)) {
144
+ throw _err("BAD_OPT", name + ": kid must be non-empty and contain no comma/equals/whitespace, got " +
145
+ JSON.stringify(kid));
146
+ }
147
+ if (kid === "t" || kid === "id") {
148
+ throw _err("BAD_OPT", name + ": kid '" + kid + "' is reserved (collides with header field)");
149
+ }
150
+ var k = keys[kid];
151
+ if (algo === ALGOS.HMAC_SHA3_512) {
152
+ if (!Buffer.isBuffer(k) && typeof k !== "string") {
153
+ throw _err("BAD_OPT", name + ": HMAC key for kid '" + kid +
154
+ "' must be a Buffer or string, got " + typeof k);
155
+ }
156
+ if (k.length === 0) {
157
+ throw _err("BAD_OPT", name + ": HMAC key for kid '" + kid + "' must be non-empty");
158
+ }
159
+ } else if (algo === ALGOS.PQC_PEM) {
160
+ if (side === "signer") {
161
+ if (!k || typeof k !== "object" || Array.isArray(k) ||
162
+ (typeof k.privateKey !== "string" && !Buffer.isBuffer(k.privateKey)) ||
163
+ (typeof k.publicKey !== "string" && !Buffer.isBuffer(k.publicKey))) {
164
+ throw _err("BAD_OPT", name + ": PQC signer key for kid '" + kid +
165
+ "' must be { privateKey, publicKey } as PEM strings/Buffers");
166
+ }
167
+ } else {
168
+ if (typeof k !== "string" && !Buffer.isBuffer(k)) {
169
+ throw _err("BAD_OPT", name + ": PQC verifier key for kid '" + kid +
170
+ "' must be a PEM string/Buffer (public key)");
171
+ }
172
+ }
173
+ }
174
+ }
175
+ }
176
+
177
+ function _validateBody(body) {
178
+ if (typeof body !== "string" && !Buffer.isBuffer(body)) {
179
+ throw _err("BAD_BODY", "webhook: body must be a string or Buffer, got " + typeof body);
180
+ }
181
+ }
182
+
183
+ // ---- Signed-string composition ----
184
+
185
+ function _composeSignedString(algo, kid, timestamp, id, body) {
186
+ var prefix = algo + "." + kid + "." + timestamp + "." + id + ".";
187
+ if (Buffer.isBuffer(body)) {
188
+ return Buffer.concat([Buffer.from(prefix, "utf8"), body]);
189
+ }
190
+ return Buffer.from(prefix + body, "utf8");
191
+ }
192
+
193
+ // ---- Sign / verify primitives ----
194
+
195
+ function _hmacSign(key, data) {
196
+ return crypto.hmacSha3(key, data); // hex string
197
+ }
198
+
199
+ function _hmacVerify(key, data, expectedHex) {
200
+ if (typeof expectedHex !== "string" || !/^[0-9a-fA-F]+$/.test(expectedHex)) return false;
201
+ var actualHex = crypto.hmacSha3(key, data);
202
+ return crypto.timingSafeEqual(actualHex, expectedHex);
203
+ }
204
+
205
+ function _pqcSign(privateKeyPem, data) {
206
+ return crypto.sign(data, privateKeyPem).toString("hex");
207
+ }
208
+
209
+ function _pqcVerify(publicKeyPem, data, expectedHex) {
210
+ if (typeof expectedHex !== "string" || expectedHex.length === 0 ||
211
+ !/^[0-9a-fA-F]+$/.test(expectedHex) || (expectedHex.length % 2) !== 0) {
212
+ return false;
213
+ }
214
+ var sigBuf;
215
+ try { sigBuf = Buffer.from(expectedHex, "hex"); }
216
+ catch (_e) { return false; }
217
+ try { return crypto.verify(data, sigBuf, publicKeyPem); }
218
+ catch (_e) { return false; }
219
+ }
220
+
221
+ // ---- Header parsing ----
222
+ //
223
+ // Format: t=<seconds>,id=<uuid>,<kid>=<hex>[,<kid>=<hex>]*
224
+ // `t` and `id` are reserved segment names; everything else is treated as
225
+ // a kid → signature pair. Whitespace tolerated around commas.
226
+
227
+ function _parseSignatureHeader(headerValue) {
228
+ var parts = headerValue.split(",");
229
+ var t = null, id = null, sigs = {};
230
+ for (var i = 0; i < parts.length; i++) {
231
+ var seg = parts[i].trim();
232
+ var eq = seg.indexOf("=");
233
+ if (eq <= 0) continue; // skip malformed segments rather than failing whole header
234
+ var name = seg.slice(0, eq);
235
+ var value = seg.slice(eq + 1);
236
+ if (name === "t") t = value;
237
+ else if (name === "id") id = value;
238
+ else if (name.length > 0) sigs[name] = value; // kid → sig hex
239
+ }
240
+ return { t: t, id: id, sigs: sigs };
241
+ }
242
+
243
+ // ---- Signer ----
244
+
245
+ function _validateSignerOpts(opts) {
246
+ if (!opts || typeof opts !== "object") {
247
+ throw _err("BAD_OPT", "webhook.signer: opts must be an object");
248
+ }
249
+ _validateAlgo(opts.algo);
250
+ _validateKeysShape("webhook.signer", opts.algo, opts.keys, "signer");
251
+ var kids = _objectKeys(opts.keys);
252
+ if (opts.defaultKid !== undefined) {
253
+ if (!_hasOwn(opts.keys, opts.defaultKid)) {
254
+ throw _err("BAD_OPT", "webhook.signer: defaultKid '" + opts.defaultKid +
255
+ "' not present in keys (have: " + JSON.stringify(kids) + ")");
256
+ }
257
+ } else if (kids.length > 1) {
258
+ throw _err("BAD_OPT", "webhook.signer: defaultKid required when keys has " +
259
+ kids.length + " entries");
260
+ }
261
+ if (opts.signatureHeader !== undefined &&
262
+ (typeof opts.signatureHeader !== "string" || opts.signatureHeader.length === 0)) {
263
+ throw _err("BAD_OPT", "webhook.signer: signatureHeader must be a non-empty string");
264
+ }
265
+ if (opts.idGenerator !== undefined && typeof opts.idGenerator !== "function") {
266
+ throw _err("BAD_OPT", "webhook.signer: idGenerator must be a function or undefined");
267
+ }
268
+ if (opts.now !== undefined && typeof opts.now !== "function") {
269
+ throw _err("BAD_OPT", "webhook.signer: now must be a function or undefined");
270
+ }
271
+ if (opts.audit !== undefined && opts.audit !== null) {
272
+ if (typeof opts.audit !== "object" || typeof opts.audit.safeEmit !== "function") {
273
+ throw _err("BAD_OPT", "webhook.signer: audit must be a b.audit-shaped object (safeEmit fn)");
274
+ }
275
+ }
276
+ }
277
+
278
+ function signer(opts) {
279
+ _validateSignerOpts(opts);
280
+ var algo = opts.algo;
281
+ var keys = opts.keys;
282
+ var kids = _objectKeys(keys);
283
+ var defaultKid = opts.defaultKid || kids[0];
284
+ var sigHeader = opts.signatureHeader || HEADER.SIGNATURE;
285
+ var idGen = opts.idGenerator || function () { return crypto.generateToken(16); };
286
+ var nowFn = opts.now || function () { return Date.now(); };
287
+ var retryOpts = opts.retry || retry.DEFAULT_RETRY;
288
+ var httpOpts = opts.http || {};
289
+ var audit = opts.audit || null;
290
+ var auditFailures = (opts.auditFailures === undefined) ? DEFAULTS.auditFailures : opts.auditFailures;
291
+ var auditSuccess = (opts.auditSuccess === undefined) ? DEFAULTS.auditSuccess : opts.auditSuccess;
292
+
293
+ function _auditEmit(action, info) {
294
+ if (!audit) return;
295
+ try { audit.safeEmit(Object.assign({ action: action }, info || {})); }
296
+ catch (_e) { /* audit best-effort */ }
297
+ }
298
+
299
+ function _signOne(body, kid) {
300
+ _validateBody(body);
301
+ var keyForKid = kids.indexOf(kid) === -1 ? null : keys[kid];
302
+ if (keyForKid == null) {
303
+ throw _err("BAD_OPT", "webhook.signer: unknown kid '" + kid + "'");
304
+ }
305
+ var timestamp = Math.floor(nowFn() / 1000);
306
+ var id = idGen();
307
+ if (typeof id !== "string" || id.length === 0 || /[,=\s]/.test(id)) {
308
+ throw _err("BAD_OPT", "webhook.signer: idGenerator must return a non-empty string with no comma/equals/whitespace, got " + JSON.stringify(id));
309
+ }
310
+ var signed = _composeSignedString(algo, kid, timestamp, id, body);
311
+ var sigHex;
312
+ if (algo === ALGOS.HMAC_SHA3_512) {
313
+ sigHex = _hmacSign(keyForKid, signed);
314
+ } else {
315
+ sigHex = _pqcSign(keyForKid.privateKey, signed);
316
+ }
317
+ return { kid: kid, timestamp: timestamp, id: id, signature: sigHex };
318
+ }
319
+
320
+ function sign(body, callOpts) {
321
+ var kid = (callOpts && callOpts.kid) || defaultKid;
322
+ var s = _signOne(body, kid);
323
+ var headerValue = "t=" + s.timestamp + ",id=" + s.id + "," + s.kid + "=" + s.signature;
324
+ var headers = {};
325
+ headers[sigHeader] = headerValue;
326
+ return {
327
+ headers: headers,
328
+ timestamp: s.timestamp,
329
+ id: s.id,
330
+ kid: s.kid,
331
+ signature: s.signature,
332
+ };
333
+ }
334
+
335
+ function headers(body, callOpts) {
336
+ return sign(body, callOpts).headers;
337
+ }
338
+
339
+ async function send(input) {
340
+ if (!input || typeof input !== "object") {
341
+ throw _err("BAD_OPT", "webhook.signer.send: input must be { url, body, headers? }");
342
+ }
343
+ var url = input.url;
344
+ var body = input.body;
345
+ safeUrl.parse(url, {
346
+ allowedProtocols: httpOpts.allowedProtocols || safeUrl.ALLOW_HTTP_TLS,
347
+ errorClass: WebhookError,
348
+ });
349
+ _validateBody(body);
350
+ var signed = sign(body, { kid: input.kid });
351
+ var mergedHeaders = Object.assign({}, input.headers || {}, signed.headers);
352
+ if (!mergedHeaders["Content-Type"] && !mergedHeaders["content-type"]) {
353
+ mergedHeaders["Content-Type"] = Buffer.isBuffer(body)
354
+ ? "application/octet-stream"
355
+ : "application/json";
356
+ }
357
+ var requestOpts = Object.assign({
358
+ method: "POST",
359
+ url: url,
360
+ headers: mergedHeaders,
361
+ body: body,
362
+ allowedProtocols: safeUrl.ALLOW_HTTP_TLS,
363
+ errorClass: WebhookError,
364
+ }, httpOpts);
365
+ requestOpts.headers = mergedHeaders;
366
+ requestOpts.url = url;
367
+ requestOpts.body = body;
368
+ requestOpts.method = "POST";
369
+ var hostLabel = "";
370
+ try { hostLabel = new URL(url).host; } catch (_e) { hostLabel = ""; }
371
+ try {
372
+ var res = await retry.withRetry(function () {
373
+ return httpClient.request(requestOpts);
374
+ }, retryOpts);
375
+ var statusCode = (res && (res.statusCode || res.status)) || 0;
376
+ _emitEvent("webhook.send", 1, {
377
+ outcome: statusCode >= 200 && statusCode < 300 ? "success" : "failure",
378
+ status: statusCode,
379
+ host: hostLabel,
380
+ });
381
+ if (auditSuccess && statusCode >= 200 && statusCode < 300) {
382
+ _auditEmit("webhook.send", {
383
+ resource: { kind: "webhook", id: hostLabel },
384
+ outcome: "success",
385
+ metadata: { status: statusCode },
386
+ });
387
+ }
388
+ if (auditFailures && (statusCode < 200 || statusCode >= 300)) {
389
+ _auditEmit("webhook.send", {
390
+ resource: { kind: "webhook", id: hostLabel },
391
+ outcome: "failure",
392
+ reason: "http-" + statusCode,
393
+ });
394
+ }
395
+ return res;
396
+ } catch (err) {
397
+ _emitEvent("webhook.send", 1, {
398
+ outcome: "failure", reason: "transport-error", host: hostLabel,
399
+ });
400
+ if (auditFailures) {
401
+ _auditEmit("webhook.send", {
402
+ resource: { kind: "webhook", id: hostLabel },
403
+ outcome: "failure",
404
+ reason: (err && err.code) || "transport-error",
405
+ });
406
+ }
407
+ throw err;
408
+ }
409
+ }
410
+
411
+ return {
412
+ sign: sign,
413
+ headers: headers,
414
+ send: send,
415
+ };
416
+ }
417
+
418
+ // ---- Verifier ----
419
+
420
+ function _validateVerifierOpts(opts) {
421
+ if (!opts || typeof opts !== "object") {
422
+ throw _err("BAD_OPT", "webhook.verifier: opts must be an object");
423
+ }
424
+ _validateAlgo(opts.algo);
425
+ _validateKeysShape("webhook.verifier", opts.algo, opts.keys, "verifier");
426
+ if (opts.toleranceMs !== undefined && !_isNonNegFinite(opts.toleranceMs)) {
427
+ throw _err("BAD_OPT", "webhook.verifier: toleranceMs must be a non-negative finite number");
428
+ }
429
+ if (opts.clockSkewMs !== undefined && !_isNonNegFinite(opts.clockSkewMs)) {
430
+ throw _err("BAD_OPT", "webhook.verifier: clockSkewMs must be a non-negative finite number");
431
+ }
432
+ if (opts.signatureHeader !== undefined &&
433
+ (typeof opts.signatureHeader !== "string" || opts.signatureHeader.length === 0)) {
434
+ throw _err("BAD_OPT", "webhook.verifier: signatureHeader must be a non-empty string");
435
+ }
436
+ if (opts.nonceStore !== undefined && opts.nonceStore !== null) {
437
+ if (typeof opts.nonceStore !== "object" ||
438
+ typeof opts.nonceStore.checkAndInsert !== "function") {
439
+ throw _err("BAD_OPT", "webhook.verifier: nonceStore must implement checkAndInsert(nonce, expireAt)");
440
+ }
441
+ }
442
+ if (opts.now !== undefined && typeof opts.now !== "function") {
443
+ throw _err("BAD_OPT", "webhook.verifier: now must be a function or undefined");
444
+ }
445
+ if (opts.audit !== undefined && opts.audit !== null) {
446
+ if (typeof opts.audit !== "object" || typeof opts.audit.safeEmit !== "function") {
447
+ throw _err("BAD_OPT", "webhook.verifier: audit must be a b.audit-shaped object (safeEmit fn)");
448
+ }
449
+ }
450
+ if (opts.auditFailures !== undefined && typeof opts.auditFailures !== "boolean") {
451
+ throw _err("BAD_OPT", "webhook.verifier: auditFailures must be a boolean");
452
+ }
453
+ if (opts.auditSuccess !== undefined && typeof opts.auditSuccess !== "boolean") {
454
+ throw _err("BAD_OPT", "webhook.verifier: auditSuccess must be a boolean");
455
+ }
456
+ }
457
+
458
+ function verifier(opts) {
459
+ _validateVerifierOpts(opts);
460
+ var algo = opts.algo;
461
+ var keys = opts.keys;
462
+ var toleranceMs = (opts.toleranceMs !== undefined) ? opts.toleranceMs : DEFAULTS.toleranceMs;
463
+ var clockSkewMs = (opts.clockSkewMs !== undefined) ? opts.clockSkewMs : DEFAULTS.clockSkewMs;
464
+ var sigHeader = (opts.signatureHeader || HEADER.SIGNATURE).toLowerCase();
465
+ var nonceStore = opts.nonceStore || null;
466
+ var nowFn = opts.now || function () { return Date.now(); };
467
+ var audit = opts.audit || null;
468
+ var auditFailures = (opts.auditFailures === undefined) ? DEFAULTS.auditFailures : opts.auditFailures;
469
+ var auditSuccess = (opts.auditSuccess === undefined) ? DEFAULTS.auditSuccess : opts.auditSuccess;
470
+
471
+ function _auditEmit(outcome, reason, info, req) {
472
+ if (!audit) return;
473
+ if (outcome === "success" && !auditSuccess) return;
474
+ if (outcome === "failure" && !auditFailures) return;
475
+ try {
476
+ audit.safeEmit({
477
+ action: "webhook.verify",
478
+ actor: requestHelpers.extractActorContext(req),
479
+ resource: { kind: "webhook" },
480
+ outcome: outcome,
481
+ reason: reason || null,
482
+ metadata: info || null,
483
+ });
484
+ } catch (_e) { /* audit best-effort */ }
485
+ }
486
+
487
+ function _failure(code, message, reason, req) {
488
+ _emitEvent("webhook.verify", 1, { outcome: "failure", reason: reason || code });
489
+ _auditEmit("failure", reason || code, null, req);
490
+ return _err(code, message);
491
+ }
492
+
493
+ async function verify(input) {
494
+ if (!input || typeof input !== "object") {
495
+ throw _err("BAD_OPT", "webhook.verifier.verify: input must be { body, headers }");
496
+ }
497
+ var headers = input.headers;
498
+ if (!headers || typeof headers !== "object") {
499
+ throw _err("BAD_OPT", "webhook.verifier.verify: headers must be an object");
500
+ }
501
+ var body = input.body;
502
+ _validateBody(body);
503
+ var ctxReq = input.req || null;
504
+
505
+ // Headers may be node-style (lowercased keys) or operator-supplied
506
+ // (mixed case). Resolve case-insensitively.
507
+ var headerValue = null;
508
+ var headerKeys = Object.keys(headers);
509
+ for (var i = 0; i < headerKeys.length; i++) {
510
+ if (headerKeys[i].toLowerCase() === sigHeader) {
511
+ headerValue = headers[headerKeys[i]];
512
+ break;
513
+ }
514
+ }
515
+ if (typeof headerValue !== "string" || headerValue.length === 0) {
516
+ throw _failure("MISSING_HEADER",
517
+ "webhook: " + (opts.signatureHeader || HEADER.SIGNATURE) + " header missing",
518
+ "missing-header", ctxReq);
519
+ }
520
+
521
+ var parsed = _parseSignatureHeader(headerValue);
522
+ if (parsed.t === null && parsed.id === null && Object.keys(parsed.sigs).length === 0) {
523
+ throw _failure("BAD_HEADER_FORMAT", "webhook: signature header could not be parsed", "bad-header-format", ctxReq);
524
+ }
525
+ if (parsed.t === null) {
526
+ throw _failure("MISSING_TIMESTAMP", "webhook: t= field missing from signature header", "missing-timestamp", ctxReq);
527
+ }
528
+ var ts = Number(parsed.t);
529
+ if (!isFinite(ts) || ts < 0 || Math.floor(ts) !== ts) {
530
+ throw _failure("BAD_TIMESTAMP", "webhook: t= field is not a non-negative integer, got " + JSON.stringify(parsed.t), "bad-timestamp", ctxReq);
531
+ }
532
+ if (parsed.id === null || parsed.id.length === 0) {
533
+ throw _failure("MISSING_ID", "webhook: id= field missing from signature header", "missing-id", ctxReq);
534
+ }
535
+ var sigKids = Object.keys(parsed.sigs);
536
+ if (sigKids.length === 0) {
537
+ throw _failure("MISSING_SIGNATURE", "webhook: no v<kid>= segment found in signature header", "missing-signature", ctxReq);
538
+ }
539
+
540
+ // Timestamp window: signed in seconds, compare to ms clock.
541
+ var nowMs = nowFn();
542
+ var ageMs = nowMs - (ts * 1000);
543
+ if (ageMs > toleranceMs) {
544
+ throw _failure("EXPIRED", "webhook: timestamp older than toleranceMs (age=" + ageMs + "ms)", "expired", ctxReq);
545
+ }
546
+ if (-ageMs > clockSkewMs) {
547
+ throw _failure("FUTURE", "webhook: timestamp in the future beyond clockSkewMs (skew=" + (-ageMs) + "ms)", "future", ctxReq);
548
+ }
549
+
550
+ // Find the first kid the verifier holds a key for.
551
+ var matchedKid = null;
552
+ for (var j = 0; j < sigKids.length; j++) {
553
+ if (_hasOwn(keys, sigKids[j])) { matchedKid = sigKids[j]; break; }
554
+ }
555
+ if (matchedKid === null) {
556
+ throw _failure("UNKNOWN_KID",
557
+ "webhook: no registered key matches signed kids " + JSON.stringify(sigKids),
558
+ "unknown-kid", ctxReq);
559
+ }
560
+
561
+ var signed = _composeSignedString(algo, matchedKid, ts, parsed.id, body);
562
+ var ok;
563
+ if (algo === ALGOS.HMAC_SHA3_512) {
564
+ ok = _hmacVerify(keys[matchedKid], signed, parsed.sigs[matchedKid]);
565
+ } else {
566
+ ok = _pqcVerify(keys[matchedKid], signed, parsed.sigs[matchedKid]);
567
+ }
568
+ if (!ok) {
569
+ throw _failure("BAD_SIGNATURE", "webhook: cryptographic verification failed", "bad-signature", ctxReq);
570
+ }
571
+
572
+ if (nonceStore) {
573
+ var expireAt = (ts * 1000) + toleranceMs;
574
+ var fresh = await nonceStore.checkAndInsert(parsed.id, expireAt);
575
+ if (!fresh) {
576
+ throw _failure("REPLAY", "webhook: id '" + parsed.id + "' has been seen before", "replay", ctxReq);
577
+ }
578
+ }
579
+
580
+ _emitEvent("webhook.verify", 1, { outcome: "success", kid: matchedKid });
581
+ _auditEmit("success", null, { kid: matchedKid }, ctxReq);
582
+ return { algo: algo, kid: matchedKid, timestamp: ts, id: parsed.id };
583
+ }
584
+
585
+ function middleware() {
586
+ return function (req, res, next) {
587
+ var raw = req.bodyRaw;
588
+ if (raw === undefined) {
589
+ if (Buffer.isBuffer(req.body)) raw = req.body;
590
+ else if (typeof req.body === "string") raw = req.body;
591
+ }
592
+ if (raw === undefined) {
593
+ return _writeError(res, 401, "MISSING_RAW_BODY",
594
+ "webhook verifier middleware requires bodyParser({ keepRawBody: true })");
595
+ }
596
+ verify({ body: raw, headers: req.headers, req: req }).then(
597
+ function (info) {
598
+ req.webhook = info;
599
+ next();
600
+ },
601
+ function (err) {
602
+ if (err && err.isWebhookError) {
603
+ _writeError(res, 401, err.code, err.message);
604
+ } else {
605
+ _writeError(res, 500, "VERIFY_ERROR", "webhook verification error");
606
+ }
607
+ }
608
+ );
609
+ };
610
+ }
611
+
612
+ return {
613
+ verify: verify,
614
+ middleware: middleware,
615
+ };
616
+ }
617
+
618
+ function _writeError(res, status, code, message) {
619
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
620
+ res.end(JSON.stringify({ error: code, message: message }));
621
+ }
622
+
623
+ // ---- Public surface ----
624
+
625
+ module.exports = {
626
+ signer: signer,
627
+ verifier: verifier,
628
+ ALGOS: ALGOS,
629
+ HEADER: HEADER,
630
+ DEFAULTS: DEFAULTS,
631
+ WebhookError: WebhookError,
632
+ };