@blamejs/blamejs-shop 0.2.15 → 0.2.18

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 (52) hide show
  1. package/CHANGELOG.md +5 -1
  2. package/README.md +2 -2
  3. package/lib/admin.js +81 -3
  4. package/lib/asset-manifest.json +5 -1
  5. package/lib/customers.js +71 -4
  6. package/lib/storefront.js +462 -0
  7. package/lib/vendor/MANIFEST.json +2 -2
  8. package/lib/vendor/blamejs/CHANGELOG.md +20 -0
  9. package/lib/vendor/blamejs/api-snapshot.json +6 -2
  10. package/lib/vendor/blamejs/examples/wiki/docker-compose.prod.yml +29 -0
  11. package/lib/vendor/blamejs/examples/wiki/docker-compose.yml +7 -0
  12. package/lib/vendor/blamejs/lib/agent-idempotency.js +15 -3
  13. package/lib/vendor/blamejs/lib/agent-orchestrator.js +39 -0
  14. package/lib/vendor/blamejs/lib/app-shutdown.js +32 -0
  15. package/lib/vendor/blamejs/lib/bounded-map.js +102 -0
  16. package/lib/vendor/blamejs/lib/cache.js +184 -23
  17. package/lib/vendor/blamejs/lib/cert.js +68 -11
  18. package/lib/vendor/blamejs/lib/cluster-storage.js +114 -10
  19. package/lib/vendor/blamejs/lib/db.js +205 -15
  20. package/lib/vendor/blamejs/lib/dual-control.js +139 -143
  21. package/lib/vendor/blamejs/lib/i18n.js +10 -1
  22. package/lib/vendor/blamejs/lib/mail-crypto-smime.js +43 -9
  23. package/lib/vendor/blamejs/lib/network-dns.js +10 -2
  24. package/lib/vendor/blamejs/lib/nonce-store.js +39 -12
  25. package/lib/vendor/blamejs/lib/queue-local.js +2 -2
  26. package/lib/vendor/blamejs/lib/redis-client.js +14 -1
  27. package/lib/vendor/blamejs/lib/subject.js +8 -1
  28. package/lib/vendor/blamejs/package.json +1 -1
  29. package/lib/vendor/blamejs/release-notes/v0.13.33.json +26 -0
  30. package/lib/vendor/blamejs/release-notes/v0.13.34.json +48 -0
  31. package/lib/vendor/blamejs/release-notes/v0.13.35.json +35 -0
  32. package/lib/vendor/blamejs/release-notes/v0.13.36.json +27 -0
  33. package/lib/vendor/blamejs/release-notes/v0.13.37.json +18 -0
  34. package/lib/vendor/blamejs/release-notes/v0.13.38.json +27 -0
  35. package/lib/vendor/blamejs/release-notes/v0.13.39.json +27 -0
  36. package/lib/vendor/blamejs/release-notes/v0.13.40.json +22 -0
  37. package/lib/vendor/blamejs/release-notes/v0.13.41.json +27 -0
  38. package/lib/vendor/blamejs/release-notes/v0.13.42.json +18 -0
  39. package/lib/vendor/blamejs/test/20-db.js +191 -0
  40. package/lib/vendor/blamejs/test/layer-0-primitives/agent-idempotency.test.js +20 -0
  41. package/lib/vendor/blamejs/test/layer-0-primitives/agent-orchestrator.test.js +33 -0
  42. package/lib/vendor/blamejs/test/layer-0-primitives/api-encrypt.test.js +35 -0
  43. package/lib/vendor/blamejs/test/layer-0-primitives/app-shutdown.test.js +64 -0
  44. package/lib/vendor/blamejs/test/layer-0-primitives/bounded-map.test.js +87 -0
  45. package/lib/vendor/blamejs/test/layer-0-primitives/cache.test.js +48 -0
  46. package/lib/vendor/blamejs/test/layer-0-primitives/cert.test.js +170 -0
  47. package/lib/vendor/blamejs/test/layer-0-primitives/cluster-storage.test.js +125 -0
  48. package/lib/vendor/blamejs/test/layer-0-primitives/codebase-patterns.test.js +92 -1
  49. package/lib/vendor/blamejs/test/layer-0-primitives/dual-control.test.js +32 -0
  50. package/lib/vendor/blamejs/test/layer-0-primitives/mail-crypto-smime.test.js +31 -0
  51. package/lib/vendor/blamejs/test/layer-0-primitives/redis-client.test.js +14 -0
  52. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.13.32",
