@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
package/CHANGELOG.md CHANGED
@@ -8,6 +8,10 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.15.x
10
10
 
11
+ - v0.15.14 (2026-06-20) — **A broad security-hardening release: every request-IP trust decision is peer-gated against the immediate connection (closing an X-Forwarded-For spoofing class — one behavior change, see Migration), a wide set of authentication and signature verifiers now fail closed, pre-auth parsers are hardened against algorithmic-complexity and frame-desync attacks, and untrusted-key allowlist lookups, at-rest encryption binding, and on-disk writes are tightened framework-wide; adds streaming and exclusive atomic-write primitives, a script-context JSON serializer, and HTTP-client bandwidth throttling.** This release tightens existing protections across the framework rather than adding opt-ins. The headline behavior change is how the client IP is trusted: the IP gates that make security decisions (network allowlist, rate limiter, break-glass grant pin) no longer trust a bare leftmost X-Forwarded-For value when trustProxy is set without an explicit proxy allowlist — they resolve the client IP by a peer-gated right-to-left walk anchored at the connecting socket, so a direct caller can no longer forge an allowed address. Operators who terminate behind a proxy now declare its address range in trustedProxies (see Migration). Alongside that, a large set of verifiers that could accept a malformed or unsigned credential now fail closed (SAML audience restriction, FDA electronic-signature, SD-JWT key-binding replay, DPoP, CIBA, mdoc trust anchor, COSE algorithm/curve binding, agent-snapshot plaintext under a regulated posture); pre-authentication parsers that an attacker reaches before any credential check are hardened against quadratic-time and frame-desync denial of service (CBOR, JSONPath, tar/PAX, gzip, YAML, ASN.1 DER, the scheduler's timer math); allowlist and posture lookups keyed by untrusted input can no longer reach Object.prototype; the framework's own file writes are now symlink-refusing and atomic; at-rest and egress paths bind ciphertext to its location and redact nested secrets; and several lost-update races are serialized. New surface is additive: streaming and exclusive atomic-write primitives, a serializer safe to embed in an inline <script>, and download/upload bandwidth throttling on the HTTP client. **Added:** *b.atomicFile.writeStream(filepath, source, opts?) and b.atomicFile.writeExclSync(filepath, data, opts?)* — Two atomic-write primitives that complete the read-side fdSafeReadSync family. writeStream writes a stream to a fresh O_EXCL|O_NOFOLLOW temporary file with an output-byte cap, then renames into place; writeExclSync stages a synchronous write through a verify-then-rename (clearing any stale temp under O_EXCL|O_NOFOLLOW first) for the small sealed-state round-trips (vault seal / unseal / rotate). Both refuse to follow a symlink at the destination or temp path, so an attacker who pre-creates a link can't redirect the write. The framework's own predictable-temp and symlink-following write sites now route through them; fdSafeReadSync also gains a withStat option that returns the bound fd's stat alongside the bytes. · *b.safeJson.stringifyForScript(value, opts?)* — A JSON serializer safe to embed directly in an inline <script> block: it escapes <, >, and & and the U+2028 / U+2029 line separators so a value containing </script> or a JS line terminator cannot break out of the script context (DOM-XSS). The import-map helper gains scriptTag(importMap, { nonce }) built on it, and the speculation-rules inline emitter uses it. · *HTTP-client bandwidth throttling* — b.httpClient requests accept a bandwidth limit that interposes a throttling transform on both the download and upload paths, so a large transfer can be rate-shaped without buffering the whole body. Useful for bounding the egress a single outbound call can consume. · *Incremental audit-chain verification* — The audit verifiers accept a from/to range so a long chain can be verified in increments rather than head-to-tail every time, report an accurate rowsVerified count, and keep the newest review when reconciling. b.vault also exposes getDefaultStore() for callers that need the process's default seal/unseal store handle. **Changed:** *DORA major-incident reporting clock is four hours* — The Digital Operational Resilience Act initial-notification deadline is corrected to four hours from classification (it had used the generic 24-hour default), incident classification weighs the affected-client-base percentage, and the deadline anchors to the prior filing where one exists. · *Range and conditional-request correctness* — Compression skips a 206 Partial Content or any Content-Range response (RFC 7233 §4.1), so it can't drop Content-Length over a now-compressed byte interval; static-file conditional handling gives If-None-Match precedence over If-Modified-Since and If-Match over If-Unmodified-Since (RFC 7232); and the object store honors the [start, end] array range contract that previously fell through to a full read. · *Declared request bodies are always validated* — A route that declares a body schema now validates it even when no body was parsed, so an omitted required body is rejected at the router instead of reaching the handler — mirroring the always-run params and query checks. **Fixed:** *Object store getStream works on remote backends* — getStream() returned a stream wrapping an unresolved promise on every remote backend, so it never delivered bytes; it now resolves the object before streaming. · *Queue and body-parser correctness* — The local queue's fail()/complete() paths guard on the current row status so a stale lease can't resurrect or double-process a job, and the body parser's raw() mode no longer matches every content type by default (it had answered 415 to nothing or everything depending on the wildcard). · *Sanctions screening and GraphQL SDL probing no longer under-match* — Sanctions screening no longer skips a candidate whose type doesn't match the query's type filter (a sanctioned entity of an unspecified type was missed) and reports a typeMatch flag; the GraphQL federation guard probes for the _service / _entities introspection fields by word boundary (an aliased field bypassed the prefix check) and over batched-array request bodies. The per-tenant query budget is a true sliding window, so a burst straddling the window boundary can't briefly double the rate. **Security:** *Request-IP trust is peer-gated end to end* — The client-IP resolution that every IP gate depends on is extracted into one trust model (a trustedProxies-aware, peer-gated right-to-left walk) so the network allowlist, rate limiter, break-glass pin, and bot-guard audit attribution all decide identity the same way. X-Forwarded-Proto is peer-gated across the security middleware on the same model, and a WebSocket reconnect to a swapped target is re-validated against the SSRF / blocked-host guard before the connection is reused. See Migration for the one behavior change. · *Authentication and signature verifiers fail closed* — A set of verifiers that could accept a malformed or unsigned credential now refuse it: SAML verifyResponse fails closed on a missing AudienceRestriction or unparseable Conditions; the FDA 21 CFR 11 electronic-signature verify refuses a record with no signature (recordHash alone is self-consistency, not authentication); the SD-JWT key-binding JWT requires an audience and nonce (replay binding) and an expiry when configured; DPoP cross-checks the proof's alg against its embedded JWK key type before importing it; CIBA verifies the ID token on poll and notification; the mdoc trust anchor is enforced (no fail-open); COSE binds the signature algorithm to the key curve; and agent-snapshot refuses allowPlaintext under a regulated compliance posture and gates sealing on vault initialization. · *Pre-auth parsers hardened against complexity and frame-desync denial of service* — Parsers an attacker reaches before any credential check are bounded. CBOR rejects the quadratic-time duplicate-map-key construction (it ran O(n^2) on every COSE / CWT / EAT / mdoc verify) and rejects non-minimal integer/key encodings in canonical mode; JSONPath caps the node-list cross-product that could exhaust memory and rejects the filter expression that could overflow the parser stack; the tar reader caps a random-access entry read and resynchronizes a PAX header whose size field is non-numeric; the gzip reader caps a random-access output size; the YAML scanner replaces a backtracking pattern with a linear scan; the ASN.1 DER reader caps high-tag-number and OID sub-identifier decoding and rejects non-minimal forms; and the scheduler clamps far-future timers so a 32-bit overflow can't make a timer fire immediately or an interval tight-loop. · *Allowlist and posture lookups keyed by untrusted input can't reach the prototype* — Lookups of the form map[untrustedKey] across the framework's allowlist and compliance-posture tables are now own-property checks, so a key like __proto__ or constructor resolves as absent instead of returning an inherited value and walking the gate (CWE-1321). The shared posture-accessor that several guards built by hand is centralized, and an inverse detector flags any re-introduced unguarded indexed lookup. · *Framework file writes are symlink-refusing and atomic* — The predictable-temp and symlink-following write sites (cookie jar, config-drift snapshot, archive extraction, local object store, backup bundle, and the vault passphrase seal/unseal/rotate) now write through the atomic-write primitives above, so a pre-planted symlink at the destination or temp path can no longer redirect a privileged write, and a partial write can't leave a torn file. A re-introduced raw write without the exclusive/no-follow flags is flagged by a detector. · *X.509 issuer chains enforce the CA basic constraint* — Node's checkIssued() does not verify that the issuer certificate is actually a CA (CVE-2002-0862 class), so a leaf signed by a non-CA certificate could be accepted as an issuer. Certificate-chain walking is centralized in one helper that requires the issuer's basicConstraints cA bit and verifies the signature, and every chain consumer (TSA, BIMI, S/MIME, mdoc, content-credentials, the FIDO MDS3 anchor match) routes through it. · *Header, value, and markup injection closed* — Mail rejects CRLF in Reply-To and in custom header keys/values (SMTP header injection); the GDPR data-export CSV writer neutralizes formula-injection prefixes; the content guards decode no-semicolon numeric HTML entities when revealing a dangerous URL scheme (so &#106;avascript: is caught); the early-hints emitter rejects CRLF in pushed link values; the HTML/SVG/BIMI comment scanners honor the WHATWG abrupt-comment-close forms (--!>, <!-->) so a mutation-XSS comment can't smuggle markup; and the CSP builder no longer emits a host source alongside 'none'. · *At-rest and egress data is bound to its context* — Backup restore binds each encrypted file blob to its manifest path as additional authenticated data, so a blob remapped to another entry fails the AEAD tag on restore (signed and unsigned bundles alike), and threads the signature-verification options through extraction; the data-subject-request lookup dual-reads the keyed and legacy subject hashes so a subject is still found across the hashing change (GDPR Art. 17); the log redactor collapses a secret nested as an array or object value, not only as a scalar; and the OTLP exporter redacts the span name and status message, not just attributes, before they leave the process. · *Network-protocol verification hardened* — OCSP responses are bound to the requested certificate serial; the WebSocket reader rejects reserved opcodes and reserved bits; the DNS parser refuses a record that reads past the message buffer; the NTP client rejects a reply whose origin timestamp does not echo the request (and the SNTP cookie path was reworked to bind the exchange); DANE TLSA matching is constant-time; and MTA-STS policy fetch fails closed rather than degrading to no-policy on an ambiguous response. · *Byte caps are measured in bytes, and middleware enforcement is per-instance* — Size limits that compared a byte budget against a string's character length (so multibyte input slipped a ~2-4x looser bound) now measure actual bytes — guard-json per-string cap, the per-tenant quota header budget, the JMAP request cap. The CSRF and fetch-metadata middleware track their gate per instance, so mounting a second, stricter instance still enforces (a shared request flag previously let the first, lenient mount disable it); the CSRF cookie is still issued once per response. The WebAssembly global is stripped from the sandbox worker so sandboxed code cannot JIT around the isolation. · *Lost-update races serialized* — Concurrent failure recording in the login lockout and bot-challenge gates is serialized per key, so parallel failed attempts can no longer each read the same pre-write counter and stay under the lockout / challenge threshold. The inline webhook delivery is claimed before the POST so a concurrent retry pass can't double-send it, and a transient transport failure now backs off and retries instead of being dead-lettered. **Migration:** *X-Forwarded-For trust now requires an explicit proxy allowlist* — The IP gates that enforce a security decision — network allowlist, rate limiter, and the break-glass grant IP pin — previously resolved the client IP from the leftmost X-Forwarded-For value whenever trustProxy was truthy. A direct caller could set that header to any address and walk an IP allowlist or evade a rate-limit key (CWE-290 / CWE-348). These gates now fail closed: with trustProxy set but no trustedProxies, they ignore X-Forwarded-For and use the connecting socket's peer address. To keep trusting a forwarded client IP, set trustedProxies to the CIDR(s) of your front proxy/load balancer — the client IP is then resolved by a peer-gated right-to-left walk that stops at the first hop not in the allowlist. For an allowlist / rate-limit / break-glass gate the new default is stricter (it trusts less), so an operator who has not migrated sees tighter enforcement, never looser. Display-only consumers (error pages, request logs) keep the lenient resolution and carry a docstring warning. The wiki example's WIKI_TRUST_PROXY flag is replaced by WIKI_ADMIN_TRUSTED_PROXIES (a CIDR list).
12
+
13
+ - v0.15.13 (2026-06-19) — **Consolidates a large set of duplicated, security-sensitive code paths — injected-dependency validation, positive-integer option caps, TOCTOU-safe file reads, markup escaping, audit emission, structured-field parsing, and untrusted-JWK import — onto shared hardened primitives, so a fix or guard now applies everywhere at once; adds a TOCTOU-safe file reader; and makes several configuration errors throw typed framework errors instead of a bare Error.** Across the framework, logic that had been hand-rolled in many places (and had quietly drifted between copies) is now single-sourced through shared primitives. The practical effect for operators is consistency: the strongest available guard is applied everywhere a given operation happens, rather than in whichever copy happened to have it. Injected dependencies (stores, backends, vaults, db handles, query objects) are validated through one contract; operator-tunable positive-integer options (pool sizes, byte caps, timeouts, stream limits) validate through one bounds primitive that forwards the caller's non-retryable / HTTP-status flags; the open-fd → fstat → read-fully pattern that several call sites used to defend file reads against a swap-after-stat race (CWE-367) is now the b.atomicFile.fdSafeReadSync primitive, with symlink refusal, inode-equality, a byte cap, and an integrity hash available as options and each caller's exact typed error preserved; and the XML/HTML markup escapers (including the b.guardHtml / b.guardSvg sanitizer output) route through one b.markupEscape so the base & < > " chain can't drift between them. A few configuration-validation paths that threw a bare Error (httpClient.configurePool, b.db stream-limit validation) now throw the module's typed framework error. No security defaults change; this release tightens and unifies existing protections rather than adding opt-ins. **Added:** *b.atomicFile.fdSafeReadSync(filepath, opts?)* — A TOCTOU-safe synchronous file read (CWE-367 / js/file-system-race): it opens the path read-only, then binds the size, content, and integrity measurement to the inode the fd holds open, so a swap between stat and read can't change which bytes are returned. Optional guards layer on top — maxBytes (refuse an over-cap file), refuseSymlink + inodeCheck (refuse a symlink source and any inode swap, the strongest posture for operator-writable paths), expectedHash (SHA3-512), encoding (return a string), allowShortRead — and an errorFor(kind, detail) callback lets each caller keep its own typed error. The framework's own file reads (atomic-file, the TLS certificate-path loader, the sealed-PEM source reader, the backup bundle reader) all route through it. · *Shared substrate primitives for previously-duplicated logic* — A set of shared primitives now back call sites that had each re-implemented the same logic: validateOpts.requireMethods (gains a `permanent` flag) for injected-dependency contract checks; numericBounds positive-finite-int validators (gain an errorOpts { permanent, statusCode }) for tunable integer options; b.markupEscape for the & < > " markup chain; structured-field parsing helpers (parseTagList, forEachKeyValue, splitUnquoted, stripDoubleQuotes, unfoldHeaderContinuations); crypto.importPublicJwk and crypto.makeBase64UrlDecoder; safeSql.toPositional; safeBuffer.makeByteCoercer; nonceStore.enforceReplay; and the audit/observability namespaced emitters. These are mostly invisible substrate — the operator-visible benefit is that a guard or fix added to one of them now covers every caller. **Changed:** *Configuration errors throw typed framework errors* — Two configuration-validation paths that threw a bare `Error` now throw the module's typed framework error: httpClient.configurePool (bad maxSockets / maxFreeSockets / keepAliveMsecs → HttpClientError, code httpclient/bad-opts) and the b.db stream-limit validation (Query.stream → DbQueryError). The thrown error remains an Error subclass, so existing `instanceof Error` / try-catch handling is unaffected; code that matched the old free-text message should match the typed error's `code` instead. Several routed validators also report a slightly more precise message ("positive finite integer" instead of "positive integer"). **Fixed:** *Webhook deliveries retry transient transport failures instead of dead-lettering them* — A delivery that failed with a transient transport error (connection reset, timeout, 5xx) was recorded as permanently failed and dead-lettered rather than retried. The destination-safety check (SSRF / blocked-host guard) now runs in its own step and is the only permanent failure; a transport failure backs off and retries up to the configured limit. · *Webhook deliveries table creates on MySQL* — The pending-delivery index used a partial-index (WHERE) clause that MySQL does not support, so the deliveries table failed to create on a MySQL backend. The index is now dialect-aware — partial on PostgreSQL / SQLite, plain on MySQL. · *Inline webhook delivery can't be double-sent by concurrent retry processing* — An inline delivery is now claimed (status set to in-flight with a claim timestamp) before the POST, so a concurrent retry pass can't pick up and re-send the same delivery; a row left in-flight by a crash is reclaimed after the stale-claim window. · *Audit checkpoint can never be anchored against a replaced database* — close() fires a best-effort final checkpoint as the database shuts down. In a narrow close-then-reopen window that checkpoint's write could resume after a fresh database had opened and anchor the prior database's chain tip into it. checkpoint() now binds to the database it read the tip from and refuses to write (returns null, fail-closed) if that handle has since been closed or replaced — so a checkpoint is only ever written against the database it measured. **Security:** *TOCTOU-safe file reads applied uniformly* — The open-fd → fstat → read pattern that anchors a file read to one inode against a swap-after-stat race is now centralized in b.atomicFile.fdSafeReadSync, and every framework file read routes through it. The sealed-PEM source reader keeps the strongest posture (symlink refusal + inode-equality + byte cap), and those guards are now available as options to any caller — a re-introduced hand-rolled read-loop is flagged by a codebase-pattern detector. · *Injected-dependency and integer-option validation can't silently drift* — Injected stores / backends / vaults / db handles / query objects are validated through one contract (validateOpts.requireMethods), and operator-tunable positive-integer options through one bounds primitive (numericBounds), both forwarding the caller's non-retryable / HTTP-status error flags so a config error stays permanent / carries its 4xx. Inverse detectors flag any re-introduced inline check, so the validation can no longer be partially copied or weakened in one place. · *Single markup-escape chain for the HTML/SVG sanitizers* — The b.guardHtml and b.guardSvg sanitizer output escapers, the AI-Act transparency and mail HTML escapers, and the XML report escapers now share one b.markupEscape for the base & < > " chain (apostrophe form as a parameter; each caller keeps its own input coercion and any extra escapes such as guardHtml.escapeAttr's backtick / = IE-attribute-injection hardening). Byte-for-byte parity with the prior escapers was verified across an XSS-vector corpus, so the consolidation cannot have introduced an escaping gap; a re-inlined & < > " chain anywhere else is flagged by a detector. · *One hardening point for untrusted public-JWK import* — The createPublicKey-from-JWK call that imports attacker-controlled key material (DID publicKeyJwk, DNSKEY, COSE_Key, DPoP / OAuth / OIDC / DBSC proof JWKs) is centralized in b.crypto.importPublicJwk, so the untrusted-key import has a single audited home; each caller keeps its own kty/crv pre-validation and typed error. · *Linear-time Content-Security-Policy header parsing* — The CSP response-header parser split directives on a `/\s*,\s*/` regex that ran in O(n^2) on a long comma-less run of whitespace, letting a crafted header stall a worker (js/polynomial-redos). It now splits on the literal comma and trims each item, which is linear and byte-for-byte equivalent. · *Parsed INI and OpenAPI path maps can't reach Object.prototype* — The INI parser already refuses a `__proto__` / `constructor` / `prototype` section or key (it throws before any write); as defense-in-depth, every parsed node — and the OpenAPI paths map keyed by URL pattern — is now a null-prototype object, so even a future gap could only ever set an own property, never mutate Object.prototype (CWE-1321).
14
+
11
15
  - v0.15.12 (2026-06-14) — **Hardens a set of defense-in-depth seams: a single-pass structured-field unescape, a constant-time content-digest member match, complete reserved-character stripping, a Trojan-Source escape on the boot logger, generic body-parse error responses, and an audit trail whenever outbound TLS certificate validation is disabled.** A sweep of low-severity but real hardening items. RFC 8941 structured-field string values (HTTP Message Signatures, Client Hints, Cache-Control) were un-escaped with two chained replaces that mis-decoded an escaped backslash adjacent to another escape; they now use one left-to-right pass that decodes each escape exactly once. The HTTP Message Signature content-digest check dropped a dead identity-replace and now matches the sha3-512 member by an exact, top-level, constant-time comparison instead of an unanchored substring scan. b.guardFilename's reserved-character strip used a non-global regex that left every separator after the first; it now strips all of them. The boot logger's TTY branch wrote raw text, bypassing the Trojan-Source / control-character escape the main logger applies — it now escapes the bidi and C0/newline control classes on every sink. The body parser no longer echoes a caught exception's detail (an fs errno + temp path, or a parse hook's thrown message) to the HTTP client — the client gets a generic status phrase while the full detail stays on the audit chain. And any outbound TLS connection that runs with peer-certificate validation disabled (an explicit operator opt-in, never a default) now emits a tls.insecure_skip_verify audit + observability event so the degraded posture is visible for compliance and incident response. **Added:** *b.structuredFields.unescapeSfStringBody(body)* — A single-pass decode of the RFC 8941 §3.3.3 quoted-string backslash escapes (the bytes between the surrounding quotes). It replaces the chained two-`.replace()` form, which is not equivalent to one decode — whichever pass runs first can rewrite a backslash the other escape sequence owns, so a lone escaped backslash decoded to two. The HTTP Message Signature, Client Hints, and Cache-Control sf-string readers now route through it. · *tls.insecure_skip_verify audit event* — b.network.tls.auditInsecureTls(meta) emits an audit + observability event at the point an outbound TLS connection honors rejectUnauthorized:false / allowInsecure. The connectWithEch, OTLP-gRPC log stream, syslog-TLS log stream, and SMTP transports all emit it when an operator disables certificate validation — parallel to the existing tls.classical_downgrade audit. No default changes; the framework never disables validation itself. **Security:** *Single-pass structured-field string unescape* — The RFC 8941 sf-string readers in HTTP Message Signatures (Signature-Input covered-component names), Client Hints, and Cache-Control directive values un-escaped with `.replace(/\\\\/g,"\\").replace(/\\"/g,'"')` — two sequential passes that mis-decode adjacent escapes (a lone escaped backslash became two). All four sites now use the single-pass b.structuredFields.unescapeSfStringBody. It is fail-closed (a mis-decoded covered-component name just fails the signature check, never bypasses it); the fix restores RFC-conformant interop with peers that legitimately escape these values. · *Constant-time, member-anchored content-digest verification* — b.crypto.httpSig.verify's covered content-digest check dropped a dead no-op replace and now parses the Content-Digest header into its top-level members and matches the sha3-512 member EXACTLY, in constant time (b.crypto.timingSafeEqual), rather than scanning for the digest text as a substring anywhere in the header. The Content-Digest header is already bound by the signature, so the substring form was not reachably exploitable; the change removes the latent ambiguity and the timing channel. · *Reserved-character filename strip removes every occurrence* — b.guardFilename's reservedCharPolicy:"strip" (the permissive profile) used a non-global regex, so only the FIRST reserved character — including path separators — was replaced and the rest leaked through. The strip is now global: every reserved character is removed. Not a traversal bypass (the unconditional security floor still throws on `..`, null bytes, NTFS ADS, UNC, overlong UTF-8), but the strip is now complete and consistent. · *Boot logger escapes control + bidi characters on every sink* — The boot-time logger's TTY branch wrote the raw message, bypassing the Trojan-Source (bidi) and control-character escapes the main logger applies — a hostile message could forge extra log lines on a terminal (CWE-117) or re-order the visible line (CVE-2021-42574). Both boot branches now escape the bidi and C0/newline control classes, matching the create() path and the logger's advertised guarantee. · *Body-parser error responses never echo internal detail* — The body-parser's terminal error path surfaced a caught exception's message verbatim to the HTTP client — a multipart filesystem error leaked the errno + temp path, and a parse hook's thrown error (which can carry secrets) was echoed back. The client now gets a curated message only for a framework-classified 4xx error and a generic status phrase otherwise; the parse-hook wrapper carries a fixed message, and full diagnostics stay on the audit chain server-side (CWE-209). The cluster leader-discovery endpoint's error body is generalized the same way.
12
16
 
13
17
  - v0.15.11 (2026-06-14) — **Replaces a family of quadratic-time regexes that hostile input could use to stall a worker with linear scans, refuses a relocatable sealed-cell downgrade on the read side, fails closed when enabling row-level security behind a non-native driver, and scans the vendored crypto for known CVEs on every build.** Several text-handling primitives stripped trailing whitespace or extracted a mail address with a regex whose backtracking is quadratic in the input length on adversarial strings — a request body, a YAML document, a CSV cell, or a From header crafted as a long run of spaces could pin a worker's CPU. Each is now a linear character scan with identical output. The HTML-content check the MCP tool surface applies gained the vbscript: and data:text/html vectors it was missing. On the data-at-rest side, an AAD-bound (or per-row-key) column now refuses a plain, unbound vault cell on read — a relocatable envelope an attacker with write access could copy in from another row defeats the cross-row binding, so the field is nulled rather than surfaced; operators mid-migration opt back in with registerTable({ allowPlainMigration: true }). declareRowPolicy now treats row-level-security as enabled only on a value that unambiguously means true, so a non-native Postgres driver that returns the string "f" can no longer be read as "already on" and silently skip the ENABLE that protects the table's rows. Finally, because the framework's crypto is vendored rather than installed, npm audit and Dependabot never see it: every build now matches the vendored versions against the OSV vulnerability database, with a complementary Semgrep pass and workflow-file static analysis alongside. **Added:** *b.safeBuffer.indexAfterOpenTag(html, tagName)* — A linear helper that returns the offset just past a `<tag ...>` opening tag (case-insensitive), or -1 when absent or unterminated — the insertion point a response rewriter uses to splice content after <body> or <head> without a regex. It replaces the O(n^2) html.match(/<body[^>]*>/i) shape and is stricter than it: a real tag boundary is required after the name, so <bodyfoo> is not mistaken for <body>. **Security:** *Linear-time replacements across a family of quadratic regexes (ReDoS class)* — Several primitives located or stripped text with a regex whose backtracking is quadratic in V8 on adversarial input (CWE-1333): b.safeBuffer and the safe-env / safe-yaml / guard-csv parsers stripped trailing horizontal whitespace with /[ \t]+$/; b.mail extracted the address from a `Name <addr>` header with /<([^>]+)>/; the bot-disclosure and speculation-rules response middleware found the <body> insertion point with /<body[^>]*>/i; and the BIMI certificate-chain splitter walked PEM blocks with a lazy /BEGIN[\s\S]*?END/ scan. A crafted field — a long run of spaces, an unterminated bracket, a body carrying many <body starts with no closing >, a chain of BEGIN markers — could drive a worker's CPU to seconds of work. Each is now a linear scan: a shared b.safeBuffer.stripTrailingHspace (backward char walk), b.safeBuffer.indexAfterOpenTag (forward indexOf walk for the tag insertion point), a forward indexOf for address extraction, and an indexOf walk for the PEM split. Output is byte-identical (the tag-find is stricter — it no longer mistakes <bodyfoo> for <body>), and 400K-character adversarial inputs that took 8–85 seconds now complete in under 2 ms. · *MCP HTML-content check covers vbscript: and data:text/html* — The dangerous-markup check applied to text/html tool content matched <script>/<iframe>/<object>/<embed> and javascript: URLs but not the vbscript: scheme or data:text/html payloads. Both are now refused; data: URLs carrying non-HTML media (data:image/png and similar) are unaffected. · *AAD-bound columns refuse a plain sealed cell on read* — b.cryptoField.unsealRow now refuses a plain, unbound vault: envelope found on an AAD-bound (or per-row-key) column and nulls the field instead of returning it. A plain envelope carries no per-cell binding, so a writer who could place one — copied from anywhere under the same vault root — would otherwise relocate a value across rows or columns and defeat the copy-protection the AAD binding advertises. Operators migrating pre-AAD rows up to bound ciphertext opt into a bounded acceptance window with registerTable({ allowPlainMigration: true }) and clear it when migration completes. · *Row-level-security enablement fails closed on non-native drivers* — b.db.declareRowPolicy read pg_class.relrowsecurity to skip a redundant ENABLE ROW LEVEL SECURITY, but tested it with a bare truthiness check. A native pg driver returns a JS boolean; a proxy or ORM may return the string "f" for a disabled table — and "f" is truthy, so the check read it as already-enabled and silently skipped the ENABLE, leaving every row in the table unprotected while the migration reported success. RLS now counts as enabled only on a value that unambiguously means true (true, 1, or "t"/"true"/"1"/"on"/"yes"); every other shape re-issues ENABLE, a harmless no-op on an already-enabled table. · *Vendored-crypto CVE scanning, complementary SAST, and workflow static analysis in CI* — The framework ships zero npm runtime dependencies — its crypto (the noble suite, the WebAuthn server, the PKI layer) is vendored under lib/vendor/, where npm audit, Dependabot, and Socket cannot see it. Every build now generates a CycloneDX SBOM of the vendored tree (each library carrying an npm purl) and runs it through OSV-Scanner, matching the exact pinned version against the OSV vulnerability database; a published CVE or GHSA affecting a vendored version fails the build so the copy is refreshed before merge. A Semgrep pass (registry security-audit + javascript packs at ERROR severity) runs alongside CodeQL as complementary SAST, and actionlint statically checks the workflow files. All three install the OSS tool from its upstream release, matching the existing secret-scan gate's posture. **Detectors:** *Quadratic trailing-whitespace and tag-find regex detectors* — Two codebase-pattern detectors refuse reintroduction of the quadratic shapes: the /[ \t]+$/ trailing-whitespace strip (as .replace, .test, or via the named TRAILING_HSPACE_RE export) outside the linear helper that owns it, and the str.match(/<tag[^>]*>/) document-tag find that the response middleware must route through b.safeBuffer.indexAfterOpenTag. Each is proven to fire on the removed shape and stay silent on the linear replacement, so the ReDoS class cannot creep back into a new parser, guard, or response rewriter.
package/index.js CHANGED
@@ -225,6 +225,7 @@ var guardYaml = require("./lib/guard-yaml");
225
225
  var guardXml = require("./lib/guard-xml");
226
226
  var guardMarkdown = require("./lib/guard-markdown");
227
227
  var guardEmail = require("./lib/guard-email");
228
+ var guardText = require("./lib/guard-text");
228
229
  var guardDomain = require("./lib/guard-domain");
229
230
  var guardUuid = require("./lib/guard-uuid");
230
231
  var guardCidr = require("./lib/guard-cidr");
@@ -609,6 +610,7 @@ module.exports = {
609
610
  guardXml: guardXml,
610
611
  guardMarkdown: guardMarkdown,
611
612
  guardEmail: guardEmail,
613
+ guardText: guardText,
612
614
  guardDomain: guardDomain,
613
615
  guardUuid: guardUuid,
614
616
  guardCidr: guardCidr,
package/lib/a2a-tasks.js CHANGED
@@ -51,7 +51,7 @@ var validateOpts = require("./validate-opts");
51
51
  var { defineClass } = require("./framework-error");
52
52
 
53
53
  var httpClient = lazyRequire(function () { return require("./http-client"); });
54
- var audit = lazyRequire(function () { return require("./audit"); });
54
+ var auditEmit = require("./audit-emit");
55
55
  var C = require("./constants");
56
56
 
57
57
  // A2aTasksError is the per-call error class — separate from A2aError
@@ -82,15 +82,7 @@ var TASK_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
82
82
  var SKILL_NAME_RE = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/; // allow:duplicate-regex — RFC-3986-unreserved identifier shape, shared across mcp.js + mcp-tool-registry.js
83
83
  // RFC-3986-unreserved identifier shape (length cap inside regex), not a byte count
84
84
 
85
- function _emitAudit(action, metadata, outcome) {
86
- try {
87
- audit().safeEmit({
88
- action: action,
89
- outcome: outcome || "success",
90
- metadata: metadata,
91
- });
92
- } catch (_e) { /* best-effort */ }
93
- }
85
+ var _emitAudit = auditEmit.emit;
94
86
 
95
87
  var bCrypto = lazyRequire(function () { return require("./crypto"); });
96
88
 
@@ -388,6 +380,18 @@ function middlewareTasks(opts) {
388
380
  throw new A2aTasksError("a2a-tasks/bad-mw-opts",
389
381
  "middleware.tasks: opts.scopes must be an object when provided", true);
390
382
  }
383
+ // Every scope VALUE must be a non-empty string. A non-string value (e.g.
384
+ // {transfer: ["a2a:transfer"]}) would make the runtime `typeof requiredScope
385
+ // === "string"` gate silently skip — a fail-open authorization bypass on a
386
+ // gated skill. Catch the operator typo at boot, not at request time.
387
+ var scopeKeys = Object.keys(opts.scopes);
388
+ for (var sk = 0; sk < scopeKeys.length; sk += 1) {
389
+ var sv = opts.scopes[scopeKeys[sk]];
390
+ if (typeof sv !== "string" || sv.length === 0) {
391
+ throw new A2aTasksError("a2a-tasks/bad-mw-opts",
392
+ "middleware.tasks: opts.scopes['" + scopeKeys[sk] + "'] must be a non-empty string", true);
393
+ }
394
+ }
391
395
  }
392
396
  var maxBytes = opts.maxBytes !== undefined ? opts.maxBytes : C.BYTES.mib(1);
393
397
  var emitAudit = opts.audit !== false;
@@ -437,16 +441,36 @@ function middlewareTasks(opts) {
437
441
  }
438
442
  var params = body.params || {};
439
443
 
440
- // Scope enforcement for tasks/send (task references a skill).
441
- if (body.method === "tasks/send" && scopes) {
442
- if (!params.task || typeof params.task !== "object" || typeof params.task.skill !== "string") {
443
- res.statusCode = 200; // JSON-RPC error envelope returns 200
444
+ // Validate the protocol identifiers on the UNTRUSTED-peer ingress before
445
+ // handing them to the operator handler — the client send/get/cancel
446
+ // dispatchers enforce these shapes on egress, the server must too (the
447
+ // sibling b.mcp middleware validates toolName/resourceUri identically).
448
+ if (body.method === "tasks/send") {
449
+ try { _validateTaskShape(params.task, "middleware.tasks.task"); }
450
+ catch (eShape) {
451
+ res.statusCode = 200;
452
+ res.setHeader("Content-Type", "application/json");
453
+ res.end(JSON.stringify(_jsonRpcError(reqId, JSONRPC_INVALID_PARAMS,
454
+ (eShape && eShape.message) || "tasks/send: invalid task")));
455
+ return;
456
+ }
457
+ } else if (body.method === "tasks/get" || body.method === "tasks/cancel") {
458
+ if (typeof params.taskId !== "string" || params.taskId.length > 64 || !TASK_ID_RE.test(params.taskId)) {
459
+ res.statusCode = 200;
444
460
  res.setHeader("Content-Type", "application/json");
445
461
  res.end(JSON.stringify(_jsonRpcError(reqId, JSONRPC_INVALID_PARAMS,
446
- "tasks/send: params.task.skill required")));
462
+ body.method + ": params.taskId must match " + TASK_ID_RE)));
447
463
  return;
448
464
  }
449
- var requiredScope = scopes[params.task.skill];
465
+ }
466
+
467
+ // Scope enforcement for tasks/send (task references a skill).
468
+ if (body.method === "tasks/send" && scopes) {
469
+ // Own-property lookup ONLY — an attacker-controlled skill like
470
+ // "constructor"/"toString" must not resolve an inherited Object.prototype
471
+ // member (proto-shadow). The skill shape is already validated above.
472
+ var hasScope = Object.prototype.hasOwnProperty.call(scopes, params.task.skill);
473
+ var requiredScope = hasScope ? scopes[params.task.skill] : undefined;
450
474
  if (typeof requiredScope === "string") {
451
475
  var grantedScopes = Array.isArray(req.a2aScopes) ? req.a2aScopes : [];
452
476
  if (grantedScopes.indexOf(requiredScope) === -1) {
@@ -515,19 +539,11 @@ function _jsonRpcError(id, code, message, data) {
515
539
  }
516
540
 
517
541
  function _readBody(req, maxBytes) {
518
- return new Promise(function (resolve, reject) {
519
- var collector = safeBuffer.boundedChunkCollector({
520
- maxBytes: maxBytes,
521
- errorClass: A2aTasksError,
522
- sizeCode: "a2a-tasks/body-too-large",
523
- sizeMessage: "a2a-tasks: request body exceeded " + maxBytes + " bytes",
524
- });
525
- req.on("data", function (chunk) {
526
- try { collector.push(chunk); }
527
- catch (capErr) { reject(capErr); }
528
- });
529
- req.on("end", function () { resolve(collector.result()); });
530
- req.on("error", function (e) { reject(e); });
542
+ return safeBuffer.collectStream(req, {
543
+ maxBytes: maxBytes,
544
+ errorClass: A2aTasksError,
545
+ sizeCode: "a2a-tasks/body-too-large",
546
+ sizeMessage: "a2a-tasks: request body exceeded " + maxBytes + " bytes",
531
547
  });
532
548
  }
533
549
 
package/lib/acme.js CHANGED
@@ -42,6 +42,7 @@
42
42
  */
43
43
 
44
44
  var nodeCrypto = require("node:crypto");
45
+ var safeBuffer = require("./safe-buffer");
45
46
 
46
47
  var C = require("./constants");
47
48
  var asn1 = require("./asn1-der");
@@ -553,7 +554,7 @@ function create(opts) {
553
554
  var id = orderOpts.identifiers[i];
554
555
  if (!id || typeof id.type !== "string" || typeof id.value !== "string" ||
555
556
  id.type.length === 0 || id.value.length === 0 ||
556
- id.value.length > C.BYTES.bytes(255)) {
557
+ safeBuffer.byteLengthOf(id.value) > C.BYTES.bytes(255)) {
557
558
  throw _err("acme/bad-identifier",
558
559
  "newOrder: identifier must be { type: string, value: string<=255 }", true);
559
560
  }
@@ -569,7 +570,7 @@ function create(opts) {
569
570
  // the field. v1-defensible scope: refuse non-string + cap length so
570
571
  // attacker-supplied profile values can't bloat the JSON payload.
571
572
  if (typeof orderOpts.profile === "string") {
572
- if (orderOpts.profile.length === 0 || orderOpts.profile.length > C.BYTES.bytes(64)) {
573
+ if (orderOpts.profile.length === 0 || safeBuffer.byteLengthOf(orderOpts.profile) > C.BYTES.bytes(64)) {
573
574
  throw _err("acme/bad-profile",
574
575
  "newOrder: profile name must be a non-empty string <= 64 bytes", true);
575
576
  }
@@ -611,7 +612,7 @@ function create(opts) {
611
612
  } else {
612
613
  throw _err("acme/bad-csr", "finalize: csr must be a DER Buffer or PEM string", true);
613
614
  }
614
- if (csrDer.length === 0 || csrDer.length > C.BYTES.kib(64)) {
615
+ if (csrDer.length === 0 || safeBuffer.byteLengthOf(csrDer) > C.BYTES.kib(64)) {
615
616
  throw _err("acme/bad-csr",
616
617
  "finalize: CSR DER size out of range (got " + csrDer.length + " bytes)", true);
617
618
  }
@@ -842,7 +843,7 @@ function create(opts) {
842
843
  }
843
844
  for (var di = 0; di < opts2.domains.length; di += 1) {
844
845
  var d = opts2.domains[di];
845
- if (typeof d !== "string" || d.length === 0 || d.length > C.BYTES.bytes(255)) {
846
+ if (typeof d !== "string" || d.length === 0 || safeBuffer.byteLengthOf(d) > C.BYTES.bytes(255)) {
846
847
  throw _err("acme/bad-csr-domain",
847
848
  "buildCsr: domains[" + di + "] must be a non-empty string <= 255 bytes", true);
848
849
  }
@@ -1328,7 +1329,7 @@ function create(opts) {
1328
1329
  if (!opts2 || typeof opts2 !== "object" || typeof opts2.identifier !== "string" || opts2.identifier.length === 0) {
1329
1330
  throw _err("acme/bad-identifier", "dnsAccount01ChallengeRecord: opts.identifier (host) is required", true);
1330
1331
  }
1331
- if (opts2.identifier.length > C.BYTES.bytes(255)) {
1332
+ if (safeBuffer.byteLengthOf(opts2.identifier) > C.BYTES.bytes(255)) {
1332
1333
  throw _err("acme/bad-identifier", "dnsAccount01ChallengeRecord: identifier exceeds 255 bytes", true);
1333
1334
  }
1334
1335
  if (!state.accountUrl) {
@@ -70,6 +70,7 @@ var agentAudit = require("./agent-audit");
70
70
  var envelopeMac = require("./agent-envelope-mac");
71
71
  var safeJson = require("./safe-json");
72
72
  var bCrypto = require("./crypto");
73
+ var boundedMap = require("./bounded-map");
73
74
 
74
75
  var audit = lazyRequire(function () { return require("./audit"); });
75
76
 
@@ -149,10 +150,10 @@ function create(opts) {
149
150
 
150
151
  function _registerTopic(topics, name, topicOpts, auditImpl) {
151
152
  guardEventBusTopic.validate(name);
152
- if (topics.has(name)) {
153
+ boundedMap.requireAbsent(topics, name, function () {
153
154
  throw new AgentEventBusError("agent-event-bus/topic-duplicate",
154
155
  "registerTopic: '" + name + "' already registered");
155
- }
156
+ });
156
157
  if (!topicOpts.schema || typeof topicOpts.schema !== "object") {
157
158
  throw new AgentEventBusError("agent-event-bus/bad-schema",
158
159
  "registerTopic: schema required (flat key→type map)");
@@ -193,10 +194,10 @@ function _registerTopic(topics, name, topicOpts, auditImpl) {
193
194
  // lifecycle traceability.
194
195
  function _unregisterTopic(topics, name, auditImpl) {
195
196
  guardEventBusTopic.validate(name);
196
- if (!topics.has(name)) {
197
+ boundedMap.requirePresent(topics, name, function () {
197
198
  throw new AgentEventBusError("agent-event-bus/unknown-topic",
198
199
  "unregisterTopic: '" + name + "' not registered");
199
- }
200
+ });
200
201
  topics.delete(name);
201
202
  _safeAudit(auditImpl, "agent.event_bus.topic_unregistered", null, { name: name });
202
203
  }
@@ -421,6 +422,19 @@ async function _subscribe(topics, pubsub, name, handler, sOpts, permissions, aud
421
422
  topic: name, reason: "require-mac-disabled", phase: "delivery",
422
423
  });
423
424
  }
425
+ // Channel binding: the authenticated _topic must match the channel this
426
+ // handler was registered for. The MAC binds _topic, so a pubsub-write
427
+ // attacker cannot FORGE it — but they CAN replay a genuinely-MAC'd
428
+ // envelope from topic A onto topic B's channel. If A and B share a
429
+ // schema and tenant, that replay would otherwise be delivered to B's
430
+ // handler as a B-event. Drop on mismatch.
431
+ if (wrapped._topic !== name) {
432
+ _safeAudit(auditImpl, "agent.event_bus.delivery_dropped", sOpts.actor, {
433
+ topic: name, reason: "topic-channel-mismatch",
434
+ envelopeTopic: typeof wrapped._topic === "string" ? wrapped._topic : null,
435
+ });
436
+ return;
437
+ }
424
438
  // Tenant-scope check: subscriber's tenantId must match the
425
439
  // publisher's tenantId from the wire envelope. If the envelope
426
440
  // lacks _tenantId (publisher omitted), that's a tampered or
@@ -143,11 +143,8 @@ function _ensureSealTable() {
143
143
  function create(opts) {
144
144
  opts = opts || {};
145
145
  var store = opts.store || _inMemoryBackend(opts.maxInMemoryEntries);
146
- if (typeof store.get !== "function" || typeof store.put !== "function" ||
147
- typeof store.delete !== "function") {
148
- throw new AgentIdempotencyError("agent-idempotency/bad-store",
149
- "create: store must expose { get, put, delete }");
150
- }
146
+ validateOpts.requireMethods(store, ["get", "put", "delete"],
147
+ "create: store", AgentIdempotencyError, "agent-idempotency/bad-store");
151
148
  var ttlMs = typeof opts.ttlMs === "number" ? opts.ttlMs : DEFAULT_TTL_MS;
152
149
  if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
153
150
  throw new AgentIdempotencyError("agent-idempotency/bad-ttl",
@@ -313,7 +310,11 @@ async function _get(store, method, actorId, key, auditImpl, ttlMs, maxResultByte
313
310
  var updatedReplayCount;
314
311
  if (typeof store.incrementReplayCount === "function") {
315
312
  var updated = await store.incrementReplayCount(method, actorId, hash);
316
- updatedReplayCount = updated && updated.replayCount ? updated.replayCount : (row.replayCount || 0) + 1;
313
+ // Coerce the store's returned count to a number a backend that returns it
314
+ // as a string (some drivers stringify integer columns) would otherwise make
315
+ // updatedReplayCount a string and corrupt downstream arithmetic/comparison.
316
+ var inc = updated && updated.replayCount != null ? Number(updated.replayCount) : NaN;
317
+ updatedReplayCount = Number.isFinite(inc) ? inc : (Number(row.replayCount) || 0) + 1;
317
318
  } else {
318
319
  _safeAudit(auditImpl, "agent.idempotency.non_atomic_increment", null, {
319
320
  method: method, actorIdHash: _truncHash(_actorIdHash(actorId)),
@@ -157,11 +157,8 @@ var _saltedFnvBasisCache = null;
157
157
  function create(opts) {
158
158
  opts = opts || {};
159
159
  var backend = opts.backend || _inMemoryBackend();
160
- if (typeof backend.get !== "function" || typeof backend.set !== "function" ||
161
- typeof backend.delete !== "function" || typeof backend.list !== "function") {
162
- throw new AgentOrchestratorError("agent-orchestrator/bad-backend",
163
- "b.agent.orchestrator.create: backend must expose { get, set, delete, list }");
164
- }
160
+ validateOpts.requireMethods(backend, ["get", "set", "delete", "list"],
161
+ "b.agent.orchestrator.create: backend", AgentOrchestratorError, "agent-orchestrator/bad-backend");
165
162
  var clusterImpl = opts.cluster || cluster();
166
163
  var auditImpl = opts.audit || audit();
167
164
  var permissions = opts.permissions || null;
package/lib/agent-saga.js CHANGED
@@ -71,6 +71,7 @@
71
71
 
72
72
  var lazyRequire = require("./lazy-require");
73
73
  var { defineClass } = require("./framework-error");
74
+ var validateOpts = require("./validate-opts");
74
75
  var guardSagaConfig = require("./guard-saga-config");
75
76
  var bCrypto = require("./crypto");
76
77
  var agentAudit = require("./agent-audit");
@@ -118,11 +119,8 @@ function create(config) {
118
119
  // `agent.saga.no_state_store` surfaces the posture per call).
119
120
  var stateStore = config.stateStore || null;
120
121
  if (stateStore !== null) {
121
- if (typeof stateStore.saveStep !== "function" ||
122
- typeof stateStore.loadResumePoint !== "function") {
123
- throw new AgentSagaError("agent-saga/bad-state-store",
124
- "create: stateStore must expose { saveStep, loadResumePoint, markCompleted?, markFailed? }");
125
- }
122
+ validateOpts.requireMethods(stateStore, ["saveStep", "loadResumePoint"],
123
+ "create: stateStore", AgentSagaError, "agent-saga/bad-state-store");
126
124
  }
127
125
  return {
128
126
  run: function (ctx, initialState, opts) { return _run(config, auditImpl, stateStore, ctx, initialState, opts || {}); },
@@ -58,6 +58,7 @@ var validateOpts = require("./validate-opts");
58
58
 
59
59
  var audit = lazyRequire(function () { return require("./audit"); });
60
60
  var auditSign = lazyRequire(function () { return require("./audit-sign"); });
61
+ var compliance = lazyRequire(function () { return require("./compliance"); });
61
62
  var vault = lazyRequire(function () { return require("./vault"); });
62
63
 
63
64
  var AgentSnapshotError = defineClass("AgentSnapshotError", { alwaysPermanent: true });
@@ -310,14 +311,40 @@ function _resolveSigner(ctx) {
310
311
  "OR pass opts.signer to b.agent.snapshot.create({ signer: { sign, verify } })");
311
312
  }
312
313
 
314
+ // allowPlaintext is a dev / single-tenant escape hatch (no at-rest sealing,
315
+ // and no signature required on load). It is REFUSED under a regulated
316
+ // compliance posture so a regulated deployment cannot silently persist OR
317
+ // restore unsealed, unsigned snapshot state. Posture is read from the
318
+ // framework's globally-pinned source (compliance().current()) — the same
319
+ // source the residency + cryptoField seal floors use.
320
+ var REGULATED_NO_PLAINTEXT = ["hipaa", "pci-dss", "gdpr", "soc2"];
321
+ function _activePosture() {
322
+ try { var c = compliance(); return (c && typeof c.current === "function") ? c.current() : null; }
323
+ catch (_e) { return null; }
324
+ }
325
+ function _refusePlaintextUnderPosture(action) {
326
+ var active = _activePosture();
327
+ if (active && REGULATED_NO_PLAINTEXT.indexOf(active) !== -1) {
328
+ throw new AgentSnapshotError("agent-snapshot/plaintext-refused-under-posture",
329
+ action + ": allowPlaintext is refused under the '" + active + "' compliance posture — " +
330
+ "wire a sealer (b.vault.init() at boot OR opts.sealer { seal, unseal }) so snapshot " +
331
+ "state is sealed + signature-verified at rest");
332
+ }
333
+ }
334
+
313
335
  function _resolveSealer(ctx) {
314
336
  if (ctx.sealer) return ctx.sealer;
315
337
  var v;
316
338
  try { v = vault(); } catch (_e) { v = null; }
317
- if (v && v.aad && typeof v.aad.seal === "function" && typeof v.aad.unseal === "function") {
339
+ // Only use the framework vault when it is actually INITIALIZED. A loaded-but-
340
+ // uninitialized vault still exposes aad.seal/unseal (they throw on call), which
341
+ // previously masked the allowPlaintext escape hatch and leaked a raw
342
+ // vault/not-initialized error instead of a clean sealer-not-wired refusal.
343
+ if (v && typeof v.isInitialized === "function" && v.isInitialized() &&
344
+ v.aad && typeof v.aad.seal === "function" && typeof v.aad.unseal === "function") {
318
345
  return v.aad;
319
346
  }
320
- if (ctx.allowPlaintext) return null;
347
+ if (ctx.allowPlaintext) { _refusePlaintextUnderPosture("persist"); return null; }
321
348
  throw new AgentSnapshotError("agent-snapshot/sealer-not-wired",
322
349
  "persist: no sealer wired — operator must run b.vault.init() at boot " +
323
350
  "OR pass opts.sealer to b.agent.snapshot.create({ sealer: { seal, unseal } }) " +
@@ -526,6 +553,9 @@ async function _unwrapAndVerify(ctx, raw, expectedId) {
526
553
  // remains visible to compliance audit.
527
554
  if (typeof snap.sig !== "string" || snap.sig.length === 0) {
528
555
  if (ctx.allowPlaintext) {
556
+ // Even the dev escape hatch cannot waive signature verification under a
557
+ // regulated posture — refuse the unsigned restore rather than trust it.
558
+ _refusePlaintextUnderPosture("load");
529
559
  agentAudit.safeAudit(ctx.audit, "agent.snapshot.unsigned_load", null, {
530
560
  snapshotId: snap.snapshotId,
531
561
  });
@@ -153,11 +153,8 @@ var TENANT_KEY_BYTES = 32;
153
153
  function create(opts) {
154
154
  opts = opts || {};
155
155
  var backend = opts.backend || _inMemoryBackend();
156
- if (typeof backend.get !== "function" || typeof backend.set !== "function" ||
157
- typeof backend.delete !== "function" || typeof backend.list !== "function") {
158
- throw new AgentTenantError("agent-tenant/bad-backend",
159
- "create: backend must expose { get, set, delete, list }");
160
- }
156
+ validateOpts.requireMethods(backend, ["get", "set", "delete", "list"],
157
+ "create: backend", AgentTenantError, "agent-tenant/bad-backend");
161
158
  var auditImpl = opts.audit || audit();
162
159
  var permissions = opts.permissions || null;
163
160
  var ctx = {
@@ -99,25 +99,12 @@ function wrap(opts) {
99
99
  var legalBasis = opts.legalBasis;
100
100
  var decide = opts.decide;
101
101
  var onAdverse = typeof opts.onAdverse === "function" ? opts.onAdverse : null;
102
- var auditOn = opts.audit !== false;
103
102
  var now = typeof opts.now === "function" ? opts.now : function () { return Date.now(); };
104
103
 
105
104
  var deadlines = REGIME_DEADLINES[legalBasis] || REGIME_DEADLINES["operator-defined"];
106
105
 
107
- function _emitAudit(action, outcome, metadata) {
108
- if (!auditOn) return;
109
- try {
110
- audit().safeEmit({
111
- action: "ai.adverse_decision." + action,
112
- outcome: outcome,
113
- metadata: metadata || {},
114
- });
115
- } catch (_e) { /* drop-silent */ }
116
- }
117
- function _emitMetric(verb, n, labels) {
118
- try { observability().safeEvent("ai.adverse_decision." + verb, n || 1, labels || {}); }
119
- catch (_e) { /* drop-silent */ }
120
- }
106
+ var _emitAudit = audit().namespaced("ai.adverse_decision", opts.audit);
107
+ var _emitMetric = observability().namespaced("ai.adverse_decision");
121
108
 
122
109
  return async function adverseDecisionDecorated(subject) {
123
110
  if (!subject || typeof subject !== "object") {
@@ -36,6 +36,7 @@
36
36
  */
37
37
 
38
38
  var validateOpts = require("./validate-opts");
39
+ var numericBounds = require("./numeric-bounds");
39
40
  var { defineClass } = require("./framework-error");
40
41
 
41
42
  var AedtBiasAuditError = defineClass("AedtBiasAuditError", { alwaysPermanent: true });
@@ -49,7 +50,7 @@ function _str(v, label) {
49
50
  return v;
50
51
  }
51
52
  function _count(v, label) {
52
- if (typeof v !== "number" || !isFinite(v) || v < 0 || Math.floor(v) !== v) throw new AedtBiasAuditError("aedt/bad-count", "aedtBiasAudit: " + label + " must be a non-negative integer");
53
+ if (!numericBounds.isNonNegativeFiniteInt(v)) throw new AedtBiasAuditError("aedt/bad-count", "aedtBiasAudit: " + label + " must be a non-negative integer");
53
54
  return v;
54
55
  }
55
56
 
@@ -239,12 +239,7 @@ function create(opts) {
239
239
  }
240
240
  var auditOn = opts.audit !== false;
241
241
 
242
- function _emitAudit(action, outcome, metadata) {
243
- if (!auditOn) return;
244
- try {
245
- audit().safeEmit({ action: action, outcome: outcome, metadata: metadata || {} });
246
- } catch (_e) { /* audit best-effort — drop-silent */ }
247
- }
242
+ var _emitAudit = audit().namespaced(null, { audit: auditOn });
248
243
 
249
244
  function describe(modelId) {
250
245
  var d = registry.get(modelId);
@@ -255,9 +255,7 @@ function report(opts) {
255
255
  * @example
256
256
  * b.ai.aiContentDetect.compliancePosture("ca-ab-853"); // → "strict"
257
257
  */
258
- function compliancePosture(posture) {
259
- return COMPLIANCE_POSTURES[posture] || null;
260
- }
258
+ var compliancePosture = gateContract.makePostureAccessor(COMPLIANCE_POSTURES);
261
259
 
262
260
  module.exports = {
263
261
  report: report,
package/lib/ai-dp.js CHANGED
@@ -429,11 +429,7 @@ function budget(opts) {
429
429
  var spentDelta = 0;
430
430
  var rdp = RDP_ORDERS.map(function () { return 0; }); // rdp accounting
431
431
 
432
- function _emitAudit(action, outcome, metadata) {
433
- if (!auditOn) return;
434
- try { audit().safeEmit({ action: action, outcome: outcome, metadata: metadata || {} }); }
435
- catch (_e) { /* drop-silent */ }
436
- }
432
+ var _emitAudit = audit().namespaced(null, { audit: auditOn });
437
433
 
438
434
  function _currentEpsilon(rdpCurve) {
439
435
  if (accounting === "basic") return spentEpsilon;
@@ -161,7 +161,7 @@ function frontierModelProtocol(opts) {
161
161
  function incidentReport(opts) {
162
162
  opts = opts || {};
163
163
  if (typeof opts !== "object") throw new FrontierProtocolError("frontier/bad-opts", "incidentReport: opts must be an object");
164
- if (!CRITICAL_INCIDENT_TYPES[opts.type]) throw new FrontierProtocolError("frontier/bad-incident-type", "incidentReport: type must be one of " + Object.keys(CRITICAL_INCIDENT_TYPES).join(", "));
164
+ if (!Object.prototype.hasOwnProperty.call(CRITICAL_INCIDENT_TYPES, opts.type)) throw new FrontierProtocolError("frontier/bad-incident-type", "incidentReport: type must be one of " + Object.keys(CRITICAL_INCIDENT_TYPES).join(", "));
165
165
 
166
166
  var discoveredMs;
167
167
  if (opts.discoveredAt == null) discoveredMs = Date.now();
package/lib/ai-input.js CHANGED
@@ -23,6 +23,7 @@
23
23
  var C = require("./constants");
24
24
  var numericBounds = require("./numeric-bounds");
25
25
  var audit = require("./audit");
26
+ var codepointClass = require("./codepoint-class");
26
27
  var { AiInputError } = require("./framework-error");
27
28
 
28
29
  var SAMPLE_TRUNC = 80; // sample truncation length, not bytes
@@ -69,8 +70,7 @@ function _featuresOf(input) {
69
70
  var cp = input.charCodeAt(i);
70
71
  if ((cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2066 && cp <= 0x2069)) bidi++;
71
72
  else if (cp === 0x200b || cp === 0x200c || cp === 0x200d || cp === 0xfeff || cp === 0x2060) zw++;
72
- else if (cp < 0x20 && cp !== 0x09 && cp !== 0x0a && cp !== 0x0d) ctrl++;
73
- else if (cp === 0x7f) ctrl++;
73
+ else if (codepointClass.isForbiddenControlChar(cp, { allowLf: true, allowCr: true })) ctrl++;
74
74
  }
75
75
  return {
76
76
  length: input.length,
@@ -95,7 +95,7 @@ function _validateDataComponent(d, idx) {
95
95
  "build.datasets[" + idx + "]: must be an object");
96
96
  }
97
97
  _requireString(d, "name", "build.datasets[" + idx + "]");
98
- if (d.type !== undefined && !VALID_DATA_TYPES[d.type]) {
98
+ if (d.type !== undefined && !Object.prototype.hasOwnProperty.call(VALID_DATA_TYPES, d.type)) {
99
99
  throw new AiModelManifestError("aibom/bad-dataset-type",
100
100
  "build.datasets[" + idx + "].type '" + d.type + "' not in CycloneDX 1.6 data-type vocabulary");
101
101
  }