@blamejs/core 0.15.12 → 0.15.14

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 (365) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/index.js +2 -0
  3. package/lib/a2a-tasks.js +45 -29
  4. package/lib/acme.js +6 -5
  5. package/lib/agent-event-bus.js +18 -4
  6. package/lib/agent-idempotency.js +7 -6
  7. package/lib/agent-orchestrator.js +2 -5
  8. package/lib/agent-saga.js +3 -5
  9. package/lib/agent-snapshot.js +32 -2
  10. package/lib/agent-tenant.js +2 -5
  11. package/lib/ai-adverse-decision.js +2 -15
  12. package/lib/ai-aedt-bias-audit.js +2 -1
  13. package/lib/ai-capability.js +1 -6
  14. package/lib/ai-content-detect.js +1 -3
  15. package/lib/ai-dp.js +1 -5
  16. package/lib/ai-frontier-protocol.js +1 -1
  17. package/lib/ai-input.js +2 -2
  18. package/lib/ai-model-manifest.js +1 -1
  19. package/lib/ai-output.js +16 -7
  20. package/lib/ai-pref.js +3 -8
  21. package/lib/ai-quota.js +3 -14
  22. package/lib/api-key.js +37 -28
  23. package/lib/api-snapshot.js +4 -1
  24. package/lib/app-shutdown.js +7 -1
  25. package/lib/archive-adapters.js +2 -4
  26. package/lib/archive-entry-policy.js +32 -0
  27. package/lib/archive-gz.js +9 -0
  28. package/lib/archive-read.js +14 -24
  29. package/lib/archive-tar-read.js +56 -24
  30. package/lib/archive.js +6 -12
  31. package/lib/arg-parser.js +7 -6
  32. package/lib/asn1-der.js +70 -22
  33. package/lib/asyncapi-traits.js +2 -6
  34. package/lib/atomic-file.js +312 -33
  35. package/lib/audit-chain.js +183 -54
  36. package/lib/audit-daily-review.js +36 -16
  37. package/lib/audit-emit.js +82 -0
  38. package/lib/audit-sign.js +258 -0
  39. package/lib/audit-tools.js +108 -23
  40. package/lib/audit.js +91 -2
  41. package/lib/auth/access-lock.js +7 -29
  42. package/lib/auth/bot-challenge.js +1 -1
  43. package/lib/auth/ciba.js +43 -4
  44. package/lib/auth/dpop.js +29 -36
  45. package/lib/auth/fido-mds3.js +14 -16
  46. package/lib/auth/jwt-external.js +26 -8
  47. package/lib/auth/jwt.js +15 -17
  48. package/lib/auth/lockout.js +24 -27
  49. package/lib/auth/oauth.js +67 -45
  50. package/lib/auth/oid4vci.js +55 -32
  51. package/lib/auth/oid4vp.js +3 -2
  52. package/lib/auth/openid-federation.js +6 -6
  53. package/lib/auth/passkey.js +4 -4
  54. package/lib/auth/password.js +8 -2
  55. package/lib/auth/saml.js +70 -40
  56. package/lib/auth/sd-jwt-vc-holder.js +2 -14
  57. package/lib/auth/sd-jwt-vc-issuer.js +2 -14
  58. package/lib/auth/sd-jwt-vc.js +25 -5
  59. package/lib/auth/status-list.js +21 -9
  60. package/lib/auth/step-up.js +15 -13
  61. package/lib/auth-bot-challenge.js +27 -39
  62. package/lib/backup/bundle.js +18 -20
  63. package/lib/backup/crypto.js +23 -8
  64. package/lib/backup/index.js +55 -67
  65. package/lib/backup/manifest.js +7 -1
  66. package/lib/bounded-map.js +112 -1
  67. package/lib/breach-deadline.js +1 -11
  68. package/lib/break-glass.js +41 -22
  69. package/lib/cache.js +7 -18
  70. package/lib/cbor.js +36 -12
  71. package/lib/cdn-cache-control.js +15 -12
  72. package/lib/cert.js +8 -13
  73. package/lib/chain-writer.js +162 -47
  74. package/lib/cli.js +10 -2
  75. package/lib/client-hints.js +7 -9
  76. package/lib/cloud-events.js +43 -33
  77. package/lib/cluster-storage.js +9 -41
  78. package/lib/cms-codec.js +2 -1
  79. package/lib/codepoint-class.js +84 -1
  80. package/lib/compliance-ai-act-logging.js +1 -6
  81. package/lib/compliance-ai-act-transparency.js +2 -4
  82. package/lib/compliance-eaa.js +2 -12
  83. package/lib/compliance-sanctions-fetcher.js +21 -28
  84. package/lib/compliance-sanctions.js +11 -21
  85. package/lib/compliance.js +3 -10
  86. package/lib/config-drift.js +24 -20
  87. package/lib/content-credentials.js +11 -8
  88. package/lib/content-digest.js +21 -12
  89. package/lib/cookies.js +15 -13
  90. package/lib/cose.js +39 -11
  91. package/lib/cra-report.js +1 -11
  92. package/lib/crdt.js +2 -1
  93. package/lib/crypto-field.js +34 -33
  94. package/lib/crypto.js +138 -7
  95. package/lib/csp.js +239 -3
  96. package/lib/daemon.js +46 -42
  97. package/lib/data-act.js +46 -13
  98. package/lib/db-file-lifecycle.js +14 -6
  99. package/lib/db-query.js +75 -49
  100. package/lib/db.js +66 -27
  101. package/lib/dbsc.js +5 -6
  102. package/lib/ddl-change-control.js +18 -14
  103. package/lib/deprecate.js +4 -5
  104. package/lib/did.js +6 -2
  105. package/lib/dora.js +43 -13
  106. package/lib/dr-runbook.js +1 -1
  107. package/lib/dsa.js +2 -1
  108. package/lib/dsr.js +30 -20
  109. package/lib/early-hints.js +19 -0
  110. package/lib/eat.js +5 -1
  111. package/lib/external-db-migrate.js +21 -22
  112. package/lib/external-db.js +74 -30
  113. package/lib/fda-21cfr11.js +42 -13
  114. package/lib/fdx.js +22 -18
  115. package/lib/file-upload.js +80 -66
  116. package/lib/flag-evaluation-context.js +5 -8
  117. package/lib/flag-providers.js +6 -2
  118. package/lib/forms.js +1 -1
  119. package/lib/framework-error.js +12 -0
  120. package/lib/framework-schema.js +19 -0
  121. package/lib/fsm.js +7 -12
  122. package/lib/gate-contract.js +911 -39
  123. package/lib/gdpr-ropa.js +22 -22
  124. package/lib/graphql-federation.js +18 -5
  125. package/lib/guard-agent-registry.js +2 -1
  126. package/lib/guard-all.js +3 -2
  127. package/lib/guard-archive.js +9 -30
  128. package/lib/guard-auth.js +23 -80
  129. package/lib/guard-cidr.js +20 -96
  130. package/lib/guard-csv.js +135 -196
  131. package/lib/guard-domain.js +23 -106
  132. package/lib/guard-dsn.js +17 -14
  133. package/lib/guard-email.js +46 -53
  134. package/lib/guard-envelope.js +2 -2
  135. package/lib/guard-event-bus-topic.js +2 -1
  136. package/lib/guard-filename.js +12 -60
  137. package/lib/guard-graphql.js +28 -75
  138. package/lib/guard-html-wcag.js +15 -2
  139. package/lib/guard-html.js +74 -128
  140. package/lib/guard-idempotency-key.js +2 -1
  141. package/lib/guard-image.js +280 -77
  142. package/lib/guard-imap-command.js +9 -10
  143. package/lib/guard-jmap.js +1 -1
  144. package/lib/guard-json.js +101 -109
  145. package/lib/guard-jsonpath.js +20 -88
  146. package/lib/guard-jwt.js +32 -114
  147. package/lib/guard-list-id.js +2 -7
  148. package/lib/guard-list-unsubscribe.js +2 -7
  149. package/lib/guard-mail-compose.js +5 -6
  150. package/lib/guard-mail-move.js +3 -2
  151. package/lib/guard-mail-query.js +5 -3
  152. package/lib/guard-mail-sieve.js +6 -7
  153. package/lib/guard-managesieve-command.js +6 -5
  154. package/lib/guard-markdown.js +76 -110
  155. package/lib/guard-message-id.js +5 -6
  156. package/lib/guard-mime.js +20 -99
  157. package/lib/guard-oauth.js +19 -73
  158. package/lib/guard-pdf.js +65 -72
  159. package/lib/guard-pop3-command.js +13 -14
  160. package/lib/guard-posture-chain.js +2 -1
  161. package/lib/guard-regex.js +24 -99
  162. package/lib/guard-saga-config.js +2 -1
  163. package/lib/guard-shell.js +22 -87
  164. package/lib/guard-smtp-command.js +9 -12
  165. package/lib/guard-sql.js +15 -13
  166. package/lib/guard-stream-args.js +2 -1
  167. package/lib/guard-svg.js +103 -149
  168. package/lib/guard-template.js +23 -80
  169. package/lib/guard-tenant-id.js +2 -1
  170. package/lib/guard-text.js +592 -0
  171. package/lib/guard-time.js +27 -95
  172. package/lib/guard-uuid.js +21 -93
  173. package/lib/guard-xml.js +76 -106
  174. package/lib/guard-yaml.js +24 -60
  175. package/lib/html-balance.js +7 -3
  176. package/lib/http-client-cache.js +5 -12
  177. package/lib/http-client-cookie-jar.js +35 -16
  178. package/lib/http-client.js +233 -74
  179. package/lib/http-message-signature.js +3 -2
  180. package/lib/i18n-messageformat.js +5 -7
  181. package/lib/i18n.js +83 -26
  182. package/lib/iab-tcf.js +3 -2
  183. package/lib/importmap-integrity.js +41 -1
  184. package/lib/inbox.js +8 -8
  185. package/lib/incident-report.js +12 -27
  186. package/lib/ip-utils.js +49 -6
  187. package/lib/jobs.js +3 -2
  188. package/lib/json-patch.js +1 -1
  189. package/lib/json-path.js +24 -3
  190. package/lib/jtd.js +2 -2
  191. package/lib/keychain.js +6 -18
  192. package/lib/legal-hold.js +30 -23
  193. package/lib/log-stream-cloudwatch.js +44 -112
  194. package/lib/log-stream-otlp-grpc.js +17 -14
  195. package/lib/log-stream-otlp.js +16 -80
  196. package/lib/log-stream-webhook.js +20 -92
  197. package/lib/log.js +2 -2
  198. package/lib/mail-agent.js +2 -2
  199. package/lib/mail-arc-sign.js +8 -3
  200. package/lib/mail-arf.js +4 -3
  201. package/lib/mail-auth.js +43 -69
  202. package/lib/mail-bimi.js +35 -55
  203. package/lib/mail-bounce.js +3 -3
  204. package/lib/mail-crypto-pgp.js +3 -2
  205. package/lib/mail-crypto-smime.js +71 -6
  206. package/lib/mail-dav.js +8 -35
  207. package/lib/mail-deploy.js +15 -14
  208. package/lib/mail-dkim.js +19 -38
  209. package/lib/mail-greylist.js +17 -30
  210. package/lib/mail-helo.js +4 -7
  211. package/lib/mail-journal.js +13 -9
  212. package/lib/mail-mdn.js +12 -7
  213. package/lib/mail-rbl.js +7 -12
  214. package/lib/mail-scan.js +5 -7
  215. package/lib/mail-send-deliver.js +33 -20
  216. package/lib/mail-server-imap.js +32 -87
  217. package/lib/mail-server-jmap.js +39 -52
  218. package/lib/mail-server-managesieve.js +29 -83
  219. package/lib/mail-server-mx.js +33 -74
  220. package/lib/mail-server-net.js +177 -0
  221. package/lib/mail-server-pop3.js +30 -83
  222. package/lib/mail-server-rate-limit.js +30 -6
  223. package/lib/mail-server-registry.js +1 -1
  224. package/lib/mail-server-submission.js +34 -73
  225. package/lib/mail-server-tls.js +98 -2
  226. package/lib/mail-spam-score.js +9 -12
  227. package/lib/mail-store-fts.js +1 -1
  228. package/lib/mail-store.js +3 -2
  229. package/lib/mail.js +28 -13
  230. package/lib/markup-escape.js +31 -0
  231. package/lib/markup-tokenizer.js +78 -0
  232. package/lib/mcp-tool-registry.js +26 -23
  233. package/lib/mcp.js +7 -5
  234. package/lib/mdoc.js +36 -14
  235. package/lib/metrics.js +46 -33
  236. package/lib/middleware/age-gate.js +3 -23
  237. package/lib/middleware/api-encrypt.js +13 -24
  238. package/lib/middleware/assetlinks.js +2 -7
  239. package/lib/middleware/bearer-auth.js +2 -1
  240. package/lib/middleware/body-parser.js +41 -52
  241. package/lib/middleware/bot-disclose.js +7 -10
  242. package/lib/middleware/bot-guard.js +28 -28
  243. package/lib/middleware/clear-site-data.js +5 -1
  244. package/lib/middleware/compression.js +9 -0
  245. package/lib/middleware/cors.js +32 -23
  246. package/lib/middleware/csrf-protect.js +73 -23
  247. package/lib/middleware/daily-byte-quota.js +12 -30
  248. package/lib/middleware/deny-response.js +19 -1
  249. package/lib/middleware/fetch-metadata.js +35 -4
  250. package/lib/middleware/idempotency-key.js +4 -20
  251. package/lib/middleware/network-allowlist.js +61 -30
  252. package/lib/middleware/rate-limit.js +45 -44
  253. package/lib/middleware/scim-server.js +5 -3
  254. package/lib/middleware/security-headers.js +33 -7
  255. package/lib/middleware/security-txt.js +2 -6
  256. package/lib/middleware/speculation-rules.js +6 -3
  257. package/lib/middleware/tus-upload.js +14 -29
  258. package/lib/middleware/web-app-manifest.js +2 -7
  259. package/lib/migrations.js +4 -13
  260. package/lib/mime-parse.js +34 -17
  261. package/lib/module-loader.js +44 -0
  262. package/lib/money.js +105 -0
  263. package/lib/mtls-ca.js +125 -41
  264. package/lib/network-byte-quota.js +4 -18
  265. package/lib/network-dane.js +8 -6
  266. package/lib/network-dns-resolver.js +98 -7
  267. package/lib/network-dns.js +9 -2
  268. package/lib/network-dnssec.js +18 -17
  269. package/lib/network-heartbeat.js +3 -2
  270. package/lib/network-smtp-policy.js +52 -46
  271. package/lib/network-tls.js +67 -47
  272. package/lib/network-tsig.js +2 -2
  273. package/lib/nis2-report.js +2 -12
  274. package/lib/nist-crosswalk.js +1 -1
  275. package/lib/nonce-store.js +81 -3
  276. package/lib/ntp-check.js +28 -0
  277. package/lib/numeric-bounds.js +31 -8
  278. package/lib/object-store/azure-blob-bucket-ops.js +2 -6
  279. package/lib/object-store/azure-blob.js +6 -47
  280. package/lib/object-store/gcs-bucket-ops.js +4 -2
  281. package/lib/object-store/gcs.js +14 -75
  282. package/lib/object-store/http-put.js +2 -7
  283. package/lib/object-store/http-request.js +157 -0
  284. package/lib/object-store/local.js +37 -17
  285. package/lib/object-store/sigv4-bucket-ops.js +2 -1
  286. package/lib/object-store/sigv4.js +10 -79
  287. package/lib/observability-otlp-exporter.js +29 -29
  288. package/lib/observability.js +95 -0
  289. package/lib/openapi-paths-builder.js +7 -3
  290. package/lib/otel-export.js +7 -10
  291. package/lib/outbox.js +54 -41
  292. package/lib/pagination.js +11 -15
  293. package/lib/parsers/safe-env.js +5 -4
  294. package/lib/parsers/safe-ini.js +10 -4
  295. package/lib/parsers/safe-toml.js +11 -9
  296. package/lib/parsers/safe-xml.js +3 -3
  297. package/lib/parsers/safe-yaml.js +28 -9
  298. package/lib/pick.js +63 -5
  299. package/lib/pipl-cn.js +69 -59
  300. package/lib/privacy-pass.js +8 -6
  301. package/lib/problem-details.js +2 -5
  302. package/lib/pubsub.js +4 -8
  303. package/lib/queue-local.js +10 -3
  304. package/lib/redact.js +9 -4
  305. package/lib/render.js +4 -2
  306. package/lib/request-helpers.js +334 -29
  307. package/lib/resource-access-lock.js +3 -3
  308. package/lib/restore-bundle.js +46 -18
  309. package/lib/restore-rollback.js +10 -4
  310. package/lib/restore.js +24 -22
  311. package/lib/retention.js +23 -9
  312. package/lib/router.js +17 -4
  313. package/lib/safe-async.js +457 -0
  314. package/lib/safe-buffer.js +137 -6
  315. package/lib/safe-decompress.js +2 -1
  316. package/lib/safe-dns.js +2 -1
  317. package/lib/safe-ical.js +14 -28
  318. package/lib/safe-icap.js +1 -1
  319. package/lib/safe-json.js +51 -8
  320. package/lib/safe-jsonpath.js +6 -5
  321. package/lib/safe-mime.js +25 -29
  322. package/lib/safe-redirect.js +2 -5
  323. package/lib/safe-schema.js +7 -6
  324. package/lib/safe-sieve.js +1 -1
  325. package/lib/safe-sql.js +126 -0
  326. package/lib/safe-vcard.js +13 -27
  327. package/lib/sandbox-worker.js +15 -2
  328. package/lib/sandbox.js +4 -3
  329. package/lib/scheduler.js +22 -13
  330. package/lib/sec-cyber.js +82 -37
  331. package/lib/seeders.js +4 -11
  332. package/lib/self-update-standalone-verifier.js +16 -0
  333. package/lib/self-update.js +92 -69
  334. package/lib/session-device-binding.js +112 -66
  335. package/lib/session.js +219 -7
  336. package/lib/sql.js +228 -81
  337. package/lib/sse.js +6 -10
  338. package/lib/static.js +201 -111
  339. package/lib/storage.js +4 -2
  340. package/lib/structured-fields.js +275 -16
  341. package/lib/template.js +7 -5
  342. package/lib/tenant-quota.js +53 -38
  343. package/lib/tsa.js +16 -17
  344. package/lib/validate-opts.js +154 -8
  345. package/lib/vault/index.js +5 -0
  346. package/lib/vault/passphrase-ops.js +22 -26
  347. package/lib/vault/passphrase-source.js +8 -3
  348. package/lib/vault/rotate.js +13 -18
  349. package/lib/vault/seal-pem-file.js +34 -49
  350. package/lib/vault-aad.js +3 -2
  351. package/lib/vc.js +3 -8
  352. package/lib/vendor/MANIFEST.json +10 -10
  353. package/lib/vendor/public-suffix-list.dat +23 -10
  354. package/lib/vendor/public-suffix-list.data.js +5498 -5494
  355. package/lib/vex.js +35 -13
  356. package/lib/web-push-vapid.js +23 -20
  357. package/lib/webhook-dispatcher.js +706 -0
  358. package/lib/webhook.js +59 -19
  359. package/lib/websocket-channels.js +9 -7
  360. package/lib/websocket.js +8 -4
  361. package/lib/worm.js +3 -4
  362. package/lib/ws-client.js +65 -56
  363. package/lib/x509-chain.js +44 -0
  364. package/package.json +1 -1
  365. package/sbom.cdx.json +6 -6