3
+ "version": "0.13.42",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.13.33",
4
+ "date": "2026-05-28",
5
+ "headline": "Encrypted-mode DB recovers from a corrupt tmpfs working copy instead of crash-looping",
6
+ "summary": "In encrypted-at-rest mode the live SQLite copy is decrypted into a tmpfs working file and re-encrypted to db.enc periodically. If that working copy was corrupted (an unclean shutdown, or a full tmpfs — Docker's /dev/shm defaults to 64 MiB), the boot path trusted it because its mtime was newer than db.enc, so db.init failed its integrity gate with \"database disk image is malformed\" identically on every boot — an unrecoverable crash loop. db now integrity-probes the newer working copy before trusting it: if it is unreadable, the working copy is discarded and db.enc (the last-good encrypted snapshot) is re-decrypted, so the next boot self-heals. db.enc is never modified by this path, and a genuinely-corrupt db.enc still fails loudly rather than wiping data. The boot error on an unreadable database is now actionable (it names the tmpfs-size cause and the recovery). The wiki production compose also gains the storage settings encrypted mode needs.",
7
+ "sections": [
8
+ {
9
+ "heading": "Fixed",
10
+ "items": [
11
+ {
12
+ "title": "Corrupt tmpfs working copy no longer causes a boot crash loop (encrypted-at-rest mode)",
13
+ "body": "`db.init`'s crash-recovery path preferred a newer tmpfs working copy over `db.enc` unconditionally. When that copy was corrupt (truncated by an unclean shutdown or a full `/dev/shm`), every boot trusted it and failed the integrity gate the same way — an unrecoverable loop. The newer working copy is now integrity-probed (`PRAGMA quick_check`); if it is unreadable it is discarded and `db.enc` — the last-good encrypted snapshot — is re-decrypted, so boot self-heals. `db.enc` is never modified, so this only ever rolls back to the persistent copy; if `db.enc` is also corrupt, boot still fails loudly (no silent data loss). A regression test pins the recovery."
14
+ },
15
+ {
16
+ "title": "Actionable boot error when the database is unreadable",
17
+ "body": "When SQLite reports a database too corrupt to even run an integrity check, the boot error now names the likely cause and recovery instead of surfacing the raw \"database disk image is malformed\": in encrypted mode it points at the tmpfs working copy and the most common operational cause (Docker's 64 MiB `/dev/shm` default — raise it via `shm_size` / `--shm-size`), or restoring `db.enc` / the DB file from backup."
18
+ },
19
+ {
20
+ "title": "Wiki production compose ships the storage encrypted mode needs",
21
+ "body": "`examples/wiki/docker-compose.prod.yml` now sets `shm_size: '512m'` (so the encrypted-mode tmpfs working copy has headroom above Docker's 64 MiB default) and mounts a persistent `wiki-data` volume at `/data` (so `db.enc` + sealed keys survive container recreate, host reboot, and image redeploys, and give a restore point). A note flags that PaaS platforms which regenerate the compose on deploy (Coolify, Dokku, CapRover, …) must set both via the platform UI — a persistent-storage mount for `/data` and a `--shm-size 512m` custom option."
22
+ }
23
+ ]
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,48 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.13.34",
4
+ "date": "2026-05-29",
5
+ "headline": "Corrupt TLS certs self-heal at boot, and graceful shutdown no longer loses the final DB flush",
6
+ "summary": "Two failure-mode fixes in the same family as the encrypted-DB recovery in 0.13.33. The cert manager treated a corrupt sealed cert or key worse than a missing one: a missing file re-issues via ACME, but a corrupt one let a raw decrypt error escape out of start(), so the same bad file was read on every boot — an unrecoverable crash loop. A corrupt sealed cert/key is now treated like an absent one and re-issued, and a corrupt derived meta.json is re-derived rather than fatal; the ACME account key (which binds order history) instead fails with an actionable error rather than a raw throw. On the shutdown side, an encrypted database that failed its final re-encrypt used to delete its plaintext working copy anyway, discarding every write since the last periodic flush; it now keeps the working copy so the next boot recovers it. The shutdown orchestrator also gains a hard-deadline watchdog: when the operator delegates signal handling to it, a phase that never settles can no longer hold the process open until the supervisor SIGKILLs it (which would skip the final DB re-encrypt) — the watchdog forces a clean exit, so exit handlers still flush. The wiki production and base compose files set a stop_grace_period above that budget so a docker stop or rolling redeploy lets the re-encrypt finish.",
7
+ "sections": [
8
+ {
9
+ "heading": "Fixed",
10
+ "items": [
11
+ {
12
+ "title": "A corrupt sealed TLS cert or key re-issues instead of crash-looping at boot",
13
+ "body": "`b.cert`'s start path read the sealed `cert.pem`/`key.pem` and let a raw unseal/decrypt error escape if the file was truncated or corrupt, so a managed restart read the same bad file on every boot — a crash loop, and worse handling than an absent file (which already re-issues). A corrupt sealed cert/key is now treated like a missing one: it is logged, an audit event is emitted, and the certificate is re-issued via ACME. A corrupt derived `meta.json` is likewise re-derived rather than throwing `cert/bad-meta`."
14
+ },
15
+ {
16
+ "title": "Unreadable ACME account key fails with an actionable error, not a raw decrypt throw",
17
+ "body": "Unlike a re-issuable certificate, the ACME account key binds existing order and authorization history, so it is not silently regenerated on corruption. An unreadable `account/jwk.json.sealed` now raises `cert/account-key-unreadable` naming the file and the recovery (restore from backup, or delete to register a fresh account) instead of letting a raw decrypt/parse error escape out of start()."
18
+ },
19
+ {
20
+ "title": "Encrypted DB keeps its working copy when the final shutdown re-encrypt fails",
21
+ "body": "`db.close()` re-encrypts the tmpfs working copy to `db.enc`, then deletes the working copy. If that final re-encrypt failed (a full `/dev/shm`, a full disk), the delete still ran, discarding every write since the last periodic flush and leaving only the older `db.enc`. The working copy is now kept whenever the re-encrypt fails, so the next boot's integrity-probed recovery picks up the latest writes (and still falls back to `db.enc` if the working copy is itself corrupt). `db.enc` is never modified by this path."
22
+ }
23
+ ]
24
+ },
25
+ {
26
+ "heading": "Changed",
27
+ "items": [
28
+ {
29
+ "title": "Shutdown watchdog forces a clean, DB-flushing exit if a phase hangs",
30
+ "body": "The graceful-shutdown orchestrator uses soft per-phase timeouts — on expiry the underlying work keeps running — so a phase that never settles could hold the event loop open past the grace window, after which a container supervisor SIGKILLs the process and skips the final DB re-encrypt. When the operator opts into signal handling, a watchdog now forces `process.exit` `graceMs + forceExitMarginMs` after the signal; exit runs the registered handlers (the DB re-encrypt), so the last flush still happens. A new `forceExitMarginMs` option (default 5000) tunes the headroom; set the container stop grace above `graceMs + forceExitMarginMs`."
31
+ },
32
+ {
33
+ "title": "Wiki compose sets stop_grace_period above the shutdown budget",
34
+ "body": "`examples/wiki/docker-compose.yml` and `docker-compose.prod.yml` now set `stop_grace_period: 40s`. Docker's 10s default would SIGKILL the container before the 30s shutdown budget reaches the DB re-encrypt phase, losing the final flush on a `docker stop` or rolling redeploy. The production note also reminds PaaS platforms that regenerate the compose (Coolify, Dokku, CapRover) to set the stop grace via the platform UI alongside the persistent-storage mount and `--shm-size`."
35
+ }
36
+ ]
37
+ },
38
+ {
39
+ "heading": "Detectors",
40
+ "items": [
41
+ {
42
+ "title": "Cross-artifact guard that stop_grace_period covers the shutdown budget",
43
+ "body": "A new codebase check fails if either wiki compose file omits `stop_grace_period` or sets it below the orchestrator's `graceMs` plus the watchdog margin read from `lib/app-shutdown.js`, so raising the shutdown budget without bumping the compose — or dropping the setting — cannot silently reopen the SIGKILL-before-re-encrypt data-loss window."
44
+ }
45
+ ]
46
+ }
47
+ ]
48
+ }
@@ -0,0 +1,35 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.13.35",
4
+ "date": "2026-05-29",
5
+ "headline": "In-memory replay, idempotency, DNS, and i18n stores gain entry-count ceilings",
6
+ "summary": "Several framework caches keyed on request-influenced input grew without an upper bound between their periodic sweeps, so a flood of unique keys could exhaust process memory faster than the sweep reclaimed it. Each now enforces a hard entry ceiling. The replay-protection nonce store is the security-sensitive one: rather than evict a live nonce to admit a new one — which would reopen a replay window for the evicted nonce — it purges expired entries and then fails closed at capacity, refusing the unrecordable request instead of admitting it unprotected. The idempotency, DNS, and i18n caches hold re-derivable values, so they evict the oldest entry instead (the worst case is a recomputed value or a single re-executed retry under flood). Ceilings are generous defaults that normal traffic never reaches; the nonce store and the agent idempotency in-memory backend expose options to tune them.",
7
+ "sections": [
8
+ {
9
+ "heading": "Security",
10
+ "items": [
11
+ {
12
+ "title": "Replay-nonce store bounds memory and fails closed under a nonce flood",
13
+ "body": "The in-memory `b.nonceStore` backend recorded every request-supplied nonce until a periodic sweep ran, so a stream of unique nonces could exhaust memory between sweeps (a memory-amplification denial of service). It now caps its entry count. Because a replay-protection store must never evict a live nonce to make room — doing so would reopen a replay window for the evicted nonce — it instead purges expired entries inline and, if still at capacity with live nonces, fails closed: the new request is refused rather than admitted without replay protection. A new `maxEntries` option tunes the ceiling (default 1,000,000)."
14
+ }
15
+ ]
16
+ },
17
+ {
18
+ "heading": "Fixed",
19
+ "items": [
20
+ {
21
+ "title": "Agent idempotency in-memory backend no longer grows without bound",
22
+ "body": "The default in-memory backend for `b.agent.idempotency` is keyed on the request-supplied idempotency key, and its garbage collector only reclaims expired rows when an operator wires a scheduler to call it — so a flood of distinct keys could grow it until the process ran out of memory. It now caps its entry count and evicts oldest-first; a dropped record just means that one key re-executes on a later retry, never a crash. A new `maxInMemoryEntries` option tunes the ceiling (default 100,000); deployments needing a hard guarantee at scale still supply a durable `store`."
23
+ },
24
+ {
25
+ "title": "DNS resolver cache is bounded",
26
+ "body": "The positive and negative resolver caches in `b.network.dns` reclaimed an expired entry only when the same hostname was looked up again, so entries for never-requeried hostnames persisted — and hostnames reaching the resolver are request-influenced (outbound request targets, mail MX lookups). Both caches now cap their entry count and evict oldest-first; DNS simply re-resolves on the next miss."
27
+ },
28
+ {
29
+ "title": "i18n formatter cache is bounded",
30
+ "body": "Per-instance `Intl` formatter caches in `b.i18n` are keyed on the locale plus a hash of the format options. The format-options shape is open-ended and caller-supplied, so the key space was request-influenced and uncapped. The cache now enforces an entry ceiling and evicts oldest-first — a formatter is pure-derived and re-created on the next miss."
31
+ }
32
+ ]
33
+ }
34
+ ]
35
+ }
@@ -0,0 +1,27 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.13.36",
4
+ "date": "2026-05-29",
5
+ "headline": "Certificate renewal trusts the sealed cert's own expiry, not the plaintext index",
6
+ "summary": "The managed-certificate renewal check decided a cached cert was still fresh by reading expiresAt from the plaintext meta.json index that sits beside the sealed cert, rather than from the certificate itself. If that index drifted from — or was tampered relative to — the actual cert (a far-future expiry recorded over a certificate that is in fact near expiry), the manager would skip renewal and keep serving a cert that was about to expire or already had. Renewal now re-derives the expiry and fingerprint from the sealed certificate itself; meta.json is treated as an advisory convenience copy. A sealed cert that no longer parses is re-issued (the same recovery as an unreadable one), and a corrupt meta.json over a valid cert now loads cleanly from the cert instead of forcing a needless re-issue. The local job queue also bounds the size of a job payload it parses back from a stored row, matching the cap the dead-letter listing already used.",
7
+ "sections": [
8
+ {
9
+ "heading": "Security",
10
+ "items": [
11
+ {
12
+ "title": "Cert renewal re-derives expiry from the sealed certificate, not the meta.json index",
13
+ "body": "`b.cert`'s renewal short-circuit read `expiresAt` from the plaintext `meta.json` written beside each sealed cert. Because that index can drift from the actual certificate (or be altered independently of it), a far-future value over an actually-expiring cert would suppress renewal and serve a cert past — or about to pass — its validity. The renewal decision now parses the expiry and fingerprint from the sealed certificate itself on load, so `meta.json` is advisory only. A sealed cert that will not parse is treated as corrupt and re-issued; a corrupt `meta.json` over an otherwise-valid cert loads from the cert without a needless re-issue."
14
+ }
15
+ ]
16
+ },
17
+ {
18
+ "heading": "Fixed",
19
+ "items": [
20
+ {
21
+ "title": "Local job queue bounds the size of a payload parsed back from a stored row",
22
+ "body": "When the local queue leased a job or re-enqueued a repeating one, it parsed the job payload back from its stored row without an upper size bound, unlike the dead-letter listing which already capped it. A row with an oversized payload (a corrupted or tampered store) could force an unbounded parse. Both paths now cap the parse at the same 64 MiB ceiling the dead-letter path uses."
23
+ }
24
+ ]
25
+ }
26
+ ]
27
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.13.37",
4
+ "date": "2026-05-29",
5
+ "headline": "Encrypted-mode DB refuses writes before a full tmpfs corrupts it",
6
+ "summary": "In encrypted-at-rest mode the live SQLite working copy is on a tmpfs (Docker's /dev/shm defaults to 64 MiB). If that fills — an append-only audit chain and session rows grow over time — SQLite hits ENOSPC and the working copy is corrupted. Earlier releases made that corruption self-heal on the next boot by rolling back to the last encrypted snapshot, but the rollback still loses writes since the last flush. This adds the prevention side: a periodic free-space probe refuses growth writes (INSERT / UPDATE / REPLACE) with a clear db/storage-low error once free space drops below a threshold, before the tmpfs fills. DELETE and reads stay available so retention can reclaim space and the application keeps serving, and the refusal lifts automatically once free space recovers. The threshold defaults to 16 MiB of headroom and is tunable; the guard is encrypted-mode only.",
7
+ "sections": [
8
+ {
9
+ "heading": "Security",
10
+ "items": [
11
+ {
12
+ "title": "Free-space guard refuses growth writes before the tmpfs working copy fills",
13
+ "body": "`b.db` in encrypted-at-rest mode now probes free space on the tmpfs holding the working copy and, when it falls below `minFreeBytes` (default 16 MiB), refuses `INSERT` / `UPDATE` / `REPLACE` with a clear `db/storage-low` error instead of letting the write run the mount out of space and corrupt the database. `DELETE`, reads, and DDL stay available so retention can prune and the app keeps serving; the refusal clears automatically when free space recovers. The error message points at the cause (Docker's 64 MiB `/dev/shm` default) and the fix (`shm_size` / `--shm-size`, or pruning). Set `minFreeBytes` to tune the headroom, or `0` to disable. This complements the existing boot-time recovery: prevention (fail clear, keep recent writes) ahead of recovery (roll back to the last snapshot)."
14
+ }
15
+ ]
16
+ }
17
+ ]
18
+ }
@@ -0,0 +1,27 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.13.38",
4
+ "date": "2026-05-29",
5
+ "headline": "Atomic cache tag invalidation, and a clusterStorage.transaction primitive for multi-statement framework writes",
6
+ "summary": "The cluster cache stored a value and its tag index with separate statements, so two concurrent writes to the same key could interleave their tag updates and leave the index out of step with the value — a later tag-based invalidation would then miss the key, letting a stale (possibly authorization-bearing) value survive a wipe. The value and tag writes now commit as one atomic unit. The enabling piece is a new b.clusterStorage.transaction primitive that runs a multi-statement read-modify-write all-or-nothing against the active backend — the external DB's pooled transaction in cluster mode, and a serialized transaction on the shared SQLite connection in single-node mode (so no concurrent statement can interleave into an open transaction).",
7
+ "sections": [
8
+ {
9
+ "heading": "Added",
10
+ "items": [
11
+ {
12
+ "title": "b.clusterStorage.transaction(fn) — atomic multi-statement framework-state writes",
13
+ "body": "Runs `fn` inside one transaction against the active backend so a multi-statement read-modify-write commits all-or-nothing. `fn` receives a transaction handle with the same `execute` / `executeOne` / `executeAll` surface, scoped to the open transaction. Cluster mode uses the external DB's pooled transaction (with its deadlock retry); single-node mode serializes against other transactions and against `execute` on the shared SQLite connection, so a concurrent statement cannot interleave into an open transaction. Use the handle's methods inside `fn` — calling the module-level `execute` from within `fn` would wait on the very transaction it is running."
14
+ }
15
+ ]
16
+ },
17
+ {
18
+ "heading": "Fixed",
19
+ "items": [
20
+ {
21
+ "title": "Cluster cache tag invalidation can no longer miss a key under concurrent writes",
22
+ "body": "The cluster cache wrote a value (`INSERT ... ON CONFLICT DO UPDATE`) and then rewrote its tag index (`DELETE` prior tags, `INSERT` new ones) as separate statements. Two concurrent `set()`s on the same key could interleave those tag statements, leaving the tag index inconsistent with the value — so a later `invalidateTag` could miss the key and a stale value would survive the wipe. The value and tag writes now run inside a single `clusterStorage.transaction`, so a concurrent writer observes either the whole prior state or the whole new state, never a mix."
23
+ }
24
+ ]
25
+ }
26
+ ]
27
+ }
@@ -0,0 +1,27 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.13.39",
4
+ "date": "2026-05-29",
5
+ "headline": "Dual-control approvals are atomic — no quorum bypass or double-consume under concurrency",
6
+ "summary": "The dual-control approval store read a grant, mutated it in memory, and wrote it back with an await in between — a non-atomic read-modify-write. Under concurrent calls (two approvals, or a retried one) each could act on a stale snapshot: the same approver could be appended twice and reach the M-of-N quorum with a single human, or a single-use grant could be consumed twice. approve / consume / revoke / cancel now commit through a new atomic cache.update primitive, so the check and the mutation are one indivisible step. The new b.cache.update is available to application code too — the memory backend is atomic by single-thread, and the cluster backend uses a transaction with compare-and-set so a concurrent writer on another node cannot lose an update.",
7
+ "sections": [
8
+ {
9
+ "heading": "Security",
10
+ "items": [
11
+ {
12
+ "title": "Dual-control quorum and single-use guarantees hold under concurrent approvals",
13
+ "body": "`b.dualControl` persisted each grant through a cache read → in-memory mutate → write-back. Because the read and the write were separate awaited steps, two concurrent `approve` calls (or a retried one behind a load balancer) could each read the same pre-approval snapshot, so the duplicate-approver guard passed twice and the same approver was counted toward the M-of-N quorum twice — reaching quorum with one human. The same shape let two concurrent `consume` calls each see an unconsumed grant and both run the destructive operation. `approve` / `consume` / `revoke` / `cancel` now perform the check-and-mutate atomically via `cache.update`, so exactly one concurrent caller wins each transition."
14
+ }
15
+ ]
16
+ },
17
+ {
18
+ "heading": "Added",
19
+ "items": [
20
+ {
21
+ "title": "b.cache.update(key, mutatorFn, opts?) — atomic read-modify-write",
22
+ "body": "Reads the current value, calls `mutatorFn(current | null)`, and commits the result in one operation so a concurrent writer cannot clobber the change — the lost-update race that makes a plain `get` → mutate → `set` unsafe for counters, sets, and quorum state. The memory backend is atomic by single-thread; the cluster backend runs a transaction with a compare-and-set (and retries on contention) so the guarantee holds across nodes. `mutatorFn` returns `{ value }` to commit, `{ abort: data }` to leave the entry untouched and surface `data`, or `{ delete: true }` to remove it; the call resolves to `{ updated, value }`, `{ updated, deleted }`, or `{ aborted }`."
23
+ }
24
+ ]
25
+ }
26
+ ]
27
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.13.40",
4
+ "date": "2026-05-29",
5
+ "headline": "Redis client stops leaking a socket and blocking exit after close; DB exit-handler registers once",
6
+ "summary": "Two handle-lifecycle fixes. The Redis client's reconnect backoff used an untracked, non-unref'd timer: during a backoff window it alone could keep the event loop alive (a process that won't exit), and a reconnect scheduled before close() fired afterward and opened a fresh socket because the connect path didn't re-check the closing flag. The timer is now tracked, unref'd, cancelled in close(), and the connect path refuses to re-open once closing. Separately, the encrypted database registered its process-exit final-flush handler on every init(), so repeated init/close cycles (long test runs, hot reload) accumulated 'exit' listeners toward the MaxListenersExceeded warning; it now registers once for the process lifetime.",
7
+ "sections": [
8
+ {
9
+ "heading": "Fixed",
10
+ "items": [
11
+ {
12
+ "title": "Redis client cancels its reconnect timer on close and won't re-open a closed connection",
13
+ "body": "The reconnect backoff scheduled `setTimeout(reconnect, delay)` without keeping a handle, without `unref()`, and the reconnect path checked only `connected`/`connecting` — not `closing`. So a backoff window could by itself hold the process open (it won't exit), and a reconnect scheduled before `close()` would fire afterward and open a fresh socket with listeners — a leak after explicit close. The timer is now tracked and `unref()`'d (a backoff no longer blocks exit), cancelled in `close()`, and the connect path returns early once closing so no socket is opened after close."
14
+ },
15
+ {
16
+ "title": "Encrypted DB registers its process-exit flush handler once, not per init()",
17
+ "body": "`b.db.init()` in encrypted mode added a `process.on(\"exit\")` final-flush handler on every call. Across repeated init/close cycles — long test suites, hot reload, embedded re-inits — these accumulated and tripped Node's MaxListenersExceeded warning (and grew memory slightly). The handler is now registered once for the process lifetime, guarded by a module flag, and still flushes whichever encrypted DB is open at exit time."
18
+ }
19
+ ]
20
+ }
21
+ ]
22
+ }
@@ -0,0 +1,27 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.13.41",
4
+ "date": "2026-05-29",
5
+ "headline": "Agent registry reads can be tenant-scoped; compliance-erasure docs clarify actor is an audit field",
6
+ "summary": "The agent orchestrator's registry reads (list and lookup) gated only on the flat agent-registry:read scope, so any holder could enumerate every tenant's agents and resolve a handle to one — even though the event bus already scopes subscribe and delivery by tenant. The orchestrator now mirrors that: with the new tenantScope option enabled, list returns only the actor's own tenant's agents and lookup refuses a cross-tenant name, unless the actor holds the framework cross-tenant-admin scope. Off by default, so single-tenant deployments are unaffected. Separately, the subject-erasure docs now state explicitly that the recorded actor is an audit field, not authentication — the caller must be authorized upstream.",
7
+ "sections": [
8
+ {
9
+ "heading": "Added",
10
+ "items": [
11
+ {
12
+ "title": "Tenant-scoped agent registry reads (opts.tenantScope)",
13
+ "body": "`b.agent.orchestrator.create({ tenantScope: true })` now scopes `list` and `lookup` to the calling actor's tenant: `list` filters out agents in other tenants and `lookup` returns null for a cross-tenant name, unless the actor holds the cross-tenant-admin scope (`b.agent.tenant.CROSS_TENANT_ADMIN_SCOPE`). This closes a cross-tenant metadata-enumeration and handle-acquisition path — `agent-registry:read` alone no longer exposes other tenants' agents — and mirrors the tenant scoping the event bus enforces on subscribe and delivery. The option defaults off; existing single-tenant orchestrators behave exactly as before. The `tenantId` argument to `list` remains a convenience filter, distinct from this authorization boundary."
14
+ }
15
+ ]
16
+ },
17
+ {
18
+ "heading": "Changed",
19
+ "items": [
20
+ {
21
+ "title": "Subject-erasure docs clarify the actor is an audit field, not authentication",
22
+ "body": "`b.subject.erase` and `b.subject.eraseHard` gate the deletion on operator acknowledgements and the legal-hold registry, not on caller identity. Their documentation now states explicitly that the recorded `actor` is an audit-record field, not authentication — the caller MUST be authenticated and authorized by the route before invoking. No behavior change; this removes an implicit assumption that could otherwise be read as the primitive authorizing the call."
23
+ }
24
+ ]
25
+ }
26
+ ]
27
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.13.42",
4
+ "date": "2026-05-29",
5
+ "headline": "S/MIME trust-chain validation binds the leaf to the key that verified the signature",
6
+ "summary": "When b.mail.crypto.smime.verify is given trust anchors, it validates the supplied certificate chain — but it picked the chain leaf unconditionally (the first cert) and never tied it to signerPublicKey, the key that actually verified the signature. A SignedData blob could therefore carry a validly-chained certificate for one identity while the signature was verified under an unrelated key, and the chain-validated result would imply a cert↔signer binding the code never made. Chain validation now selects the leaf as the certificate whose public key matches signerPublicKey, and refuses (signer-not-in-chain) when no certificate in the chain carries that key — so a chain-validated signature is bound to the cert it claims.",
7
+ "sections": [
8
+ {
9
+ "heading": "Security",
10
+ "items": [
11
+ {
12
+ "title": "Trust-chain leaf is bound to the verified signer key",
13
+ "body": "`smime.verify({ trustAnchorCertsPem })` validated the supplied chain starting from `chain[0]` without checking that the leaf's public key was the one that verified the signature (the operator-supplied `signerPublicKey`). A crafted `SignedData` could pair a validly-chained certificate for identity A with a signature verified under an unrelated key, and the chain-valid result would assert a binding that didn't hold. The chain walk now selects the leaf as the certificate whose public key equals `signerPublicKey` (matched against the certificate's SPKI, raw key or full-encoding form), and throws `mail-crypto/smime/signer-not-in-chain` when no certificate in `SignedData.certificates` carries that key. A certificate whose key cannot be extracted is treated as a non-match, so validation fails closed rather than trusting an unverifiable binding."
14
+ }
15
+ ]
16
+ }
17
+ ]
18
+ }
@@ -456,12 +456,203 @@ async function testUnsealRowNullsForgedValue() {
456
456
  }
