@blamejs/core 0.9.12 → 0.9.15

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 (119) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/lib/a2a.js +11 -11
  3. package/lib/acme.js +5 -5
  4. package/lib/ai-input.js +2 -2
  5. package/lib/api-key.js +4 -4
  6. package/lib/api-snapshot.js +10 -7
  7. package/lib/app-shutdown.js +2 -2
  8. package/lib/app.js +5 -5
  9. package/lib/archive.js +8 -8
  10. package/lib/argon2-builtin.js +2 -2
  11. package/lib/atomic-file.js +53 -53
  12. package/lib/audit-sign.js +8 -8
  13. package/lib/audit-tools.js +22 -22
  14. package/lib/audit.js +29 -17
  15. package/lib/auth/dpop.js +3 -3
  16. package/lib/auth/sd-jwt-vc.js +2 -2
  17. package/lib/backup/bundle.js +17 -17
  18. package/lib/backup/index.js +36 -36
  19. package/lib/budr.js +3 -3
  20. package/lib/bundler.js +20 -20
  21. package/lib/circuit-breaker.js +24 -9
  22. package/lib/cli.js +25 -26
  23. package/lib/cluster.js +2 -2
  24. package/lib/compliance-sanctions.js +2 -2
  25. package/lib/config-drift.js +15 -15
  26. package/lib/content-credentials.js +4 -4
  27. package/lib/credential-hash.js +3 -3
  28. package/lib/crypto.js +145 -0
  29. package/lib/daemon.js +19 -19
  30. package/lib/db-file-lifecycle.js +24 -24
  31. package/lib/db-schema.js +2 -2
  32. package/lib/db.js +35 -35
  33. package/lib/dev.js +10 -10
  34. package/lib/dr-runbook.js +5 -5
  35. package/lib/dsr.js +22 -15
  36. package/lib/dual-control.js +2 -2
  37. package/lib/external-db-migrate.js +2 -2
  38. package/lib/external-db.js +2 -2
  39. package/lib/fdx.js +2 -2
  40. package/lib/file-upload.js +30 -30
  41. package/lib/flag-providers.js +4 -4
  42. package/lib/gate-contract.js +5 -5
  43. package/lib/graphql-federation.js +4 -7
  44. package/lib/honeytoken.js +6 -6
  45. package/lib/http-client-cookie-jar.js +6 -6
  46. package/lib/http-client.js +18 -18
  47. package/lib/i18n.js +5 -5
  48. package/lib/inbox.js +21 -15
  49. package/lib/keychain.js +9 -9
  50. package/lib/legal-hold.js +2 -2
  51. package/lib/local-db-thin.js +9 -9
  52. package/lib/log-stream-local.js +17 -17
  53. package/lib/log-stream-syslog.js +2 -2
  54. package/lib/log-stream.js +3 -3
  55. package/lib/mail-bounce.js +2 -2
  56. package/lib/mail-mdn.js +2 -2
  57. package/lib/mail-srs.js +2 -2
  58. package/lib/mail.js +4 -4
  59. package/lib/mcp.js +2 -2
  60. package/lib/metrics.js +249 -2
  61. package/lib/middleware/api-encrypt.js +16 -16
  62. package/lib/middleware/body-parser.js +16 -16
  63. package/lib/middleware/compression.js +3 -3
  64. package/lib/middleware/csp-nonce.js +4 -4
  65. package/lib/middleware/health.js +7 -7
  66. package/lib/middleware/idempotency-key.js +250 -0
  67. package/lib/migrations.js +3 -3
  68. package/lib/mtls-ca.js +26 -26
  69. package/lib/mtls-engine-default.js +5 -5
  70. package/lib/network-dns.js +2 -2
  71. package/lib/network-nts.js +2 -2
  72. package/lib/network-proxy.js +3 -3
  73. package/lib/network-smtp-policy.js +2 -2
  74. package/lib/network-tls.js +17 -17
  75. package/lib/network.js +13 -13
  76. package/lib/notify.js +3 -3
  77. package/lib/object-store/gcs-bucket-ops.js +2 -2
  78. package/lib/object-store/gcs.js +5 -5
  79. package/lib/object-store/index.js +6 -6
  80. package/lib/object-store/local.js +19 -19
  81. package/lib/object-store/sigv4.js +3 -3
  82. package/lib/observability-tracer.js +4 -4
  83. package/lib/otel-export.js +3 -3
  84. package/lib/pagination.js +5 -5
  85. package/lib/parsers/safe-xml.js +3 -3
  86. package/lib/pqc-agent.js +116 -26
  87. package/lib/pqc-gate.js +5 -5
  88. package/lib/pubsub-redis.js +2 -2
  89. package/lib/queue-local.js +3 -3
  90. package/lib/queue.js +2 -2
  91. package/lib/redis-client.js +4 -4
  92. package/lib/restore-bundle.js +18 -18
  93. package/lib/restore-rollback.js +34 -34
  94. package/lib/restore.js +16 -16
  95. package/lib/retry.js +50 -0
  96. package/lib/router.js +13 -13
  97. package/lib/sandbox.js +8 -8
  98. package/lib/sec-cyber.js +3 -3
  99. package/lib/security-assert.js +2 -2
  100. package/lib/seeders.js +4 -4
  101. package/lib/self-update-standalone-verifier.js +280 -0
  102. package/lib/self-update.js +32 -26
  103. package/lib/session-device-binding.js +2 -2
  104. package/lib/static.js +22 -22
  105. package/lib/template.js +19 -19
  106. package/lib/testing.js +7 -7
  107. package/lib/tls-exporter.js +5 -5
  108. package/lib/tracing.js +3 -3
  109. package/lib/vault/index.js +11 -11
  110. package/lib/vault/passphrase-ops.js +37 -37
  111. package/lib/vault/passphrase-source.js +2 -2
  112. package/lib/vault/rotate.js +70 -66
  113. package/lib/vault/seal-pem-file.js +26 -26
  114. package/lib/watcher.js +23 -23
  115. package/lib/webhook.js +10 -10
  116. package/lib/worker-pool.js +6 -6
  117. package/lib/ws-client.js +4 -4
  118. package/package.json +1 -1
  119. package/sbom.cdx.json +6 -6
