@blamejs/blamejs-shop 0.4.85 → 0.4.86

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 (59) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/lib/asset-manifest.json +1 -1
  3. package/lib/order.js +4 -2
  4. package/lib/security-middleware.js +1 -0
  5. package/lib/vendor/MANIFEST.json +71 -39
  6. package/lib/vendor/blamejs/CHANGELOG.md +2 -0
  7. package/lib/vendor/blamejs/api-snapshot.json +11 -3
  8. package/lib/vendor/blamejs/lib/atomic-file.js +34 -0
  9. package/lib/vendor/blamejs/lib/auth/fido-mds3.js +10 -0
  10. package/lib/vendor/blamejs/lib/auth/password.js +1 -0
  11. package/lib/vendor/blamejs/lib/auth/saml.js +11 -3
  12. package/lib/vendor/blamejs/lib/daemon.js +4 -1
  13. package/lib/vendor/blamejs/lib/external-db.js +131 -0
  14. package/lib/vendor/blamejs/lib/graphql-federation.js +25 -15
  15. package/lib/vendor/blamejs/lib/log-stream-cloudwatch.js +1 -0
  16. package/lib/vendor/blamejs/lib/log-stream-local.js +14 -1
  17. package/lib/vendor/blamejs/lib/log-stream-otlp.js +1 -0
  18. package/lib/vendor/blamejs/lib/log-stream-webhook.js +1 -0
  19. package/lib/vendor/blamejs/lib/mail-auth.js +69 -14
  20. package/lib/vendor/blamejs/lib/mail-bimi.js +6 -0
  21. package/lib/vendor/blamejs/lib/mail-crypto-smime.js +10 -0
  22. package/lib/vendor/blamejs/lib/mail-dkim.js +68 -15
  23. package/lib/vendor/blamejs/lib/mail.js +39 -0
  24. package/lib/vendor/blamejs/lib/middleware/api-encrypt.js +6 -2
  25. package/lib/vendor/blamejs/lib/network-dns-resolver.js +61 -11
  26. package/lib/vendor/blamejs/lib/network-dns.js +47 -2
  27. package/lib/vendor/blamejs/lib/network-nts.js +16 -0
  28. package/lib/vendor/blamejs/lib/network-proxy.js +55 -2
  29. package/lib/vendor/blamejs/lib/object-store/azure-blob-bucket-ops.js +1 -0
  30. package/lib/vendor/blamejs/lib/object-store/gcs-bucket-ops.js +1 -0
  31. package/lib/vendor/blamejs/lib/object-store/http-request.js +4 -0
  32. package/lib/vendor/blamejs/lib/outbox.js +29 -0
  33. package/lib/vendor/blamejs/lib/queue-sqs.js +1 -0
  34. package/lib/vendor/blamejs/lib/request-helpers.js +25 -6
  35. package/lib/vendor/blamejs/lib/session-device-binding.js +46 -24
  36. package/lib/vendor/blamejs/lib/session.js +85 -28
  37. package/lib/vendor/blamejs/package.json +1 -1
  38. package/lib/vendor/blamejs/release-notes/v0.15.16.json +94 -0
  39. package/lib/vendor/blamejs/test/layer-0-primitives/api-encrypt.test.js +51 -0
  40. package/lib/vendor/blamejs/test/layer-0-primitives/atomic-file-open-append-nofollow.test.js +87 -0
  41. package/lib/vendor/blamejs/test/layer-0-primitives/codebase-patterns.test.js +48 -0
  42. package/lib/vendor/blamejs/test/layer-0-primitives/external-db-non-atomic-backend.test.js +200 -0
  43. package/lib/vendor/blamejs/test/layer-0-primitives/fido-mds3-cert-bad-validity.test.js +159 -0
  44. package/lib/vendor/blamejs/test/layer-0-primitives/graphql-federation.test.js +49 -2
  45. package/lib/vendor/blamejs/test/layer-0-primitives/mail-auth-dmarc-policy-failclosed.test.js +139 -0
  46. package/lib/vendor/blamejs/test/layer-0-primitives/mail-bimi-cert-validity-unparseable.test.js +137 -0
  47. package/lib/vendor/blamejs/test/layer-0-primitives/mail-crypto-smime-bad-validity.test.js +134 -0
  48. package/lib/vendor/blamejs/test/layer-0-primitives/mail-dkim-numericdate-failclosed.test.js +155 -0
  49. package/lib/vendor/blamejs/test/layer-0-primitives/mail-proxy-framing-bounds.test.js +263 -0
  50. package/lib/vendor/blamejs/test/layer-0-primitives/network-dns-lookup-timeout-default.test.js +116 -0
  51. package/lib/vendor/blamejs/test/layer-0-primitives/network-dns-resolver-timeout.test.js +126 -0
  52. package/lib/vendor/blamejs/test/layer-0-primitives/network-nts-handshake-byte-cap.test.js +127 -0
  53. package/lib/vendor/blamejs/test/layer-0-primitives/saml-subjectconfirmation-notbefore.test.js +238 -0
  54. package/lib/vendor/blamejs/test/layer-0-primitives/session-destroy-all-store-backed.test.js +128 -0
  55. package/lib/vendor/blamejs/test/layer-0-primitives/session-device-binding-ipv6-canonical-and-no-store.test.js +202 -0
  56. package/lib/vendor/blamejs/test/layer-0-primitives/session-device-binding.test.js +18 -9
  57. package/lib/vendor/blamejs/test/layer-0-primitives/webhook-verify-nonce-atomic.test.js +169 -0
  58. package/lib/webhooks.js +38 -9
  59. package/package.json +1 -1
@@ -8,6 +8,8 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.15.x
10
10
 
