@blamejs/core 0.15.8 → 0.15.9

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.
package/CHANGELOG.md CHANGED
@@ -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.9 (2026-06-13) — **Raises the Node floor to 24.16, adds SQLite parse-time resource caps, retries Windows rename locks on every atomic write and download, and ships a one-call secure logout that wipes client-side state.** This release moves the engines floor to the current Node 24 LTS patch level and adds three hardening primitives. node:sqlite handles now construct with SQLITE_LIMIT_* caps: a statement over 1 MiB is rejected at parse time (a DoS floor on the raw-SQL surface, complementary to the existing row-count gate) and ATTACH DATABASE is denied. Every final temp-to-destination rename — the file written by an atomic write, a downloaded file, a sealed vault key, a rotated log, an extracted archive entry — now routes through a single retry that rides out a transient Windows lock (antivirus, the search indexer, or a file-sync client briefly holding the destination), instead of surfacing the lock as a hard failure; the retry, previously hand-rolled and unreachable, is now the reusable b.atomicFile.renameWithRetry. And b.session.logout destroys a session and tells the browser to wipe its client-side state in one call: it emits an RFC 9527 Clear-Site-Data header and expires the session cookie before destroying the row, the secure-default logout that previously had to be assembled by hand. **Added:** *b.session.logout — one-call secure logout* — `b.session.logout(res, token, opts?)` destroys the server-side session AND tells the browser to wipe its client-side state in one call: it emits an RFC 9527 Clear-Site-Data response header (cookies + storage + cache + execution contexts by default) and expires the session cookie, then destroys the session row. `b.session.destroy` alone is a store operation with no response object, so it could not wipe the browser's cached pages, storage, or a stale tab still holding the now-revoked cookie — that wiring previously had to be mounted by hand. Pass `cookieName` to match a non-default cookie and `types` to choose the Clear-Site-Data directives. **Changed:** *Node engines floor raised to >=24.16.0* — The minimum supported Node is now 24.16.0 (the current Node 24 LTS patch level), up from 24.14.1. This is an LTS-currency bump — there are no Node CVE fixes between 24.14.1 and 24.16.0 (24.14.1 already carried the CVE-2026-21713 HMAC fix); it keeps the framework on the latest patched LTS and makes the node:sqlite resource-cap hardening below available everywhere. Pre-1.0, operators upgrade across the floor; Node 26 continues to satisfy it. **Fixed:** *b.watcher canonicalizes its root on Windows* — `b.watcher.create` now resolves its `root` to the real long path before watching. On Windows a root with an 8.3 short-name component (the system temp directory commonly resolves to one) made the native recursive backend deliver long-name event paths that no longer prefix-matched the watched root, which could abort the process under a strict libuv fs-event assertion. The watcher now canonicalizes the root (expanding short names and resolving symlinks), so events match the watched directory on Windows. **Security:** *SQLite parse-time statement-size cap* — Every node:sqlite database the framework opens — the main db handle and the CLI's handle — now constructs with a SQLITE_LIMIT_LENGTH cap: a SQL statement over 1 MiB is rejected at parse time. Because the query builder parameterizes every value, the size cap guards the raw-SQL surface (`b.db.runSql`) against an attacker-influenced megaquery the parser would otherwise process (SQLite's default is 1 GB); it is a parse-time DoS floor complementary to the existing row-count gate. Legitimate framework and operator statements are far under the cap. · *Windows rename-lock retry on every atomic rename and download* — On Windows a freshly-written file's destination is briefly held by antivirus, the search indexer, or a file-sync client (Dropbox, OneDrive), surfacing as a transient EPERM / EACCES / EBUSY on rename even though the temp file is fine. `b.atomicFile.writeSync` already retried this, but `b.httpClient.downloadStream` did not — a download into a cloud-synced or AV-scanned directory could fail hard on the lock. The retry is now the reusable `b.atomicFile.renameWithRetry`, and every final temp-to-destination rename in the framework routes through it: downloads, sealed vault keys, CA key/cert writes, log rotation, archive extraction, config-drift sidecars, the self-update binary swap, and restore/rollback moves. A non-transient error still throws immediately; POSIX renames are unaffected. **Detectors:** *Rename-retry, SQLite-limits, and Clear-Site-Data guards* — Three recurrence detectors ship with the fixes: a bare `nodeFs.renameSync` final rename that doesn't route through `atomicFile.renameWithRetry`; a main `DatabaseSync` handle constructed without the SQLITE_LIMIT_LENGTH `limits`; and a hand-rolled Clear-Site-Data header value that skips the shared RFC 9527 builder.
12
+
11
13
  - v0.15.8 (2026-06-13) — **Redacts OTLP log-sink attributes to close a secret/PII egress the span fix missed, adds EU DSA and China PIPL cross-border compliance record-builders, ships an SSDF producer self-attestation with every release, and makes the published tarball reproducible.** This release closes a telemetry egress hole, adds two compliance record-builder namespaces, and hardens the release supply chain. The OTLP log sinks (HTTP-JSON and gRPC) shipped a log record's meta attributes and the resource attributes to the collector unredacted — a log line carrying a bearer token, password, or API key reached the wire verbatim (CWE-532). The 0.15.4 fix wired the telemetry redactor into the span and metric exporters but the log sinks were missed; both now run record and resource attributes through the same redactor before serialization. New b.dsa builds the EU Digital Services Act (Reg 2022/2065) records an intermediary or platform must keep — Art. 16 notice-and-action, Art. 17 statement of reasons, and the Art. 15 / 24(3) transparency report. New b.pipl builds the China PIPL cross-border transfer records — an Art. 38/40 assessment that determines whether a CAC security assessment is mandatory (CIIO, important data, or the volume / sensitive-PI thresholds), and an Art. 40 security-assessment certificate. On the supply-chain side, every release now ships ssdf-attestation.json, a machine-readable NIST SP 800-218 / OMB M-22-18 producer self-attestation mapping each secure-development practice to its implementing control, and the published tarball is now packed with SOURCE_DATE_EPOCH so an operator can rebuild it byte-for-byte from the release commit. **Added:** *b.dsa — EU Digital Services Act compliance record-builders* — `b.dsa` builds the dated, frozen records the EU Digital Services Act (Regulation (EU) 2022/2065) requires an online intermediary or platform to keep: `b.dsa.noticeAndAction` (Art. 16) records a notice against a piece of content and computes the action-due window; `b.dsa.statementOfReasons` (Art. 17) records a moderation decision with its legal or contractual ground (exactly one is required), the facts, whether it was automated, and the redress routes offered; `b.dsa.transparencyReport` (Art. 15 / 24(3)) aggregates the period counts into a report with the next-due date. The builders perform no network I/O and emit a best-effort audit event; they map to the `dsa` compliance posture. · *b.pipl — China PIPL cross-border transfer record-builders* — `b.pipl.sccFilingAssessment` builds a PIPL Art. 38/40/55 cross-border transfer assessment and determines the lawful mechanism: it forces a CAC security assessment (over a self-selected standard contract or certification) when the exporter is a critical-information-infrastructure operator, exports important data, handles personal information of more than 1,000,000 individuals, or crosses the cumulative volume / sensitive-PI thresholds. `b.pipl.securityAssessmentCertificate` records an Art. 40 security-assessment self-declaration with a 3-year validity clock. Both return frozen dated records and map to the `pipl-cn` posture. · *SSDF producer self-attestation shipped with every release* — Every release now attaches `ssdf-attestation.json` — a machine-readable NIST SP 800-218 (SSDF v1.1) / OMB M-22-18 producer self-attestation. It maps each secure-software-development practice to its implementing control in the tree (SLSA L3 provenance, SSH-signed tags, vendored zero-runtime-dep supply chain, OSV-Scanner gating, coordinated disclosure) and is deterministic from the release commit. Its sha256 is a subject of the SLSA L3 provenance, so verifying the provenance verifies the attestation has not been tampered with. Downstream consumers who require SSDF supplier-compliance evidence can download it from the release page. **Security:** *OTLP log sinks redact record and resource attributes before export* — `b.logStream`'s OTLP log sinks (HTTP-JSON and gRPC) shipped a log record's `meta` attributes and the sink's resource attributes to the collector UNREDACTED, so a log line whose meta carried a bearer token, password, or API key — or a credential placed in a resource attribute — reached the OTLP wire verbatim (CWE-532). The 0.15.4 change baked the telemetry redactor into the span and metric exporters but its detector was anchored on the span/metric encoder function names, leaving the log sinks uncovered. Both log sinks now run record and resource attributes through `b.observability.redactAttrs` before serialization, the same egress contract the span and metric exporters already hold. · *Reproducible published tarball (SOURCE_DATE_EPOCH)* — The release workflow now exports `SOURCE_DATE_EPOCH` (derived from the tagged commit's author date) before `npm pack`, so the mtime stamped into every tar header is deterministic. An operator can re-pack the package from the same commit and match the published tarball's sha256 byte-for-byte, strengthening the source-to-artifact verification path alongside the existing SLSA L3 provenance and PQC signatures. **Detectors:** *otlp-log-sink-encodes-attrs-without-redactor* — Fires when an OTLP log-sink encoder hands a raw `record.meta` or resource-attribute map to serialization without routing it through `observability.redactAttrs` — the class the span/metric detector could not see because the log sinks carry the OTLP-logs schema function names.
12
14
 
13
15
  - v0.15.7 (2026-06-13) — **Hardens the new URL canonicalizer against an IPv4-mapped allowlist bypass, enforces the OIDC azp authorized-party check, and closes a set of audited correctness gaps in retention, credential rehashing, the scheduler, and SD-JWT key binding.** This release deepens the URL/host canonicalizer shipped in 0.15.6 and clears a batch of audited correctness gaps. The canonicalizer now folds an IPv4-mapped IPv6 address (::ffff:1.2.3.4) to its embedded IPv4 and strips every trailing dot from a host, so a dual-stack peer can no longer slip past an operator's dotted-IPv4 allowlist and host./host.. no longer evade a host comparison. (NAT64 and 6to4 hosts are deliberately kept as IPv6 so canonicalizing then classifying agrees with the SSRF classifier, which treats them as reserved.) On the OIDC side, verifyIdToken now enforces OIDC Core 3.1.3.7: a multi-audience ID token must carry an azp (authorized party) and a present azp must equal the client_id, closing a confused-deputy hole where a token minted for a different client but listing this RP in its audience array verified clean. The rest are audited fixes: retention.complianceFloor now honors the active posture set via applyPosture (the documented inheritance was unimplemented); credentialHash.needsRehash now drives the advertised SHAKE256 length-rotation (raising the output length now triggers a rehash, upgrade-only); the task scheduler no longer lets a run abandoned by its watchdog clobber the next run's state or emit a stale success when its slow promise settles late; and the SD-JWT key-binding JWT compares its audience and nonce in constant time. **Fixed:** *retention.complianceFloor honors the active compliance posture* — `b.retention.complianceFloor` required an explicit posture and never read the active posture set by `applyPosture` (the `b.compliance.set` cascade), so the documented inheritance was unimplemented dead state. It now inherits the active posture when none is passed — `complianceFloor(candidateTtlMs)` uses the active posture, an explicit posture still overrides it — and `applyPosture(null)` now clears the active posture (it was a silent no-op, so `b.compliance.clear` could not reset it). · *credentialHash.needsRehash drives the SHAKE256 length-rotation* — `b.credentialHash.needsRehash` never compared the stored SHAKE256 digest length against the configured length, so raising the output length never triggered a rehash and the advertised length-rotation was a silent no-op. It now flags a digest shorter than the configured/default length for rehash (upgrade-only — a longer-than-target digest is never shortened, matching the Argon2 convention). · *The scheduler no longer lets a watchdog-abandoned run corrupt the next run* — `b.scheduler`'s watchdog force-clears a task's running flag after `maxJobMs` so a hung handler can't lock out future fires, and the next tick re-fires. The original slow promise then settled late and unconditionally overwrote the task's running / lastFinish / lastError state and emitted a `system.scheduler.task.success`|`failure` for a run the watchdog had already given up on — clobbering the new run and double-counting. Each run is now tagged with a generation that the watchdog and every fire bump; a settle whose tag is stale is ignored. **Security:** *The URL canonicalizer folds IPv4-mapped IPv6 addresses to IPv4* — `b.safeUrl.canonicalize` / `b.ssrfGuard.canonicalizeHost` now fold an IPv4-mapped IPv6 address (`::ffff:1.2.3.4`, the `::ffff:0:0/96` block) to its embedded IPv4 dotted form. Previously it canonicalized to an IPv6 string, so a dual-stack peer never unified with an operator's `1.2.3.4` allow/deny entry — an allowlist bypass. Only the IPv4-mapped block folds, because the SSRF classifier maps it to the embedded v4 verdict directly; NAT64 (`64:ff9b::/96`) and 6to4 (`2002::/16`) are deliberately kept as IPv6, since the classifier treats a NAT64 literal as reserved and folding it would turn a blocked verdict into an allowed public IPv4. The host canonicalizer also now strips every trailing dot, so `host`, `host.`, and `host..` collapse to one form. · *verifyIdToken enforces the OIDC azp (authorized party) check* — `b.auth.oauth`'s `verifyIdToken` validated only that its `client_id` was present in the token's `aud`, ignoring `azp`. Per OIDC Core 3.1.3.7, a multi-audience ID token must carry an `azp` and a present `azp` must equal the RP's `client_id`. Without it, a token whose authorized party is a different client — but whose `aud` array also lists this RP — verified clean (a confused-deputy / token-substitution hole). The verifier now rejects a multi-audience token with no `azp` (`auth-oauth/azp-required`) and any token whose `azp` is not the `client_id` (`auth-oauth/azp-mismatch`). A single-audience token with no `azp` (the common case) is unaffected. · *SD-JWT key-binding audience and nonce compare in constant time* — `b.auth.sdJwtVc.verify` compared the key-binding JWT's `aud` and `nonce` with a short-circuiting `!==`, while the adjacent `sd_hash` check already used a constant-time compare. The `nonce` is a verifier-issued replay-defense value, so a non-constant-time compare leaks a matching-prefix timing oracle; both checks now use the constant-time helper.
package/README.md CHANGED
@@ -52,7 +52,7 @@ var b = require("@blamejs/core");
52
52
  })();