457
457
  }
458
458
 
459
+ async function testEncryptedTmpfsCorruptionAutoRecovers() {
460
+ // Regression: in encrypted-at-rest mode the live SQLite copy lives in a
461
+ // tmpfs working file; a corrupt newer working copy (unclean shutdown, or
462
+ // a full /dev/shm — Docker's 64 MiB default) must NOT be trusted on
463
+ // boot. decryptToTmp's "newer plaintext wins" crash-recovery path used
464
+ // to keep it unconditionally, so db.init failed its integrity gate with
465
+ // "database disk image is malformed" identically on every boot — an
466
+ // unrecoverable crash loop (the blamejs.com wiki looped 4,625 times).
467
+ // The fix: integrity-probe the newer working copy; if bad, discard it
468
+ // and re-decrypt the last-good db.enc. db.enc is never modified.
469
+ //
470
+ // Scratch dir lives under the repo-local .test-output (not os.tmpdir):
471
+ // this test intentionally corrupts its working file in place, which
472
+ // static analysis (CodeQL js/insecure-temporary-file) flags as an
473
+ // insecure OS-temp-dir write. A gitignored per-test dir outside the
474
+ // shared OS temp dir sidesteps that false positive and is cleaner for
475
+ // test isolation besides.
476
+ var scratchBase = path.join(__dirname, "..", ".test-output");
477
+ fs.mkdirSync(scratchBase, { recursive: true });
478
+ var tmpDir = fs.mkdtempSync(path.join(scratchBase, "db-tmpfs-corrupt-"));
479
+ var schema = [{ name: "recovery_t", columns: { _id: "TEXT PRIMARY KEY", v: "TEXT" } }];
480
+ try {
481
+ await setupTestDb(tmpDir, schema);
482
+ check("recovery test runs in encrypted mode", b.db.getMode() === "encrypted");
483
+ b.db.prepare("INSERT INTO recovery_t (_id, v) VALUES (?, ?)").run("r1", "survives");
484
+ await b.db.flushToDisk(); // persist to db.enc (last-good snapshot)
485
+ b.db._resetForTest(); // close handle; leaves the working file on disk
486
+
487
+ // Locate the tmpfs working copy under our own scratch dir (setupTestDb
488
+ // points the working dir at <tmpDir>/tmpfs). Resolve it from `tmpDir`
489
+ // — our .test-output mkdtemp — rather than b.db.getDbPath(), so the
490
+ // path's non-OS-temp provenance stays visible to static analysis.
491
+ var workingDir = path.join(tmpDir, "tmpfs");
492
+ var workingFile = fs.readdirSync(workingDir).filter(function (f) { return /\.db$/.test(f); })[0];
493
+ var workingPath = path.join(workingDir, workingFile);
494
+
495
+ // Corrupt the existing working copy in place — overwrite the SQLite
496
+ // header so the file is no longer a valid database — and stamp it
497
+ // newer than db.enc (the exact trap shape that produced the crash
498
+ // loop). Open with "r+" (must already exist; never creates a file) so
499
+ // this is an in-place corruption of a known file.
500
+ var corruptFd = fs.openSync(workingPath, "r+");
501
+ try { fs.writeSync(corruptFd, Buffer.from("not a sqlite database -- corrupt header\n".repeat(8)), 0, undefined, 0); }
502
+ finally { fs.closeSync(corruptFd); }
503
+ var future = new Date(Date.now() + 60000);
504
+ fs.utimesSync(workingPath, future, future);
505
+
506
+ // Re-init against the same dataDir. Mirror setupTestDb's pre-init
507
+ // reset (passphrase env + audit reset) so db.init re-wires audit-sign
508
+ // from the same passphrase — but do NOT reset the vault, so the
509
+ // existing db.enc key still decrypts. The corrupt newer working copy
510
+ // must be discarded and db.enc re-decrypted — boot must succeed.
511
+ setTestPassphraseEnv();
512
+ b.audit._resetForTest();
513
+ await b.db.init({ dataDir: tmpDir, tmpDir: path.join(tmpDir, "tmpfs"), schema: schema });
514
+ var row = b.db.prepare("SELECT v FROM recovery_t WHERE _id = ?").get("r1");
515
+ check("corrupt tmpfs working copy auto-recovers from db.enc (no crash loop)",
516
+ row && row.v === "survives");
517
+ } finally {
518
+ try { b.db._resetForTest(); } catch (_e) { /* best effort */ }
519
+ await teardownTestDb(tmpDir);
520
+ }
521
+ }
522
+
523
+ async function testEncryptedCloseKeepsPlaintextWhenEncryptFails() {
524
+ // close()'s final re-encrypt can fail (full /dev/shm, disk-full). When it
525
+ // does, the plaintext working copy is the ONLY carrier of writes since
526
+ // the last periodic flush — close() must NOT unlink it (it used to do so
527
+ // unconditionally), so the next boot's newer-mtime recovery can pick it
528
+ // up. db.enc still holds the prior snapshot, so nothing is lost either
529
+ // way; the bug was discarding the MORE-recent state on an encrypt error.
530
+ var scratchBase = path.join(__dirname, "..", ".test-output");
531
+ fs.mkdirSync(scratchBase, { recursive: true });
532
+ var tmpDir = fs.mkdtempSync(path.join(scratchBase, "db-close-encfail-"));
533
+ var schema = [{ name: "close_t", columns: { _id: "TEXT PRIMARY KEY", v: "TEXT" } }];
534
+ try {
535
+ await setupTestDb(tmpDir, schema);
536
+ check("close-encfail test runs in encrypted mode", b.db.getMode() === "encrypted");
537
+ b.db.prepare("INSERT INTO close_t (_id, v) VALUES (?, ?)").run("c1", "kept");
538
+ await b.db.flushToDisk(); // db.enc now holds the prior snapshot
539
+
540
+ var workingDir = path.join(tmpDir, "tmpfs");
541
+ var workingFile = fs.readdirSync(workingDir).filter(function (f) { return /\.db$/.test(f); })[0];
542
+ var workingPath = path.join(workingDir, workingFile);
543
+ check("working copy exists before close", fs.existsSync(workingPath));
544
+
545
+ // Force the final encrypt to throw: replace db.enc with a directory so
546
+ // atomicFile's rename-into-place fails (portable across platforms).
547
+ var encPath = path.join(tmpDir, "db.enc");
548
+ fs.rmSync(encPath, { force: true });
549
+ fs.mkdirSync(encPath);
550
+
551
+ // The real close() (the appShutdown db-phase path), not _resetForTest.
552
+ b.db.close();
553
+
554
+ check("encrypt-failed close keeps the plaintext working copy for recovery",
555
+ fs.existsSync(workingPath));
556
+ } finally {
557
+ try { b.db._resetForTest(); } catch (_e) { /* best effort */ }
558
+ await teardownTestDb(tmpDir);
559
+ }
560
+ }
561
+
562
+ async function testTmpfsLowSpaceRefusesWritesFailClear() {
563
+ // When the encrypted-mode tmpfs working copy runs low on free space, the
564
+ // DB must REFUSE growth writes (INSERT/UPDATE/REPLACE) with a clear error
565
+ // instead of proceeding into an ENOSPC corruption. DELETE + reads stay
566
+ // available so retention can reclaim space and the app keeps serving. An
567
+ // injected statfs reader drives the probe deterministically.
568
+ var BYTES = b.constants.BYTES;
569
+ var scratchBase = path.join(__dirname, "..", ".test-output");
570
+ fs.mkdirSync(scratchBase, { recursive: true });
571
+ var tmpDir = fs.mkdtempSync(path.join(scratchBase, "db-lowspace-"));
572
+ var schema = [{ name: "space_t", columns: { _id: "TEXT PRIMARY KEY", v: "TEXT" } }];
573
+ var fakeFree = BYTES.mib(100); // start healthy
574
+ var fakeStatfs = function () { return { bavail: fakeFree, bsize: 1 }; };
575
+ try {
576
+ process.env.BLAMEJS_SKIP_NTP_CHECK = "1";
577
+ setTestPassphraseEnv();
578
+ b.cluster._resetForTest();
579
+ b.audit._resetForTest();
580
+ b.vault._resetForTest();
581
+ b.db._resetForTest();
582
+ await b.vault.init({ dataDir: tmpDir });
583
+ await b.db.init({
584
+ dataDir: tmpDir, tmpDir: path.join(tmpDir, "tmpfs"), schema: schema,
585
+ minFreeBytes: BYTES.mib(16), _statfsForTest: fakeStatfs,
586
+ });
587
+ check("low-space test runs in encrypted mode", b.db.getMode() === "encrypted");
588
+
589
+ b.db.prepare("INSERT INTO space_t (_id, v) VALUES (?, ?)").run("a", "1");
590
+ check("healthy free space → INSERT succeeds",
591
+ b.db.prepare("SELECT v FROM space_t WHERE _id = ?").get("a").v === "1");
592
+
593
+ // Drop below the threshold and force a probe.
594
+ fakeFree = BYTES.mib(1);
595
+ var st = b.db._probeStorageForTest();
596
+ check("low free space flips writesRefused", st.writesRefused === true);
597
+
598
+ var threw = null;
599
+ try { b.db.prepare("INSERT INTO space_t (_id, v) VALUES (?, ?)").run("bb", "2"); }
600
+ catch (e) { threw = e; }
601
+ check("low space → INSERT throws db/storage-low (fail-clear, not corruption)",
602
+ threw && threw.code === "db/storage-low");
603
+
604
+ // DELETE + reads must still work — the retention escape valve + serving.
605
+ var delThrew = null;
606
+ try { b.db.prepare("DELETE FROM space_t WHERE _id = ?").run("a"); } catch (e) { delThrew = e; }
607
+ check("low space → DELETE still allowed", delThrew === null);
608
+ check("low space → reads still allowed",
609
+ b.db.prepare("SELECT COUNT(*) AS n FROM space_t").get().n === 0);
610
+
611
+ // Recover: free space returns → flag clears → growth writes resume.
612
+ fakeFree = BYTES.mib(100);
613
+ var st2 = b.db._probeStorageForTest();
614
+ check("recovered free space clears writesRefused", st2.writesRefused === false);
615
+ var okErr = null;
616
+ try { b.db.prepare("INSERT INTO space_t (_id, v) VALUES (?, ?)").run("cc", "3"); }
617
+ catch (e) { okErr = e; }
618
+ check("recovered → INSERT succeeds again", okErr === null);
619
+ } finally {
620
+ try { b.db._resetForTest(); } catch (_e) { /* best effort */ }
621
+ await teardownTestDb(tmpDir);
622
+ }
623
+ }
624
+
625
+ async function testExitHandlerRegisteredOnce() {
626
+ // The process-exit final-flush handler must register ONCE for the process
627
+ // lifetime, not on every init(). Re-registering per init leaked an 'exit'
628
+ // listener on each init/close cycle (MaxListenersExceeded under long runs).
629
+ var scratchBase = path.join(__dirname, "..", ".test-output");
630
+ fs.mkdirSync(scratchBase, { recursive: true });
631
+ var schema = [{ name: "el_t", columns: { _id: "TEXT PRIMARY KEY" } }];
632
+ var before = process.listenerCount("exit");
633
+ for (var i = 0; i < 3; i++) {
634
+ var tmpDir = fs.mkdtempSync(path.join(scratchBase, "db-exit-listener-"));
635
+ try {
636
+ await setupTestDb(tmpDir, schema);
637
+ b.db._resetForTest();
638
+ } finally {
639
+ await teardownTestDb(tmpDir);
640
+ }
641
+ }
642
+ var added = process.listenerCount("exit") - before;
643
+ check("exit handler registered once across init/close cycles (no listener leak)", added <= 1);
644
+ }
645
+
459
646
  // ---- run() ----