@@ -57,9 +57,9 @@
57
57
  * bun:sqlite).
58
58
  */
59
59
 
60
- var fs = require("fs");
60
+ var nodeFs = require("fs");
61
61
  var os = require("os");
62
- var path = require("path");
62
+ var nodePath = require("path");
63
63
  var atomicFile = require("./atomic-file");
64
64
  var C = require("./constants");
65
65
  var { generateBytes, generateToken, encryptPacked, decryptPacked } = require("./crypto");
@@ -92,7 +92,7 @@ function _resolveTmpDir(operatorTmpDir, allowDiskFallback) {
92
92
  // Linux: /dev/shm is the standard tmpfs mount.
93
93
  if (process.platform === "linux") {
94
94
  try {
95
- var st = fs.statSync("/dev/shm");
95
+ var st = nodeFs.statSync("/dev/shm");
96
96
  if (st && st.isDirectory()) return "/dev/shm";
97
97
  } catch (_e) { /* fall through */ }
98
98
  }
@@ -115,8 +115,8 @@ function _resolveTmpDir(operatorTmpDir, allowDiskFallback) {
115
115
  * Returns an encrypted-DB-file lifecycle handle. Methods:
116
116
  *
117
117
  * - `decryptToTmp()` — decrypt the encrypted DB file to a fresh
118
- * tmpfs path and return the path. Idempotent: subsequent calls
119
- * return the existing path.
118
+ * tmpfs path and return the nodePath. Idempotent: subsequent calls
119
+ * return the existing nodePath.
120
120
  * - `dbPath` — the resolved plaintext-tmpfs path (set after
121
121
  * `decryptToTmp()` runs).
122
122
  * - `startFlushTimer(db, opts?)` — start a periodic flush timer
@@ -164,15 +164,15 @@ function fileLifecycle(opts) {
164
164
  var label = opts.label || "default";
165
165
  var encName = opts.encryptedDbName || "db.enc";
166
166
  var encPath = opts.encryptedDbPath
167
- ? path.resolve(opts.encryptedDbPath)
168
- : path.join(opts.dataDir, encName);
167
+ ? nodePath.resolve(opts.encryptedDbPath)
168
+ : nodePath.join(opts.dataDir, encName);
169
169
  var keyPath = opts.dbKeyPath
170
- ? path.resolve(opts.dbKeyPath)
171
- : path.join(opts.dataDir, "db.key.enc");
170
+ ? nodePath.resolve(opts.dbKeyPath)
171
+ : nodePath.join(opts.dataDir, "db.key.enc");
172
172
  var flushIntervalMs = opts.flushIntervalMs || DEFAULT_FLUSH_INTERVAL_MS;
173
173
  var tmpDir = _resolveTmpDir(opts.tmpDir, opts.allowDiskFallback === true);
174
- if (!fs.existsSync(tmpDir)) fs.mkdirSync(tmpDir, { recursive: true });
175
- if (!fs.existsSync(opts.dataDir)) fs.mkdirSync(opts.dataDir, { recursive: true });
174
+ if (!nodeFs.existsSync(tmpDir)) nodeFs.mkdirSync(tmpDir, { recursive: true });
175
+ if (!nodeFs.existsSync(opts.dataDir)) nodeFs.mkdirSync(opts.dataDir, { recursive: true });
176
176
 
177
177
  var dbPath = null;
178
178
  var encKey = null;
@@ -181,8 +181,8 @@ function fileLifecycle(opts) {
181
181
 
182
182
  function _loadOrGenerateKey() {
183
183
  if (encKey) return encKey;
184
- if (fs.existsSync(keyPath)) {
185
- var sealedKey = fs.readFileSync(keyPath, "utf8");
184
+ if (nodeFs.existsSync(keyPath)) {
185
+ var sealedKey = nodeFs.readFileSync(keyPath, "utf8");
186
186
  var keyB64;
187
187
  try { keyB64 = opts.vault.unseal(sealedKey); }
188
188
  catch (e) {
@@ -208,10 +208,10 @@ function fileLifecycle(opts) {
208
208
  function decryptToTmp() {
209
209
  if (decrypted) return dbPath;
210
210
  _loadOrGenerateKey();
211
- dbPath = path.join(tmpDir, "blamejs-fl-" + label + "-" +
211
+ dbPath = nodePath.join(tmpDir, "blamejs-fl-" + label + "-" +
212
212
  generateToken(TMP_NAME_BYTES) + ".db");
213
- if (fs.existsSync(encPath)) {
214
- var packed = fs.readFileSync(encPath);
213
+ if (nodeFs.existsSync(encPath)) {
214
+ var packed = nodeFs.readFileSync(encPath);
215
215
  if (packed.length < 26) { // allow:raw-byte-literal — minimum envelope length
216
216
  throw new DbFileLifecycleError("db-file-lifecycle/short-envelope",
217
217
  "fileLifecycle: " + encPath + " too short to be a valid envelope (" + packed.length + " bytes)");
@@ -231,7 +231,7 @@ function fileLifecycle(opts) {
231
231
  label: label,
232
232
  encPath: encPath,
233
233
  dbPath: dbPath,
234
- isEmpty: !fs.existsSync(encPath),
234
+ isEmpty: !nodeFs.existsSync(encPath),
235
235
  });
236
236
  _emitMetric("decrypted");
237
237
  return dbPath;
@@ -246,8 +246,8 @@ function fileLifecycle(opts) {
246
246
  try { db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").run(); }
247
247
  catch (_e) { /* best-effort — operators on read-only handles or pre-init still flush */ }
248
248
  }
249
- if (!fs.existsSync(dbPath)) return null;
250
- var plain = fs.readFileSync(dbPath);
249
+ if (!nodeFs.existsSync(dbPath)) return null;
250
+ var plain = nodeFs.readFileSync(dbPath);
251
251
  var packed = encryptPacked(plain, encKey, _aad(opts.dataDir, label));
252
252
  atomicFile.writeSync(encPath, packed);
253
253
  _emitAudit("flushed", "success", { label: label, bytes: plain.length });
@@ -264,11 +264,11 @@ function fileLifecycle(opts) {
264
264
  try { db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").run(); }
265
265
  catch (_e) { /* best-effort */ }
266
266
  }
267
- if (!fs.existsSync(dbPath)) {
267
+ if (!nodeFs.existsSync(dbPath)) {
268
268
  throw new DbFileLifecycleError("db-file-lifecycle/no-source",
269
269
  "fileLifecycle.snapshot: " + dbPath + " is missing");
270
270
  }
271
- var plain = fs.readFileSync(dbPath);
271
+ var plain = nodeFs.readFileSync(dbPath);
272
272
  return encryptPacked(plain, encKey, _aad(opts.dataDir, label));
273
273
  }
274
274
 
@@ -308,9 +308,9 @@ function fileLifecycle(opts) {
308
308
  try { db.close(); } catch (_e) { /* best-effort */ }
309
309
  }
310
310
  if (fopts.removePlaintext === true && dbPath) {
311
- try { fs.unlinkSync(dbPath); } catch (_e) { /* best-effort */ }
312
- try { fs.unlinkSync(dbPath + "-wal"); } catch (_e) { /* best-effort */ }
313
- try { fs.unlinkSync(dbPath + "-shm"); } catch (_e) { /* best-effort */ }
311
+ try { nodeFs.unlinkSync(dbPath); } catch (_e) { /* best-effort */ }
312
+ try { nodeFs.unlinkSync(dbPath + "-wal"); } catch (_e) { /* best-effort */ }
313
+ try { nodeFs.unlinkSync(dbPath + "-shm"); } catch (_e) { /* best-effort */ }
314
314
  }
315
315
  _emitAudit("shutdown", "success", { label: label });
316
316
  }
package/lib/db-schema.js CHANGED
@@ -36,7 +36,7 @@
36
36
  * surfaces a rollback throw without
37
37
  * swallowing the original error.
38
38
  */
39
- var path = require("path");
39
+ var nodePath = require("path");
40
40
  var atomicFile = require("./atomic-file");
41
41
  var safeSql = require("./safe-sql");
42
42
 
@@ -280,7 +280,7 @@ function runMigrations(database, migrationDir) {
280
280
  skipped.push(file);
281
281
  continue;
282
282
  }
283
- var fullPath = path.join(migrationDir, file);
283
+ var fullPath = nodePath.join(migrationDir, file);
284
284
  var mig;
285
285
  try {
286
286
  // Operator-supplied migration file — by definition not statically
package/lib/db.js CHANGED
@@ -41,8 +41,8 @@
41
41
  * @card
42
42
  * Database core — SQLite (node:sqlite) wrapped in encrypted-at-rest storage, sealed-column field-level crypto, append-only audit-chain integration, declarative schema reconcile, and run-once migrations.
43
43
  */
44
- var fs = require("fs");
45
- var path = require("path");
44
+ var nodeFs = require("fs");
45
+ var nodePath = require("path");
46
46
  var { DatabaseSync } = require("node:sqlite");
47
47
  var { Readable } = require("node:stream");
48
48
  var atomicFile = require("./atomic-file");
@@ -92,7 +92,7 @@ var _dbErr = DbError.factory;
92
92
 
93
93
  // Lazy: cluster-storage's _localDb pulls db back in, so eager require
94
94
  // would deadlock the load order. cluster-storage is only used on the
95
- // purge-audit-chain external-db path, which always runs after init.
95
+ // purge-audit-chain external-db nodePath, which always runs after init.
96
96
  var clusterStorage = lazyRequire(function () { return require("./cluster-storage"); });
97
97
 
98
98
  // Lazy refs for the test-reset cascade. Each module requires db.js
@@ -639,7 +639,7 @@ function resolveTmpDir(optsTmpDir) {
639
639
  if (optsTmpDir) return optsTmpDir;
640
640
  var envTmp = safeEnv.readVar("BLAMEJS_TMPDIR");
641
641
  if (envTmp) return envTmp;
642
- if (fs.existsSync("/dev/shm")) return "/dev/shm";
642
+ if (nodeFs.existsSync("/dev/shm")) return "/dev/shm";
643
643
  return null;
644
644
  }
645
645
 
@@ -650,8 +650,8 @@ function loadOrCreateDbKey(dataDirPath, keyPathOverride) {
650
650
  // needs to live outside `dataDir` (e.g. a separate volume mounted
651
651
  // from a KMS-fronted secret store). Default places it next to the
652
652
  // encrypted DB so backup capture is one-tarball.
653
- var keyPath = keyPathOverride || path.join(dataDirPath, "db.key.enc");
654
- if (fs.existsSync(keyPath)) {
653
+ var keyPath = keyPathOverride || nodePath.join(dataDirPath, "db.key.enc");
654
+ if (nodeFs.existsSync(keyPath)) {
655
655
  var sealed = atomicFile.readSync(keyPath, { encoding: "utf8" }).trim();
656
656
  var b64 = vault.unseal(sealed);
657
657
  if (!b64) {
@@ -669,18 +669,18 @@ function loadOrCreateDbKey(dataDirPath, keyPathOverride) {
669
669
  }
670
670
 
671
671
  function decryptToTmp() {
672
- if (!encPath || !fs.existsSync(encPath)) return;
672
+ if (!encPath || !nodeFs.existsSync(encPath)) return;
673
673
  // If a plaintext file already exists in tmpfs from a prior process, prefer
674
674
  // the newer mtime (crash recovery — operator's most recent state wins).
675
- if (fs.existsSync(dbPath)) {
676
- var plainStat = fs.statSync(dbPath);
677
- var encStat = fs.statSync(encPath);
675
+ if (nodeFs.existsSync(dbPath)) {
676
+ var plainStat = nodeFs.statSync(dbPath);
677
+ var encStat = nodeFs.statSync(encPath);
678
678
  if (plainStat.mtimeMs > encStat.mtimeMs && plainStat.size > 0) {
679
679
  log("plaintext is newer than encrypted — keeping plaintext (crash recovery)");
680
680
  return;
681
681
  }
682
682
  }
683
- var packed = fs.readFileSync(encPath);
683
+ var packed = nodeFs.readFileSync(encPath);
684
684
  if (packed.length < 26) return; // too short to be a valid envelope
685
685
  // AAD binds the envelope to this deployment's data dir so two
686
686
  // installs sharing the same operator passphrase can't swap each
@@ -703,8 +703,8 @@ function encryptToDisk() {
703
703
  if (!encPath) return;
704
704
  // Force WAL checkpoint so the .db file holds all committed transactions.
705
705
  try { runSql(database, "PRAGMA wal_checkpoint(TRUNCATE)"); } catch (_e) { /* best effort */ }
706
- if (!fs.existsSync(dbPath)) return;
707
- atomicFile.writeSync(encPath, encryptPacked(fs.readFileSync(dbPath), encKey, _dbEncAad(dataDir)));
706
+ if (!nodeFs.existsSync(dbPath)) return;
707
+ atomicFile.writeSync(encPath, encryptPacked(nodeFs.readFileSync(dbPath), encKey, _dbEncAad(dataDir)));
708
708
  }
709
709
 
710
710
  /**
@@ -737,11 +737,11 @@ function snapshot() {
737
737
  // so the snapshot reflects the current logical state, not just the
738
738
  // pre-WAL pages.
739
739
  try { runSql(database, "PRAGMA wal_checkpoint(TRUNCATE)"); } catch (_e) { /* best effort */ }
740
- if (!fs.existsSync(dbPath)) {
740
+ if (!nodeFs.existsSync(dbPath)) {
741
741
  throw _dbErr("db/snapshot-no-source",
742
742
  "snapshot: plaintext DB at " + dbPath + " is missing — did init complete?");
743
743
  }
744
- var plain = fs.readFileSync(dbPath);
744
+ var plain = nodeFs.readFileSync(dbPath);
745
745
  if (!encPath || !encKey) {
746
746
  // atRest: 'plain' — return the raw bytes. Operators wanting an
747
747
  // encrypted snapshot under plain mode wrap with their own
@@ -756,9 +756,9 @@ function snapshot() {
756
756
  // database.close().
757
757
  function removePlaintextFiles() {
758
758
  if (!dbPath) return;
759
- try { fs.unlinkSync(dbPath); } catch (_e) { /* cleanup */ }
760
- try { fs.unlinkSync(dbPath + "-wal"); } catch (_e) { /* cleanup */ }
761
- try { fs.unlinkSync(dbPath + "-shm"); } catch (_e) { /* cleanup */ }
759
+ try { nodeFs.unlinkSync(dbPath); } catch (_e) { /* cleanup */ }
760
+ try { nodeFs.unlinkSync(dbPath + "-wal"); } catch (_e) { /* cleanup */ }
761
+ try { nodeFs.unlinkSync(dbPath + "-shm"); } catch (_e) { /* cleanup */ }
762
762
  }
763
763
 
764
764
  // Clean up stale plaintext DB files left by previously-crashed processes.
@@ -771,9 +771,9 @@ function cleanStaleTmpDbs(tmpDir) {
771
771
  for (var i = 0; i < entries.length; i++) {
772
772
  var full = entries[i].fullPath;
773
773
  if (full === dbPath) continue;
774
- try { fs.unlinkSync(full); } catch (_e) { /* concurrent cleanup */ }
775
- try { fs.unlinkSync(full + "-wal"); } catch (_e) { /* may not exist */ }
776
- try { fs.unlinkSync(full + "-shm"); } catch (_e) { /* may not exist */ }
774
+ try { nodeFs.unlinkSync(full); } catch (_e) { /* concurrent cleanup */ }
775
+ try { nodeFs.unlinkSync(full + "-wal"); } catch (_e) { /* may not exist */ }
776
+ try { nodeFs.unlinkSync(full + "-shm"); } catch (_e) { /* may not exist */ }
777
777
  }
778
778
  }
779
779
 
@@ -865,7 +865,7 @@ async function init(opts) {
865
865
  streamLimit = opts.streamLimit;
866
866
  }
867
867
  dataDir = opts.dataDir;
868
- if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
868
+ if (!nodeFs.existsSync(dataDir)) nodeFs.mkdirSync(dataDir, { recursive: true });
869
869
 
870
870
  if (atRest === "encrypted") {
871
871
  var tmpDir = resolveTmpDir(opts.tmpDir);
@@ -874,7 +874,7 @@ async function init(opts) {
874
874
  "FATAL: atRest: 'encrypted' (default) requires tmpfs but none was found. " +
875
875
  "Provide opts.tmpDir or set BLAMEJS_TMPDIR, or pass atRest: 'plain' (with warning).");
876
876
  }
877
- if (!fs.existsSync(tmpDir)) fs.mkdirSync(tmpDir, { recursive: true });
877
+ if (!nodeFs.existsSync(tmpDir)) nodeFs.mkdirSync(tmpDir, { recursive: true });
878
878
 
879
879
  // D-H7 — if the resolved tmpDir is NOT actually tmpfs, the
880
880
  // plaintext DB file lives on persistent storage. statvfs/statfs
@@ -884,7 +884,7 @@ async function init(opts) {
884
884
  // out-of-band.
885
885
  if (process.platform === "linux") {
886
886
  var realTmp = "";
887
- try { realTmp = fs.realpathSync(tmpDir); } catch (_e) { /* stat best-effort */ }
887
+ try { realTmp = nodeFs.realpathSync(tmpDir); } catch (_e) { /* stat best-effort */ }
888
888
  if (realTmp.indexOf("/dev/shm") !== 0 && realTmp.indexOf("/run/shm") !== 0 &&
889
889
  realTmp.indexOf("/run/user/") !== 0 && realTmp.indexOf("/tmp") !== 0) {
890
890
  log.warn("WARNING: db.init: tmpDir '" + tmpDir + "' (real: '" + realTmp +
@@ -894,13 +894,13 @@ async function init(opts) {
894
894
  }
895
895
  }
896
896
 
897
- // Operator overrides for the encrypted-DB on-disk path. `opts.encryptedDbPath`
898
- // takes a fully-qualified path; `opts.encryptedDbName` overrides
897
+ // Operator overrides for the encrypted-DB on-disk nodePath. `opts.encryptedDbPath`
898
+ // takes a fully-qualified nodePath; `opts.encryptedDbName` overrides
899
899
  // just the basename under `dataDir` (default "db.enc"). Helps when
900
900
  // multiple framework-shaped instances share a dataDir.
901
901
  encPath = opts.encryptedDbPath ||
902
- path.join(dataDir, opts.encryptedDbName || "db.enc");
903
- dbPath = path.join(tmpDir, "blamejs-" + generateToken(C.BYTES.bytes(16)) + ".db");
902
+ nodePath.join(dataDir, opts.encryptedDbName || "db.enc");
903
+ dbPath = nodePath.join(tmpDir, "blamejs-" + generateToken(C.BYTES.bytes(16)) + ".db");
904
904
  encKey = loadOrCreateDbKey(dataDir, opts.dbKeyPath);
905
905
 
906
906
  cleanStaleTmpDbs(tmpDir);
@@ -910,7 +910,7 @@ async function init(opts) {
910
910
  log.warn("WARNING: atRest: 'plain' — DB structure and row counts visible on disk.");
911
911
  log.warn(" Field-level encryption (sealedFields) still protects sealed columns,");
912
912
  log.warn(" but the simpler at-rest model is opt-out only. Default is 'encrypted'.");
913
- dbPath = path.join(dataDir, "blamejs.db");
913
+ dbPath = nodePath.join(dataDir, "blamejs.db");
914
914
  encPath = null;
915
915
  encKey = null;
916
916
  }
@@ -1479,7 +1479,7 @@ function stream(sql) {
1479
1479
  this.destroy(new DbError("db/stream-limit-exceeded",
1480
1480
  "db.stream: emitted " + emitted + " rows, exceeding streamLimit " +
1481
1481
  perCallLimit + ". Pass opts.streamLimit higher OR raise via " +
1482
- "db.init({ streamLimit }) after auditing the export path."));
1482
+ "db.init({ streamLimit }) after auditing the export nodePath."));
1483
1483
  return;
1484
1484
  }
1485
1485
  var step = iter.next();
@@ -1499,7 +1499,7 @@ function stream(sql) {
1499
1499
  // review can reconstruct schema evolution from the chain alone (D-M1).
1500
1500
  var DDL_RE = /^\s*(CREATE|DROP|ALTER|TRUNCATE|RENAME|ATTACH|DETACH|REINDEX)\b/i;
1501
1501
 
1502
- // D-L7 — slow-query observability buckets for the local SQLite path.
1502
+ // D-L7 — slow-query observability buckets for the local SQLite nodePath.
1503
1503
  // Highest matched bucket wins so the per-query emit is single-shot;
1504
1504
  // operators dashboard on the `bucket` label.
1505
1505
  var _SLOW_QUERY_BUCKETS_LOCAL = Object.freeze([
@@ -1907,7 +1907,7 @@ function exportCsv(opts) {
1907
1907
  * cluster leader, re-encrypts the live tmpfs database back to
1908
1908
  * `<dataDir>/db.enc`, closes the SQLite handle (releasing the file
1909
1909
  * lock on Windows), then unlinks the plaintext sidecar files in
1910
- * tmpfs. Safe to call multiple times — no-ops after the first
1910
+ * tmpnodeFs. Safe to call multiple times — no-ops after the first
1911
1911
  * successful close.
1912
1912
  *
1913
1913
  * @example
@@ -2327,8 +2327,8 @@ function eraseHard(tableName, rowId, opts) {
2327
2327
  // Read the audit.tip sidecar file in dataDir and compare to the current
2328
2328
  // audit_log MAX(monotonicCounter). Refuse boot on rollback (current < tip).
2329
2329
  function _checkRollback(dataDirPath) {
2330
- var tipPath = path.join(dataDirPath, "audit.tip");
2331
- if (!fs.existsSync(tipPath)) {
2330
+ var tipPath = nodePath.join(dataDirPath, "audit.tip");
2331
+ if (!nodeFs.existsSync(tipPath)) {
2332
2332
  log("no audit.tip sidecar — skipping rollback check (first boot or operator-cleared)");
2333
2333
  return;
2334
2334
  }
@@ -3104,7 +3104,7 @@ module.exports = {
3104
3104
  // Helper for audit.checkpoint to write the rollback-detection sidecar
3105
3105
  _writeAuditTip: function (tip) {
3106
3106
  if (!dataDir) return;
3107
- var tipPath = path.join(dataDir, "audit.tip");
3107
+ var tipPath = nodePath.join(dataDir, "audit.tip");
3108
3108
  atomicFile.writeSync(tipPath, JSON.stringify(tip, null, 2), { fileMode: 0o600 });
3109
3109
  },
3110
3110
  };
package/lib/dev.js CHANGED
@@ -11,7 +11,7 @@
11
11
  * spawned app's logs unchanged.
12
12
  *
13
13
  * The hot-reload loop spawns the app as a child process, watches the
14
- * source directories with `fs.watch({ recursive: true })`, and
14
+ * source directories with `nodeFs.watch({ recursive: true })`, and
15
15
  * restarts the child when an unignored file changes. On-disk state
16
16
  * (vault keys, encrypted DB, sealed cookies) survives the restart
17
17
  * because the child re-opens the files; only in-process state is
@@ -41,18 +41,18 @@
41
41
  *
42
42
  * Test seams: `opts._spawn(cmd, args, sopts)` and
43
43
  * `opts._watch(dir, wopts, listener)` default to `child_process.spawn`
44
- * and `fs.watch`; unit tests pass fakes to drive the engine without
44
+ * and `nodeFs.watch`; unit tests pass fakes to drive the engine without
45
45
  * real subprocesses.
46
46
  *
47
47
  * @card
48
48
  * Dev-mode helpers — hot-reload signal (file watch + child-process restart), route-list dump exposed via `dev.stats()`, and a request inspector courtesy of `stdio: 'inherit'` so the operator sees the spawned app's logs unchanged.
49
49
  */
50
50
 
51
- var path = require("path");
52
- var fs = require("fs");
51
+ var nodePath = require("path");
52
+ var nodeFs = require("fs");
53
53
  var lazyRequire = require("./lazy-require");
54
54
  var logModule = require("./log");
55
- var nb = require("./numeric-bounds");
55
+ var numericBounds = require("./numeric-bounds");
56
56
  var safeEnv = require("./parsers/safe-env");
57
57
  var validateOpts = require("./validate-opts");
58
58
  var { FrameworkError } = require("./framework-error");
@@ -166,11 +166,11 @@ function create(opts) {
166
166
  var ignore = Array.isArray(opts.ignore)
167
167
  ? DEFAULT_IGNORE.concat(opts.ignore)
168
168
  : DEFAULT_IGNORE.slice();
169
- nb.requireNonNegativeFiniteIntIfPresent(opts.graceMs,
169
+ numericBounds.requireNonNegativeFiniteIntIfPresent(opts.graceMs,
170
170
  "dev.create: opts.graceMs", DevError, "dev/bad-grace-ms");
171
171
  var graceMs = opts.graceMs !== undefined ? opts.graceMs : DEFAULT_GRACE_MS;
172
172
  var killSignal = typeof opts.killSignal === "string" ? opts.killSignal : DEFAULT_KILL_SIGNAL;
173
- nb.requireNonNegativeFiniteIntIfPresent(opts.killTimeoutMs,
173
+ numericBounds.requireNonNegativeFiniteIntIfPresent(opts.killTimeoutMs,
174
174
  "dev.create: opts.killTimeoutMs", DevError, "dev/bad-kill-timeout-ms");
175
175
  var killTimeoutMs = opts.killTimeoutMs !== undefined ? opts.killTimeoutMs : DEFAULT_KILL_TIMEOUT_MS;
176
176
  var log = opts.log || null;
@@ -198,7 +198,7 @@ function create(opts) {
198
198
  return childProcess().spawn(cmd, sargs, sopts);
199
199
  };
200
200
  var watchFn = opts._watch || function (dir, wopts, listener) {
201
- return fs.watch(dir, wopts, listener);
201
+ return nodeFs.watch(dir, wopts, listener);
202
202
  };
203
203
  var setTimeoutFn = opts._setTimeout || setTimeout;
204
204
  var clearTimeoutFn = opts._clearTimeout || clearTimeout;
@@ -313,7 +313,7 @@ function create(opts) {
313
313
  function _onWatchEvent(dir, eventType, filename) {
314
314
  if (!filename) return;
315
315
  var rel = String(filename);
316
- var full = path.join(dir, rel);
316
+ var full = nodePath.join(dir, rel);
317
317
  if (_matchesAny(ignore, rel) || _matchesAny(ignore, full)) return;
318
318
  _scheduleRestart(eventType + ":" + rel);
319
319
  }
@@ -321,7 +321,7 @@ function create(opts) {
321
321
  function _armWatchers() {
322
322
  for (var i = 0; i < watch.length; i++) {
323
323
  (function (dir) {
324
- var resolved = path.isAbsolute(dir) ? dir : path.resolve(cwd, dir);
324
+ var resolved = nodePath.isAbsolute(dir) ? dir : nodePath.resolve(cwd, dir);
325
325
  var w;
326
326
  try {
327
327
  w = watchFn(resolved, { recursive: true, persistent: false }, function (eventType, filename) {
package/lib/dr-runbook.js CHANGED
@@ -42,8 +42,8 @@
42
42
  * Disaster-recovery runbook executor — composes pre-recorded regulatory steps, operator confirmation gates, and the framework's audit chain into a posture-appropriate Markdown runbook a regulator can read alongside `b.audit`.
43
43
  */
44
44
 
45
- var fs = require("fs");
46
- var path = require("path");
45
+ var nodeFs = require("fs");
46
+ var nodePath = require("path");
47
47
  var C = require("./constants");
48
48
  var atomicFile = require("./atomic-file");
49
49
  var lazyRequire = require("./lazy-require");
@@ -333,11 +333,11 @@ async function emit(opts) {
333
333
  var body = sections.join("\n");
334
334
 
335
335
  // Ensure outDir exists.
336
- if (!fs.existsSync(opts.outDir)) {
337
- fs.mkdirSync(opts.outDir, { recursive: true });
336
+ if (!nodeFs.existsSync(opts.outDir)) {
337
+ nodeFs.mkdirSync(opts.outDir, { recursive: true });
338
338
  }
339
339
  var filename = opts.filename || ("runbook-" + opts.posture + ".md");
340
- var outPath = path.join(opts.outDir, filename);
340
+ var outPath = nodePath.join(opts.outDir, filename);
341
341
  atomicFile.writeSync(outPath, body, { fileMode: 0o644 });
342
342
 
343
343
  if (auditOn) {
package/lib/dsr.js CHANGED
@@ -113,6 +113,7 @@ var C = require("./constants");
113
113
  var bCrypto = require("./crypto");
114
114
  var lazyRequire = require("./lazy-require");
115
115
  var validateOpts = require("./validate-opts");
116
+ var safeSql = require("./safe-sql");
116
117
  var { defineClass } = require("./framework-error");
117
118
 
118
119
  var DsrError = defineClass("DsrError", { alwaysPermanent: true });
@@ -939,15 +940,21 @@ function dbTicketStore(opts) {
939
940
  throw new DsrError("dsr/bad-db",
940
941
  "dbTicketStore: opts.db must be a b.db-shaped handle (with runSql + prepare)");
941
942
  }
942
- var table = opts.table || "dsr_tickets";
943
- if (typeof table !== "string" || !/^[A-Za-z][A-Za-z0-9_]*$/.test(table)) {
943
+ var tableRaw = opts.table || "dsr_tickets";
944
+ var qTable, qEmailIdx, qStatusIdx;
945
+ try {
946
+ qTable = safeSql.quoteIdentifier(tableRaw, "sqlite");
947
+ qEmailIdx = safeSql.quoteIdentifier(tableRaw + "_email_idx", "sqlite");
948
+ qStatusIdx = safeSql.quoteIdentifier(tableRaw + "_status_idx", "sqlite");
949
+ } catch (sqlErr) {
944
950
  throw new DsrError("dsr/bad-table",
945
- "dbTicketStore: table must be a SQL identifier ([A-Za-z][A-Za-z0-9_]*)");
951
+ "dbTicketStore: table must be a valid SQL identifier: " +
952
+ (sqlErr && sqlErr.message ? sqlErr.message : String(sqlErr)));
946
953
  }
947
954
 
948
955
  // Auto-provision schema if not already present. Idempotent.
949
956
  function ensureSchema() {
950
- db.runSql("CREATE TABLE IF NOT EXISTS " + table + " (" +
957
+ db.runSql("CREATE TABLE IF NOT EXISTS " + qTable + " (" +
951
958
  "id TEXT PRIMARY KEY, " +
952
959
  "type TEXT NOT NULL, " +
953
960
  "status TEXT NOT NULL, " +
@@ -961,16 +968,16 @@ function dbTicketStore(opts) {
961
968
  "posture TEXT, " +
962
969
  "payload TEXT NOT NULL" +
963
970
  ")");
964
- db.runSql("CREATE INDEX IF NOT EXISTS " + table + "_email_idx ON " +
965
- table + " (subject_email)");
966
- db.runSql("CREATE INDEX IF NOT EXISTS " + table + "_status_idx ON " +
967
- table + " (status)");
971
+ db.runSql("CREATE INDEX IF NOT EXISTS " + qEmailIdx + " ON " +
972
+ qTable + " (subject_email)");
973
+ db.runSql("CREATE INDEX IF NOT EXISTS " + qStatusIdx + " ON " +
974
+ qTable + " (status)");
968
975
  }
969
976
  ensureSchema();
970
977
 
971
978
  return {
972
979
  insert: async function (ticket) {
973
- var stmt = db.prepare("INSERT INTO " + table +
980
+ var stmt = db.prepare("INSERT INTO " + qTable +
974
981
  " (id, type, status, subject_id, subject_email, subject_phone, " +
975
982
  " submitted_at, deadline_at, processed_at, verification_level, posture, payload) " +
976
983
  " VALUES ($id, $type, $status, $sid, $email, $phone, $submittedAt, " +
@@ -991,14 +998,14 @@ function dbTicketStore(opts) {
991
998
  });
992
999
  },
993
1000
  get: async function (id) {
994
- var rows = db.prepare("SELECT payload FROM " + table + " WHERE id = $id")
1001
+ var rows = db.prepare("SELECT payload FROM " + qTable + " WHERE id = $id")
995
1002
  .all({ $id: id });
996
1003
  if (!rows || rows.length === 0) return null;
997
1004
  return JSON.parse(rows[0].payload); // allow:bare-json-parse — payload was JSON.stringify-ed by this same store, never from operator/network input
998
1005
  },
999
1006
  list: async function (filter) {
1000
1007
  filter = filter || {};
1001
- var sql = "SELECT payload FROM " + table;
1008
+ var sql = "SELECT payload FROM " + qTable;
1002
1009
  var conds = [];
1003
1010
  var params = {};
1004
1011
  if (filter.status) {
@@ -1021,7 +1028,7 @@ function dbTicketStore(opts) {
1021
1028
  return rows.map(function (r) { return JSON.parse(r.payload); }); // allow:bare-json-parse — payload was JSON.stringify-ed by this same store, never from operator/network input
1022
1029
  },
1023
1030
  update: async function (id, ticket) {
1024
- var stmt = db.prepare("UPDATE " + table + " SET " +
1031
+ var stmt = db.prepare("UPDATE " + qTable + " SET " +
1025
1032
  " type = $type, status = $status, subject_id = $sid, " +
1026
1033
  " subject_email = $email, subject_phone = $phone, " +
1027
1034
  " submitted_at = $submittedAt, deadline_at = $deadlineAt, " +
@@ -1051,10 +1058,10 @@ function dbTicketStore(opts) {
1051
1058
  // Bulk-delete tickets in terminal states whose retentionUntil
1052
1059
  // is in the past. Returns the number of rows removed.
1053
1060
  var asOf = (typeof asOfMs === "number" && isFinite(asOfMs)) ? asOfMs : Date.now();
1054
- var rows = db.prepare("SELECT id, payload FROM " + table +
1061
+ var rows = db.prepare("SELECT id, payload FROM " + qTable +
1055
1062
  " WHERE status IN ('completed','partially_completed','cancelled','rejected','expired')").all({});
1056
1063
  var purged = 0;
1057
- var del = db.prepare("DELETE FROM " + table + " WHERE id = $id");
1064
+ var del = db.prepare("DELETE FROM " + qTable + " WHERE id = $id");
1058
1065
  for (var i = 0; i < rows.length; i++) {
1059
1066
  try {
1060
1067
  var t = JSON.parse(rows[i].payload); // allow:bare-json-parse — payload was JSON.stringify-ed by this same store, never from operator/network input
@@ -1066,7 +1073,7 @@ function dbTicketStore(opts) {
1066
1073
  }
1067
1074
  return purged;
1068
1075
  },
1069
- _table: table,
1076
+ _table: tableRaw,
1070
1077
  _ensureSchema: ensureSchema,
1071
1078
  };
1072
1079
  }
@@ -31,7 +31,7 @@
31
31
  * M-of-N approval workflow for destructive operations (eraseHard, key rotation, etc.).
32
32
  */
33
33
  var lazyRequire = require("./lazy-require");
34
- var crypto = require("./crypto");
34
+ var bCrypto = require("./crypto");
35
35
  var requestHelpers = require("./request-helpers");
36
36
  var validateOpts = require("./validate-opts");
37
37
  var C = require("./constants");
@@ -261,7 +261,7 @@ function create(opts) {
261
261
  if (reasonProblem) {
262
262
  return Object.assign({ grantId: null }, reasonProblem);
263
263
  }
264
- var grantId = "dc-" + crypto.generateToken(C.BYTES.bytes(8));
264
+ var grantId = "dc-" + bCrypto.generateToken(C.BYTES.bytes(8));
265
265
  var nowMs = Date.now();
266
266
  var record = {
267
267
  grantId: grantId,
@@ -48,7 +48,7 @@
48
48
  * - externaldb.migrate.lock.acquired { holder }
49
49
  * - externaldb.migrate.lock.released { holder }
50
50
  */
51
- var path = require("path");
51
+ var nodePath = require("path");
52
52
  var atomicFile = require("./atomic-file");
53
53
  var canonicalJson = require("./canonical-json");
54
54
  var { sha3Hash } = require("./crypto");
@@ -285,7 +285,7 @@ function _list(dir) {
285
285
  }
286
286
 
287
287
  function _loadMigration(file, dir) {
288
- var fullPath = path.join(dir, file);
288
+ var fullPath = nodePath.join(dir, file);
289
289
  // Drop the require cache so a test/dev that edits a file picks up the
290
290
  // new content. Matches lib/migrations.js semantics.
291
291
  try { delete require.cache[require.resolve(fullPath)]; } catch (_e) { /* not yet cached */ }
@@ -754,8 +754,8 @@ async function transaction(fn, opts) {
754
754
  if (isTransient && attempt <= maxRetries) {
755
755
  _emitMetric("externaldb.transaction.retry", 1,
756
756
  { backend: b.name, code: txErr.code, attempt: String(attempt) });
757
- var nodeCryptoRetry = require("node:crypto");
758
- var jitter = nodeCryptoRetry.randomInt(0, 6); // allow:raw-byte-literal — 0-5ms jitter
757
+ var nodeCrypto = require("node:crypto");
758
+ var jitter = nodeCrypto.randomInt(0, 6); // allow:raw-byte-literal — 0-5ms jitter
759
759
  await safeAsync.sleep(attempt * 5 + jitter); // allow:raw-time-literal — sub-second backoff
760
760
  continue;
761
761
  }
package/lib/fdx.js CHANGED
@@ -85,7 +85,7 @@ var fapi2 = require("./fapi2");
85
85
  var C = require("./constants");
86
86
  var audit = require("./audit");
87
87
  var validateOpts = require("./validate-opts");
88
- var nb = require("./numeric-bounds");
88
+ var numericBounds = require("./numeric-bounds");
89
89
  var { defineClass } = require("./framework-error");
90
90
  var FdxError = defineClass("FdxError", { alwaysPermanent: true });
91
91
 
@@ -327,7 +327,7 @@ function consentReceipt(opts) {
327
327
  throw FdxError.factory("BAD_SCOPES",
328
328
  "fdx.consentReceipt: scopes must be a non-empty array");
329
329
  }
330
- nb.requirePositiveFiniteIntIfPresent(opts.durationMs,
330
+ numericBounds.requirePositiveFiniteIntIfPresent(opts.durationMs,
331
331
  "fdx.consentReceipt: durationMs", FdxError, "BAD_DURATION");
332
332
 
333
333
  var issuedAt = Date.now();