53
53
  ```
54
54
 
55
- **Requirements:** Node.js 24.14+ (current active LTS, fixes CVE-2026-21713 non-constant-time HMAC compare). Node 26 satisfies the floor and the framework test suite runs cleanly on it today; the floor itself will bump to `>=26.x` when Node 26 promotes to Active LTS. Two Node 26 platform changes operators integrating with blamejs should know about: the new `localStorage` global (the framework's storage backend is `b.backup.diskStorage`; the legacy `b.backup.localStorage` alias was removed in v0.11.20 — update call sites accordingly), and the seed-only ML-KEM / ML-DSA PKCS8 export shape (sealed material from Node 24 re-imports cleanly on Node 26; new material from Node 26 in the seed-only shape). See [SECURITY.md](SECURITY.md#node-26-compatibility) for the details.
55
+ **Requirements:** Node.js 24.16+ (current active LTS line; 24.14.1 fixed CVE-2026-21713 non-constant-time HMAC compare, 24.16 is the current patch level). Node 26 satisfies the floor and the framework test suite runs cleanly on it today; the floor itself will bump to `>=26.x` when Node 26 promotes to Active LTS. Two Node 26 platform changes operators integrating with blamejs should know about: the new `localStorage` global (the framework's storage backend is `b.backup.diskStorage`; the legacy `b.backup.localStorage` alias was removed in v0.11.20 — update call sites accordingly), and the seed-only ML-KEM / ML-DSA PKCS8 export shape (sealed material from Node 24 re-imports cleanly on Node 26; new material from Node 26 in the seed-only shape). See [SECURITY.md](SECURITY.md#node-26-compatibility) for the details.
56
56
 
57
57
  ## What ships in the box
58
58
 
@@ -60,7 +60,7 @@ The framework bundles the surface a typical Node app reaches for. Every primitiv
60
60
 
61
61
  ### Data layer
62
62
 
63
- - **SQLite with sealed-by-default columns** — `b.db`, migrations, seeders, atomic-file writes
63
+ - **SQLite with sealed-by-default columns** — `b.db`, migrations, seeders, atomic-file writes; the db handle constructs with a SQLITE_LIMIT_LENGTH parse-time cap (a >1 MiB statement is rejected) as a DoS floor on the raw-SQL surface
64
64
  - **Chainable query builder** — atomic `.increment(col, delta)`, closure-form `.whereGroup` / top-level `.orWhere` OR composition, `.search(fields, term)` LIKE-OR with safe `%`/`_` ESCAPE handling, `.paginate(opts)` returning `{ items, total, page, totalPages }`; a column-membership gate (`db.init({ columnGate })`, default reject) fails a query closed when it names a column the table never declared, and `whereRaw` refuses an embedded string literal so values bind through placeholders
65
65
  - **Mongo-style document-store facade** — `b.db.collection(name, opts?)` with `$set` / `$inc` / `$unset` / `$eq` / `$ne` / `$gt` / `$gte` / `$lt` / `$lte` / `$in` / `$like`; schemaless-document opts via `overflow: "<col>"` (folds unknown fields into a JSON-text column; rewrites `WHERE` on virtual fields to `JSON_EXTRACT`), `jsonColumns: [...]` (auto-stringify on write + parse via `b.safeJson` on read), `sealedFields: { email: "emailHash" }` (co-locates a `b.cryptoField` sealed-column / derived-hash declaration so plaintext lookups auto-rewrite to hash-column lookups)
66
66
  - **DB lifecycle** — in-memory encrypted snapshot via `b.db.snapshot()`; standalone encrypted-DB-file lifecycle (`b.db.fileLifecycle({ dataDir, vault })` — decrypt-to-tmpfs, periodic re-encrypt flush, graceful shutdown — same envelope as `b.db`, no schema/audit-chain coupling); `db.init` opt-outs `frameworkTables: false` / `auditSigning: false` and path overrides `encryptedDbPath` / `encryptedDbName` / `dbKeyPath`
@@ -86,6 +86,7 @@ The framework bundles the surface a typical Node app reaches for. Every primitiv
86
86
  - Opaque-userId anonymous sessions via `create({ anonymous: true })`
87
87
  - Idle / absolute timeouts, fingerprint drift detection + anomaly scoring, brute-force lockout
88
88
  - Session-fixation rotation (`b.session.rotate`) re-keys the sid-bound device fingerprint to the new id — pass the same `{ req, fingerprintFields }` used at `create` (a fingerprint-bound session rotated without `req` is refused, so the binding can never silently break or false-drift)
89
+ - One-call secure logout (`b.session.logout(res, token)`) destroys the session AND wipes client-side state — emits an RFC 9527 Clear-Site-Data header (cookies + storage + cache) and expires the session cookie before deleting the row
89
90
  - **Authorization** — RBAC + per-role DB binding + role-spec `requireMfa` + per-route MFA freshness window + ABAC predicate registry (`b.permissions`); API keys with rotation (`b.apiKey`)
90
91
  - **Workflow gates** — break-glass column gates with second-factor + audit (`b.breakGlass`); two-person-rule m-of-n approval with cooling-off lock + cancellation (`b.dualControl`)
91
92
  - **Financial / Open Banking** — FAPI 2.0 Final composite posture (PAR + PKCE-S256 + DPoP-or-mTLS + RFC 9207); runtime enforcement helpers `b.fapi2.assertCallback` (refuses missing iss + bare-param under message-signing) and `b.fapi2.assertAuthzRequest` (refuses non-JAR); CFPB §1033 / FDX 6.0 consumer-financial-data-sharing wrapper (`b.fdx`)
@@ -42,6 +42,7 @@ var nodeFs = require("node:fs");
42
42
  var C = require("./constants");
43
43
  var lazyRequire = require("./lazy-require");
44
44
  var { defineClass } = require("./framework-error");
45
+ var atomicFile = require("./atomic-file");
45
46
 
46
47
  var ArchiveReadError = defineClass("ArchiveReadError", { alwaysPermanent: true });
47
48
 
@@ -925,7 +926,7 @@ function zip(adapter, opts) {
925
926
  // the rename targets a non-existent path.
926
927
  var tmpPath = resolvedPath + ".__blamejs-archive-read-tmp__";
927
928
  nodeFs.writeFileSync(tmpPath, body);
928
- nodeFs.renameSync(tmpPath, resolvedPath);
929
+ atomicFile.renameWithRetry(tmpPath, resolvedPath);
929
930
  written.push({ name: entry.name, bytesWritten: body.length, path: resolvedPath });
930
931
  bytesExtracted += body.length;
931
932
  }
@@ -14,6 +14,7 @@ var C = require("./constants");
14
14
  var lazyRequire = require("./lazy-require");
15
15
  var safeBuffer = require("./safe-buffer");
16
16
  var archiveTar = require("./archive-tar");
17
+ var atomicFile = require("./atomic-file");
17
18
 
18
19
  var TarError = archiveTar.TarError;
19
20
  var _parseHeader = archiveTar._parseHeader;
@@ -428,7 +429,7 @@ function tar(adapter, opts) {
428
429
  }
429
430
  var tmpPath = resolvedPath + ".__blamejs-archive-tar-tmp__";
430
431
  nodeFs.writeFileSync(tmpPath, body);
431
- nodeFs.renameSync(tmpPath, resolvedPath);
432
+ atomicFile.renameWithRetry(tmpPath, resolvedPath);
432
433
  written.push({ name: entry.name, bytesWritten: body.length, path: resolvedPath });
433
434
  bytesExtracted += body.length;
434
435
  }
@@ -1077,6 +1077,11 @@ module.exports = {
1077
1077
  fsync: fsync,
1078
1078
  fsyncDir: fsyncDir,
1079
1079
  ensureDir: ensureDir,
1080
+ // Atomic rename with a bounded retry on Windows-transient lock errors
1081
+ // (EPERM/EACCES/EBUSY from AV / search indexer / Dropbox / OneDrive briefly
1082
+ // holding the destination). Exposed so any final temp->dest rename routes
1083
+ // through the same retry instead of hand-rolling it (or, worse, omitting it).
1084
+ renameWithRetry: _renameWithRetry,
1080
1085
  copyDirRecursive: copyDirRecursive,
1081
1086
  pathTimestamp: pathTimestamp,
1082
1087
  conflictPath: conflictPath,
package/lib/cli.js CHANGED
@@ -94,7 +94,14 @@ function _openSqlite(dbPath) {
94
94
  // Lazy-required so the CLI doesn't crash on `blamejs version` or
95
95
  // `blamejs help` if node:sqlite isn't usable for some reason.
96
96
  var { DatabaseSync } = require("node:sqlite");
97
- return new DatabaseSync(dbPath);
97
+ // Same SQLITE_LIMIT_ sqlLength cap as db.init's main handle — the CLI opens
98
+ // the operator's real database for migrate / inspect, so the parse-time DoS
99
+ // floor applies here too.
100
+ return new DatabaseSync(dbPath, {
101
+ limits: {
102
+ sqlLength: C.BYTES.mib(1),
103
+ },
104
+ });
98
105
  }
99
106
 
100
107
  // ---- Subcommand: migrate ----
@@ -44,6 +44,7 @@ var lazyRequire = require("./lazy-require");
44
44
  var safeJson = require("./safe-json");
45
45
  var validateOpts = require("./validate-opts");
46
46
  var { defineClass } = require("./framework-error");
47
+ var atomicFile = require("./atomic-file");
47
48
 
48
49
  var audit = lazyRequire(function () { return require("./audit"); });
49
50
 
@@ -201,7 +202,7 @@ function create(opts) {
201
202
  };
202
203
  var tmp = sidecarPath + ".tmp";
203
204
  nodeFs.writeFileSync(tmp, JSON.stringify(payload, null, 2));
204
- nodeFs.renameSync(tmp, sidecarPath);
205
+ atomicFile.renameWithRetry(tmp, sidecarPath);
205
206
  }
206
207
 
207
208
  function _verifySidecar(parsed) {
package/lib/db.js CHANGED
@@ -1156,8 +1156,21 @@ async function init(opts) {
1156
1156
  encKey = null;
1157
1157
  }
1158
1158
 
1159
- // Open the database
1160
- database = new DatabaseSync(dbPath);
1159
+ // Open the database. The node:sqlite `limits` option sets SQLITE_LIMIT_*
1160
+ // caps at construction — a parse-time DoS floor complementary to the
1161
+ // streamLimit row-count gate (one bounds statement size, the other bounds
1162
+ // result cardinality). sqlLength rejects a megaquery (>1 MiB) before the
1163
+ // parser chews CPU/memory on it; the framework never legitimately emits a
1164
+ // statement anywhere near 1 MiB, and a 1 GB attacker-influenced statement
1165
+ // would otherwise be parsed. The limits option is part of node:sqlite from
1166
+ // Node 24.10+, comfortably under the engines floor. (SQLITE_LIMIT_ATTACHED is
1167
+ // left at the SQLite default — the snapshot / backup path relies on the
1168
+ // attach mechanism.)
1169
+ database = new DatabaseSync(dbPath, {
1170
+ limits: {
1171
+ sqlLength: C.BYTES.mib(1),
1172
+ },
1173
+ });
1161
1174
 
1162
1175
  // Performance pragmas
1163
1176
  runSql(database, "PRAGMA journal_mode=WAL");
@@ -2000,9 +2000,12 @@ async function downloadStream(opts) {
2000
2000
  }
2001
2001
  }
2002
2002
 
2003
- // Atomic rename + dir fsync.
2003
+ // Atomic rename + dir fsync. Route the final rename through
2004
+ // atomicFile.renameWithRetry so a Windows-transient lock on the destination
2005
+ // (AV / search indexer / Dropbox / OneDrive) is retried rather than surfaced
2006
+ // as a hard download failure — the same retry b.atomicFile.writeSync applies.
2004
2007
  try {
2005
- nodeFs.renameSync(tmpPath, dest);
2008
+ atomicFile.renameWithRetry(tmpPath, dest);
2006
2009
  atomicFile.fsyncDir(dir);
2007
2010
  } catch (e) {
2008
2011
  try { nodeFs.unlinkSync(tmpPath); } catch (_u) { /* best-effort cleanup */ }
@@ -59,6 +59,7 @@ var lazyRequire = require("./lazy-require");
59
59
  var validateOpts = require("./validate-opts");
60
60
  var safeSql = require("./safe-sql");
61
61
  var { LocalDbThinError } = require("./framework-error");
62
+ var atomicFile = require("./atomic-file");
62
63
 
63
64
  var audit = lazyRequire(function () { return require("./audit"); });
64
65
 
@@ -203,7 +204,7 @@ function thin(opts) {
203
204
  var lastRenameErr = null;
204
205
  for (var attempt = 0; attempt < 20 && !renamed; attempt += 1) {
205
206
  try {
206
- if (nodeFs.existsSync(file)) nodeFs.renameSync(file, renamedTo);
207
+ if (nodeFs.existsSync(file)) atomicFile.renameWithRetry(file, renamedTo);
207
208
  renamed = true;
208
209
  } catch (re) {
209
210
  lastRenameErr = re;
@@ -228,7 +229,7 @@ function thin(opts) {
228
229
  ["-wal", "-shm"].forEach(function (suffix) {
229
230
  var sibling = file + suffix;
230
231
  if (nodeFs.existsSync(sibling)) {
231
- try { nodeFs.renameSync(sibling, sibling + ".corrupt-" + stamp); }
232
+ try { atomicFile.renameWithRetry(sibling, sibling + ".corrupt-" + stamp); }
232
233
  catch (_se) { /* best-effort */ }
233
234
  }
234
235
  });
@@ -85,7 +85,7 @@ function create(config) {
85
85
  var stamp = time.toIso8601NoMs(new Date()).replace(/[-:]/g, "");
86
86
  var rotated = nodePath.join(dir, cfg.fileNamePrefix + "-" + stamp + ".log");
87
87
  if (nodeFs.existsSync(activePath)) {
88
- nodeFs.renameSync(activePath, rotated);
88
+ atomicFile.renameWithRetry(activePath, rotated);
89
89
  if (cfg.compressRotations) {
90
90
  var data = nodeFs.readFileSync(rotated);
91
91
  var gz = zlib.gzipSync(data);
@@ -87,29 +87,51 @@ var DEFAULT_TYPES = ["cookies", "storage", "cache", "executionContexts"];
87
87
  * },
88
88
  * ]);
89
89
  */
90
- function create(opts) {
91
- opts = opts || {};
92
- validateOpts(opts, ["types"], "middleware.clearSiteData");
93
- var types = opts.types === undefined ? DEFAULT_TYPES : opts.types;
90
+ /**
91
+ * @primitive b.middleware.clearSiteData.headerValue
92
+ * @signature b.middleware.clearSiteData.headerValue(types, label?)
93
+ * @since 0.15.9
94
+ * @status stable
95
+ * @related b.middleware.clearSiteData, b.session.logout
96
+ *
97
+ * Build the RFC 9527 §3 Clear-Site-Data header value from a list of directive
98
+ * types — a comma-separated list of double-quoted tokens — validating each
99
+ * against the known set (`cookies`, `storage`, `cache`, `executionContexts`).
100
+ * The middleware factory and `b.session.logout` both compose it so every
101
+ * emitter produces the same validated header instead of hand-rolling the
102
+ * quoting. Throws a `TypeError` on an unknown directive or a non-array input
103
+ * (config-time / entry-point tier).
104
+ *
105
+ * @example
106
+ * b.middleware.clearSiteData.headerValue(["cookies", "storage"]);
107
+ * // → '"cookies", "storage"'
108
+ */
109
+ function headerValue(types, label) {
110
+ label = label || "middleware.clearSiteData";
94
111
  if (!Array.isArray(types) || types.length === 0) {
95
- throw new TypeError("middleware.clearSiteData: opts.types must be a non-empty array");
112
+ throw new TypeError(label + ": types must be a non-empty array");
96
113
  }
97
114
  for (var i = 0; i < types.length; i += 1) {
98
115
  var t = types[i];
99
116
  if (typeof t !== "string" || !KNOWN_TYPES[t]) {
100
117
  throw new TypeError(
101
- "middleware.clearSiteData: unknown type '" + t +
118
+ label + ": unknown type '" + t +
102
119
  "' (expected one of: " + Object.keys(KNOWN_TYPES).join(", ") + ")");
103
120
  }
104
121
  }
105
- // Header value is a comma-separated list of double-quoted tokens
106
- // per RFC 9527 §3 (Structured Field Value List of Strings). Build
107
- // once at construction time — runtime cost is one setHeader call.
108
- var headerValue = types.map(function (t) { return '"' + t + '"'; }).join(", ");
122
+ return types.map(function (t) { return '"' + t + '"'; }).join(", ");
123
+ }
124
+
125
+ function create(opts) {
126
+ opts = opts || {};
127
+ validateOpts(opts, ["types"], "middleware.clearSiteData");
128
+ var types = opts.types === undefined ? DEFAULT_TYPES : opts.types;
129
+ // Header value built once at construction; runtime cost is one setHeader.
130
+ var headerVal = headerValue(types, "middleware.clearSiteData");
109
131
 
110
132
  return function clearSiteData(req, res, next) {
111
133
  if (typeof res.setHeader === "function") {
112
- res.setHeader("Clear-Site-Data", headerValue);
134
+ res.setHeader("Clear-Site-Data", headerVal);
113
135
  }
114
136
  next();
115
137
  };
@@ -117,6 +139,9 @@ function create(opts) {
117
139
 
118
140
  module.exports = {
119
141
  create: create,
142
+ // The shared RFC 9527 header-value builder — b.session.logout composes it so
143
+ // the logout path emits the same validated Clear-Site-Data header.
144
+ headerValue: headerValue,
120
145
  KNOWN_TYPES: Object.keys(KNOWN_TYPES),
121
146
  DEFAULT_TYPES: DEFAULT_TYPES,
122
147
  };
package/lib/mtls-ca.js CHANGED
@@ -336,8 +336,8 @@ function create(opts) {
336
336
  _writeExclusive(keyTmp, opts2.caKeyPem, 0o600);
337
337
  }
338
338
  _writeExclusive(certTmp, opts2.caCertPem, 0o644);
339
- nodeFs.renameSync(keyTmp, keyDest);
340
- nodeFs.renameSync(certTmp, paths.caCert);
339
+ atomicFile.renameWithRetry(keyTmp, keyDest);
340
+ atomicFile.renameWithRetry(certTmp, paths.caCert);
341
341
  } catch (e) {
342
342
  // Best-effort cleanup of half-written tmp files; the original
343
343
  // commit error is what we re-raise. Log cleanup failures at debug
@@ -119,7 +119,7 @@ function swap(opts) {
119
119
  // Step 1: rename current dataDir → rollback nodePath. Skipped on first
120
120
  // restore (no existing dataDir).
121
121
  if (hadDataDir) {
122
- try { nodeFs.renameSync(opts.dataDir, rollbackPath); }
122
+ try { atomicFile.renameWithRetry(opts.dataDir, rollbackPath); }
123
123
  catch (e) {
124
124
  throw new RestoreRollbackError("restore-rollback/rename-existing-failed",
125
125
  "swap: could not move existing dataDir to rollback: " + ((e && e.message) || String(e)));
@@ -127,11 +127,11 @@ function swap(opts) {
127
127
  }
128
128
 
129
129
  // Step 2: rename staging → dataDir
130
- try { nodeFs.renameSync(opts.stagingDir, opts.dataDir); }
130
+ try { atomicFile.renameWithRetry(opts.stagingDir, opts.dataDir); }
131
131
  catch (e) {
132
132
  // Step 2 failed — try to undo step 1 so the operator's dataDir is back
133
133
  if (hadDataDir) {
134
- try { nodeFs.renameSync(rollbackPath, opts.dataDir); }
134
+ try { atomicFile.renameWithRetry(rollbackPath, opts.dataDir); }
135
135
  catch (_e) { /* dataDir is now in rollbackPath; operator must recover manually */ }
136
136
  }
137
137
  throw new RestoreRollbackError("restore-rollback/rename-staging-failed",
@@ -220,7 +220,7 @@ async function rollback(opts) {
220
220
  atomicFile.ensureDir(rollbackRoot);
221
221
  discardedAt = atomicFile.pathTimestamp();
222
222
  var discardedPath = nodePath.join(rollbackRoot, "discarded-" + discardedAt);
223
- try { nodeFs.renameSync(opts.dataDir, discardedPath); }
223
+ try { atomicFile.renameWithRetry(opts.dataDir, discardedPath); }
224
224
  catch (e) {
225
225
  throw new RestoreRollbackError("restore-rollback/rename-existing-failed",
226
226
  "rollback: could not move current dataDir aside: " + ((e && e.message) || String(e)));
@@ -229,7 +229,7 @@ async function rollback(opts) {
229
229
  }
230
230
 
231
231
  // Rename the rollback dir back into dataDir's place
232
- try { nodeFs.renameSync(opts.rollbackPath, opts.dataDir); }
232
+ try { atomicFile.renameWithRetry(opts.rollbackPath, opts.dataDir); }
233
233
  catch (e) {
234
234
  throw new RestoreRollbackError("restore-rollback/rollback-rename-failed",
235
235
  "rollback: could not move rollback into dataDir: " + ((e && e.message) || String(e)) +
@@ -676,7 +676,7 @@ async function swap(opts) {
676
676
  // don't silently lose both binaries (the prior best-effort comment
677
677
  // swallowed the rollback exception — SSDF RV.1 violation).
678
678
  try {
679
- nodeFs.renameSync(from, to);
679
+ atomicFile.renameWithRetry(from, to);
680
680
  } catch (e) {
681
681
  if (e && e.code === "EXDEV") {
682
682
  // Cross-device — copy + unlink. Use atomicFile.copy for the safety
package/lib/session.js CHANGED
@@ -65,6 +65,9 @@ var { SessionError } = require("./framework-error");
65
65
  // the cookie-side sid so the wire token is ciphertext rather than
66
66
  // plaintext (sealed-cookie default since v0.8.61).
67
67
  var vault = lazyRequire(function () { return require("./vault"); });
68
+ // Lazy — b.session.logout composes the Clear-Site-Data header builder; keep it
69
+ // out of the boot require graph (no cycle, but session is a low-level primitive).
70
+ var clearSiteData = lazyRequire(function () { return require("./middleware/clear-site-data"); });
68
71
 
69
72
  // Pluggable session-storage backend. Default uses cluster-storage (which
70
73
  // in turn dispatches to the framework's main DB or external DB). An
@@ -705,6 +708,66 @@ async function destroy(token) {
705
708
  return await _deleteBySidHash(_hashSid(sid));
706
709
  }
707
710
 
711
+ /**
712
+ * @primitive b.session.logout
713
+ * @signature b.session.logout(res, token, opts?)
714
+ * @since 0.15.9
715
+ * @status stable
716
+ * @related b.session.destroy, b.middleware.clearSiteData
717
+ *
718
+ * Secure logout in one call: destroy the server-side session AND tell the
719
+ * browser to wipe its client-side state. It emits an RFC 9527 Clear-Site-Data
720
+ * response header (cookies + storage + cache + executionContexts by default)
721
+ * and expires the session cookie, then destroys the session row. `destroy()`
722
+ * alone is a store operation with no `res`, so it cannot wipe the browser's
723
+ * cached pages / storage / any stale tab still holding the now-revoked cookie;
724
+ * this composes the secure-default logout the middleware otherwise had to be
725
+ * mounted by hand. Returns whether a session was destroyed. Leader-only.
726
+ *
727
+ * @opts
728
+ * cookieName: string, // default: "sid" — the session cookie to expire
729
+ * types: string[], // default: the RFC 9527 Clear-Site-Data directive set
730
+ *
731
+ * @example
732
+ * app.post("/logout", async function (req, res) {
733
+ * await b.session.logout(res, req.cookies.sid);
734
+ * res.end("logged out");
735
+ * });
736
+ * // → emits Clear-Site-Data + expires the sid cookie + destroys the session
737
+ */
738
+ async function logout(res, token, opts) {
739
+ if (!res || typeof res.setHeader !== "function") {
740
+ throw new SessionError("session/bad-res",
741
+ "b.session.logout: res must be an HTTP response with setHeader()");
742
+ }
743
+ opts = opts || {};
744
+ var cookieName = opts.cookieName === undefined ? "sid" : opts.cookieName;
745
+ if (typeof cookieName !== "string" || cookieName.length === 0) {
746
+ throw new SessionError("session/bad-cookie-name",
747
+ "b.session.logout: opts.cookieName must be a non-empty string");
748
+ }
749
+ var csd = clearSiteData();
750
+ var types = opts.types === undefined ? csd.DEFAULT_TYPES : opts.types;
751
+ // Build (and validate) the RFC 9527 header BEFORE any side effect — an
752
+ // unknown directive throws here, queuing nothing.
753
+ var clearSiteDataValue = csd.headerValue(types, "b.session.logout");
754
+
755
+ // Revoke the server-side session FIRST. If destroy() throws (a follower
756
+ // failing cluster.requireLeader(), or a store/DB error), no client-wipe
757
+ // headers have been queued — an error response can't then expire the
758
+ // browser cookie + Clear-Site-Data while the session row is still live,
759
+ // which would leave a copied token usable server-side.
760
+ var destroyed = await destroy(token);
761
+
762
+ // Now wipe the client-side state: RFC 9527 Clear-Site-Data (cookies /
763
+ // storage / cache) + expire the session cookie (belt-and-suspenders with the
764
+ // "cookies" directive, and effective even if the client ignores the header).
765
+ res.setHeader("Clear-Site-Data", clearSiteDataValue);
766
+ res.setHeader("Set-Cookie",
767
+ cookieName + "=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0");
768
+ return destroyed;
769
+ }
770
+
708
771
  async function _deleteBySidHash(sidHash) {
709
772
  var built = sql.delete(_sessionSqlTable(), _sessionSqlOpts())
710
773
  .where("sidHash", sidHash)
@@ -1245,6 +1308,7 @@ module.exports = {
1245
1308
  create: create,
1246
1309
  verify: verify,
1247
1310
  destroy: destroy,
1311
+ logout: logout,
1248
1312
  destroyAllForUser: destroyAllForUser,
1249
1313
  touch: touch,
1250
1314
  rotate: rotate,
@@ -169,7 +169,7 @@ async function seal(opts) {
169
169
  }
170
170
 
171
171
  // Step 3: atomic rename sealed.tmp → sealed
172
- nodeFs.renameSync(p.sealedTmp, p.sealed);
172
+ atomicFile.renameWithRetry(p.sealedTmp, p.sealed);
173
173
  atomicFile.fsyncDir(opts.dataDir);
174
174
 
175
175
  // Step 4: delete plaintext (unless keepPlaintext)
@@ -220,7 +220,7 @@ async function unseal(opts) {
220
220
  }
221
221
 
222
222
  // Step 3: atomic rename plaintext.tmp → plaintext
223
- nodeFs.renameSync(p.plaintextTmp, p.plaintext);
223
+ atomicFile.renameWithRetry(p.plaintextTmp, p.plaintext);
224
224
  atomicFile.fsyncDir(opts.dataDir);
225
225
 
226
226
  // Step 4: delete sealed file
@@ -293,7 +293,7 @@ async function rotate(opts) {
293
293
  }
294
294
 
295
295
  // Step 3: atomic rename — swap in the new sealed file
296
- nodeFs.renameSync(p.sealedTmp, p.sealed);
296
+ atomicFile.renameWithRetry(p.sealedTmp, p.sealed);
297
297
  atomicFile.fsyncDir(opts.dataDir);
298
298
 
299
299
  return { sealedPath: p.sealed };
package/lib/watcher.js CHANGED
@@ -316,6 +316,14 @@ function create(opts) {
316
316
  _validateOpts(opts);
317
317
 
318
318
  var root = nodePath.resolve(opts.root);
319
+ // Canonicalize to the real long path. On Windows a path with an 8.3
320
+ // short-name component (os.tmpdir() commonly resolves to C:\Users\RUNNER~1\…)
321
+ // makes the native recursive backend (ReadDirectoryChangesW) deliver
322
+ // long-name event paths that no longer prefix-match the watched root, which
323
+ // trips a libuv fs-event assertion and aborts the process on some Node builds.
324
+ // realpathSync.native expands short names and resolves symlinks; guarded so a
325
+ // non-existent root still falls through to the watcher's own not-found error.
326
+ try { root = nodeFs.realpathSync.native(root); } catch (_e) { /* keep resolved path */ }
319
327
  var debounceMs = (opts.debounceMs !== undefined) ? opts.debounceMs : DEFAULT_DEBOUNCE_MS;
320
328
  var maxPending = (opts.maxPending !== undefined) ? opts.maxPending : DEFAULT_MAX_PENDING;
321
329
  var requestedMode = opts.mode || "fs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.15.8",
3
+ "version": "0.15.9",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
@@ -54,7 +54,7 @@
54
54
  "owns-its-stack"
55
55
  ],
56
56
  "engines": {
57
- "node": ">=24.14.1"
57
+ "node": ">=24.16.0"
58
58
  },
59
59
  "files": [
60
60
  "index.js",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:d7b8bc62-0d13-40fc-86ee-e6263eb44d87",
5
+ "serialNumber": "urn:uuid:19fb1b2e-d7b6-4169-b9c6-f60726097293",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-06-13T19:33:49.247Z",
8
+ "timestamp": "2026-06-14T00:18:26.195Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -15,18 +15,18 @@
15
15
  {
16
16
  "vendor": "npm",
17
17
  "name": "cli",
18
- "version": "11.11.0"
18
+ "version": "11.13.0"
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/core@0.15.8",
22
+ "bom-ref": "@blamejs/core@0.15.9",
23
23
  "type": "application",
24
24
  "name": "blamejs",
25
- "version": "0.15.8",
25
+ "version": "0.15.9",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "The Node framework that owns its stack.",
29
- "purl": "pkg:npm/%40blamejs/core@0.15.8",
29
+ "purl": "pkg:npm/%40blamejs/core@0.15.9",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/core@0.15.8",
57
+ "ref": "@blamejs/core@0.15.9",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]