@@ -57,7 +57,9 @@ var nodeCrypto = require("node:crypto");
57
57
  var zlib = require("node:zlib");
58
58
  var asn1 = require("./asn1-der");
59
59
  var lazyRequire = require("./lazy-require");
60
+ var networkDnsResolver = lazyRequire(function () { return require("./network-dns-resolver"); });
60
61
  var validateOpts = require("./validate-opts");
62
+ var structuredFields = require("./structured-fields");
61
63
  var bCrypto = require("./crypto");
62
64
  var safeUrl = require("./safe-url");
63
65
  var safeJson = require("./safe-json");
@@ -91,14 +93,12 @@ function _parseStsPolicy(text) {
91
93
  "MTA-STS policy text is empty");
92
94
  }
93
95
  var policy = { version: null, mode: null, mx: [], max_age: null };
94
- var lines = text.split(/\r?\n/);
95
- for (var i = 0; i < lines.length; i += 1) {
96
- var line = lines[i].trim();
97
- if (line.length === 0) continue;
98
- var colonAt = line.indexOf(":");
99
- if (colonAt === -1) continue;
100
- var key = line.slice(0, colonAt).trim().toLowerCase();
101
- var val = line.slice(colonAt + 1).trim();
96
+ // RFC 8461 §3.2 — newline-separated `key: value` lines, no quoted-string;
97
+ // mx may repeat, so iterate pairs (a last-wins map would drop hosts).
98
+ var pairs = structuredFields.parseTagList(text, { sep: /\r?\n/, kvSep: ":" });
99
+ for (var i = 0; i < pairs.length; i += 1) {
100
+ var key = pairs[i][0];
101
+ var val = pairs[i][1];
102
102
  if (key === "version") policy.version = val;
103
103
  else if (key === "mode") policy.mode = val.toLowerCase();
104
104
  else if (key === "mx") policy.mx.push(val.toLowerCase());
@@ -123,17 +123,13 @@ function _parseStsPolicy(text) {
123
123
  // cached policy forever (defeating operator rotation), and would also
124
124
  // fetch policies from domains that don't publish one.
125
125
  async function _fetchStsTxt(domain, dnsLookup) {
126
- var records;
127
- try {
128
- records = dnsLookup
129
- ? await dnsLookup("_mta-sts." + domain, "TXT")
130
- : await dnsPromises.resolveTxt("_mta-sts." + domain);
131
- } catch (e) {
132
- if (e && (e.code === "ENOTFOUND" || e.code === "ENODATA")) return null;
133
- throw new SmtpPolicyError("smtp/mta-sts-txt-lookup-failed",
134
- "_mta-sts." + domain + " TXT lookup failed: " +
135
- ((e && e.message) || String(e)));
136
- }
126
+ // Secure DNS path — a spoofed _mta-sts TXT could downgrade mail TLS, so this
127
+ // must not use plaintext dnsPromises.
128
+ var records = await networkDnsResolver().safeResolveTxt("_mta-sts." + domain, {
129
+ dnsLookup: dnsLookup,
130
+ errorFactory: function (code, msg) { return new SmtpPolicyError(code, msg); },
131
+ code: "smtp/mta-sts-txt-lookup-failed",
132
+ });
137
133
  if (!Array.isArray(records)) return null;
138
134
  for (var i = 0; i < records.length; i += 1) {
139
135
  var rec = Array.isArray(records[i]) ? records[i].join("") : records[i];
@@ -180,6 +176,15 @@ async function mtaStsFetch(domain, opts) {
180
176
  rejectUnauthorized: true,
181
177
  });
182
178
  } catch (_e) {
179
+ // RFC 8461 opportunistic fallback: a policy that can't be fetched — a
180
+ // network error, OR (with rejectUnauthorized:true + pinned servername
181
+ // above) a TLS-validation failure that signals a possible MITM of the
182
+ // policy endpoint — yields "no enforceable policy", so the sender
183
+ // proceeds without MTA-STS. This is the documented TOFU limitation for an
184
+ // UN-cached first fetch only: a valid cached policy is honored by the
185
+ // _getStsCache().wrap() wrapper and never reaches this catch, and the TLS
186
+ // failure itself is independently audited by httpClient's TLS layer — so
187
+ // this is a deliberate opportunistic fallback, not a silent swallow.
183
188
  return null;
184
189
  }
185
190
  if (res.statusCode === 404) return null; // HTTP 404
@@ -407,23 +412,32 @@ function _selectorBytes(certDer, selector) {
407
412
  return null;
408
413
  }
409
414
 
415
+ // Constant-time byte-compare for TLSA association data. The TLSA record is
416
+ // public DNS so there is no secret to leak via timing, but the framework
417
+ // compares all crypto material (digests, certs) in constant time so the
418
+ // boundary stays uniform and can't regress into a leaky compare elsewhere.
419
+ function _constEqBytes(a, b) {
420
+ // bCrypto.timingSafeEqual is the length-tolerant constant-time wrapper.
421
+ return Buffer.isBuffer(a) && Buffer.isBuffer(b) && bCrypto.timingSafeEqual(a, b);
422
+ }
423
+
410
424
  function _matchTlsaAgainstCert(rec, certDer) {
411
425
  // Returns null on no-match, or { ok: true, mtypeLabel } on match.
412
426
  var bytes = _selectorBytes(certDer, rec.selector);
413
427
  if (!bytes) return null;
414
- var dataHex = String(rec.dataHex || "").toLowerCase();
428
+ var dataHex = (typeof rec.dataHex === "string" ? rec.dataHex : "").toLowerCase();
429
+ var want = Buffer.from(dataHex, "hex");
415
430
  // RFC 6698 §2.1.3 matching types — Full byte match (0) or hashed
416
431
  // comparison via SHA two-family (1 short / 2 long digest).
417
432
  if (rec.mtype === 0) {
418
- return bytes.toString("hex") === dataHex
419
- ? { ok: true, mtype: "Full" } : null;
433
+ return _constEqBytes(bytes, want) ? { ok: true, mtype: "Full" } : null;
420
434
  }
421
435
  if (rec.mtype === 1) {
422
- return _hashHex("sha256", bytes) === dataHex
436
+ return _constEqBytes(nodeCrypto.createHash("sha256").update(bytes).digest(), want)
423
437
  ? { ok: true, mtype: "SHA-256" } : null;
424
438
  }
425
439
  if (rec.mtype === 2) {
426
- return _hashHex("sha512", bytes) === dataHex
440
+ return _constEqBytes(nodeCrypto.createHash("sha512").update(bytes).digest(), want)
427
441
  ? { ok: true, mtype: "SHA-512" } : null;
428
442
  }
429
443
  return null;
@@ -577,19 +591,14 @@ async function tlsRptFetchPolicy(domain, opts) {
577
591
  }
578
592
  opts = opts || {};
579
593
  var qname = "_smtp._tls." + domain;
580
- var records;
581
- try {
582
- if (opts.dnsLookup) {
583
- records = await opts.dnsLookup(qname, "TXT");
584
- } else {
585
- records = await dnsPromises.resolveTxt(qname);
586
- }
587
- } catch (e) {
588
- if (e && (e.code === "ENOTFOUND" || e.code === "ENODATA")) return null;
589
- throw new SmtpPolicyError("smtp/tls-rpt-lookup-failed",
590
- "TLS-RPT TXT lookup for " + qname + " failed: " +
591
- ((e && e.message) || String(e)));
592
- }
594
+ // Secure DNS path — not plaintext dnsPromises (a spoofed TLS-RPT TXT could
595
+ // redirect failure reports).
596
+ var records = await networkDnsResolver().safeResolveTxt(qname, {
597
+ dnsLookup: opts.dnsLookup,
598
+ errorFactory: function (code, msg) { return new SmtpPolicyError(code, msg); },
599
+ code: "smtp/tls-rpt-lookup-failed",
600
+ });
601
+ if (records === null) return null;
593
602
  // Pick the first record that begins with v=TLSRPTv1 per RFC 8460 §3.
594
603
  var joined = "";
595
604
  for (var i = 0; i < (records || []).length; i += 1) {
@@ -598,16 +607,13 @@ async function tlsRptFetchPolicy(domain, opts) {
598
607
  if (/^v=TLSRPTv1\b/i.test(s)) { joined = s; break; }
599
608
  }
600
609
  if (joined.length === 0) return null;
601
- var parts = joined.split(";"); // allow:bare-split-on-quoted-header — allow:raw-time-literal — TLS-RPT record grammar (RFC 8460 §3): `tlsrpt-record = "v=TLSRPTv1;" *(WSP) tlsrpt-rua` with token-only values; no quoted-string
610
+ // TLS-RPT record grammar (RFC 8460 §3): `"v=TLSRPTv1;" *(WSP) tlsrpt-rua`
611
+ // with token-only values, no quoted-string — the naive split is correct.
612
+ var pairs = structuredFields.parseTagList(joined);
602
613
  var rua = [];
603
- for (var p = 0; p < parts.length; p += 1) {
604
- var t = parts[p].trim();
605
- var eq = t.indexOf("=");
606
- if (eq === -1) continue;
607
- var k = t.slice(0, eq).trim().toLowerCase();
608
- var v = t.slice(eq + 1).trim();
609
- if (k === "rua") {
610
- var uris = v.split(","); // allow:bare-split-on-quoted-header — allow:raw-time-literal — TLS-RPT rua grammar (RFC 8460 §3): rua = tlsrpt-uri *("," tlsrpt-uri); URIs percent-encode reserved chars, no quoted-string
614
+ for (var p = 0; p < pairs.length; p += 1) {
615
+ if (pairs[p][0] === "rua") {
616
+ var uris = pairs[p][1].split(","); // allow:bare-split-on-quoted-header — allow:raw-time-literal — TLS-RPT rua grammar (RFC 8460 §3): rua = tlsrpt-uri *("," tlsrpt-uri); URIs percent-encode reserved chars, no quoted-string
611
617
  for (var u = 0; u < uris.length; u += 1) {
612
618
  var uri = uris[u].trim();
613
619
  if (uri.length > 0) rua.push(uri);
@@ -5,6 +5,8 @@ var nodeFs = require("node:fs");
5
5
  var nodePath = require("node:path");
6
6
  var net = require("node:net");
7
7
  var nodeCrypto = require("node:crypto");
8
+ var numericBounds = require("./numeric-bounds");
9
+ var atomicFile = require("./atomic-file");
8
10
 
9
11
  var bCrypto = require("./crypto");
10
12
  var C = require("./constants");
@@ -103,7 +105,7 @@ function _certMetadata(pem) {
103
105
 
104
106
  function _isPathLike(s) {
105
107
  if (s.indexOf("-----BEGIN") !== -1) return false;
106
- if (s.length > C.BYTES.kib(1)) return false;
108
+ if (safeBuffer.byteLengthOf(s) > C.BYTES.kib(1)) return false;
107
109
  if (safeBuffer.hasCrlf(s)) return false;
108
110
  return true;
109
111
  }
@@ -115,20 +117,13 @@ function _isPathLike(s) {
115
117
  // shape, where an attacker who could swap the file in-between could
116
118
  // short-circuit the PEM marker check downstream.
117
119
  function _readPathFile(p) {
118
- var fd = nodeFs.openSync(p, "r");
119
- try {
120
- var fstat = nodeFs.fstatSync(fd);
121
- var buf = Buffer.alloc(fstat.size);
122
- var read = 0;
123
- while (read < fstat.size) {
124
- var n = nodeFs.readSync(fd, buf, read, fstat.size - read, null);
125
- if (n === 0) break;
126
- read += n;
127
- }
128
- return buf.slice(0, read).toString("utf8");
129
- } finally {
130
- try { nodeFs.closeSync(fd); } catch (_c) { /* close best-effort */ }
131
- }
120
+ // TOCTOU-safe read via atomic-file: utf8 string, slice on a short read,
121
+ // raw ENOENT preserved (errorFor returns undefined → rethrow).
122
+ return atomicFile.fdSafeReadSync(p, {
123
+ encoding: "utf8",
124
+ allowShortRead: true,
125
+ errorFor: function () { return undefined; },
126
+ });
132
127
  }
133
128
 
134
129
  function _readPath(p) {
@@ -198,6 +193,21 @@ function getTrustStore() {
198
193
  });
199
194
  }
200
195
 
196
+ // _certAuditMetadata(m) — the shared cert-identity fields stamped on every
197
+ // network.tls.ca.* audit event (the add / remove emitters overlay their
198
+ // own label / reason on top via Object.assign). Distinct from
199
+ // _certMetadata(pem), which PARSES a PEM into the meta object `m`.
200
+ function _certAuditMetadata(m) {
201
+ return {
202
+ subject: m.subject,
203
+ issuer: m.issuer,
204
+ fingerprint256: m.fingerprint256,
205
+ validFrom: m.validFrom,
206
+ validTo: m.validTo,
207
+ isSelfSigned: m.isSelfSigned,
208
+ };
209
+ }
210
+
201
211
  function _emitAuditRemove(metaList, reason) {
202
212
  var sink;
203
213
  try { sink = audit(); } catch (_e) { sink = null; }
@@ -208,16 +218,10 @@ function _emitAuditRemove(metaList, reason) {
208
218
  sink.safeEmit({
209
219
  action: "network.tls.ca.removed",
210
220
  outcome: "success",
211
- metadata: {
212
- subject: m.subject,
213
- issuer: m.issuer,
214
- fingerprint256: m.fingerprint256,
215
- validFrom: m.validFrom,
216
- validTo: m.validTo,
217
- isSelfSigned: m.isSelfSigned,
218
- label: m.label,
219
- reason: reason || "operator",
220
- },
221
+ metadata: Object.assign(_certAuditMetadata(m), {
222
+ label: m.label,
223
+ reason: reason || "operator",
224
+ }),
221
225
  });
222
226
  } catch (_e) { /* audit best-effort — never break the caller */ }
223
227
  }
@@ -515,7 +519,7 @@ var DEFAULT_PQC_KEY_SHARES = Object.freeze([
515
519
  ]);
516
520
 
517
521
  function _validateKeyShare(name) {
518
- if (typeof name !== "string" || name.length === 0 || name.length > C.BYTES.bytes(64)) { // bound
522
+ if (typeof name !== "string" || name.length === 0 || safeBuffer.byteLengthOf(name) > C.BYTES.bytes(64)) { // bound
519
523
  throw new TlsTrustError("tls/bad-key-share",
520
524
  "tls.pqc.setKeyShares: each entry must be a non-empty string up to 64 chars");
521
525
  }
@@ -714,15 +718,7 @@ function _emitAuditAdd(metaList, opts) {
714
718
  sink.safeEmit({
715
719
  action: "network.tls.ca.added",
716
720
  outcome: "success",
717
- metadata: {
718
- subject: m.subject,
719
- issuer: m.issuer,
720
- fingerprint256: m.fingerprint256,
721
- validFrom: m.validFrom,
722
- validTo: m.validTo,
723
- isSelfSigned: m.isSelfSigned,
724
- label: opts.label || null,
725
- },
721
+ metadata: Object.assign(_certAuditMetadata(m), { label: opts.label || null }),
726
722
  });
727
723
  } catch (_e) { /* audit best-effort — never break the caller */ }
728
724
  }
@@ -1097,6 +1093,15 @@ function _verifyOcspSignature(parsed, issuerPem) {
1097
1093
  // `ocsp.requireStapled` or any other source) plus the issuer cert PEM
1098
1094
  // and returns a structured outcome:
1099
1095
  // { ok, status, certStatus, thisUpdate, nextUpdate, signatureValid, errors }
1096
+ // Normalize a certificate serial for comparison: lowercase, drop separators
1097
+ // (X509Certificate.serialNumber is uppercase, no colons here but defensive) and
1098
+ // the optional DER leading sign-zero, so a serial from node:crypto and one
1099
+ // parsed from the OCSP certID DER compare equal. Both sides go through this.
1100
+ function _normOcspSerial(s) {
1101
+ var h = String(s || "").toLowerCase().replace(/[^0-9a-f]/g, "");
1102
+ return h.replace(/^0+/, "") || "0";
1103
+ }
1104
+
1100
1105
  function evaluateOcspResponse(ocspDer, opts) {
1101
1106
  opts = opts || {};
1102
1107
  var issuerPem = opts.issuerPem;
@@ -1124,12 +1129,21 @@ function evaluateOcspResponse(ocspDer, opts) {
1124
1129
  return { ok: false, status: parsed.status, signatureValid: false,
1125
1130
  errors: ["OCSP signature did not verify against the issuer key"] };
1126
1131
  }
1127
- // Look up the requested cert serial in the responses; "good" wins.
1128
- var serial = opts.serialHex || (parsed.basic.responses[0] && parsed.basic.responses[0].certIdSerialHex);
1132
+ // Bind the response to the serial of the certificate UNDER VALIDATION. The
1133
+ // old code defaulted an absent serialHex to responses[0]'s own serial and
1134
+ // then matched it — so a CA-signed "good" response covering a DIFFERENT cert
1135
+ // of the same issuer (replayed/mis-routed batch reply) was accepted. Require
1136
+ // a bound serial and fail closed without one; compare normalized (lowercase,
1137
+ // strip separators + DER leading sign-zero on both sides).
1138
+ if (!opts.serialHex) {
1139
+ return { ok: false, status: parsed.status, signatureValid: true,
1140
+ errors: ["OCSP evaluation requires opts.serialHex (the serial of the certificate being validated) to bind the response"] };
1141
+ }
1142
+ var wantSerial = _normOcspSerial(opts.serialHex);
1129
1143
  var match = null;
1130
1144
  for (var i = 0; i < parsed.basic.responses.length; i += 1) {
1131
1145
  var r = parsed.basic.responses[i];
1132
- if (!serial || r.certIdSerialHex === serial) { match = r; break; }
1146
+ if (_normOcspSerial(r.certIdSerialHex) === wantSerial) { match = r; break; }
1133
1147
  }
1134
1148
  if (!match) {
1135
1149
  return { ok: false, status: parsed.status, signatureValid: true,
@@ -1422,7 +1436,9 @@ async function fetchOcspResponse(opts) {
1422
1436
  }
1423
1437
  var evald = evaluateOcspResponse(res.body, {
1424
1438
  issuerPem: opts.issuerPem,
1425
- serialHex: opts.serialHex || null,
1439
+ // Bind to the leaf being checked (its serial), not whatever the response
1440
+ // happens to carry — defaults to leafX.serialNumber when not overridden.
1441
+ serialHex: opts.serialHex || leafX.serialNumber,
1426
1442
  expectedNonce: opts.nonce === false ? null : built.nonce,
1427
1443
  });
1428
1444
  if (!evald.ok) {
@@ -1462,7 +1478,9 @@ var ocsp = Object.freeze({
1462
1478
  }
1463
1479
  var evald = evaluateOcspResponse(rv.ocspBytes, {
1464
1480
  issuerPem: opts.issuerPem,
1465
- serialHex: opts.serialHex || null,
1481
+ // Bind to the connected peer's certificate serial (not the response's own
1482
+ // entry) — without it evaluateOcspResponse fails closed.
1483
+ serialHex: opts.serialHex || (rv.peerCert && rv.peerCert.serialNumber) || null,
1466
1484
  });
1467
1485
  if (!evald.ok) {
1468
1486
  throw new TlsTrustError("tls/ocsp-not-good",
@@ -2701,11 +2719,8 @@ function connectWithEch(opts) {
2701
2719
  validateOpts.requireNonEmptyString(opts.host, "connectWithEch: host",
2702
2720
  NetworkTlsError, "tls/ech-bad-opts");
2703
2721
  var port = opts.port === undefined ? 443 : opts.port; // HTTPS default port
2704
- if (typeof port !== "number" || !isFinite(port) ||
2705
- port <= 0 || port > 65535 || Math.floor(port) !== port) { // TCP port range
2706
- throw new NetworkTlsError("tls/ech-bad-opts",
2707
- "connectWithEch: port must be an integer in 1..65535");
2708
- }
2722
+ numericBounds.requirePositiveFiniteInt(port,
2723
+ "connectWithEch: port", NetworkTlsError, "tls/ech-bad-opts", { max: 65535 });
2709
2724
  if (opts.alpn !== undefined && !Array.isArray(opts.alpn)) {
2710
2725
  throw new NetworkTlsError("tls/ech-bad-opts",
2711
2726
  "connectWithEch: alpn must be an array of strings");
@@ -2742,8 +2757,13 @@ function connectWithEch(opts) {
2742
2757
  if (typeof opts.checkServerIdentity === "function") {
2743
2758
  connectOpts.checkServerIdentity = opts.checkServerIdentity;
2744
2759
  }
2745
- if (opts.rejectUnauthorized === false) {
2746
- connectOpts.rejectUnauthorized = false;
2760
+ // rejectUnauthorized defaults to true (full validation). An operator may
2761
+ // explicitly opt out — audited, never a framework default. Derived from
2762
+ // the operator's own value (operator-governed shape, mirroring mail.js /
2763
+ // log-stream-syslog.js), not a hardcoded literal.
2764
+ var rejectUnauthorized = opts.rejectUnauthorized !== false;
2765
+ connectOpts.rejectUnauthorized = rejectUnauthorized;
2766
+ if (!rejectUnauthorized) {
2747
2767
  auditInsecureTls({ host: opts.host, port: port, source: "network.tls.connectWithEch" });
2748
2768
  }
2749
2769
  var echAttached = false;
@@ -61,8 +61,8 @@ var ERROR = { NOERROR: 0, BADSIG: 16, BADKEY: 17, BADTIME: 18, BADTRUNC: 22 };
61
61
 
62
62
  function _normAlg(name, allowLegacy) {
63
63
  var key = String(name || "hmac-sha256").toLowerCase().replace(/\.$/, "");
64
- if (ALGORITHMS[key]) return { name: key, hash: ALGORITHMS[key] };
65
- if (LEGACY_ALGORITHMS[key]) {
64
+ if (Object.prototype.hasOwnProperty.call(ALGORITHMS, key)) return { name: key, hash: ALGORITHMS[key] };
65
+ if (Object.prototype.hasOwnProperty.call(LEGACY_ALGORITHMS, key)) {
66
66
  if (!allowLegacy) throw new TsigError("tsig/legacy-algorithm", "tsig: algorithm '" + key + "' is broken; pass allowLegacy:true to permit it for legacy interop");
67
67
  return { name: key, hash: LEGACY_ALGORITHMS[key] };
68
68
  }
@@ -54,7 +54,7 @@ function create(opts) {
54
54
  validateOpts.requireNonEmptyString(opts.entityId,
55
55
  "nis2.report.create: opts.entityId is required (NIS2 registration ID)",
56
56
  Nis2ReportError, "nis2-report/bad-entity-id");
57
- if (!VALID_ENTITY_TYPES[opts.entityType]) {
57
+ if (!Object.prototype.hasOwnProperty.call(VALID_ENTITY_TYPES, opts.entityType)) {
58
58
  throw new Nis2ReportError("nis2-report/bad-entity-type",
59
59
  "nis2.report.create: opts.entityType must be 'essential' or 'important' (NIS2 Article 3 classification)");
60
60
  }
@@ -66,7 +66,6 @@ function create(opts) {
66
66
  var sectorAnnex = opts.sectorAnnex;
67
67
  var csirtEndpoint = opts.csirtEndpoint || null;
68
68
  var httpClient = opts.httpClient || null;
69
- var auditOn = opts.audit !== false;
70
69
 
71
70
  var ir = incidentReport().create({
72
71
  audit: opts.audit,
@@ -79,16 +78,7 @@ function create(opts) {
79
78
  },
80
79
  });
81
80
 
82
- function _emitAudit(action, outcome, metadata) {
83
- if (!auditOn) return;
84
- try {
85
- audit().safeEmit({
86
- action: "nis2.report." + action,
87
- outcome: outcome,
88
- metadata: metadata || {},
89
- });
90
- } catch (_e) { /* drop-silent */ }
91
- }
81
+ var _emitAudit = audit().namespaced("nis2.report", opts.audit);
92
82
 
93
83
  async function _submitToCsirt(payload) {
94
84
  if (!csirtEndpoint || !httpClient) {
@@ -199,7 +199,7 @@ var CATALOGS = {
199
199
  * // → ["b.permissions", "b.middleware.requireAuth", ...]
200
200
  */
201
201
  function controls(catalog) {
202
- if (typeof catalog !== "string" || !CATALOGS[catalog]) {
202
+ if (typeof catalog !== "string" || !Object.prototype.hasOwnProperty.call(CATALOGS, catalog)) {
203
203
  throw new NistCrosswalkError("nist-crosswalk/unknown-catalog",
204
204
  "controls: unknown catalog '" + catalog + "'. Known: " +
205
205
  Object.keys(CATALOGS).join(", "));
@@ -13,6 +13,16 @@
13
13
  * inserting second would race on concurrent requests carrying
14
14
  * the same nonce.
15
15
  *
16
+ * await store.release(nonce) → boolean
17
+ * Un-claims a single nonce so a later checkAndInsert of the same value
18
+ * succeeds again — the rollback half of reserve -> commit -> rollback.
19
+ * A handler that claims an event id the moment a signature verifies (to
20
+ * win the race against a concurrent duplicate) MUST release it when
21
+ * downstream processing fails, otherwise the provider's at-least-once
22
+ * redelivery is reported as a replay and the event is dropped. Returns
23
+ * whether a live claim existed. Pair with checkAndInsert; without it an
24
+ * eager claim inverts the at-least-once contract on any failure.
25
+ *
16
26
  * await store.purgeExpired() → number
17
27
  * Removes entries past their expireAt. Called periodically by the
18
28
  * middleware that uses the store. Returns the count purged.
@@ -32,8 +42,11 @@
32
42
  * table _blamejs_api_encrypt_nonces. The PRIMARY KEY race is what
33
43
  * makes the check + insert atomic across nodes.
34
44
  *
35
- * { checkAndInsert, purgeExpired, close } — operator-supplied
36
- * custom backend (Redis SETNX, Memcached add, etc.). Use this
45
+ * { checkAndInsert, release?, purgeExpired?, close? } — operator-supplied
46
+ * custom backend (Redis SETNX, Memcached add, etc.). release() is
47
+ * optional but required to use reserve -> rollback; a backend omitting
48
+ * it throws NONCE_BACKEND_NO_RELEASE the first time release() is called
49
+ * (a loud gap, never a silent dropped rollback). Use this
37
50
  * for cross-process accuracy without a per-request SQL hop.
38
51
  *
39
52
  * Sweep cadence: memory backend sweeps every opts.sweepIntervalMs
@@ -132,6 +145,21 @@ function _memoryBackend(opts) {
132
145
  return Promise.resolve(true);
133
146
  }
134
147
 
148
+ // Un-claim a nonce so a future checkAndInsert of the same value succeeds
149
+ // again — the rollback half of reserve -> commit -> rollback. A handler
150
+ // that claims an event id the moment a signature verifies (to win the race
151
+ // against a concurrent duplicate) MUST release it when downstream processing
152
+ // fails, otherwise the provider's at-least-once redelivery is reported as a
153
+ // replay and the event is dropped. Returns whether a live claim existed.
154
+ function release(nonce) {
155
+ if (typeof nonce !== "string" || nonce.length === 0) {
156
+ return Promise.reject(_err("INVALID_NONCE", "nonce must be a non-empty string"));
157
+ }
158
+ var existed = seen.get(nonce) !== undefined;
159
+ if (existed) seen.delete(nonce);
160
+ return Promise.resolve(existed);
161
+ }
162
+
135
163
  function purgeExpired() {
136
164
  return Promise.resolve(_purgeExpiredSync());
137
165
  }
@@ -144,6 +172,7 @@ function _memoryBackend(opts) {
144
172
  return {
145
173
  name: "memory",
146
174
  checkAndInsert: checkAndInsert,
175
+ release: release,
147
176
  purgeExpired: purgeExpired,
148
177
  close: close,
149
178
  // Test hooks — underlying entry count + count of capacity fail-closed
@@ -178,6 +207,19 @@ function _clusterBackend(_opts) {
178
207
  return (result && result.rowCount > 0);
179
208
  }
180
209
 
210
+ async function release(nonce) {
211
+ if (typeof nonce !== "string" || nonce.length === 0) {
212
+ throw _err("INVALID_NONCE", "nonce must be a non-empty string");
213
+ }
214
+ // Un-claim a single nonce (the reserve -> rollback half). The middleware
215
+ // hashes the raw nonce before it reaches here, so we delete by hash.
216
+ var built = sql.delete(frameworkSchema.tableName(NONCE_TABLE), _nonceSqlOpts())
217
+ .where("nonceHash", "=", nonce)
218
+ .toSql();
219
+ var result = await clusterStorage.execute(built.sql, built.params);
220
+ return (result && result.rowCount > 0);
221
+ }
222
+
181
223
  async function purgeExpired() {
182
224
  var built = sql.delete(frameworkSchema.tableName(NONCE_TABLE), _nonceSqlOpts())
183
225
  .where("expireAt", "<=", Date.now())
@@ -191,6 +233,7 @@ function _clusterBackend(_opts) {
191
233
  return {
192
234
  name: "cluster",
193
235
  checkAndInsert: checkAndInsert,
236
+ release: release,
194
237
  purgeExpired: purgeExpired,
195
238
  close: close,
196
239
  };
@@ -208,6 +251,15 @@ function create(opts) {
208
251
  return Object.assign({
209
252
  name: "custom",
210
253
  purgeExpired: function () { return Promise.resolve(0); },
254
+ // A custom backend that omits release() cannot participate in
255
+ // reserve -> rollback. Fail LOUDLY (not a silent no-op) so the gap
256
+ // surfaces the first time a handler tries to un-claim, rather than
257
+ // silently dropping the rollback and inverting the at-least-once contract.
258
+ release: function () {
259
+ return Promise.reject(_err("BACKEND_NO_RELEASE",
260
+ "this custom nonce backend does not implement release(nonce); " +
261
+ "the reserve -> commit -> rollback pattern requires it"));
262
+ },
211
263
  close: function () {},
212
264
  }, backend);
213
265
  }
@@ -215,11 +267,37 @@ function create(opts) {
215
267
  if (!backend || backend === "memory") return _memoryBackend(opts);
216
268
  throw _err("UNKNOWN_BACKEND",
217
269
  "nonce-store: unknown backend '" + backend +
218
- "' (must be 'memory', 'cluster', or { checkAndInsert, purgeExpired, close })");
270
+ "' (must be 'memory', 'cluster', or { checkAndInsert, release?, purgeExpired?, close? })");
271
+ }
272
+
273
+ // enforceReplay(store, jti, expireAtMs, opts) — single-use enforcement
274
+ // against a replay store: `await store.checkAndInsert(jti, expireAtMs)`,
275
+ // raising opts.errorClass(opts.storeFailedCode, …) if the store itself
276
+ // fails (a store outage must NOT be mistaken for a clean token) and
277
+ // opts.errorClass(opts.replayCode, "<opts.tokenLabel> jti='<jti>' has
278
+ // been seen before — replay refused") if the jti was already seen. The
279
+ // fail-closed anti-replay control flow every JWT / DPoP verifier repeated
280
+ // identically — centralised here so the contract lives in one place.
281
+ // Verifiers with a divergent message or store contract (e.g. an atomic
282
+ // back-channel-logout-token store) keep their own inline check.
283
+ async function enforceReplay(store, jti, expireAtMs, opts) {
284
+ opts = opts || {};
285
+ var inserted;
286
+ try {
287
+ inserted = await store.checkAndInsert(jti, expireAtMs);
288
+ } catch (e) {
289
+ throw new opts.errorClass(opts.storeFailedCode,
290
+ "replayStore.checkAndInsert threw: " + ((e && e.message) || String(e)));
291
+ }
292
+ if (inserted === false) {
293
+ throw new opts.errorClass(opts.replayCode,
294
+ opts.tokenLabel + " jti='" + jti + "' has been seen before — replay refused");
295
+ }
219
296
  }
220
297
 
221
298
  module.exports = {
222
299
  create: create,
300
+ enforceReplay: enforceReplay,
223
301
  NonceStoreError: NonceStoreError,
224
302
  _memoryBackend: _memoryBackend,
225
303
  _clusterBackend: _clusterBackend,
package/lib/ntp-check.js CHANGED
@@ -45,6 +45,8 @@
45
45
  * Boot-time clock-drift verification against an external NTP / NTS-KE reference.
46
46
  */
47
47
  var dgram = require("node:dgram");
48
+ var nodeCrypto = require("node:crypto");
49
+ var bCrypto = require("./crypto");
48
50
  var C = require("./constants");
49
51
  var lazyRequire = require("./lazy-require");
50
52
  var safeAsync = require("./safe-async");
@@ -200,6 +202,14 @@ function querySingle(server, opts) {
200
202
  // LI=0 (no warning), VN=4, Mode=3 (client). Other bytes zero.
201
203
  var req = Buffer.alloc(NTP_PACKET_BYTES);
202
204
  req[0] = 0x23;
205
+ // RFC 5905 §8 client-cookie: put a random 64-bit nonce in the request's
206
+ // Transmit Timestamp (bytes 40-47). A conformant server copies it verbatim
207
+ // into the reply's Originate Timestamp (bytes 24-31). Verifying that echo
208
+ // rejects an off-path spoofed reply — without it ANY 48-byte UDP datagram
209
+ // reaching our ephemeral port becomes the authoritative time, letting a
210
+ // spoofer force a fatal-drift refuse-to-boot under BLAMEJS_NTP_STRICT.
211
+ var originCookie = nodeCrypto.randomBytes(8);
212
+ originCookie.copy(req, 40);
203
213
  var sendTimeMs = Date.now();
204
214
 
205
215
  socket.on("error", function (e) {
@@ -213,6 +223,24 @@ function querySingle(server, opts) {
213
223
  if (!Buffer.isBuffer(msg) || msg.length < NTP_PACKET_BYTES) {
214
224
  return done({ code: "ntp/bad-reply", message: "reply too short (" + (msg && msg.length) + " bytes)" });
215
225
  }
226
+ // Origin-cookie echo (RFC 5905 §8): the reply's Originate Timestamp
227
+ // (bytes 24-31) MUST equal the nonce we sent. An off-path spoofer can't
228
+ // know it, so this is the primary reply-authenticity check.
229
+ if (!bCrypto.timingSafeEqual(msg.subarray(24, 32), originCookie)) {
230
+ return done({ code: "ntp/origin-mismatch",
231
+ message: server + ": reply Originate Timestamp does not echo the request nonce (spoofed/stale reply)" });
232
+ }
233
+ // Reject a non-server mode, an unsynchronized/kiss-o'-death stratum
234
+ // (0 or >= 16), or LI=3 (alarm — clock not synchronized): such a peer
235
+ // cannot supply a trustworthy time and must not drive drift.
236
+ var mode = msg[0] & 0x07;
237
+ var li = (msg[0] >> 6) & 0x03;
238
+ var stratum = msg[1];
239
+ if (mode !== 4 || li === 3 || stratum === 0 || stratum >= 16) {
240
+ return done({ code: "ntp/unsynchronized",
241
+ message: server + ": reply mode=" + mode + " stratum=" + stratum + " LI=" + li +
242
+ " is not a synchronized server response" });
243
+ }
216
244
  // Bytes 40-47 = Transmit Timestamp (NTP epoch seconds.fraction)
217
245
  var ntpSeconds = msg.readUInt32BE(40); // NTP packet offset
218
246
  var ntpFraction = msg.readUInt32BE(44); // NTP packet offset