@blamejs/core 0.4.1

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 (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
package/lib/cluster.js ADDED
@@ -0,0 +1,691 @@
1
+ "use strict";
2
+ /**
3
+ * Cluster coordination — leader election + fencing tokens.
4
+ *
5
+ * Opt-in via `b.cluster.init(...)`. When init is never called, the
6
+ * local process behaves as a permanent single leader: `isLeader()`
7
+ * always returns true, `fencingToken()` returns 0, no heartbeat thread
8
+ * runs, no DB is touched. Single-node deployments pay zero overhead.
9
+ *
10
+ * When init IS called, the framework starts a heartbeat that renews
11
+ * the leader lease via the configured provider. On lease loss (network
12
+ * partition, takeover, lease expiry) the node transitions to follower
13
+ * and write-side framework primitives throw `NotLeaderError`.
14
+ *
15
+ * Threat model:
16
+ * - Two leaders writing simultaneously: prevented by fencing tokens.
17
+ * Every leader-only DB write includes the current token; a
18
+ * CHECK constraint on the audit-tip row rejects a stale token.
19
+ * The application-layer `requireLeader()` gate is just an early
20
+ * rejection optimisation; the DB constraint is the canonical guard.
21
+ * - Follower receiving a write: rejected at the framework boundary.
22
+ * Operators front the cluster with a load balancer that routes
23
+ * write paths to the current leader.
24
+ * - External-db unreachable: heartbeat fails; after `leaseTtl` no
25
+ * leader exists and writes fail closed. When the DB recovers,
26
+ * election resumes.
27
+ *
28
+ * Public API:
29
+ * await cluster.init(opts) one-time bootstrap
30
+ * cluster.isLeader() sync; true on leader (or single-node)
31
+ * cluster.currentNodeId() sync; configured nodeId
32
+ * cluster.endpoint() sync; this node's routable URL
33
+ * (operator-supplied at init), or
34
+ * null if unconfigured. Stored in
35
+ * the leader-election row so
36
+ * external observers can resolve
37
+ * "where is the current leader?"
38
+ * cluster.fencingToken() sync; current monotonic token
39
+ * cluster.requireLeader() sync; throws NotLeaderError
40
+ * cluster.currentLeader() async; { nodeId, leaseExpiresAt,
41
+ * fencingToken,
42
+ * endpoint } | null
43
+ * cluster.discoveryHandler() returns an HTTP request handler
44
+ * (req, res) → JSON. Mount on any
45
+ * route to expose the current
46
+ * leader for service-mesh / LB
47
+ * consumption. 200 with leader,
48
+ * 503 with `{ leader: null }`
49
+ * when no leader.
50
+ * cluster.onTransition(fn) register transition handler
51
+ * await cluster.shutdown() releases lease, stops heartbeat
52
+ */
53
+ var C = require("./constants");
54
+ var { boot } = require("./log");
55
+ var safeUrl = require("./safe-url");
56
+ var { FrameworkError, ClusterError } = require("./framework-error");
57
+
58
+ var DEFAULT_LEASE_TTL = C.TIME.seconds(30);
59
+ var DEFAULT_HEARTBEAT = C.TIME.seconds(10);
60
+ var MIN_LEASE_TTL = C.TIME.seconds(5);
61
+ var MIN_HEARTBEAT = C.TIME.seconds(1);
62
+
63
+ var initialized = false;
64
+ var terminated = false; // set true by shutdown() so the
65
+ // permanent-leader fallback isn't
66
+ // re-engaged after a graceful exit
67
+ var nodeId = null;
68
+ var role = null; // 'leader' | 'follower'
69
+ var provider = null;
70
+ var lease = null; // current lease (if leader)
71
+ var heartbeatTimer = null;
72
+ var heartbeatMs = null;
73
+ var leaseTtlMs = null;
74
+ var transitionHandlers = [];
75
+ // Backend coordinates for write-dispatch code in audit/consent/etc.
76
+ // These are set when cluster.init is called with `externalDbBackend`
77
+ // (the default DB-row provider path); operators using a custom
78
+ // provider can set them via init opts directly.
79
+ var configuredExternalDbBackend = null;
80
+ var configuredDialect = null;
81
+ // Operator-supplied routable endpoint for THIS node, used by external
82
+ // load balancers / service meshes to learn where to send write traffic.
83
+ // Stored in the leader-election row on every acquire/renew so any node
84
+ // (or external observer) can resolve "where is the current leader?"
85
+ // via cluster.currentLeader() / cluster.discoveryHandler().
86
+ var configuredEndpoint = null;
87
+
88
+ var log = boot("cluster");
89
+
90
+ class NotLeaderError extends FrameworkError {
91
+ constructor(message) {
92
+ super(message || "not leader: write rejected by cluster gate", "NOT_LEADER");
93
+ this.name = "NotLeaderError";
94
+ this.statusCode = 503; // operator's load balancer should retry on the leader
95
+ this.isClusterError = true;
96
+ this.isNotLeaderError = true;
97
+ }
98
+ }
99
+
100
+ var _err = ClusterError.factory;
101
+
102
+ function _emitTransition(kind, detail) {
103
+ var event = Object.assign({ kind: kind, nodeId: nodeId, at: Date.now() }, detail || {});
104
+ for (var i = 0; i < transitionHandlers.length; i++) {
105
+ try { transitionHandlers[i](event); }
106
+ catch (e) { log.error("transition handler threw: " + e.message); }
107
+ }
108
+ }
109
+
110
+ // ---- init ----
111
+
112
+ async function init(opts) {
113
+ if (initialized) {
114
+ throw _err("ALREADY_INITIALIZED", "cluster.init() called twice", true);
115
+ }
116
+ opts = opts || {};
117
+ if (!opts.nodeId) {
118
+ throw _err("INVALID_CONFIG", "cluster.init({ nodeId }) is required", true);
119
+ }
120
+ nodeId = String(opts.nodeId);
121
+
122
+ leaseTtlMs = opts.leaseTtl != null ? Number(opts.leaseTtl) : DEFAULT_LEASE_TTL;
123
+ if (leaseTtlMs < MIN_LEASE_TTL) {
124
+ throw _err("INVALID_TTL",
125
+ "leaseTtl must be >= " + MIN_LEASE_TTL + "ms (got " + leaseTtlMs + ")",
126
+ true);
127
+ }
128
+ heartbeatMs = opts.heartbeatInterval != null
129
+ ? Number(opts.heartbeatInterval)
130
+ : DEFAULT_HEARTBEAT;
131
+ if (heartbeatMs < MIN_HEARTBEAT) {
132
+ throw _err("INVALID_HEARTBEAT",
133
+ "heartbeatInterval must be >= " + MIN_HEARTBEAT + "ms (got " + heartbeatMs + ")",
134
+ true);
135
+ }
136
+ if (heartbeatMs >= leaseTtlMs) {
137
+ throw _err("INVALID_HEARTBEAT",
138
+ "heartbeatInterval must be < leaseTtl (got heartbeat=" + heartbeatMs +
139
+ ", leaseTtl=" + leaseTtlMs + "); recommend ~1/3 of leaseTtl",
140
+ true);
141
+ }
142
+
143
+ role = (opts.role || "leader").toLowerCase();
144
+ if (role !== "leader" && role !== "follower") {
145
+ throw _err("INVALID_ROLE", "role must be 'leader' or 'follower'", true);
146
+ }
147
+
148
+ // Optional endpoint. If provided, validate scheme + shape via url-safe
149
+ // — HTTPS-only by default since this is the URL external services use
150
+ // to reach the leader. Operators with internal cleartext clusters opt
151
+ // in via opts.allowedProtocols (safeUrl.ALLOW_HTTP_ALL).
152
+ if (opts.endpoint != null) {
153
+ try {
154
+ safeUrl.parse(opts.endpoint, {
155
+ allowedProtocols: opts.allowedProtocols || safeUrl.ALLOW_HTTP_TLS,
156
+ errorClass: ClusterError,
157
+ });
158
+ } catch (e) {
159
+ // Re-throw with a config-shaped error so operators see the cluster.init
160
+ // boundary, not a bare url-safe trace.
161
+ throw _err("INVALID_ENDPOINT",
162
+ "cluster.init({ endpoint }) rejected: " + e.message, true);
163
+ }
164
+ configuredEndpoint = String(opts.endpoint);
165
+ } else {
166
+ configuredEndpoint = null;
167
+ }
168
+
169
+ if (typeof opts.onTransition === "function") {
170
+ transitionHandlers.push(opts.onTransition);
171
+ }
172
+
173
+ // Provider: either operator-supplied, or build the default DB-row
174
+ // provider against an externalDb backend.
175
+ if (opts.provider) {
176
+ provider = opts.provider;
177
+ // Operator-custom provider: they may still be writing framework
178
+ // state to an externalDb backend, in which case they pass these
179
+ // separately so write-dispatch code knows where to go.
180
+ configuredExternalDbBackend = opts.externalDbBackend || null;
181
+ configuredDialect = (opts.dialect || "postgres").toLowerCase();
182
+ } else {
183
+ if (!opts.externalDbBackend) {
184
+ throw _err("INVALID_CONFIG",
185
+ "cluster.init requires either { provider } or { externalDbBackend }", true);
186
+ }
187
+ var dbProvider = require("./cluster-provider-db");
188
+ provider = dbProvider.create({
189
+ externalDbBackend: opts.externalDbBackend,
190
+ dialect: opts.dialect,
191
+ });
192
+ configuredExternalDbBackend = opts.externalDbBackend;
193
+ configuredDialect = (opts.dialect || "postgres").toLowerCase();
194
+ }
195
+
196
+ if (typeof provider.ensureSchema === "function") {
197
+ await provider.ensureSchema();
198
+ }
199
+
200
+ initialized = true;
201
+ log("initialized as nodeId='" + nodeId + "', role='" + role + "'");
202
+
203
+ // Initial acquisition attempt (only if role === 'leader')
204
+ if (role === "leader") {
205
+ await _tryAcquire();
206
+ }
207
+
208
+ // Boot-time rollback detection on the audit + consent chains. Runs
209
+ // regardless of role — every node should refuse to participate in a
210
+ // cluster whose shared chains have been rolled back (a follower
211
+ // would face the same chain integrity failure if it later took
212
+ // over). Skipped when configuredExternalDbBackend is unset, which
213
+ // means a custom provider is in use without externalDb-resident
214
+ // framework state — the operator owns rollback detection in that
215
+ // case.
216
+ if (configuredExternalDbBackend) {
217
+ await _checkChainTipRollback("audit", "_blamejs_audit_log", "_blamejs_audit_tip");
218
+ await _checkChainTipRollback("consent", "_blamejs_consent_log", "_blamejs_consent_tip");
219
+ // Vault-key consistency: every node in a cluster must hold the
220
+ // SAME vault key. A node booting with a different key would seal
221
+ // new writes under a key the rest of the cluster can't unseal,
222
+ // and (on takeover) be unable to unseal the rest of the cluster's
223
+ // sealed columns — silent corruption. Compare a fingerprint of
224
+ // this node's vault keys against the canonical one stored at
225
+ // first cluster boot; refuse to participate on mismatch.
226
+ await _checkVaultKeyConsistency();
227
+ }
228
+
229
+ // Start heartbeat
230
+ heartbeatTimer = setInterval(_heartbeat, heartbeatMs);
231
+ heartbeatTimer.unref();
232
+ }
233
+
234
+ // Cluster-mode equivalent of db.js's single-node audit.tip-sidecar
235
+ // rollback check. Reads the persistent _blamejs_audit_tip row and
236
+ // compares to the current chain head in _blamejs_audit_log:
237
+ //
238
+ // - No tip row: first cluster boot or operator-cleared. Skip
239
+ // silently (matches the single-node sidecar-missing path).
240
+ // - Tip recorded a counter > current MAX: chain was truncated /
241
+ // restored from older snapshot. FATAL — refuse boot.
242
+ // - Tip recorded a hash that doesn't match the row at that
243
+ // counter: the row at that counter was substituted (different
244
+ // hash for same counter). FATAL — refuse boot.
245
+ //
246
+ // process.exit(1) is the framework's convention for boot-time
247
+ // integrity failures (audit chain, checkpoints, single-node
248
+ // rollback). Cluster mode keeps the same posture so operators see
249
+ // a single boot-time failure mode regardless of deployment shape.
250
+ // Generalized boot-time rollback check used by both audit and consent
251
+ // chains. chainName is the human-readable label included in log
252
+ // output ("audit" / "consent"). logTable is the chain table
253
+ // (_blamejs_audit_log / _blamejs_consent_log). tipTable is the
254
+ // single-row coordination table that records the latest counter +
255
+ // rowHash + fencingToken (_blamejs_audit_tip / _blamejs_consent_tip).
256
+ //
257
+ // Surfaces three outcomes:
258
+ // - tip table missing → operator running cluster gates-only mode
259
+ // (cluster wired for leader election but framework state still
260
+ // lives in per-node SQLite without `frameworkSchema.ensureSchema`);
261
+ // skip silently.
262
+ // - no tip row → first cluster boot or operator-cleared; skip.
263
+ // - currentMax < tipCounter, or tip rowHash != row-at-counter
264
+ // hash → FATAL via process.exit(1). Same posture as the
265
+ // single-node audit.tip sidecar rollback check.
266
+ async function _checkChainTipRollback(chainName, logTable, tipTable) {
267
+ // Lazy require because external-db isn't available before
268
+ // cluster.init (and cluster is required from many subsystems —
269
+ // a top-of-file require would form a circular load with
270
+ // external-db's audit emit path).
271
+ var externalDb = require("./external-db");
272
+
273
+ var tipRows;
274
+ try {
275
+ tipRows = await externalDb.query(
276
+ "SELECT atMonotonicCounter, rowHash FROM " + tipTable +
277
+ " WHERE scope = '" + chainName + "'",
278
+ [],
279
+ { backend: configuredExternalDbBackend }
280
+ );
281
+ } catch (e) {
282
+ var msg = (e && e.message) || "";
283
+ if (/no such table|does not exist|relation .* does not exist/i.test(msg)) {
284
+ log(chainName + "-tip table not present — skipping rollback check (cluster gates-only mode)");
285
+ return;
286
+ }
287
+ throw e;
288
+ }
289
+ if (!tipRows.rows || tipRows.rows.length === 0) {
290
+ log("no " + chainName + "-tip row — skipping rollback check (first cluster boot or operator-cleared)");
291
+ return;
292
+ }
293
+ var tip = tipRows.rows[0];
294
+ var tipCounter = Number(tip.atMonotonicCounter);
295
+ var tipHash = tip.rowHash;
296
+
297
+ var currentRows = await externalDb.query(
298
+ "SELECT MAX(monotonicCounter) AS m FROM " + logTable,
299
+ [],
300
+ { backend: configuredExternalDbBackend }
301
+ );
302
+ var currentMax = (currentRows.rows && currentRows.rows[0] && currentRows.rows[0].m)
303
+ ? Number(currentRows.rows[0].m)
304
+ : 0;
305
+
306
+ if (currentMax < tipCounter) {
307
+ log.error("FATAL: cluster-mode " + chainName + "-log rollback detected.");
308
+ log.error(" " + chainName + "-tip counter: " + tipCounter);
309
+ log.error(" current external-db max: " + currentMax);
310
+ log.error("Either external-db was restored from an older snapshot, or " +
311
+ logTable + " rows have been deleted. Investigate before continuing.");
312
+ process.exit(1);
313
+ }
314
+
315
+ if (tipHash) {
316
+ var hashRows = await externalDb.query(
317
+ "SELECT rowHash FROM " + logTable + " WHERE monotonicCounter = " +
318
+ (configuredDialect === "postgres" ? "$1" : "?"),
319
+ [tipCounter],
320
+ { backend: configuredExternalDbBackend }
321
+ );
322
+ if (hashRows.rows && hashRows.rows.length > 0) {
323
+ var rowAtTip = hashRows.rows[0].rowHash;
324
+ if (rowAtTip !== tipHash) {
325
+ log.error("FATAL: cluster-mode " + chainName + "-log rollback detected (row-hash mismatch).");
326
+ log.error(" " + chainName + "-tip counter: " + tipCounter);
327
+ log.error(" " + chainName + "-tip rowHash: " + tipHash);
328
+ log.error(" current row rowHash: " + rowAtTip);
329
+ log.error("The row at the recorded tip counter has a different hash — " +
330
+ "indicates row substitution at the chain head. Investigate before continuing.");
331
+ process.exit(1);
332
+ }
333
+ }
334
+ }
335
+ log("cluster " + chainName + "-tip rollback check ok (tip counter " + tipCounter +
336
+ ", current " + currentMax + ")");
337
+ }
338
+
339
+ // Compute a deterministic fingerprint of THIS node's vault keys.
340
+ // SHA3-512 of the concatenated public keys (PQC + classical halves of
341
+ // the hybrid encryption keypair). One-way: nothing about the private
342
+ // key material is recoverable from the fingerprint, so it's safe to
343
+ // store in the coordination table that all cluster nodes can read.
344
+ //
345
+ // Returns null if vault.init() hasn't been called — cluster gates-only
346
+ // mode (no sealed-column work) doesn't need this check, same defensive
347
+ // posture as the audit-tip rollback check skipping when there's no
348
+ // audit-tip table.
349
+ function _vaultKeyFingerprint() {
350
+ // Lazy require to avoid the circular load risk: vault → db → cluster
351
+ // (the audit module pulls cluster in, db loads audit at init).
352
+ var vault = require("./vault");
353
+ var crypto = require("./crypto");
354
+ var safeJson = require("./safe-json");
355
+ var keysJson;
356
+ try {
357
+ keysJson = vault.getKeysJson();
358
+ } catch (e) {
359
+ // vault.init() not called — gates-only mode. Skip silently.
360
+ if (/vault.init\(\) must be awaited/.test((e && e.message) || "")) {
361
+ return null;
362
+ }
363
+ throw e;
364
+ }
365
+ // vault.getKeysJson() returns the keys serialized as JSON (the same
366
+ // format vault writes to disk). Parse to extract the public halves;
367
+ // we never touch privateKey/ecPrivateKey here.
368
+ var keys = safeJson.parse(keysJson);
369
+ if (!keys || !keys.publicKey || !keys.ecPublicKey) return null;
370
+ // Domain-separation prefix so this fingerprint can't be confused
371
+ // with a hash of the same bytes computed elsewhere in the framework.
372
+ return crypto.sha3Hash("blamejs/cluster-state/v1\n" +
373
+ keys.publicKey + "\n" +
374
+ keys.ecPublicKey);
375
+ }
376
+
377
+ async function _checkVaultKeyConsistency() {
378
+ var localFp = _vaultKeyFingerprint();
379
+ if (localFp === null) {
380
+ log("vault not initialized — skipping vault-key consistency check (cluster gates-only mode)");
381
+ return;
382
+ }
383
+ var externalDb = require("./external-db");
384
+ var nowMs = Date.now();
385
+ var ph = configuredDialect === "postgres";
386
+
387
+ // First boot: try to record THIS node's fingerprint. ON CONFLICT DO
388
+ // NOTHING means the FIRST node to boot wins; subsequent nodes
389
+ // observe whatever's already there. Every node then SELECTs and
390
+ // compares — any mismatch (including ours after a losing race)
391
+ // surfaces the drift.
392
+ try {
393
+ await externalDb.query(
394
+ "INSERT INTO _blamejs_cluster_state " +
395
+ " (scope, vaultKeyFp, recordedAt, recordedByNode) " +
396
+ "VALUES ('state', " +
397
+ (ph ? "$1, $2, $3" : "?, ?, ?") + ") " +
398
+ "ON CONFLICT (scope) DO NOTHING",
399
+ [localFp, nowMs, nodeId],
400
+ { backend: configuredExternalDbBackend }
401
+ );
402
+ } catch (e) {
403
+ // Table missing → the cluster-provider-db ensureSchema didn't run
404
+ // (custom provider that doesn't create _blamejs_cluster_state).
405
+ // Skip silently — same defensive posture as the audit-tip check.
406
+ var msg = (e && e.message) || "";
407
+ if (/no such table|does not exist|relation .* does not exist/i.test(msg)) {
408
+ log("cluster-state table not present — skipping vault-key consistency check (custom provider)");
409
+ return;
410
+ }
411
+ throw e;
412
+ }
413
+
414
+ // Read whatever fingerprint is canonical (ours if first boot,
415
+ // someone else's if we lost the race or are joining an existing cluster).
416
+ var rows = await externalDb.query(
417
+ "SELECT vaultKeyFp, recordedByNode, recordedAt FROM _blamejs_cluster_state " +
418
+ "WHERE scope = 'state'",
419
+ [],
420
+ { backend: configuredExternalDbBackend }
421
+ );
422
+ if (!rows.rows || rows.rows.length === 0) {
423
+ // Should never happen — we just INSERTed. Surface as fatal so the
424
+ // condition isn't silently ignored.
425
+ log.error("FATAL: cluster-state row missing immediately after INSERT — " +
426
+ "external-db may not be honoring writes. Refusing boot.");
427
+ process.exit(1);
428
+ }
429
+ var canonical = rows.rows[0];
430
+ if (canonical.vaultKeyFp !== localFp) {
431
+ log.error("FATAL: vault-key drift detected.");
432
+ log.error(" local node: " + nodeId);
433
+ log.error(" local fingerprint: " + localFp.slice(0, 16) + "…");
434
+ log.error(" canonical recorded by: " + canonical.recordedByNode);
435
+ log.error(" canonical fingerprint: " + canonical.vaultKeyFp.slice(0, 16) + "…");
436
+ log.error("This node holds a DIFFERENT vault key than the rest of the " +
437
+ "cluster. Sealed-column writes from this node would be unreadable " +
438
+ "by the others (and vice versa). Restore the same vault key file " +
439
+ "before booting this node into the cluster.");
440
+ process.exit(1);
441
+ }
442
+ log("cluster vault-key consistency ok (fingerprint " +
443
+ localFp.slice(0, 16) + "… recorded by " + canonical.recordedByNode + ")");
444
+ }
445
+
446
+ async function _tryAcquire() {
447
+ if (role !== "leader") return; // pinned-follower role: never claim
448
+ try {
449
+ var got = await provider.acquireLease(nodeId, leaseTtlMs, {
450
+ endpoint: configuredEndpoint,
451
+ });
452
+ if (got) {
453
+ var wasLeader = !!lease;
454
+ lease = got;
455
+ if (!wasLeader) {
456
+ log("acquired lease — fencingToken=" + lease.fencingToken);
457
+ _emitTransition("lease-acquired", { fencingToken: lease.fencingToken });
458
+ }
459
+ }
460
+ } catch (e) {
461
+ log.error("acquire failed: " + e.message);
462
+ }
463
+ }
464
+
465
+ async function _heartbeat() {
466
+ if (!initialized) return;
467
+ if (!lease) {
468
+ // Not currently leader — try to acquire (lease may have expired
469
+ // on the previous holder).
470
+ await _tryAcquire();
471
+ return;
472
+ }
473
+ // We hold a lease — renew it. Re-supply the configured endpoint so a
474
+ // hot-reload of the operator's config (e.g. node moves to a new
475
+ // routable URL after a restart) eventually reaches the discovery row.
476
+ try {
477
+ lease = await provider.renewLease(lease, { endpoint: configuredEndpoint });
478
+ } catch (e) {
479
+ if (e.code === "LEASE_LOST") {
480
+ log.error("lease lost: " + e.message);
481
+ var lostToken = lease ? lease.fencingToken : null;
482
+ lease = null;
483
+ _emitTransition("lease-lost", { fencingToken: lostToken });
484
+ // Attempt to re-acquire on the next heartbeat naturally.
485
+ } else {
486
+ // Transient error — retry on next heartbeat. If it persists past
487
+ // leaseTtl another node will steal, and we'll detect via LEASE_LOST.
488
+ log.error("renew failed transiently: " + e.message);
489
+ }
490
+ }
491
+ }
492
+
493
+ // ---- public sync surface ----
494
+
495
+ function isLeader() {
496
+ if (terminated) return false; // post-shutdown: never leader
497
+ if (!initialized) return true; // never-initialized: permanent leader
498
+ return !!lease && Date.now() < lease.expiresAt;
499
+ }
500
+
501
+ // Has cluster.init been called with a real configuration? Used by
502
+ // write-dispatch code (audit, consent, …) to decide whether framework
503
+ // state should go to local SQLite or external-db.
504
+ function isClusterMode() {
505
+ return initialized && !!configuredExternalDbBackend;
506
+ }
507
+
508
+ function externalDbBackend() {
509
+ return configuredExternalDbBackend;
510
+ }
511
+
512
+ function dialect() {
513
+ return configuredDialect;
514
+ }
515
+
516
+ function currentNodeId() {
517
+ return initialized ? nodeId : "single-node-local";
518
+ }
519
+
520
+ // This node's routable endpoint (operator-configured at cluster.init).
521
+ // Returns null when not configured or in single-node fallback. External
522
+ // observers should call discoveryHandler() / currentLeader() instead —
523
+ // this getter is for the local node's own self-identity.
524
+ function endpoint() {
525
+ return configuredEndpoint;
526
+ }
527
+
528
+ function fencingToken() {
529
+ if (!initialized) return 0;
530
+ return lease ? lease.fencingToken : 0;
531
+ }
532
+
533
+ function requireLeader() {
534
+ if (!isLeader()) {
535
+ throw new NotLeaderError(
536
+ "node '" + currentNodeId() + "' is not currently leader" +
537
+ (initialized ? "" : " (cluster not initialized)")
538
+ );
539
+ }
540
+ }
541
+
542
+ async function currentLeader() {
543
+ if (!initialized) {
544
+ return {
545
+ nodeId: "single-node-local",
546
+ leaseExpiresAt: Infinity,
547
+ fencingToken: 0,
548
+ endpoint: null,
549
+ };
550
+ }
551
+ return await provider.currentLeader();
552
+ }
553
+
554
+ // HTTP request handler — replies with the current cluster leader for
555
+ // service-mesh / load-balancer discovery. Operators mount this at
556
+ // whatever route they want (`/cluster/leader`, `/health/leader`, etc.).
557
+ //
558
+ // 200 application/json — leader present
559
+ // { leader: { nodeId, endpoint, fencingToken, leaseExpiresAt },
560
+ // self: { nodeId, endpoint, isLeader } }
561
+ //
562
+ // 503 application/json — no leader (no row, expired lease, DB
563
+ // unreachable, single-node not initialized with cluster mode)
564
+ // { leader: null, self: { nodeId, endpoint, isLeader } }
565
+ //
566
+ // No auth — this endpoint is intended to be called by infrastructure
567
+ // inside the trust boundary (LB, healthcheck, dashboard). Operators
568
+ // who expose it externally should layer auth via their own middleware.
569
+ //
570
+ // Handler is method-agnostic so it works behind any HTTP probe shape
571
+ // (GET, HEAD, etc.). Cache-Control: no-store to avoid stale-leader
572
+ // responses pinned by a caching proxy during a takeover.
573
+ function discoveryHandler() {
574
+ return async function (req, res) {
575
+ var selfInfo = {
576
+ nodeId: currentNodeId(),
577
+ endpoint: configuredEndpoint,
578
+ isLeader: isLeader(),
579
+ };
580
+ var body;
581
+ var status;
582
+ try {
583
+ var leader = await currentLeader();
584
+ if (leader && leader.nodeId && leader.nodeId !== "single-node-local") {
585
+ body = { leader: leader, self: selfInfo };
586
+ status = 200;
587
+ } else if (leader && leader.nodeId === "single-node-local") {
588
+ // Permanent-leader fallback (cluster.init never called). Reply
589
+ // 200 — the operator's app is healthy and the "leader" is this
590
+ // process. Useful so the discovery endpoint is never a false
591
+ // negative in single-node deployments.
592
+ body = { leader: leader, self: selfInfo };
593
+ status = 200;
594
+ } else {
595
+ body = { leader: null, self: selfInfo };
596
+ status = 503;
597
+ }
598
+ } catch (e) {
599
+ body = { leader: null, self: selfInfo, error: e.message };
600
+ status = 503;
601
+ }
602
+ var json = JSON.stringify(body);
603
+ res.writeHead(status, {
604
+ "Content-Type": "application/json; charset=utf-8",
605
+ "Content-Length": Buffer.byteLength(json),
606
+ "Cache-Control": "no-store",
607
+ });
608
+ res.end(json);
609
+ };
610
+ }
611
+
612
+ function onTransition(handler) {
613
+ if (typeof handler !== "function") {
614
+ throw _err("INVALID_HANDLER", "onTransition expects a function", true);
615
+ }
616
+ transitionHandlers.push(handler);
617
+ }
618
+
619
+ async function shutdown() {
620
+ if (!initialized) return;
621
+ if (heartbeatTimer) {
622
+ clearInterval(heartbeatTimer);
623
+ heartbeatTimer = null;
624
+ }
625
+ if (lease) {
626
+ try {
627
+ await provider.releaseLease(lease);
628
+ _emitTransition("lease-released", { fencingToken: lease.fencingToken });
629
+ log("lease released on shutdown");
630
+ } catch (e) {
631
+ log.error("release on shutdown failed: " + e.message);
632
+ }
633
+ lease = null;
634
+ }
635
+ initialized = false;
636
+ terminated = true;
637
+ provider = null;
638
+ role = null;
639
+ leaseTtlMs = null;
640
+ heartbeatMs = null;
641
+ configuredExternalDbBackend = null;
642
+ configuredDialect = null;
643
+ configuredEndpoint = null;
644
+ transitionHandlers = [];
645
+ // nodeId is preserved post-shutdown so audit metadata still reflects
646
+ // who this process was; cleared only by _resetForTest.
647
+ }
648
+
649
+ // ---- test helpers — not part of public contract ----
650
+
651
+ function _resetForTest() {
652
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
653
+ heartbeatTimer = null;
654
+ initialized = false;
655
+ terminated = false;
656
+ nodeId = null;
657
+ role = null;
658
+ provider = null;
659
+ lease = null;
660
+ leaseTtlMs = null;
661
+ heartbeatMs = null;
662
+ configuredExternalDbBackend = null;
663
+ configuredDialect = null;
664
+ configuredEndpoint = null;
665
+ transitionHandlers = [];
666
+ }
667
+
668
+ async function _heartbeatNowForTest() {
669
+ // Drive one heartbeat synchronously without waiting for the timer —
670
+ // lets tests deterministically observe lease state transitions.
671
+ await _heartbeat();
672
+ }
673
+
674
+ module.exports = {
675
+ init: init,
676
+ isLeader: isLeader,
677
+ isClusterMode: isClusterMode,
678
+ externalDbBackend: externalDbBackend,
679
+ dialect: dialect,
680
+ currentNodeId: currentNodeId,
681
+ endpoint: endpoint,
682
+ fencingToken: fencingToken,
683
+ requireLeader: requireLeader,
684
+ currentLeader: currentLeader,
685
+ discoveryHandler: discoveryHandler,
686
+ onTransition: onTransition,
687
+ shutdown: shutdown,
688
+ NotLeaderError: NotLeaderError,
689
+ _resetForTest: _resetForTest,
690
+ _heartbeatNowForTest: _heartbeatNowForTest,
691
+ };