11
+ - v0.15.16 (2026-06-22) — **A correctness and hardening release: a broad set of credential and certificate verifiers now fail closed on a present-but-unparseable timestamp instead of silently skipping the check, outbound network clients gain an overall wall-clock timeout and a bounded framing buffer, DMARC refuses a record with no usable policy, append-only log sinks refuse a symlinked path, and the interactive-transaction and replay-store contracts refuse a backend that cannot honor them.** This release closes a family of fail-open and resource-exhaustion gaps without adding opt-ins to the request path. A recurring pattern across the verifiers — a timestamp parsed with a lenient parser, then gated by isFinite() so an unparseable value disables the check — is converted to fail-closed everywhere it appears: DKIM x=/t=/l=, ARC AMS/AS t=/x=, SAML Bearer and holder-of-key NotBefore, and the FIDO MDS3 / BIMI / S/MIME certificate validity windows now refuse a malformed value rather than accepting the credential. DMARC now validates and requires a usable p= policy and never recommends delivery for a failing message with an absent or unrecognized policy. Outbound clients that exposed a single timeout but applied it only as an idle (zero-progress) timer now also enforce it as an overall wall-clock cap, so a peer that trickles bytes within the idle window can no longer hold a request open indefinitely: the encrypted HTTP client, the object-store and SQS request paths, the CloudWatch / OTLP / webhook log sinks, and the password breach check. The DNS resolver and the lower-level DNS client gain a per-query wall-clock deadline that also tears the socket down, the SMTP client and the proxy CONNECT tunnel bound their framing buffers and add an overall deadline, and the NTS key-establishment handshake bounds its accumulator. The append-only local log sink and the daemon log open with O_NOFOLLOW so a symlink planted at the path is refused rather than followed. b.externalDb.transaction and b.outbox now refuse a backend that declares it cannot provide an interactive transaction instead of silently running a non-atomic block, and the GraphQL-federation replay store adopts the framework's atomic check-and-insert contract. **Added:** *b.atomicFile.openAppendNoFollowSync — symlink-refusing append open* — Opens a long-lived append target (an active log file kept open across appends and reopened on rotation) with O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW: the file is created or appended normally, but a symlink at the final path component fails the open closed (ELOOP) rather than redirecting writes. The append-sink counterpart to openNoFollowSync (read) and the exclusive-create temp open. · *b.externalDb.supportsTransactions() and stateless-adapter declaration* — A backend adapter may declare supportsTransactions: false (a stateless / autocommit-per-statement adapter) and/or provide a batch(client, statements) hook for an atomic multi-statement path. b.externalDb.supportsTransactions() reports whether the picked backend can provide an interactive transaction, so a consumer built on the dual-write guarantee can refuse a non-atomic backend up front. · *Store-free device fingerprint* — b.sessionDeviceBinding.fingerprint(req, opts) is now a static entry point returning the request-shape digest with no store, and b.sessionDeviceBinding.create() with neither a bindingStore nor storeInSession returns an instance whose stateless fingerprint() works while bind()/verify() throw a clear "no store configured". Soft device binding for self-validating tokens (a sealed cookie or JWT carrying the fingerprint) no longer needs a fabricated no-op store. **Changed:** *Device fingerprint IP masking is canonical* — b.sessionDeviceBinding masked the client IP into its prefix bucket by textual group slicing with no IPv6 normalization, so equivalent forms of one address (a ::-compressed form vs its fully-expanded form) hashed to different fingerprints and a roaming client could be logged out on a false drift. It now masks through the same canonical prefix helper b.session uses, preserving the configured prefix width (the IPv6 default stays /48, and ipPrefixBits is honored). b.requestHelpers.ipPrefix accepts { v4Bits, v6Bits } to override the /24 + /64 default for a function-form fingerprint or other reuse. **Fixed:** *b.session.destroyAllForUser works for pluggable-store consumers* — A consumer configuring sessions through b.session.useStore without calling b.db.init() got a db/not-initialized error from destroyAllForUser — every "log out everywhere" / suspend / delete path rejected with a 500 after the store rows had already been deleted, because the stateless valid-from boundary write was routed only to the framework database. The boundary now prefers the framework database when one is initialized and otherwise falls back to the configured session store (provisioning its table on demand), so store-backed deployments raise the stateless boundary successfully; it still fails closed when neither a framework database nor a store is available. **Security:** *Certificate and credential verifiers fail closed on an unparseable timestamp* — A present-but-unparseable date no longer silently disables a validity check. DKIM x= / t= (signature expiry, future-date, ordering) and l= (body-length cap), ARC AMS/AS t= / x=, SAML Bearer and holder-of-key SubjectConfirmationData NotBefore, and the FIDO MDS3, BIMI, and S/MIME certificate validity windows previously parsed the value, then guarded the comparison with isFinite() — so a value that did not parse (NaN) skipped the check and the credential was accepted. Each now refuses a present-but-unparseable value (a permerror / not-valid result) and only an absent optional field is ignored, matching the existing fail-closed handling of the SAML Conditions block. · *DMARC refuses a record with no usable policy* — The DMARC policy tag p= (and the subdomain sp=) were taken verbatim with no validation and p= was never required, so the disposition mapped a null or typo'd policy to the catch-all "deliver". A failing, unaligned message against a domain whose record omitted p= or carried an unrecognized value was therefore delivered. p= and sp= are now validated against none|quarantine|reject, p= is required for a record to carry a policy at all, an invalid record is a permerror (not a transient temperror), and the disposition is an explicit fail-closed mapping that never delivers a failing message on an absent or unrecognized policy. · *Outbound clients enforce an overall wall-clock timeout, not only an idle timeout* — Several clients exposed a single timeout but forwarded it to the underlying request only as idleTimeoutMs (a zero-progress cap that resets on every received byte), leaving no overall bound — a peer that trickles one byte inside each idle window holds the call open indefinitely. b.httpClient.encrypted (which dropped timeoutMs entirely, and now also forwards the caller's AbortSignal), the object-store request path and Azure/GCS bucket operations, the SQS queue client, the CloudWatch / OTLP / webhook log sinks, and the password HIBP breach check now set the overall wall-clock timeout alongside the idle timeout. · *DNS lookups gain a default wall-clock deadline and tear the socket down* — The DNS resolver's DoH transport had no time bound of any kind and the lower-level DNS client defaulted its lookup timeout to zero (no deadline). A non-responsive or slow-trickle upstream — reachable while resolving DKIM/SPF/BIMI records for inbound mail — held the lookup pending forever. The resolver now takes a per-query timeout (default 10s) wrapping every query and CNAME hop, the DNS client defaults its lookup timeout to 10s (operators opt out with a zero timeout), and the raw DoH/DoT request paths arm a socket timeout that destroys the connection on a stall rather than leaking the descriptor. · *SMTP, proxy-CONNECT, and NTS clients bound their read buffers and add deadlines* — The SMTP client accumulated the server's reply without a byte cap and relied on an idle timer alone; a hostile or broken MX that never sent a line terminator could exhaust memory, and a slow trickle held the transaction open. It now caps the accumulated reply (refusing once it exceeds the response ceiling) and enforces an overall transaction deadline. The proxy CONNECT-tunnel client, which accumulated the proxy's reply unbounded with no socket timeout, now caps the header buffer and times out the connect. The NTS key-establishment handshake reader caps its record accumulator so a server streaming non-terminating records cannot exhaust memory before the handshake timer fires. · *Append-only log sinks refuse a symlinked path* — The local log sink and the daemon log opened the active file in append mode without O_NOFOLLOW, so a symlink planted at the log path (including one re-planted in the race window after a caller's pre-check) was followed, redirecting log writes to an attacker-chosen file. Both now open with O_NOFOLLOW via the new b.atomicFile.openAppendNoFollowSync, refusing a symlinked final path component. · *Transaction and replay-store contracts refuse a backend that cannot honor them* — b.externalDb.transaction and b.outbox.create now refuse a backend that declares it cannot provide an interactive transaction (a stateless / autocommit-per-statement adapter) instead of silently running BEGIN, the body, and COMMIT on different sessions — no isolation, no rollback — while reporting success. b.graphqlFederation.guardSdl now consults its replay nonce store through the framework's atomic checkAndInsert(nonce, expireAt) contract (the same one b.webhook and b.nonceStore use) rather than a non-atomic has()-then-remember() check that raced concurrent redeliveries; a store lacking checkAndInsert is refused at construction. **Migration:** *DNS lookups now time out by default* — The lower-level DNS client's lookup timeout previously defaulted to zero (no deadline); it now defaults to 10 seconds. A deployment that intentionally ran DNS lookups with no wall-clock bound must set the lookup timeout to zero explicitly to restore the old behavior. The b.network.dns.resolver default timeout is also 10 seconds and is configurable via its timeoutMs option. · *b.graphqlFederation.guardSdl nonceStore contract* — guardSdl's optional replay nonceStore now requires the atomic checkAndInsert(nonce, expireAt) contract (b.nonceStore.create is the reference store) and refuses the previous { has, remember } shape at construction. Operators using the old shape should pass b.nonceStore.create(...) or an adapter exposing checkAndInsert. · *Interactive transactions on a stateless backend are refused* — If an externalDb backend adapter declares supportsTransactions: false, b.externalDb.transaction and b.outbox.create now throw rather than running a silently non-atomic block. Existing stateful adapters (Postgres / MySQL / SQLite, and any adapter that supplies beginTx/commit/rollback or omits the flag) are unaffected. A stateless / autocommit-per-statement adapter should supply interactive transaction hooks or a batch adapter.
12
+
11
13
  - v0.15.15 (2026-06-21) — **A focused correctness and hardening release: more authentication and signature verifiers fail closed (JWT issuer, SAML recipient binding, OAuth nonce, CIBA token binding, FIDO certification level), the WebSocket client bounds a fragmented message before it completes, DMARC resolves the From domain before the policy lookup, and the CSP builder refuses a directive-injecting source; fixes a middleware pipeline promise that never settled on a write-and-halt, and exposes the X.509 CA-bit issuer test, an IP-prefix helper, and a reverse-proxy-aware session fingerprint option.** This release continues to tighten existing protections without adding opt-ins on the request path. A further set of authentication and signature verifiers now refuse malformed or unbound credentials: JWT verify rejects an array-valued issuer claim (an any-match bypass, CVE-2025-30144 class), SAML requires the mandatory Recipient on a Bearer or holder-of-key confirmation and enforces every AudienceRestriction, OAuth no longer skips the ID-token nonce check on an empty nonce, CIBA binds the returned ID token to its auth_req_id, the FIDO MDS3 certification level reflects the authenticator's current status rather than its historical maximum, and a JOSE header that decodes to a non-object is a typed error rather than an uncaught throw. The WebSocket client now bounds a fragmented incoming message by its running total instead of only at the final frame, DMARC validates the From-header domain before the policy lookup, the data-residency write gate compares the residency column case-insensitively, and the SQL builder refuses an equality against NULL and validates every IN-list element. The CSP builder refuses a source token containing whitespace or a semicolon (directive injection). A middleware pipeline that a request handler halted by writing the response without calling next() left its promise pending forever, retaining the request closure — it now settles. New surface is additive and backward compatible: the basicConstraints-enforcing X.509 issuer test is exposed publicly, the session device fingerprint can resolve the client IP through a trusted-proxy allowlist, and the /24+/64 IP-prefix masking it uses is exposed for reuse. **Added:** *b.x509Chain — the CA-bit-enforcing X.509 issuer test* — isCaCert(cert) and issuerValidlyIssued(issuer, subject) are now public. Node's X509Certificate.checkIssued() does not enforce the basicConstraints cA bit (CVE-2002-0862 class), so a non-CA leaf can be accepted as an issuer; these helpers require cA:TRUE and verify the signature, fail closed on any malformed input, and are the same test the framework's own chain walkers use. A consumer validating a chain outside a TLS handshake (an operator-uploaded CA bundle, a non-handshake PQ-signed certificate) can now use the hardened path instead of raw checkIssued(). · *Reverse-proxy-aware session device fingerprint* — b.session.create / verify / rotate accept { trustedProxies } (CIDRs) or { clientIpResolver } so the built-in clientIp / clientIpPrefix fingerprint fields resolve the real client IP behind a trusted proxy, consistent with b.requestHelpers.trustedClientIp. Without the option the fingerprint still binds to the bare socket peer (unchanged default), so existing fingerprints keep matching; pass the same option to create, verify, and rotate. The /24 (IPv4) + /64 (IPv6) subnet masking is exposed as b.requestHelpers.ipPrefix for an operator using a function-form fingerprint field. **Changed:** *DKIM l= is counted over the canonicalized body* — On verify, the l= body-length tag was applied to the raw body before canonicalization, so a legitimate relaxed/relaxed signature whose l= matched the canonicalized length was rejected with a body-hash mismatch whenever relaxed canonicalization changed the byte count within the first l= octets. The body is now canonicalized first and the canonicalized octet stream truncated to l= (RFC 6376 §3.4.5). · *PIPL cross-border security-assessment threshold documentation corrected* — The b.pipl.sccFilingAssessment contract stated the CAC security assessment becomes mandatory above 100,000 cumulative PI subjects (the superseded 2022 figure). The builder enforces the current CAC Provisions on Promoting and Regulating Cross-Border Data Flows — a security assessment above 1,000,000 non-sensitive PI subjects or 10,000 sensitive, with the 100,000–1,000,000 band in the standard-contract / certification tier. The documentation now matches the enforced thresholds. **Fixed:** *composePipeline settles its promise when a middleware halts* — A regular middleware that wrote the response and returned without calling next() — the intended way to halt the chain from an auth / rate-limit / bot block — left the promise returned by b.middleware.composePipeline pending forever, retaining its request/response closure (an unbounded leak under sustained blocked traffic). The halt path now settles the promise without advancing to the route handler; the same applies to an error handler that consumes the error without calling next(). · *Quality-list header parsing is quote-aware* — parseQualityList mis-read a q= substring that appeared inside a quoted media-range or Accept-* parameter, mis-weighting content negotiation. It now parses the q parameter with quote-aware splitting. **Security:** *More authentication and signature verifiers fail closed* — JWT verify rejects an array-valued iss claim (it had passed through a generic any-match built for the legitimately-array aud claim, so a multi-issuer array satisfied a single-issuer expectation — CVE-2025-30144 class), matching the external JWT and OIDC verifiers. SAML verifyResponse requires the Recipient attribute on a Bearer or holder-of-key SubjectConfirmation and confirms it equals the ACS URL (an absent Recipient was silently skipped), and enforces every AudienceRestriction (AND-combined per SAML core). OAuth no longer fails open and skips the ID-token nonce replay check when the supplied nonce is empty. CIBA binds the polled / notified ID token to its auth_req_id so a token minted for another request can't be accepted. The FIDO MDS3 certification level reflects the authenticator's current status, not the highest level it ever held, so a later decertification or downgrade is honored by a step-up policy. A JOSE header or payload that decodes to JSON null or a non-object now raises a typed authentication error instead of an uncaught TypeError. · *WebSocket fragmented-message reassembly is bounded before completion* — The client enforced maxMessageBytes only when a fragmented message's final frame arrived, so a peer could stream unbounded continuation frames and exhaust memory before the limit was ever checked. The running reassembly total is now enforced per frame, and a frame arriving after close is ignored. · *DMARC resolves the From domain before the policy lookup* — The From-header bare addr-spec domain extraction did not reject RFC 5322 group syntax or a trailing semicolon, so a crafted From header could yield a corrupted domain that defeated the DMARC alignment / policy lookup. The domain is now validated (length-bounded, rejecting the group and punctuation forms) before it is used. · *Data-residency and SQL builder correctness* — The per-row data-residency write gate compares the residency column name case-insensitively, so a raw UPDATE that spells the column in a different letter case can no longer slip the cross-border transfer check. The SQL builder refuses an equality against NULL (col = NULL is always false; use IS NULL) and validates every element of an IN-list on the Postgres = ANY(?) path, matching the sqlite / MySQL path. · *CSP builder refuses a directive-injecting source* — A CSP source is a single non-whitespace token. build() and mergeDirectives() now reject a source containing whitespace or a semicolon — because the emitter space-joins sources and semicolon-joins directives, a value like "https://x; script-src https://evil" injected a live directive.
12
14
 
13
15
  - 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).
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 1,
3
- "frameworkVersion": "0.15.15",
4
- "createdAt": "2026-06-22T00:16:09.227Z",
3
+ "frameworkVersion": "0.15.16",
4
+ "createdAt": "2026-06-22T12:04:10.257Z",
5
5
  "exports": {
6
6
  "a2a": {
7
7
  "type": "object",
@@ -2346,6 +2346,10 @@
2346
2346
  "type": "function",
2347
2347
  "arity": 3
2348
2348
  },
2349
+ "openAppendNoFollowSync": {
2350
+ "type": "function",
2351
+ "arity": 2
2352
+ },
2349
2353
  "openNoFollowSync": {
2350
2354
  "type": "function",
2351
2355
  "arity": 2
@@ -16060,6 +16064,10 @@
16060
16064
  "type": "function",
16061
16065
  "arity": 0
16062
16066
  },
16067
+ "supportsTransactions": {
16068
+ "type": "function",
16069
+ "arity": 1
16070
+ },
16063
16071
  "transaction": {
16064
16072
  "type": "function",
16065
16073
  "arity": 2
@@ -49213,7 +49221,7 @@
49213
49221
  },
49214
49222
  "ipPrefix": {
49215
49223
  "type": "function",
49216
- "arity": 1
49224
+ "arity": 2
49217
49225
  },
49218
49226
  "makeResourceAuditEmitter": {
49219
49227
  "type": "function",
@@ -1336,6 +1336,39 @@ function openNoFollowSync(filepath, mode) {
1336
1336
  return nodeFs.openSync(filepath, flags, mode === undefined ? 0o600 : mode);
1337
1337
  }
1338
1338
 
1339
+ /**
1340
+ * @primitive b.atomicFile.openAppendNoFollowSync
1341
+ * @signature b.atomicFile.openAppendNoFollowSync(filepath, mode?)
1342
+ * @since 0.15.16
1343
+ * @status stable
1344
+ * @related b.atomicFile.openNoFollowSync, b.atomicFile.writeSync
1345
+ *
1346
+ * Open a path for append with `O_NOFOLLOW` so a symlink at the final path
1347
+ * component is refused (`ELOOP`) instead of followed — the append-sink
1348
+ * counterpart to `openNoFollowSync` (read) and `_openExclTemp` (exclusive
1349
+ * create). For long-lived append targets a one-shot atomic write can't
1350
+ * model: an active log file kept open across many appends and reopened on
1351
+ * rotation. The flags are `O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW` —
1352
+ * the file is created (mode-applied) if absent and appended to if it is a
1353
+ * regular file, but a symlink at the path fails the open closed rather than
1354
+ * redirecting writes to an attacker-chosen target (CWE-59). A bare
1355
+ * `openSync(path, "a")` instead follows such a symlink, so a caller's
1356
+ * pre-check-then-unlink defense still races a symlink re-planted before the
1357
+ * sink's own open — this primitive makes the symlink refusal atomic with the
1358
+ * open. `O_NOFOLLOW` is POSIX-only; on platforms without it the flag is 0
1359
+ * (a plain append open) — Windows symlink semantics differ and are out of
1360
+ * scope. Throws the raw `openSync` error (caller maps `ELOOP` / `ENOENT`).
1361
+ *
1362
+ * @example
1363
+ * var fd = b.atomicFile.openAppendNoFollowSync(activeLogPath, 0o600);
1364
+ * fs.writeSync(fd, line); // appends; a symlink at activeLogPath → ELOOP
1365
+ */
1366
+ function openAppendNoFollowSync(filepath, mode) {
1367
+ var flags = nodeFs.constants.O_WRONLY | nodeFs.constants.O_APPEND |
1368
+ nodeFs.constants.O_CREAT | (nodeFs.constants.O_NOFOLLOW || 0);
1369
+ return nodeFs.openSync(filepath, flags, mode === undefined ? 0o600 : mode);
1370
+ }
1371
+
1339
1372
  module.exports = {
1340
1373
  write: write,
1341
1374
  writeSync: writeSync,
@@ -1345,6 +1378,7 @@ module.exports = {
1345
1378
  readSync: readSync,
1346
1379
  fdSafeReadSync: fdSafeReadSync,
1347
1380
  openNoFollowSync: openNoFollowSync,
1381
+ openAppendNoFollowSync: openAppendNoFollowSync,
1348
1382
  writeJson: writeJson,
1349
1383
  readJson: readJson,
1350
1384
  copy: copy,
@@ -214,6 +214,16 @@ function _validateChain(x5c, rootPems) {
214
214
  for (var v = 0; v < chain.length; v++) {
215
215
  var notBefore = Date.parse(chain[v].validFrom);
216
216
  var notAfter = Date.parse(chain[v].validTo);
217
+ // Fail closed on an unparseable validity window: a cert whose
218
+ // notBefore/notAfter is present but does not parse (Date.parse ->
219
+ // NaN) must not slip past the window checks below — otherwise a
220
+ // forged / malformed validity date silently disables both the
221
+ // not-yet-valid and the expired guards.
222
+ if (!isFinite(notBefore) || !isFinite(notAfter)) {
223
+ throw new FidoMds3Error("fido-mds3/cert-bad-validity",
224
+ "x5c[" + v + "] has unparseable validity dates (validFrom=" +
225
+ chain[v].validFrom + ", validTo=" + chain[v].validTo + ")");
226
+ }
217
227
  if (isFinite(notBefore) && now < notBefore) {
218
228
  throw new FidoMds3Error("fido-mds3/cert-not-yet-valid",
219
229
  "x5c[" + v + "] is not yet valid (notBefore=" + chain[v].validFrom + ")");
@@ -434,6 +434,7 @@ function policy(opts) {
434
434
  method: "GET",
435
435
  url: url,
436
436
  headers: { "User-Agent": "blamejs-password-policy/1" },
437
+ timeoutMs: p.hibpTimeoutMs,
437
438
  idleTimeoutMs: p.hibpTimeoutMs,
438
439
  errorClass: AuthError,
439
440
  });
@@ -692,8 +692,13 @@ function create(opts) {
692
692
  if (!noaHok) continue; // §3.1 (incorporates §3) — time-bound required
693
693
  var noaHokSec = Date.parse(noaHok) / 1000; // ms→s
694
694
  if (!isFinite(noaHokSec) || noaHokSec < nowSec - clockSkewSec) continue; // unparseable or expired
695
- if (nbHok && isFinite(Date.parse(nbHok) / 1000) && // ms→s
696
- Date.parse(nbHok) / 1000 > nowSec + clockSkewSec) continue; // ms→s
695
+ if (nbHok) {
696
+ // Fail CLOSED on a present-but-unparseable HoK NotBefore (same shape
697
+ // as the Bearer path + NotOnOrAfter above) — an unparseable bound
698
+ // can't establish the confirmation has begun, so skip this SCD.
699
+ var nbHokSec = Date.parse(nbHok) / 1000; // ms→s
700
+ if (!isFinite(nbHokSec) || nbHokSec > nowSec + clockSkewSec) continue; // unparseable or not-yet-valid
701
+ }
697
702
  var recipHok = _attr(scdHok, "Recipient");
698
703
  if (!recipHok || recipHok !== opts.assertionConsumerServiceUrl) continue; // §3.1→§4.1.4.2 — Recipient is mandatory; absent fails the endpoint binding
699
704
  hokOk = true;
@@ -709,7 +714,10 @@ function create(opts) {
709
714
  var notBefore = _attr(scd, "NotBefore");
710
715
  if (notBefore) {
711
716
  var nb = Date.parse(notBefore) / 1000; // ms→s
712
- if (isFinite(nb) && nb > nowSec + clockSkewSec) continue;
717
+ // Fail CLOSED on a present-but-unparseable NotBefore (mirrors the
718
+ // NotOnOrAfter line above + the Conditions block) — an unparseable
719
+ // bound can't establish the confirmation has begun, so skip this SCD.
720
+ if (!isFinite(nb) || nb > nowSec + clockSkewSec) continue;
713
721
  }
714
722
  // §4.1.4.2 — a Bearer SubjectConfirmationData delivered to an ACS MUST
715
723
  // carry a Recipient equal to this SP's ACS URL. Absent Recipient fails
@@ -151,7 +151,10 @@ function _maybeReapStale(pidFile) {
151
151
  function _openLogFd(logFile) {
152
152
  if (typeof logFile !== "string" || logFile.length === 0) return null;
153
153
  atomicFile.ensureDir(nodePath.dirname(logFile));
154
- var fd = nodeFs.openSync(logFile, "a", DEFAULT_LOG_FILE_MODE);
154
+ // O_NOFOLLOW append: refuse (ELOOP) a symlink planted at the daemon log
155
+ // path rather than redirecting the detached process's stdout/stderr to an
156
+ // attacker-chosen file (CWE-59).
157
+ var fd = atomicFile.openAppendNoFollowSync(logFile, DEFAULT_LOG_FILE_MODE);
155
158
  return fd;
156
159
  }
157
160
 
@@ -706,6 +706,8 @@ class Pool {
706
706
  * // close(client): async → void (optional; default no-op)
707
707
  * // ping(client): async → void (optional; default `SELECT 1`)
708
708
  * // beginTx / commit / rollback(client): async → void (optional; default `BEGIN`/`COMMIT`/`ROLLBACK`)
709
+ * // batch(client, statements): async → void (optional; atomic multi-statement path for batch-only adapters, e.g. D1 db.batch)
710
+ * // supportsTransactions: boolean (interactive-tx capability; set false on a stateless/autocommit-per-statement adapter so transaction()/outbox REFUSE rather than silently run non-atomic — default assumes stateful)
709
711
  * // dialect: "postgres" | "mysql" | "sqlite" | "mongodb" | "other" (default "postgres")
710
712
  * // requireTls: boolean (opt-in TLS posture gate; default off — see below)
711
713
  * // tls / ssl / sslmode: transport-TLS declaration consulted by requireTls (tls:true | ssl:<obj> | sslmode:"require"|"verify-ca"|"verify-full")
@@ -796,6 +798,60 @@ function init(opts) {
796
798
  applicationName.length + ")", true);
797
799
  }
798
800
  }
801
+ // ---- Interactive-transaction capability ----
802
+ //
803
+ // transaction(fn) and the b.outbox dual-write guarantee both require
804
+ // an INTERACTIVE transaction: BEGIN, the body statements, and COMMIT
805
+ // must all run on the SAME session so the body sees isolation and a
806
+ // throw rolls everything back. A stateless / autocommit-per-statement
807
+ // adapter (connect() returns a sentinel, each query() is an
808
+ // independent round-trip — e.g. an HTTP bridge to Cloudflare D1) makes
809
+ // BEGIN / body / COMMIT land on different sessions: no isolation, no
810
+ // rollback, yet every call resolves, so the consumer wrongly believes
811
+ // the block was atomic. Detect that posture up front and REFUSE
812
+ // loudly rather than silently degrade to no-op BEGIN/COMMIT.
813
+ //
814
+ // An INTERACTIVE transaction (transaction(fn) runs arbitrary async
815
+ // operator logic between tx.query calls) requires a stateful session;
816
+ // it cannot be transparently replayed as a static batch, so a backend
817
+ // can provide interactive transactions only when:
818
+ // - it supplies interactive-tx hooks (beginTx / commit / rollback)
819
+ // bound to a stateful client, OR
820
+ // - it explicitly declares supportsTransactions: true (operator
821
+ // asserts the default BEGIN/COMMIT runs on a stateful client).
822
+ // It CANNOT when it explicitly declares supportsTransactions: false
823
+ // (the stateless / autocommit-per-statement declaration). When the
824
+ // flag is omitted and no hooks are present the backend is assumed
825
+ // stateful — the historical default — so existing stateful pg / sqlite
826
+ // / mysql backends are unaffected.
827
+ //
828
+ // A batch(client, statements) hook is a SEPARATE atomic-multi-statement
829
+ // path for batch-only adapters (e.g. D1's db.batch([...])); it does NOT
830
+ // make interactive transaction(fn) safe (the interleaved operator logic
831
+ // can't be captured as a static statement list), so its presence is
832
+ // recorded but does not flip supportsTransactions.
833
+ if (cfg.supportsTransactions !== undefined && cfg.supportsTransactions !== null) {
834
+ validateOpts.optionalBoolean(cfg.supportsTransactions,
835
+ "backend '" + name + "': supportsTransactions", ExternalDbError, "INVALID_CONFIG");
836
+ }
837
+ if (cfg.batch !== undefined && cfg.batch !== null && typeof cfg.batch !== "function") {
838
+ throw _err("INVALID_CONFIG",
839
+ "backend '" + name + "': batch must be a function (client, statements) when supplied", true);
840
+ }
841
+ var hasInteractiveHooks =
842
+ typeof cfg.beginTx === "function" &&
843
+ typeof cfg.commit === "function" &&
844
+ typeof cfg.rollback === "function";
845
+ var hasBatch = typeof cfg.batch === "function";
846
+ var supportsTransactions;
847
+ if (cfg.supportsTransactions === false) {
848
+ supportsTransactions = false;
849
+ } else {
850
+ // true flag, interactive hooks, or (historical default) flag omitted
851
+ // with no hooks → assume a stateful interactive session.
852
+ supportsTransactions = true;
853
+ }
854
+
799
855
  var rawConnect = cfg.connect;
800
856
  var rawQuery = cfg.query;
801
857
  var connectFn = rawConnect;
@@ -834,6 +890,9 @@ function init(opts) {
834
890
  beginTx: cfg.beginTx || function (client) { return cfg.query(client, "BEGIN", []); },
835
891
  commit: cfg.commit || function (client) { return cfg.query(client, "COMMIT", []); },
836
892
  rollback: cfg.rollback || function (client) { return cfg.query(client, "ROLLBACK", []); },
893
+ supportsTransactions: supportsTransactions,
894
+ hasInteractiveHooks: hasInteractiveHooks,
895
+ batch: hasBatch ? cfg.batch : null,
837
896
  classifications: Array.isArray(cfg.classifications) && cfg.classifications.length > 0
838
897
  ? cfg.classifications.slice()
839
898
  : ["*"],
@@ -1015,6 +1074,62 @@ function _servesClassification(b, cls) {
1015
1074
  return b.classifications.indexOf("*") !== -1 || b.classifications.indexOf(cls) !== -1;
1016
1075
  }
1017
1076
 
1077
+ // Refuse an interactive-transaction request against a backend that cannot
1078
+ // honor it (declared supportsTransactions:false, no beginTx/commit/rollback
1079
+ // hooks, no batch path). Such a backend would run BEGIN / body / COMMIT as
1080
+ // independent autocommit round-trips on different sessions — no isolation,
1081
+ // no rollback — and resolve, leaving the consumer believing the block was
1082
+ // atomic. Fail closed at the gate (CWE-662-shaped: improper synchronization
1083
+ // → lost atomicity) so the operator wires interactive-tx hooks or a batch
1084
+ // adapter rather than shipping a silently non-atomic dual-write.
1085
+ function _assertInteractiveTransactions(b, where) {
1086
+ if (!b) return;
1087
+ if (b.supportsTransactions === false) {
1088
+ throw _err("NON_ATOMIC_BACKEND",
1089
+ "externalDb." + where + " requires an interactive transaction, but backend '" +
1090
+ b.name + "' declares supportsTransactions: false (a stateless / " +
1091
+ "autocommit-per-statement adapter). BEGIN / the body statements / COMMIT " +
1092
+ "would each run on a different session — no isolation, no rollback — so the " +
1093
+ "block would NOT be atomic. Supply interactive beginTx / commit / rollback " +
1094
+ "hooks, or a batch(client, statements) adapter, on this backend before using " +
1095
+ "externalDb." + where + " (and b.outbox, which is built on it).",
1096
+ true);
1097
+ }
1098
+ }
1099
+
1100
+ /**
1101
+ * @primitive b.externalDb.supportsTransactions
1102
+ * @signature b.externalDb.supportsTransactions(opts?)
1103
+ * @since 0.15.16
1104
+ * @related b.externalDb.transaction, b.externalDb.init
1105
+ *
1106
+ * Report whether the picked (or default) backend can provide an
1107
+ * interactive transaction. Returns `false` only when the backend declares
1108
+ * `supportsTransactions: false` at `init()` — a stateless /
1109
+ * autocommit-per-statement adapter on which `transaction()` would run
1110
+ * `BEGIN` / the body / `COMMIT` on different sessions (no isolation, no
1111
+ * rollback). Consumers built on the dual-write guarantee (`b.outbox`) call
1112
+ * this at construction so a non-atomic backend is refused up front rather
1113
+ * than at the first transaction.
1114
+ *
1115
+ * Same backend-selection `opts` as `b.externalDb.query` (`backend` /
1116
+ * `classification`).
1117
+ *
1118
+ * @opts
1119
+ * backend?: string, // explicit backend name
1120
+ * classification?: string, // route by data class
1121
+ *
1122
+ * @example
1123
+ * if (!b.externalDb.supportsTransactions()) {
1124
+ * throw new Error("this backend cannot run atomic transactions");
1125
+ * }
1126
+ */
1127
+ function supportsTransactions(opts) {
1128
+ _requireInit();
1129
+ var b = _pickBackend(opts);
1130
+ return !!(b && b.supportsTransactions !== false);
1131
+ }
1132
+
1018
1133
  // ---- Public API ----
1019
1134
 
1020
1135
  /**
@@ -1158,6 +1273,13 @@ async function query(sql, params, opts) {
1158
1273
  * `BEGIN`, so RLS state set by `sessionGucs` (`SET LOCAL`) applies for
1159
1274
  * the duration of the transaction and resets at COMMIT/ROLLBACK.
1160
1275
  *
1276
+ * Refuses (`NON_ATOMIC_BACKEND`) when the picked backend declares
1277
+ * `supportsTransactions: false` — a stateless / autocommit-per-statement
1278
+ * adapter on which BEGIN / the body / COMMIT would run on different
1279
+ * sessions (no isolation, no rollback). Supply interactive
1280
+ * `beginTx`/`commit`/`rollback` hooks or a `batch` adapter on the backend
1281
+ * instead of shipping a silently non-atomic block.
1282
+ *
1161
1283
  * @opts
1162
1284
  * backend?: string, // explicit backend name
1163
1285
  * classification?: string, // route by data class
@@ -1185,6 +1307,14 @@ async function transaction(fn, opts) {
1185
1307
  if (typeof fn !== "function") throw _err("INVALID_FN", "transaction requires a function", true);
1186
1308
  opts = opts || {};
1187
1309
  var b = _pickBackend(opts);
1310
+ // Fail closed on a backend that cannot provide interactive transactions
1311
+ // (stateless / autocommit-per-statement adapter declared
1312
+ // supportsTransactions:false with no beginTx/commit/rollback hooks and
1313
+ // no batch path). Running the default BEGIN / body / COMMIT against such
1314
+ // a backend lands each statement on a different session — no isolation,
1315
+ // no rollback — yet resolves, so the consumer wrongly believes the block
1316
+ // was atomic. Refuse instead of silently degrading.
1317
+ _assertInteractiveTransactions(b, "transaction");
1188
1318
  var role = dbRoleContext.getRole();
1189
1319
 
1190
1320
  // sessionGucs — per-transaction `SET LOCAL "name" = value` plumbing.
@@ -2608,6 +2738,7 @@ module.exports = {
2608
2738
  init: init,
2609
2739
  query: query,
2610
2740
  transaction: transaction,
2741
+ supportsTransactions: supportsTransactions,
2611
2742
  healthCheck: healthCheck,
2612
2743
  listBackends: listBackends,
2613
2744
  shutdown: shutdown,
@@ -27,6 +27,7 @@ var numericBounds = require("./numeric-bounds");
27
27
  var safeJson = require("./safe-json");
28
28
  var safeBuffer = require("./safe-buffer");
29
29
  var requestHelpers = require("./request-helpers");
30
+ var validateOpts = require("./validate-opts");
30
31
  var audit = require("./audit");
31
32
  var { GraphqlFederationError } = require("./framework-error");
32
33
 
@@ -121,7 +122,7 @@ function _readBody(req, errorClass) {
121
122
  * @opts
122
123
  * publicSchemaOk: boolean, // default false — explicit override to publish the SDL
123
124
  * routerToken: string, // required unless publicSchemaOk; 32+ chars
124
- * nonceStore: { has(nonce): bool, remember(nonce, ttlMs) }, // optional replay protection
125
+ * nonceStore: { checkAndInsert(nonce, expireAt): bool }, // optional atomic replay protection (b.nonceStore-shaped)
125
126
  * nonceHeader: string, // default "x-apollographql-router-nonce" — request header carrying the replay nonce
126
127
  * nonceTtlMs: number, // default 5 minutes
127
128
  * errorClass: Function, // default GraphqlFederationError
@@ -143,8 +144,15 @@ function guardSdl(opts) {
143
144
  throw errorClass.factory("graphql-federation/bad-opts",
144
145
  "graphqlFederation.guardSdl: routerToken (32+ char) required unless publicSchemaOk=true");
145
146
  }
146
- var nonceStore = opts.nonceStore && typeof opts.nonceStore.has === "function" &&
147
- typeof opts.nonceStore.remember === "function" ? opts.nonceStore : null;
147
+ // Replay store speaks the framework's ATOMIC checkAndInsert(nonce, expireAt)
148
+ // contract the same one b.webhook.verify and b.nonceStore.create use — so
149
+ // the framework's own replay store drops in and concurrent redeliveries of a
150
+ // captured token can't both pass a non-atomic has()-then-remember() race
151
+ // (CWE-367). A store lacking checkAndInsert is refused at config time.
152
+ validateOpts.optionalObjectWithMethod(opts.nonceStore, "checkAndInsert",
153
+ "graphqlFederation.guardSdl: nonceStore", errorClass, "graphql-federation/bad-nonce-store",
154
+ "must implement checkAndInsert(nonce, expireAt) — b.nonceStore.create is the reference store");
155
+ var nonceStore = opts.nonceStore || null;
148
156
  numericBounds.requirePositiveFiniteIntIfPresent(opts.nonceTtlMs, "graphqlFederation.guardSdl: opts.nonceTtlMs", errorClass, "BAD_TTL");
149
157
  var nonceTtlMs = opts.nonceTtlMs || C.TIME.minutes(5);
150
158
  var auditOn = opts.audit !== false;
@@ -215,21 +223,23 @@ function guardSdl(opts) {
215
223
  _emitDenied(req, "missing nonce", {});
216
224
  return _refuse(res, 401, "graphql federation: nonce required");
217
225
  }
218
- return Promise.resolve(nonceStore.has(nonce)).then(function (seen) {
219
- if (seen) {
226
+ // Atomic check-and-insert: a redelivered nonce returns false (already
227
+ // present) and is refused; a fresh nonce is inserted with an absolute
228
+ // expiry in one operation, so two concurrent deliveries of the same
229
+ // captured token can't both observe "unseen" and pass.
230
+ return Promise.resolve(nonceStore.checkAndInsert(nonce, Date.now() + nonceTtlMs)).then(function (fresh) {
231
+ if (!fresh) {
220
232
  _emitDenied(req, "nonce replay", { nonce: nonce.slice(0, NONCE_PREVIEW_LEN) + "..." });
221
233
  return _refuse(res, 401, "graphql federation: nonce replay");
222
234
  }
223
- return Promise.resolve(nonceStore.remember(nonce, nonceTtlMs)).then(function () {
224
- if (auditOn) {
225
- audit.safeEmit({
226
- action: "graphqlfederation.sdl_allowed",
227
- outcome: "success",
228
- metadata: {},
229
- });
230
- }
231
- if (typeof next === "function") next();
232
- });
235
+ if (auditOn) {
236
+ audit.safeEmit({
237
+ action: "graphqlfederation.sdl_allowed",
238
+ outcome: "success",
239
+ metadata: {},
240
+ });
241
+ }
242
+ if (typeof next === "function") next();
233
243
  });
234
244
  }
235
245
  if (auditOn) {
@@ -161,6 +161,7 @@ function _post(cfg, body, headers) {
161
161
  url: _resolveEndpoint(cfg),
162
162
  headers: headers,
163
163
  body: body,
164
+ timeoutMs: cfg.timeoutMs,
164
165
  idleTimeoutMs: cfg.timeoutMs,
165
166
  maxResponseBytes: MAX_RESPONSE_BYTES,
166
167
  errorClass: LogStreamError,
@@ -57,7 +57,20 @@ function create(config) {
57
57
  var bytesWritten = 0;
58
58
 
59
59
  function _open() {
60
- fd = nodeFs.openSync(activePath, "a", cfg.fileMode);
60
+ // O_NOFOLLOW append open: a symlink planted at the active log path is
61
+ // refused (ELOOP) instead of followed, so log writes can't be redirected
62
+ // to an attacker-chosen file (CWE-59). This makes the symlink refusal
63
+ // atomic with the open — a caller's pre-check-then-unlink can't close the
64
+ // race on its own because the sink's own open is what follows the link.
65
+ try {
66
+ fd = atomicFile.openAppendNoFollowSync(activePath, cfg.fileMode);
67
+ } catch (e) {
68
+ if (e && e.code === "ELOOP") {
69
+ throw _err("SYMLINK_REFUSED",
70
+ "refusing to open log at a symlink: " + activePath, true);
71
+ }
72
+ throw e;
73
+ }
61
74
  openedAt = Date.now();
62
75
  try {
63
76
  var stat = nodeFs.fstatSync(fd);
@@ -188,6 +188,7 @@ function _post(url, body, headers, timeoutMs, allowedProtocols, allowInternal) {
188
188
  url: url,
189
189
  headers: headers,
190
190
  body: body,
191
+ timeoutMs: timeoutMs,
191
192
  idleTimeoutMs: timeoutMs,
192
193
  maxResponseBytes: MAX_RESPONSE_BYTES,
193
194
  errorClass: LogStreamError,
@@ -67,6 +67,7 @@ function _post(url, body, headers, timeoutMs, allowedProtocols, allowInternal) {
67
67
  url: url,
68
68
  headers: headers,
69
69
  body: body,
70
+ timeoutMs: timeoutMs,
70
71
  idleTimeoutMs: timeoutMs,
71
72
  maxResponseBytes: MAX_RESPONSE_BYTES,
72
73
  errorClass: LogStreamError,