460
647
 
461
648
  async function run() {
462
649
  // db basic
463
650
  await testDbBasic();
464
651
  await testUnsealRowNullsForgedValue();
652
+ await testEncryptedTmpfsCorruptionAutoRecovers();
653
+ await testEncryptedCloseKeepsPlaintextWhenEncryptFails();
654
+ await testTmpfsLowSpaceRefusesWritesFailClear();
655
+ await testExitHandlerRegisteredOnce();
465
656
  await testDbWriteOps();
466
657
  await testDbSealedWithoutDerived();
467
658
  await testDbTransactions();
@@ -38,6 +38,25 @@ async function testBasicGetPut() {
38
38
  check("hit2 replayCount = 2", hit2 && hit2.replayCount === 2);
39
39
  }
40
40
 
41
+ async function testInMemoryBackendBounded() {
42
+ // The default in-memory backend caps its entry count so a flood of
43
+ // distinct idempotency keys can't grow it without bound (OOM). Eviction
44
+ // is oldest-first — a dropped record just means that one key re-executes
45
+ // on retry, never a crash. Operators needing a hard guarantee at scale
46
+ // supply a durable opts.store.
47
+ var idem = b.agent.idempotency.create({ maxInMemoryEntries: 3 });
48
+ await idem.put("m", "u", "k1", { n: 1 });
49
+ await idem.put("m", "u", "k2", { n: 2 });
50
+ await idem.put("m", "u", "k3", { n: 3 });
51
+ check("at cap: oldest still present", (await idem.get("m", "u", "k1")) !== null);
52
+ // 4th distinct key pushes past the cap → evicts the oldest (k1).
53
+ await idem.put("m", "u", "k4", { n: 4 });
54
+ check("over cap: newest key retained", (await idem.get("m", "u", "k4")) !== null);
55
+ check("over cap: oldest key evicted", (await idem.get("m", "u", "k1")) === null);
56
+ check("over cap: middle keys retained",
57
+ (await idem.get("m", "u", "k2")) !== null && (await idem.get("m", "u", "k3")) !== null);
58
+ }
59
+
41
60
  async function testCrossActorIsolation() {
42
61
  var idem = b.agent.idempotency.create({});
43
62
  await idem.put("move", "u1", "shared-key", { changed: 1 });
@@ -275,6 +294,7 @@ async function run() {
275
294
  testSurface();
276
295
  await testAtRestSealingWithVault();
277
296
  await testBasicGetPut();
297
+ await testInMemoryBackendBounded();
278
298
  await testCrossActorIsolation();
279
299
  await testCrossMethodIsolation();
280
300
  await testKeyReuseDifferentArgs();
@@ -66,6 +66,38 @@ async function testList() {
66
66
  check("list filter tenant", aOnly.length === 2);
67
67
  }
68
68
 
69
+ async function testTenantScopeRegistryReads() {
70
+ // With tenantScope on, registry reads are scoped to the actor's tenant:
71
+ // an actor can't enumerate or acquire a handle to another tenant's agent
72
+ // (the leak agent-event-bus already prevented; orchestrator now mirrors).
73
+ var perms = {
74
+ check: function (actor, scope) {
75
+ // cross-tenant-admin only for actor "admin"; everyone may read.
76
+ if (scope === "framework-cross-tenant-admin") return !!(actor && actor.id === "admin");
77
+ return true;
78
+ },
79
+ };
80
+ var orch = b.agent.orchestrator.create({ tenantScope: true, permissions: perms });
81
+ var registrar = { id: "registrar", scopes: ["agent-registry:write"] };
82
+ await orch.register("ta.mail", _fakeAgent("a"), { agentKind: "mail", tenantId: "a", actor: registrar });
83
+ await orch.register("tb.mail", _fakeAgent("b"), { agentKind: "mail", tenantId: "b", actor: registrar });
84
+
85
+ var actorA = { id: "ua", tenantId: "a", scopes: ["agent-registry:read"] };
86
+ var listA = await orch.list({ actor: actorA });
87
+ check("tenant-scope list: actor sees only own-tenant agents",
88
+ listA.length === 1 && listA[0].tenantId === "a");
89
+ var ownLook = await orch.lookup("ta.mail", { actor: actorA });
90
+ check("tenant-scope lookup: own-tenant agent resolves", ownLook && typeof ownLook === "object");
91
+ var crossLook = await orch.lookup("tb.mail", { actor: actorA });
92
+ check("tenant-scope lookup: cross-tenant agent refused (null)", crossLook === null);
93
+
94
+ var admin = { id: "admin", tenantId: "ops", scopes: ["agent-registry:read", "framework-cross-tenant-admin"] };
95
+ var listAdmin = await orch.list({ actor: admin });
96
+ check("tenant-scope list: cross-tenant-admin sees all", listAdmin.length === 2);
97
+ var adminCross = await orch.lookup("ta.mail", { actor: admin });
98
+ check("tenant-scope lookup: cross-tenant-admin resolves any tenant", adminCross && typeof adminCross === "object");
99
+ }
100
+
69
101
  async function testGuardRefusals() {
70
102
  var orch = b.agent.orchestrator.create({});
71
103
  await expectRejection("register refuses bad name",
@@ -401,6 +433,7 @@ async function run() {
401
433
  testSurface();
402
434
  await testRegisterLookupUnregister();
403
435
  await testList();
436
+ await testTenantScopeRegistryReads();
404
437
  await testGuardRefusals();
405
438
  await testElect();
406
439
  await testElectCluster();