@blamejs/core 0.7.1 → 0.7.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 (180) hide show
  1. package/CHANGELOG.md +423 -389
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -282
  5. package/lib/api-key.js +660 -672
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt.js +311 -311
  16. package/lib/auth/lockout.js +436 -436
  17. package/lib/auth/oauth.js +721 -721
  18. package/lib/auth/passkey.js +181 -181
  19. package/lib/auth/password.js +594 -594
  20. package/lib/backup/bundle.js +217 -217
  21. package/lib/backup/crypto.js +176 -176
  22. package/lib/backup/index.js +515 -515
  23. package/lib/backup/manifest.js +282 -282
  24. package/lib/break-glass.js +1338 -1338
  25. package/lib/bundler.js +441 -441
  26. package/lib/cache-redis.js +256 -266
  27. package/lib/cache.js +1206 -1211
  28. package/lib/canonical-json.js +115 -115
  29. package/lib/chain-writer.js +234 -234
  30. package/lib/cli-helpers.js +206 -206
  31. package/lib/cli.js +2334 -2334
  32. package/lib/cluster-provider-db.js +317 -317
  33. package/lib/cluster-storage.js +226 -226
  34. package/lib/cluster.js +703 -703
  35. package/lib/codepoint-class.js +196 -0
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -286
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -421
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/file-upload.js +1136 -0
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -202
  58. package/lib/framework-schema.js +717 -717
  59. package/lib/gate-contract.js +971 -0
  60. package/lib/guard-all.js +405 -0
  61. package/lib/guard-archive.js +739 -0
  62. package/lib/guard-csv.js +816 -0
  63. package/lib/guard-email.js +744 -0
  64. package/lib/guard-filename.js +724 -0
  65. package/lib/guard-html.js +976 -0
  66. package/lib/guard-json.js +729 -0
  67. package/lib/guard-markdown.js +586 -0
  68. package/lib/guard-svg.js +976 -0
  69. package/lib/guard-xml.js +405 -0
  70. package/lib/guard-yaml.js +529 -0
  71. package/lib/handlers.js +350 -350
  72. package/lib/http-client-cookie-jar.js +508 -508
  73. package/lib/http-client.js +1195 -1195
  74. package/lib/i18n.js +878 -878
  75. package/lib/jobs.js +185 -185
  76. package/lib/log-stream-cloudwatch.js +369 -369
  77. package/lib/log-stream-local.js +146 -146
  78. package/lib/log-stream-otlp-grpc.js +410 -410
  79. package/lib/log-stream-otlp.js +286 -286
  80. package/lib/log-stream-syslog.js +302 -302
  81. package/lib/log-stream-webhook.js +199 -199
  82. package/lib/log-stream.js +330 -330
  83. package/lib/log.js +500 -500
  84. package/lib/mail-bounce.js +528 -528
  85. package/lib/mail-dkim.js +369 -362
  86. package/lib/mail.js +981 -962
  87. package/lib/metrics.js +683 -683
  88. package/lib/middleware/api-encrypt.js +936 -573
  89. package/lib/middleware/attach-user.js +157 -157
  90. package/lib/middleware/body-parser.js +1170 -1091
  91. package/lib/middleware/bot-guard.js +178 -178
  92. package/lib/middleware/compression.js +452 -452
  93. package/lib/middleware/cors.js +314 -314
  94. package/lib/middleware/csp-nonce.js +348 -348
  95. package/lib/middleware/csrf-protect.js +316 -316
  96. package/lib/middleware/db-role-for.js +264 -269
  97. package/lib/middleware/health.js +392 -392
  98. package/lib/middleware/index.js +79 -79
  99. package/lib/middleware/rate-limit.js +358 -358
  100. package/lib/middleware/request-id.js +61 -61
  101. package/lib/middleware/request-log.js +168 -168
  102. package/lib/middleware/require-auth.js +104 -104
  103. package/lib/middleware/security-headers.js +116 -116
  104. package/lib/middleware/sse.js +166 -166
  105. package/lib/migrations.js +383 -383
  106. package/lib/mtls-ca.js +518 -518
  107. package/lib/mtls-engine-default.js +481 -481
  108. package/lib/network-dns.js +632 -632
  109. package/lib/network-heartbeat.js +290 -290
  110. package/lib/network-nts.js +574 -574
  111. package/lib/network-proxy.js +265 -265
  112. package/lib/network-tls.js +328 -328
  113. package/lib/network.js +233 -233
  114. package/lib/notify.js +612 -614
  115. package/lib/ntp-check.js +229 -229
  116. package/lib/numeric-bounds.js +111 -91
  117. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  118. package/lib/object-store/azure-blob.js +488 -451
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -479
  121. package/lib/object-store/http-put.js +153 -153
  122. package/lib/object-store/index.js +197 -197
  123. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  124. package/lib/object-store/sigv4.js +903 -855
  125. package/lib/observability.js +151 -151
  126. package/lib/otel-export.js +269 -269
  127. package/lib/pagination.js +464 -464
  128. package/lib/parsers/index.js +80 -80
  129. package/lib/parsers/safe-env.js +642 -642
  130. package/lib/parsers/safe-ini.js +292 -292
  131. package/lib/parsers/safe-toml.js +784 -784
  132. package/lib/parsers/safe-xml.js +390 -390
  133. package/lib/parsers/safe-yaml.js +1015 -1015
  134. package/lib/permissions.js +708 -708
  135. package/lib/pqc-agent.js +87 -87
  136. package/lib/pqc-gate.js +279 -279
  137. package/lib/protobuf-encoder.js +190 -190
  138. package/lib/protocol-dispatcher.js +161 -161
  139. package/lib/pubsub-redis.js +167 -177
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -752
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -489
  146. package/lib/request-helpers.js +340 -336
  147. package/lib/restore-bundle.js +237 -237
  148. package/lib/restore-rollback.js +259 -259
  149. package/lib/restore.js +409 -409
  150. package/lib/retry.js +376 -376
  151. package/lib/router.js +748 -748
  152. package/lib/safe-async.js +735 -735
  153. package/lib/safe-buffer.js +237 -237
  154. package/lib/safe-json.js +541 -541
  155. package/lib/safe-schema.js +1266 -1266
  156. package/lib/safe-url.js +159 -159
  157. package/lib/scheduler.js +706 -706
  158. package/lib/security-assert.js +373 -373
  159. package/lib/seeders.js +618 -630
  160. package/lib/session.js +478 -478
  161. package/lib/slug.js +269 -269
  162. package/lib/ssrf-guard.js +401 -401
  163. package/lib/static.js +879 -114
  164. package/lib/storage.js +471 -471
  165. package/lib/subject.js +281 -281
  166. package/lib/template.js +791 -791
  167. package/lib/testing.js +798 -798
  168. package/lib/time.js +310 -310
  169. package/lib/totp.js +302 -302
  170. package/lib/tracing.js +494 -494
  171. package/lib/uuid.js +132 -132
  172. package/lib/validate-opts.js +340 -270
  173. package/lib/vault/index.js +308 -308
  174. package/lib/vault/rotate.js +784 -784
  175. package/lib/vault/wrap.js +296 -296
  176. package/lib/vendor/noble-ciphers.cjs +9 -9
  177. package/lib/webhook.js +595 -598
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
@@ -1,717 +1,717 @@
1
- "use strict";
2
- /**
3
- * Framework state schema for cluster-mode external storage.
4
- *
5
- * When cluster mode is active, the framework's audit chain + consent
6
- * log + audit checkpoints + audit tip live in the operator's external-db
7
- * (configured via b.externalDb.init). This module owns the DDL for
8
- * those tables and exposes a single idempotent ensureSchema() entry
9
- * point that operators (or the framework's leader-acquire hook in a
10
- * later release) call to create them.
11
- *
12
- * In external-db the framework tables are prefixed with `_blamejs_`
13
- * to avoid collision with the operator's app data:
14
- *
15
- * audit_log local-SQLite name
16
- * _blamejs_audit_log external-db name
17
- *
18
- * The mapping is exposed via tableName(local) so write-dispatch code
19
- * (cluster-storage.js) uses a single name reference and the
20
- * dialect-aware ensureSchema fans out the DDL to either the local-
21
- * SQLite (db.js's FRAMEWORK_SCHEMA) or the external-db backend.
22
- *
23
- * Dialects: Postgres + SQLite. Both support CREATE TABLE IF NOT EXISTS,
24
- * CREATE INDEX IF NOT EXISTS, and the same column types modulo
25
- * INTEGER/BIGINT and BLOB/BYTEA differences. MySQL is not currently
26
- * supported — operators on MySQL must use one of the supported
27
- * dialects until a MySQL adapter ships.
28
- *
29
- * What ensureSchema does NOT do:
30
- * - Migrate existing audit_log rows from local SQLite into external-db.
31
- * That migration belongs to a separate operator-driven tool.
32
- * - Verify chain integrity in external-db. That happens at boot via
33
- * the audit module's regular verify() path on every read.
34
- * - Install append-only triggers. The framework's tamper-evidence
35
- * model is the audit chain's hash linkage + SLH-DSA-signed
36
- * checkpoints — triggers would add a defense-in-depth layer
37
- * but they're not load-bearing for the threat model. Operators
38
- * who want triggers add them per their dialect's syntax.
39
- *
40
- * Public API:
41
- * await frameworkSchema.ensureSchema({ externalDbBackend, dialect })
42
- * frameworkSchema.tableName(localName) external table name lookup
43
- * frameworkSchema.LOCAL_TO_EXTERNAL mapping (read-only)
44
- * frameworkSchema.FrameworkSchemaError error class
45
- */
46
-
47
- var externalDb = require("./external-db");
48
- var { FrameworkError } = require("./framework-error");
49
-
50
- class FrameworkSchemaError extends FrameworkError {
51
- constructor(message, code) {
52
- super(message);
53
- this.name = "FrameworkSchemaError";
54
- this.code = code || "framework-schema/invalid";
55
- this.isFrameworkSchemaError = true;
56
- }
57
- }
58
-
59
- // Local-SQLite name → external-db name. The prefix protects against
60
- // operator-app-table collision when the framework writes alongside
61
- // app tables in the same database.
62
- var LOCAL_TO_EXTERNAL = Object.freeze({
63
- audit_log: "_blamejs_audit_log",
64
- consent_log: "_blamejs_consent_log",
65
- audit_checkpoints: "_blamejs_audit_checkpoints",
66
- // No local equivalent — only exists in external-db. Coordinates with
67
- // the cluster module's lease + fencing-token guard.
68
- _blamejs_audit_tip: "_blamejs_audit_tip",
69
- // Same shape and purpose as _blamejs_audit_tip but for consent_log.
70
- // Single-row coordination state recording the tip of the consent
71
- // chain so a new leader (or any boot) can detect external-db
72
- // rollback against the consent chain too.
73
- _blamejs_consent_tip: "_blamejs_consent_tip",
74
- // Single-row anchor recording the boundary of the most recent
75
- // audit-tools.purge(). After a purge, audit-chain.verifyChain reads
76
- // this row to set its starting prevHash to lastPurgedRowHash and skip
77
- // rows whose monotonicCounter ≤ lastPurgedCounter — without it the
78
- // chain math breaks the moment the row referenced by survivors'
79
- // prevHash is gone.
80
- _blamejs_audit_purge_anchor: "_blamejs_audit_purge_anchor",
81
- // Scheduler tick-claim table: closes the once-globally gap during
82
- // cluster leader hand-offs (where two leaders briefly coexist) by
83
- // making each fire claim a row before dispatching. UNIQUE on the
84
- // composite tickKey (name + ":" + scheduledAtUnix) — loser of the
85
- // INSERT race skips the tick.
86
- _blamejs_scheduler_ticks: "_blamejs_scheduler_ticks",
87
- // Rate-limit cluster-shared backend storage — fixed-window counter
88
- // per key. The middleware atomically INSERT...ON CONFLICT increments
89
- // count within the current window and rolls over when the window
90
- // advances. Created in cluster mode by ensureSchema; mirrored in
91
- // single-node SQLite by db.js's FRAMEWORK_SCHEMA so the same SQL
92
- // works on either side of cluster-storage's dispatch.
93
- _blamejs_rate_limit_counters: "_blamejs_rate_limit_counters",
94
- // WebSocket channel-hub cluster fan-out — publish() writes a row,
95
- // other nodes poll for new ids and dispatch to their local
96
- // subscribers. Same dual-storage shape as sessions / jobs / etc.
97
- _blamejs_pubsub_messages: "_blamejs_pubsub_messages",
98
- _blamejs_api_encrypt_nonces: "_blamejs_api_encrypt_nonces",
99
- // _blamejs_api_keys — operator-facing API-key registry table for the
100
- // b.apiKey primitive. PRIMARY KEY is namespace-scoped id (so multiple
101
- // namespaces can coexist in one table). Sealed columns: ownerId,
102
- // scopes (JSON array), metadata (JSON object). Indexed lookup by
103
- // ownerIdHash. The secret itself never lands here — only its
104
- // SHA3-512 hash, constant-time-compared on verify.
105
- _blamejs_api_keys: "_blamejs_api_keys",
106
- // _blamejs_sessions exists in both local SQLite (single-node mode,
107
- // created by db.js's FRAMEWORK_SCHEMA at boot) and external-db
108
- // (cluster mode, created by ensureSchema below). Same name in both
109
- // places — cluster-storage.execute routes the SQL to the right DB
110
- // based on cluster.isClusterMode().
111
- _blamejs_sessions: "_blamejs_sessions",
112
- // _blamejs_jobs — same dual-storage pattern as sessions. The local-
113
- // protocol queue (lib/queue-local.js) routes through cluster-storage
114
- // so writes/reads land in the leader's external-db when cluster
115
- // mode is active and any node can observe the queue state.
116
- _blamejs_jobs: "_blamejs_jobs",
117
- // _blamejs_cache — operator-facing cache primitive's cluster backend.
118
- // Single shared table across all CacheInstance instances; the
119
- // namespace prefix in cacheKey isolates instances. JSON-serialized
120
- // values, BIGINT expiresAt for ttl. Indexed on expiresAt for the
121
- // periodic prune query.
122
- _blamejs_cache: "_blamejs_cache",
123
- // _blamejs_cache_tags — junction table for tag-based cache
124
- // invalidation on the cluster backend. Composite PK
125
- // (cacheKey, tag) lets a single cacheKey carry many tags;
126
- // index on tag makes invalidateTag(t) a single indexed scan.
127
- _blamejs_cache_tags: "_blamejs_cache_tags",
128
- // _blamejs_seeders — registry of applied seed files for b.seeders
129
- // (lib/seeders.js). Composite PK (env, name) lets the same filename
130
- // apply per env. Mirrors the local-SQLite shape in db.js
131
- // FRAMEWORK_SCHEMA so cluster-storage.execute routes to either side.
132
- _blamejs_seeders: "_blamejs_seeders",
133
- _blamejs_seeders_lock: "_blamejs_seeders_lock",
134
- // Break-glass policy + grant tables. Cluster-shared so a grant
135
- // issued on node A is honored on node B; policies updated on the
136
- // leader propagate to all followers via the shared table.
137
- _blamejs_break_glass_policies: "_blamejs_break_glass_policies",
138
- _blamejs_break_glass_grants: "_blamejs_break_glass_grants",
139
- });
140
-
141
- function tableName(localName) {
142
- if (Object.prototype.hasOwnProperty.call(LOCAL_TO_EXTERNAL, localName)) {
143
- return LOCAL_TO_EXTERNAL[localName];
144
- }
145
- // For framework-internal tables that are already prefixed locally
146
- // (any name starting with _blamejs_), keep the same name.
147
- return localName;
148
- }
149
-
150
- // ---- Dialect-specific column types ----
151
- // TEXT and BOOLEAN are identical across both. INTEGER and BLOB diverge.
152
-
153
- function _types(dialect) {
154
- if (dialect === "postgres") {
155
- return { INT: "BIGINT", BLOB: "BYTEA" };
156
- }
157
- if (dialect === "sqlite") {
158
- return { INT: "INTEGER", BLOB: "BLOB" };
159
- }
160
- throw new FrameworkSchemaError(
161
- "unsupported dialect '" + dialect + "' (postgres or sqlite)",
162
- "framework-schema/unsupported-dialect"
163
- );
164
- }
165
-
166
- // ---- Table DDL builders ----
167
- //
168
- // Each builder returns { create: <CREATE TABLE SQL>, indexes: [<CREATE INDEX SQL>, ...] }.
169
- // All DDL uses IF NOT EXISTS so re-running is idempotent.
170
-
171
- function _auditLogDDL(dialect) {
172
- var t = _types(dialect);
173
- var name = LOCAL_TO_EXTERNAL.audit_log;
174
- return {
175
- create:
176
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
177
- " _id TEXT PRIMARY KEY," +
178
- " recordedAt " + t.INT + " NOT NULL," +
179
- " monotonicCounter " + t.INT + " NOT NULL," +
180
- " actorUserId TEXT," +
181
- " actorUserIdHash TEXT," +
182
- " actorIp TEXT," +
183
- " actorUserAgent TEXT," +
184
- " actorSessionId TEXT," +
185
- " action TEXT NOT NULL," +
186
- " resourceKind TEXT," +
187
- " resourceId TEXT," +
188
- " resourceIdHash TEXT," +
189
- " outcome TEXT NOT NULL," +
190
- " reason TEXT," +
191
- " metadata TEXT," +
192
- " requestId TEXT," +
193
- " prevHash TEXT NOT NULL," +
194
- " rowHash TEXT NOT NULL," +
195
- " nonce " + t.BLOB + " NOT NULL," +
196
- " fencingToken " + t.INT + " NOT NULL DEFAULT 0" +
197
- ")",
198
- indexes: [
199
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_actorUserIdHash ON " + name + " (actorUserIdHash)",
200
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_resourceIdHash ON " + name + " (resourceIdHash)",
201
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_recordedAt ON " + name + " (recordedAt)",
202
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_action ON " + name + " (action)",
203
- "CREATE UNIQUE INDEX IF NOT EXISTS idx_" + name + "_monotonic ON " + name + " (monotonicCounter)",
204
- ],
205
- };
206
- }
207
-
208
- function _consentLogDDL(dialect) {
209
- var t = _types(dialect);
210
- var name = LOCAL_TO_EXTERNAL.consent_log;
211
- return {
212
- create:
213
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
214
- " _id TEXT PRIMARY KEY," +
215
- " recordedAt " + t.INT + " NOT NULL," +
216
- " monotonicCounter " + t.INT + " NOT NULL," +
217
- " subjectId TEXT NOT NULL," +
218
- " subjectIdHash TEXT NOT NULL," +
219
- " purpose TEXT NOT NULL," +
220
- " lawfulBasis TEXT NOT NULL," +
221
- " action TEXT NOT NULL," +
222
- " scope TEXT," +
223
- " channel TEXT NOT NULL," +
224
- " evidenceRef TEXT," +
225
- " prevHash TEXT NOT NULL," +
226
- " rowHash TEXT NOT NULL," +
227
- " nonce " + t.BLOB + " NOT NULL," +
228
- " fencingToken " + t.INT + " NOT NULL DEFAULT 0" +
229
- ")",
230
- indexes: [
231
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_subjectIdHash ON " + name + " (subjectIdHash)",
232
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_recordedAt ON " + name + " (recordedAt)",
233
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_purpose ON " + name + " (purpose)",
234
- "CREATE UNIQUE INDEX IF NOT EXISTS idx_" + name + "_monotonic ON " + name + " (monotonicCounter)",
235
- ],
236
- };
237
- }
238
-
239
- function _auditCheckpointsDDL(dialect) {
240
- var t = _types(dialect);
241
- var name = LOCAL_TO_EXTERNAL.audit_checkpoints;
242
- return {
243
- create:
244
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
245
- " _id TEXT PRIMARY KEY," +
246
- " createdAt " + t.INT + " NOT NULL," +
247
- " atMonotonicCounter " + t.INT + " NOT NULL," +
248
- " atRowHash TEXT NOT NULL," +
249
- " signature " + t.BLOB + " NOT NULL," +
250
- " publicKeyFingerprint TEXT NOT NULL," +
251
- " fencingToken " + t.INT + " NOT NULL DEFAULT 0" +
252
- ")",
253
- indexes: [
254
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_createdAt ON " + name + " (createdAt)",
255
- "CREATE UNIQUE INDEX IF NOT EXISTS idx_" + name + "_chkpt_counter ON " + name + " (atMonotonicCounter)",
256
- ],
257
- };
258
- }
259
-
260
- // audit_tip is single-row coordination state for cluster-mode rollback
261
- // detection. The CHECK constraint on fencingToken is the canonical
262
- // fencing-token guard from the cluster spec — enforced at the DB
263
- // level so a partitioned old leader can't insert rows behind a new
264
- // leader's back regardless of application-layer state.
265
- //
266
- // Postgres and SQLite both honour CHECK constraints. The single-row
267
- // invariant is enforced via PRIMARY KEY on the constant-valued
268
- // `scope` column.
269
- function _auditTipDDL(dialect) {
270
- var t = _types(dialect);
271
- var name = LOCAL_TO_EXTERNAL._blamejs_audit_tip;
272
- return {
273
- create:
274
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
275
- " scope TEXT PRIMARY KEY," +
276
- " atMonotonicCounter " + t.INT + " NOT NULL," +
277
- " rowHash TEXT," +
278
- " signedAt TEXT," +
279
- " fencingToken " + t.INT + " NOT NULL DEFAULT 0," +
280
- " CHECK (scope = 'audit')" +
281
- ")",
282
- indexes: [],
283
- };
284
- }
285
-
286
- // Same shape + invariants as audit_tip but for the consent chain.
287
- // Updated on every consent.grant / consent.withdraw write so the boot-
288
- // time rollback check can detect external-db rollback against the
289
- // consent chain (previously only the audit chain had this protection).
290
- function _consentTipDDL(dialect) {
291
- var t = _types(dialect);
292
- var name = LOCAL_TO_EXTERNAL._blamejs_consent_tip;
293
- return {
294
- create:
295
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
296
- " scope TEXT PRIMARY KEY," +
297
- " atMonotonicCounter " + t.INT + " NOT NULL," +
298
- " rowHash TEXT," +
299
- " signedAt TEXT," +
300
- " fencingToken " + t.INT + " NOT NULL DEFAULT 0," +
301
- " CHECK (scope = 'consent')" +
302
- ")",
303
- indexes: [],
304
- };
305
- }
306
-
307
- // _blamejs_audit_purge_anchor — single-row chain-origin anchor written
308
- // by audit-tools.purge(). Holds the lastRowHash of the most recently
309
- // purged range so verifyChain can ground its walk at the new origin.
310
- // Single-row invariant via PRIMARY KEY on the constant-valued `scope`
311
- // column (matches _blamejs_audit_tip pattern).
312
- function _auditPurgeAnchorDDL(dialect) {
313
- var t = _types(dialect);
314
- var name = LOCAL_TO_EXTERNAL._blamejs_audit_purge_anchor;
315
- return {
316
- create:
317
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
318
- " scope TEXT PRIMARY KEY," +
319
- " lastPurgedCounter " + t.INT + " NOT NULL," +
320
- " lastPurgedRowHash TEXT NOT NULL," +
321
- " archiveBundleId TEXT NOT NULL," +
322
- " purgedAt " + t.INT + " NOT NULL," +
323
- " CHECK (scope = 'audit')" +
324
- ")",
325
- indexes: [],
326
- };
327
- }
328
-
329
- // _blamejs_scheduler_ticks — exactly-once tick-claim table. PRIMARY KEY
330
- // on composite tickKey makes concurrent INSERTs race; the loser skips
331
- // the tick. claimedBy carries the node id for diagnostic.
332
- function _schedulerTicksDDL(dialect) {
333
- var t = _types(dialect);
334
- var name = LOCAL_TO_EXTERNAL._blamejs_scheduler_ticks;
335
- return {
336
- create:
337
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
338
- " tickKey TEXT PRIMARY KEY," +
339
- " name TEXT NOT NULL," +
340
- " scheduledAtUnix " + t.INT + " NOT NULL," +
341
- " claimedAtUnix " + t.INT + " NOT NULL," +
342
- " claimedBy TEXT" +
343
- ")",
344
- indexes: [
345
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_scheduledAt ON " + name + " (scheduledAtUnix)",
346
- ],
347
- };
348
- }
349
-
350
- // _blamejs_rate_limit_counters — fixed-window counter table for the
351
- // cluster-shared rate-limit backend. PRIMARY KEY on the rate-limit
352
- // key lets INSERT...ON CONFLICT atomically increment within a window
353
- // and roll over on window advance. The windowStart index supports
354
- // retention sweeps of expired windows.
355
- function _rateLimitCountersDDL(dialect) {
356
- var t = _types(dialect);
357
- var name = LOCAL_TO_EXTERNAL._blamejs_rate_limit_counters;
358
- return {
359
- create:
360
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
361
- " key TEXT PRIMARY KEY," +
362
- " windowStart " + t.INT + " NOT NULL," +
363
- " count " + t.INT + " NOT NULL DEFAULT 0" +
364
- ")",
365
- indexes: [
366
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_windowStart ON " + name + " (windowStart)",
367
- ],
368
- };
369
- }
370
-
371
- // _blamejs_pubsub_messages — cluster fan-out for `b.pubsub` (the
372
- // generalization of the previous WebSocket-specific table). publish()
373
- // on any node writes a row; other nodes poll for new ids past their
374
- // last seen and dispatch to local subscribers. Auto-incrementing id
375
- // is essential — postgres needs BIGSERIAL, sqlite gets INTEGER
376
- // PRIMARY KEY (which auto-increments implicitly).
377
- function _pubsubMessagesDDL(dialect) {
378
- var t = _types(dialect);
379
- var name = LOCAL_TO_EXTERNAL._blamejs_pubsub_messages;
380
- var idCol = dialect === "postgres"
381
- ? "id BIGSERIAL PRIMARY KEY"
382
- : "id INTEGER PRIMARY KEY AUTOINCREMENT";
383
- return {
384
- create:
385
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
386
- " " + idCol + "," +
387
- " topic TEXT NOT NULL," +
388
- " payload TEXT NOT NULL," +
389
- " publishedAt " + t.INT + " NOT NULL," +
390
- " publishedBy TEXT NOT NULL" +
391
- ")",
392
- indexes: [
393
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_publishedAt ON " + name + " (publishedAt)",
394
- ],
395
- };
396
- }
397
-
398
- function _apiEncryptNoncesDDL(dialect) {
399
- var t = _types(dialect);
400
- var name = LOCAL_TO_EXTERNAL._blamejs_api_encrypt_nonces;
401
- return {
402
- create:
403
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
404
- " nonceHash TEXT PRIMARY KEY," +
405
- " expireAt " + t.INT + " NOT NULL" +
406
- ")",
407
- indexes: [
408
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_expireAt ON " + name + " (expireAt)",
409
- ],
410
- };
411
- }
412
-
413
- // _blamejs_api_keys — operator-facing API-key registry. PRIMARY KEY is
414
- // the namespace-scoped id ("<namespace>:<idHex>"); ownerId/scopes/metadata
415
- // are sealed by cryptoField. ownerIdHash supports indexed listForOwner
416
- // lookups; expiresAt index supports purgeExpired sweeps.
417
- function _apiKeysDDL(dialect) {
418
- var t = _types(dialect);
419
- var name = LOCAL_TO_EXTERNAL._blamejs_api_keys;
420
- return {
421
- create:
422
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
423
- " id TEXT PRIMARY KEY," +
424
- " namespace TEXT NOT NULL," +
425
- " ownerId TEXT NOT NULL," +
426
- " ownerIdHash TEXT NOT NULL," +
427
- " secretHash TEXT NOT NULL," +
428
- " secondarySecretHash TEXT," +
429
- " secondaryExpiresAt " + t.INT + "," +
430
- " scopes TEXT," +
431
- " metadata TEXT," +
432
- " createdAt " + t.INT + " NOT NULL," +
433
- " expiresAt " + t.INT + "," +
434
- " revokedAt " + t.INT + "," +
435
- " lastUsedAt " + t.INT + "," +
436
- " prefix TEXT NOT NULL" +
437
- ")",
438
- indexes: [
439
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_ownerIdHash ON " + name + " (ownerIdHash)",
440
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_namespace_owner ON " + name + " (namespace, ownerIdHash)",
441
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_expiresAt ON " + name + " (expiresAt)",
442
- ],
443
- };
444
- }
445
-
446
- // _blamejs_sessions — DB-backed session store. Mirrors the local-SQLite
447
- // schema in db.js's FRAMEWORK_SCHEMA so single-node and cluster-mode
448
- // behavior is identical at the column level. Sealed columns (userId,
449
- // data) are stored vault-sealed; sidHash is the PRIMARY KEY (the raw
450
- // session id never lands here).
451
- function _sessionsDDL(dialect) {
452
- var t = _types(dialect);
453
- var name = LOCAL_TO_EXTERNAL._blamejs_sessions;
454
- return {
455
- create:
456
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
457
- " sidHash TEXT PRIMARY KEY," +
458
- " userId TEXT NOT NULL," +
459
- " userIdHash TEXT NOT NULL," +
460
- " data TEXT," +
461
- " createdAt " + t.INT + " NOT NULL," +
462
- " expiresAt " + t.INT + " NOT NULL," +
463
- " lastActivity " + t.INT + " NOT NULL" +
464
- ")",
465
- indexes: [
466
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_userIdHash ON " + name + " (userIdHash)",
467
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_expiresAt ON " + name + " (expiresAt)",
468
- ],
469
- };
470
- }
471
-
472
- // _blamejs_jobs — local-protocol queue jobs. Mirrors db.js's
473
- // FRAMEWORK_SCHEMA for the same table; sealed columns (payload,
474
- // lastError) are stored vault-sealed. Indexes target the lease
475
- // hot-path (queueName + status + availableAt) and lease-expiry
476
- // sweep (leaseExpiresAt).
477
- function _jobsDDL(dialect) {
478
- var t = _types(dialect);
479
- var name = LOCAL_TO_EXTERNAL._blamejs_jobs;
480
- return {
481
- create:
482
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
483
- " _id TEXT PRIMARY KEY," +
484
- " queueName TEXT NOT NULL," +
485
- " payload TEXT," +
486
- " status TEXT NOT NULL," +
487
- " enqueuedAt " + t.INT + " NOT NULL," +
488
- " availableAt " + t.INT + " NOT NULL," +
489
- " leasedAt " + t.INT + "," +
490
- " leaseExpiresAt " + t.INT + "," +
491
- " attempts " + t.INT + " NOT NULL DEFAULT 0," +
492
- " maxAttempts " + t.INT + " NOT NULL DEFAULT 5," +
493
- " lastError TEXT," +
494
- " finishedAt " + t.INT + "," +
495
- " traceId TEXT," +
496
- " classification TEXT," +
497
- " priority " + t.INT + " NOT NULL DEFAULT 0," +
498
- " repeatCron TEXT," +
499
- " repeatTimezone TEXT," +
500
- " flowId TEXT," +
501
- " flowChildName TEXT," +
502
- " dependsOn TEXT" +
503
- ")",
504
- indexes: [
505
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_lease ON " + name + " (queueName, status, availableAt)",
506
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_priority ON " + name + " (queueName, status, priority, availableAt)",
507
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_flow ON " + name + " (flowId)",
508
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_leaseExpiresAt ON " + name + " (leaseExpiresAt)",
509
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_finishedAt ON " + name + " (finishedAt)",
510
- ],
511
- };
512
- }
513
-
514
- // _blamejs_seeders — registry of applied seed files for the b.seeders
515
- // primitive (lib/seeders.js). Composite PK (env, name) so the same
516
- // filename can apply per env without collision. rerunnable=1 entries
517
- // have their appliedAt updated in place on each run; non-rerunnable
518
- // entries are insert-once.
519
- function _seedersDDL(dialect) {
520
- var t = _types(dialect);
521
- var name = LOCAL_TO_EXTERNAL._blamejs_seeders;
522
- return {
523
- create:
524
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
525
- " env TEXT NOT NULL," +
526
- " name TEXT NOT NULL," +
527
- " description TEXT," +
528
- " appliedAt TEXT NOT NULL," +
529
- " rerunnable " + t.INT + " NOT NULL DEFAULT 0," +
530
- " PRIMARY KEY (env, name)" +
531
- ")",
532
- indexes: [],
533
- };
534
- }
535
-
536
- // _blamejs_seeders_lock — single-row advisory lock matching the
537
- // _blamejs_migrations_lock pattern. CHECK enforces single row.
538
- function _seedersLockDDL(dialect) {
539
- var t = _types(dialect);
540
- var name = LOCAL_TO_EXTERNAL._blamejs_seeders_lock;
541
- return {
542
- create:
543
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
544
- " scope TEXT PRIMARY KEY CHECK (scope = 'lock')," +
545
- " lockedAt " + t.INT + " NOT NULL," +
546
- " lockedBy TEXT NOT NULL" +
547
- ")",
548
- indexes: [],
549
- };
550
- }
551
-
552
- // _blamejs_cache — operator-facing cache primitive's cluster backend
553
- // (lib/cache.js). PRIMARY KEY is the composite "<namespace>:<key>" so a
554
- // single shared table serves every CacheInstance regardless of namespace
555
- // without per-namespace table proliferation. valueJson is the
556
- // JSON-serialized stored value; expiresAt is the unix-ms TTL boundary
557
- // (Number.MAX_SAFE_INTEGER for never-expiring entries). Indexed on
558
- // expiresAt for the periodic prune query.
559
- function _cacheDDL(dialect) {
560
- var t = _types(dialect);
561
- var name = LOCAL_TO_EXTERNAL._blamejs_cache;
562
- return {
563
- create:
564
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
565
- " cacheKey TEXT PRIMARY KEY," +
566
- " valueJson TEXT NOT NULL," +
567
- " expiresAt " + t.INT + " NOT NULL," +
568
- " updatedAt " + t.INT + " NOT NULL" +
569
- ")",
570
- indexes: [
571
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_expiresAt ON " + name + " (expiresAt)",
572
- ],
573
- };
574
- }
575
-
576
- // _blamejs_cache_tags — tag→cacheKey junction for cluster-backend
577
- // tag invalidation. b.cache.invalidateTag(t) finds matching cacheKeys
578
- // via the indexed `tag` column, deletes them from _blamejs_cache, and
579
- // drops the junction rows. Cleared on cache.clear() and del() too.
580
- function _cacheTagsDDL(_dialect) {
581
- // Junction table is TEXT-only — no dialect-specific INT / BLOB needed.
582
- var name = LOCAL_TO_EXTERNAL._blamejs_cache_tags;
583
- return {
584
- create:
585
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
586
- " cacheKey TEXT NOT NULL," +
587
- " tag TEXT NOT NULL," +
588
- " PRIMARY KEY (cacheKey, tag)" +
589
- ")",
590
- indexes: [
591
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_tag ON " + name + " (tag)",
592
- ],
593
- };
594
- }
595
-
596
- // _blamejs_break_glass_policies — column-level break-glass policy
597
- // registry. One row per (table) declares which columns are
598
- // glass-locked + the operator's grant rules. Sealed columns hide
599
- // column-list / factor-list / bypass config from cleartext browsing.
600
- function _breakGlassPoliciesDDL(dialect) {
601
- var t = _types(dialect);
602
- var name = LOCAL_TO_EXTERNAL._blamejs_break_glass_policies;
603
- return {
604
- create:
605
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
606
- " tableName TEXT PRIMARY KEY," +
607
- " columnsJson TEXT NOT NULL," +
608
- " factorsJson TEXT NOT NULL," +
609
- " cryptographic " + t.INT + " NOT NULL DEFAULT 0," +
610
- " grantTtlMs " + t.INT + " NOT NULL," +
611
- " maxRowsPerGrant " + t.INT + " NOT NULL DEFAULT 1," +
612
- " reasonRequired " + t.INT + " NOT NULL DEFAULT 1," +
613
- " reasonMinLength " + t.INT + " NOT NULL DEFAULT 12," +
614
- " pinIp " + t.INT + " NOT NULL DEFAULT 1," +
615
- " sessionPin " + t.INT + " NOT NULL DEFAULT 1," +
616
- " onLockedAccess TEXT NOT NULL DEFAULT 'throw'," +
617
- " requireScope TEXT," +
618
- " serviceAccountBypassJson TEXT," +
619
- " dekSealed TEXT," +
620
- " auditReasonStorage TEXT NOT NULL DEFAULT 'cleartext'," +
621
- " updatedAt " + t.INT + " NOT NULL" +
622
- ")",
623
- indexes: [],
624
- };
625
- }
626
-
627
- // _blamejs_break_glass_grants — issued grants. One row per successful
628
- // step-up. Default maxRowsPerGrant=1 enforces row-by-row auth per the
629
- // operator-confirmed shape ("each row access = its own grant").
630
- function _breakGlassGrantsDDL(dialect) {
631
- var t = _types(dialect);
632
- var name = LOCAL_TO_EXTERNAL._blamejs_break_glass_grants;
633
- return {
634
- create:
635
- "CREATE TABLE IF NOT EXISTS " + name + " (" +
636
- " _id TEXT PRIMARY KEY," +
637
- " issuedToActorId TEXT NOT NULL," +
638
- " issuedToActorHash TEXT NOT NULL," +
639
- " factorType TEXT NOT NULL," +
640
- " reasonSealed TEXT," +
641
- " scopeTable TEXT NOT NULL," +
642
- " scopeColumnsJson TEXT NOT NULL," +
643
- " issuedAt " + t.INT + " NOT NULL," +
644
- " expiresAt " + t.INT + " NOT NULL," +
645
- " maxRowsPerGrant " + t.INT + " NOT NULL," +
646
- " rowsConsumed " + t.INT + " NOT NULL DEFAULT 0," +
647
- " revokedAt " + t.INT + "," +
648
- " sessionId TEXT," +
649
- " ip TEXT," +
650
- " kwGrantHalf TEXT" +
651
- ")",
652
- indexes: [
653
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_actor ON " + name + " (issuedToActorHash)",
654
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_table ON " + name + " (scopeTable)",
655
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_expires ON " + name + " (expiresAt)",
656
- "CREATE INDEX IF NOT EXISTS idx_" + name + "_revoked ON " + name + " (revokedAt)",
657
- ],
658
- };
659
- }
660
-
661
- // ---- ensureSchema ----
662
-
663
- async function ensureSchema(opts) {
664
- if (!opts || !opts.externalDbBackend) {
665
- throw new FrameworkSchemaError(
666
- "ensureSchema requires { externalDbBackend: <name> }",
667
- "framework-schema/invalid-config"
668
- );
669
- }
670
- var dialect = (opts.dialect || "postgres").toLowerCase();
671
- if (dialect !== "postgres" && dialect !== "sqlite") {
672
- throw new FrameworkSchemaError(
673
- "unsupported dialect '" + dialect + "' (postgres or sqlite)",
674
- "framework-schema/unsupported-dialect"
675
- );
676
- }
677
-
678
- var ddls = [
679
- _auditLogDDL(dialect),
680
- _consentLogDDL(dialect),
681
- _auditCheckpointsDDL(dialect),
682
- _auditTipDDL(dialect),
683
- _consentTipDDL(dialect),
684
- _auditPurgeAnchorDDL(dialect),
685
- _schedulerTicksDDL(dialect),
686
- _rateLimitCountersDDL(dialect),
687
- _pubsubMessagesDDL(dialect),
688
- _apiEncryptNoncesDDL(dialect),
689
- _apiKeysDDL(dialect),
690
- _sessionsDDL(dialect),
691
- _jobsDDL(dialect),
692
- _cacheDDL(dialect),
693
- _cacheTagsDDL(dialect),
694
- _seedersDDL(dialect),
695
- _seedersLockDDL(dialect),
696
- _breakGlassPoliciesDDL(dialect),
697
- _breakGlassGrantsDDL(dialect),
698
- ];
699
-
700
- var created = [];
701
- for (var i = 0; i < ddls.length; i++) {
702
- var d = ddls[i];
703
- await externalDb.query(d.create, [], { backend: opts.externalDbBackend });
704
- for (var j = 0; j < d.indexes.length; j++) {
705
- await externalDb.query(d.indexes[j], [], { backend: opts.externalDbBackend });
706
- }
707
- created.push(d.create.match(/CREATE TABLE IF NOT EXISTS\s+(\S+)/)[1]);
708
- }
709
- return { tables: created };
710
- }
711
-
712
- module.exports = {
713
- ensureSchema: ensureSchema,
714
- tableName: tableName,
715
- LOCAL_TO_EXTERNAL: LOCAL_TO_EXTERNAL,
716
- FrameworkSchemaError: FrameworkSchemaError,
717
- };
1
+ "use strict";
2
+ /**
3
+ * Framework state schema for cluster-mode external storage.
4
+ *
5
+ * When cluster mode is active, the framework's audit chain + consent
6
+ * log + audit checkpoints + audit tip live in the operator's external-db
7
+ * (configured via b.externalDb.init). This module owns the DDL for
8
+ * those tables and exposes a single idempotent ensureSchema() entry
9
+ * point that operators (or the framework's leader-acquire hook in a
10
+ * later release) call to create them.
11
+ *
12
+ * In external-db the framework tables are prefixed with `_blamejs_`
13
+ * to avoid collision with the operator's app data:
14
+ *
15
+ * audit_log local-SQLite name
16
+ * _blamejs_audit_log external-db name
17
+ *
18
+ * The mapping is exposed via tableName(local) so write-dispatch code
19
+ * (cluster-storage.js) uses a single name reference and the
20
+ * dialect-aware ensureSchema fans out the DDL to either the local-
21
+ * SQLite (db.js's FRAMEWORK_SCHEMA) or the external-db backend.
22
+ *
23
+ * Dialects: Postgres + SQLite. Both support CREATE TABLE IF NOT EXISTS,
24
+ * CREATE INDEX IF NOT EXISTS, and the same column types modulo
25
+ * INTEGER/BIGINT and BLOB/BYTEA differences. MySQL is not currently
26
+ * supported — operators on MySQL must use one of the supported
27
+ * dialects until a MySQL adapter ships.
28
+ *
29
+ * What ensureSchema does NOT do:
30
+ * - Migrate existing audit_log rows from local SQLite into external-db.
31
+ * That migration belongs to a separate operator-driven tool.
32
+ * - Verify chain integrity in external-db. That happens at boot via
33
+ * the audit module's regular verify() path on every read.
34
+ * - Install append-only triggers. The framework's tamper-evidence
35
+ * model is the audit chain's hash linkage + SLH-DSA-signed
36
+ * checkpoints — triggers would add a defense-in-depth layer
37
+ * but they're not load-bearing for the threat model. Operators
38
+ * who want triggers add them per their dialect's syntax.
39
+ *
40
+ * Public API:
41
+ * await frameworkSchema.ensureSchema({ externalDbBackend, dialect })
42
+ * frameworkSchema.tableName(localName) external table name lookup
43
+ * frameworkSchema.LOCAL_TO_EXTERNAL mapping (read-only)
44
+ * frameworkSchema.FrameworkSchemaError error class
45
+ */
46
+
47
+ var externalDb = require("./external-db");
48
+ var { FrameworkError } = require("./framework-error");
49
+
50
+ class FrameworkSchemaError extends FrameworkError {
51
+ constructor(message, code) {
52
+ super(message);
53
+ this.name = "FrameworkSchemaError";
54
+ this.code = code || "framework-schema/invalid";
55
+ this.isFrameworkSchemaError = true;
56
+ }
57
+ }
58
+
59
+ // Local-SQLite name → external-db name. The prefix protects against
60
+ // operator-app-table collision when the framework writes alongside
61
+ // app tables in the same database.
62
+ var LOCAL_TO_EXTERNAL = Object.freeze({
63
+ audit_log: "_blamejs_audit_log",
64
+ consent_log: "_blamejs_consent_log",
65
+ audit_checkpoints: "_blamejs_audit_checkpoints",
66
+ // No local equivalent — only exists in external-db. Coordinates with
67
+ // the cluster module's lease + fencing-token guard.
68
+ _blamejs_audit_tip: "_blamejs_audit_tip",
69
+ // Same shape and purpose as _blamejs_audit_tip but for consent_log.
70
+ // Single-row coordination state recording the tip of the consent
71
+ // chain so a new leader (or any boot) can detect external-db
72
+ // rollback against the consent chain too.
73
+ _blamejs_consent_tip: "_blamejs_consent_tip",
74
+ // Single-row anchor recording the boundary of the most recent
75
+ // audit-tools.purge(). After a purge, audit-chain.verifyChain reads
76
+ // this row to set its starting prevHash to lastPurgedRowHash and skip
77
+ // rows whose monotonicCounter ≤ lastPurgedCounter — without it the
78
+ // chain math breaks the moment the row referenced by survivors'
79
+ // prevHash is gone.
80
+ _blamejs_audit_purge_anchor: "_blamejs_audit_purge_anchor",
81
+ // Scheduler tick-claim table: closes the once-globally gap during
82
+ // cluster leader hand-offs (where two leaders briefly coexist) by
83
+ // making each fire claim a row before dispatching. UNIQUE on the
84
+ // composite tickKey (name + ":" + scheduledAtUnix) — loser of the
85
+ // INSERT race skips the tick.
86
+ _blamejs_scheduler_ticks: "_blamejs_scheduler_ticks",
87
+ // Rate-limit cluster-shared backend storage — fixed-window counter
88
+ // per key. The middleware atomically INSERT...ON CONFLICT increments
89
+ // count within the current window and rolls over when the window
90
+ // advances. Created in cluster mode by ensureSchema; mirrored in
91
+ // single-node SQLite by db.js's FRAMEWORK_SCHEMA so the same SQL
92
+ // works on either side of cluster-storage's dispatch.
93
+ _blamejs_rate_limit_counters: "_blamejs_rate_limit_counters",
94
+ // WebSocket channel-hub cluster fan-out — publish() writes a row,
95
+ // other nodes poll for new ids and dispatch to their local
96
+ // subscribers. Same dual-storage shape as sessions / jobs / etc.
97
+ _blamejs_pubsub_messages: "_blamejs_pubsub_messages",
98
+ _blamejs_api_encrypt_nonces: "_blamejs_api_encrypt_nonces",
99
+ // _blamejs_api_keys — operator-facing API-key registry table for the
100
+ // b.apiKey primitive. PRIMARY KEY is namespace-scoped id (so multiple
101
+ // namespaces can coexist in one table). Sealed columns: ownerId,
102
+ // scopes (JSON array), metadata (JSON object). Indexed lookup by
103
+ // ownerIdHash. The secret itself never lands here — only its
104
+ // SHA3-512 hash, constant-time-compared on verify.
105
+ _blamejs_api_keys: "_blamejs_api_keys",
106
+ // _blamejs_sessions exists in both local SQLite (single-node mode,
107
+ // created by db.js's FRAMEWORK_SCHEMA at boot) and external-db
108
+ // (cluster mode, created by ensureSchema below). Same name in both
109
+ // places — cluster-storage.execute routes the SQL to the right DB
110
+ // based on cluster.isClusterMode().
111
+ _blamejs_sessions: "_blamejs_sessions",
112
+ // _blamejs_jobs — same dual-storage pattern as sessions. The local-
113
+ // protocol queue (lib/queue-local.js) routes through cluster-storage
114
+ // so writes/reads land in the leader's external-db when cluster
115
+ // mode is active and any node can observe the queue state.
116
+ _blamejs_jobs: "_blamejs_jobs",
117
+ // _blamejs_cache — operator-facing cache primitive's cluster backend.
118
+ // Single shared table across all CacheInstance instances; the
119
+ // namespace prefix in cacheKey isolates instances. JSON-serialized
120
+ // values, BIGINT expiresAt for ttl. Indexed on expiresAt for the
121
+ // periodic prune query.
122
+ _blamejs_cache: "_blamejs_cache",
123
+ // _blamejs_cache_tags — junction table for tag-based cache
124
+ // invalidation on the cluster backend. Composite PK
125
+ // (cacheKey, tag) lets a single cacheKey carry many tags;
126
+ // index on tag makes invalidateTag(t) a single indexed scan.
127
+ _blamejs_cache_tags: "_blamejs_cache_tags",
128
+ // _blamejs_seeders — registry of applied seed files for b.seeders
129
+ // (lib/seeders.js). Composite PK (env, name) lets the same filename
130
+ // apply per env. Mirrors the local-SQLite shape in db.js
131
+ // FRAMEWORK_SCHEMA so cluster-storage.execute routes to either side.
132
+ _blamejs_seeders: "_blamejs_seeders",
133
+ _blamejs_seeders_lock: "_blamejs_seeders_lock",
134
+ // Break-glass policy + grant tables. Cluster-shared so a grant
135
+ // issued on node A is honored on node B; policies updated on the
136
+ // leader propagate to all followers via the shared table.
137
+ _blamejs_break_glass_policies: "_blamejs_break_glass_policies",
138
+ _blamejs_break_glass_grants: "_blamejs_break_glass_grants",
139
+ });
140
+
141
+ function tableName(localName) {
142
+ if (Object.prototype.hasOwnProperty.call(LOCAL_TO_EXTERNAL, localName)) {
143
+ return LOCAL_TO_EXTERNAL[localName];
144
+ }
145
+ // For framework-internal tables that are already prefixed locally
146
+ // (any name starting with _blamejs_), keep the same name.
147
+ return localName;
148
+ }
149
+
150
+ // ---- Dialect-specific column types ----
151
+ // TEXT and BOOLEAN are identical across both. INTEGER and BLOB diverge.
152
+
153
+ function _types(dialect) {
154
+ if (dialect === "postgres") {
155
+ return { INT: "BIGINT", BLOB: "BYTEA" };
156
+ }
157
+ if (dialect === "sqlite") {
158
+ return { INT: "INTEGER", BLOB: "BLOB" };
159
+ }
160
+ throw new FrameworkSchemaError(
161
+ "unsupported dialect '" + dialect + "' (postgres or sqlite)",
162
+ "framework-schema/unsupported-dialect"
163
+ );
164
+ }
165
+
166
+ // ---- Table DDL builders ----
167
+ //
168
+ // Each builder returns { create: <CREATE TABLE SQL>, indexes: [<CREATE INDEX SQL>, ...] }.
169
+ // All DDL uses IF NOT EXISTS so re-running is idempotent.
170
+
171
+ function _auditLogDDL(dialect) {
172
+ var t = _types(dialect);
173
+ var name = LOCAL_TO_EXTERNAL.audit_log;
174
+ return {
175
+ create:
176
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
177
+ " _id TEXT PRIMARY KEY," +
178
+ " recordedAt " + t.INT + " NOT NULL," +
179
+ " monotonicCounter " + t.INT + " NOT NULL," +
180
+ " actorUserId TEXT," +
181
+ " actorUserIdHash TEXT," +
182
+ " actorIp TEXT," +
183
+ " actorUserAgent TEXT," +
184
+ " actorSessionId TEXT," +
185
+ " action TEXT NOT NULL," +
186
+ " resourceKind TEXT," +
187
+ " resourceId TEXT," +
188
+ " resourceIdHash TEXT," +
189
+ " outcome TEXT NOT NULL," +
190
+ " reason TEXT," +
191
+ " metadata TEXT," +
192
+ " requestId TEXT," +
193
+ " prevHash TEXT NOT NULL," +
194
+ " rowHash TEXT NOT NULL," +
195
+ " nonce " + t.BLOB + " NOT NULL," +
196
+ " fencingToken " + t.INT + " NOT NULL DEFAULT 0" +
197
+ ")",
198
+ indexes: [
199
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_actorUserIdHash ON " + name + " (actorUserIdHash)",
200
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_resourceIdHash ON " + name + " (resourceIdHash)",
201
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_recordedAt ON " + name + " (recordedAt)",
202
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_action ON " + name + " (action)",
203
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_" + name + "_monotonic ON " + name + " (monotonicCounter)",
204
+ ],
205
+ };
206
+ }
207
+
208
+ function _consentLogDDL(dialect) {
209
+ var t = _types(dialect);
210
+ var name = LOCAL_TO_EXTERNAL.consent_log;
211
+ return {
212
+ create:
213
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
214
+ " _id TEXT PRIMARY KEY," +
215
+ " recordedAt " + t.INT + " NOT NULL," +
216
+ " monotonicCounter " + t.INT + " NOT NULL," +
217
+ " subjectId TEXT NOT NULL," +
218
+ " subjectIdHash TEXT NOT NULL," +
219
+ " purpose TEXT NOT NULL," +
220
+ " lawfulBasis TEXT NOT NULL," +
221
+ " action TEXT NOT NULL," +
222
+ " scope TEXT," +
223
+ " channel TEXT NOT NULL," +
224
+ " evidenceRef TEXT," +
225
+ " prevHash TEXT NOT NULL," +
226
+ " rowHash TEXT NOT NULL," +
227
+ " nonce " + t.BLOB + " NOT NULL," +
228
+ " fencingToken " + t.INT + " NOT NULL DEFAULT 0" +
229
+ ")",
230
+ indexes: [
231
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_subjectIdHash ON " + name + " (subjectIdHash)",
232
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_recordedAt ON " + name + " (recordedAt)",
233
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_purpose ON " + name + " (purpose)",
234
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_" + name + "_monotonic ON " + name + " (monotonicCounter)",
235
+ ],
236
+ };
237
+ }
238
+
239
+ function _auditCheckpointsDDL(dialect) {
240
+ var t = _types(dialect);
241
+ var name = LOCAL_TO_EXTERNAL.audit_checkpoints;
242
+ return {
243
+ create:
244
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
245
+ " _id TEXT PRIMARY KEY," +
246
+ " createdAt " + t.INT + " NOT NULL," +
247
+ " atMonotonicCounter " + t.INT + " NOT NULL," +
248
+ " atRowHash TEXT NOT NULL," +
249
+ " signature " + t.BLOB + " NOT NULL," +
250
+ " publicKeyFingerprint TEXT NOT NULL," +
251
+ " fencingToken " + t.INT + " NOT NULL DEFAULT 0" +
252
+ ")",
253
+ indexes: [
254
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_createdAt ON " + name + " (createdAt)",
255
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_" + name + "_chkpt_counter ON " + name + " (atMonotonicCounter)",
256
+ ],
257
+ };
258
+ }
259
+
260
+ // audit_tip is single-row coordination state for cluster-mode rollback
261
+ // detection. The CHECK constraint on fencingToken is the canonical
262
+ // fencing-token guard from the cluster spec — enforced at the DB
263
+ // level so a partitioned old leader can't insert rows behind a new
264
+ // leader's back regardless of application-layer state.
265
+ //
266
+ // Postgres and SQLite both honour CHECK constraints. The single-row
267
+ // invariant is enforced via PRIMARY KEY on the constant-valued
268
+ // `scope` column.
269
+ function _auditTipDDL(dialect) {
270
+ var t = _types(dialect);
271
+ var name = LOCAL_TO_EXTERNAL._blamejs_audit_tip;
272
+ return {
273
+ create:
274
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
275
+ " scope TEXT PRIMARY KEY," +
276
+ " atMonotonicCounter " + t.INT + " NOT NULL," +
277
+ " rowHash TEXT," +
278
+ " signedAt TEXT," +
279
+ " fencingToken " + t.INT + " NOT NULL DEFAULT 0," +
280
+ " CHECK (scope = 'audit')" +
281
+ ")",
282
+ indexes: [],
283
+ };
284
+ }
285
+
286
+ // Same shape + invariants as audit_tip but for the consent chain.
287
+ // Updated on every consent.grant / consent.withdraw write so the boot-
288
+ // time rollback check can detect external-db rollback against the
289
+ // consent chain (previously only the audit chain had this protection).
290
+ function _consentTipDDL(dialect) {
291
+ var t = _types(dialect);
292
+ var name = LOCAL_TO_EXTERNAL._blamejs_consent_tip;
293
+ return {
294
+ create:
295
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
296
+ " scope TEXT PRIMARY KEY," +
297
+ " atMonotonicCounter " + t.INT + " NOT NULL," +
298
+ " rowHash TEXT," +
299
+ " signedAt TEXT," +
300
+ " fencingToken " + t.INT + " NOT NULL DEFAULT 0," +
301
+ " CHECK (scope = 'consent')" +
302
+ ")",
303
+ indexes: [],
304
+ };
305
+ }
306
+
307
+ // _blamejs_audit_purge_anchor — single-row chain-origin anchor written
308
+ // by audit-tools.purge(). Holds the lastRowHash of the most recently
309
+ // purged range so verifyChain can ground its walk at the new origin.
310
+ // Single-row invariant via PRIMARY KEY on the constant-valued `scope`
311
+ // column (matches _blamejs_audit_tip pattern).
312
+ function _auditPurgeAnchorDDL(dialect) {
313
+ var t = _types(dialect);
314
+ var name = LOCAL_TO_EXTERNAL._blamejs_audit_purge_anchor;
315
+ return {
316
+ create:
317
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
318
+ " scope TEXT PRIMARY KEY," +
319
+ " lastPurgedCounter " + t.INT + " NOT NULL," +
320
+ " lastPurgedRowHash TEXT NOT NULL," +
321
+ " archiveBundleId TEXT NOT NULL," +
322
+ " purgedAt " + t.INT + " NOT NULL," +
323
+ " CHECK (scope = 'audit')" +
324
+ ")",
325
+ indexes: [],
326
+ };
327
+ }
328
+
329
+ // _blamejs_scheduler_ticks — exactly-once tick-claim table. PRIMARY KEY
330
+ // on composite tickKey makes concurrent INSERTs race; the loser skips
331
+ // the tick. claimedBy carries the node id for diagnostic.
332
+ function _schedulerTicksDDL(dialect) {
333
+ var t = _types(dialect);
334
+ var name = LOCAL_TO_EXTERNAL._blamejs_scheduler_ticks;
335
+ return {
336
+ create:
337
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
338
+ " tickKey TEXT PRIMARY KEY," +
339
+ " name TEXT NOT NULL," +
340
+ " scheduledAtUnix " + t.INT + " NOT NULL," +
341
+ " claimedAtUnix " + t.INT + " NOT NULL," +
342
+ " claimedBy TEXT" +
343
+ ")",
344
+ indexes: [
345
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_scheduledAt ON " + name + " (scheduledAtUnix)",
346
+ ],
347
+ };
348
+ }
349
+
350
+ // _blamejs_rate_limit_counters — fixed-window counter table for the
351
+ // cluster-shared rate-limit backend. PRIMARY KEY on the rate-limit
352
+ // key lets INSERT...ON CONFLICT atomically increment within a window
353
+ // and roll over on window advance. The windowStart index supports
354
+ // retention sweeps of expired windows.
355
+ function _rateLimitCountersDDL(dialect) {
356
+ var t = _types(dialect);
357
+ var name = LOCAL_TO_EXTERNAL._blamejs_rate_limit_counters;
358
+ return {
359
+ create:
360
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
361
+ " key TEXT PRIMARY KEY," +
362
+ " windowStart " + t.INT + " NOT NULL," +
363
+ " count " + t.INT + " NOT NULL DEFAULT 0" +
364
+ ")",
365
+ indexes: [
366
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_windowStart ON " + name + " (windowStart)",
367
+ ],
368
+ };
369
+ }
370
+
371
+ // _blamejs_pubsub_messages — cluster fan-out for `b.pubsub` (the
372
+ // generalization of the previous WebSocket-specific table). publish()
373
+ // on any node writes a row; other nodes poll for new ids past their
374
+ // last seen and dispatch to local subscribers. Auto-incrementing id
375
+ // is essential — postgres needs BIGSERIAL, sqlite gets INTEGER
376
+ // PRIMARY KEY (which auto-increments implicitly).
377
+ function _pubsubMessagesDDL(dialect) {
378
+ var t = _types(dialect);
379
+ var name = LOCAL_TO_EXTERNAL._blamejs_pubsub_messages;
380
+ var idCol = dialect === "postgres"
381
+ ? "id BIGSERIAL PRIMARY KEY"
382
+ : "id INTEGER PRIMARY KEY AUTOINCREMENT";
383
+ return {
384
+ create:
385
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
386
+ " " + idCol + "," +
387
+ " topic TEXT NOT NULL," +
388
+ " payload TEXT NOT NULL," +
389
+ " publishedAt " + t.INT + " NOT NULL," +
390
+ " publishedBy TEXT NOT NULL" +
391
+ ")",
392
+ indexes: [
393
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_publishedAt ON " + name + " (publishedAt)",
394
+ ],
395
+ };
396
+ }
397
+
398
+ function _apiEncryptNoncesDDL(dialect) {
399
+ var t = _types(dialect);
400
+ var name = LOCAL_TO_EXTERNAL._blamejs_api_encrypt_nonces;
401
+ return {
402
+ create:
403
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
404
+ " nonceHash TEXT PRIMARY KEY," +
405
+ " expireAt " + t.INT + " NOT NULL" +
406
+ ")",
407
+ indexes: [
408
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_expireAt ON " + name + " (expireAt)",
409
+ ],
410
+ };
411
+ }
412
+
413
+ // _blamejs_api_keys — operator-facing API-key registry. PRIMARY KEY is
414
+ // the namespace-scoped id ("<namespace>:<idHex>"); ownerId/scopes/metadata
415
+ // are sealed by cryptoField. ownerIdHash supports indexed listForOwner
416
+ // lookups; expiresAt index supports purgeExpired sweeps.
417
+ function _apiKeysDDL(dialect) {
418
+ var t = _types(dialect);
419
+ var name = LOCAL_TO_EXTERNAL._blamejs_api_keys;
420
+ return {
421
+ create:
422
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
423
+ " id TEXT PRIMARY KEY," +
424
+ " namespace TEXT NOT NULL," +
425
+ " ownerId TEXT NOT NULL," +
426
+ " ownerIdHash TEXT NOT NULL," +
427
+ " secretHash TEXT NOT NULL," +
428
+ " secondarySecretHash TEXT," +
429
+ " secondaryExpiresAt " + t.INT + "," +
430
+ " scopes TEXT," +
431
+ " metadata TEXT," +
432
+ " createdAt " + t.INT + " NOT NULL," +
433
+ " expiresAt " + t.INT + "," +
434
+ " revokedAt " + t.INT + "," +
435
+ " lastUsedAt " + t.INT + "," +
436
+ " prefix TEXT NOT NULL" +
437
+ ")",
438
+ indexes: [
439
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_ownerIdHash ON " + name + " (ownerIdHash)",
440
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_namespace_owner ON " + name + " (namespace, ownerIdHash)",
441
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_expiresAt ON " + name + " (expiresAt)",
442
+ ],
443
+ };
444
+ }
445
+
446
+ // _blamejs_sessions — DB-backed session store. Mirrors the local-SQLite
447
+ // schema in db.js's FRAMEWORK_SCHEMA so single-node and cluster-mode
448
+ // behavior is identical at the column level. Sealed columns (userId,
449
+ // data) are stored vault-sealed; sidHash is the PRIMARY KEY (the raw
450
+ // session id never lands here).
451
+ function _sessionsDDL(dialect) {
452
+ var t = _types(dialect);
453
+ var name = LOCAL_TO_EXTERNAL._blamejs_sessions;
454
+ return {
455
+ create:
456
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
457
+ " sidHash TEXT PRIMARY KEY," +
458
+ " userId TEXT NOT NULL," +
459
+ " userIdHash TEXT NOT NULL," +
460
+ " data TEXT," +
461
+ " createdAt " + t.INT + " NOT NULL," +
462
+ " expiresAt " + t.INT + " NOT NULL," +
463
+ " lastActivity " + t.INT + " NOT NULL" +
464
+ ")",
465
+ indexes: [
466
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_userIdHash ON " + name + " (userIdHash)",
467
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_expiresAt ON " + name + " (expiresAt)",
468
+ ],
469
+ };
470
+ }
471
+
472
+ // _blamejs_jobs — local-protocol queue jobs. Mirrors db.js's
473
+ // FRAMEWORK_SCHEMA for the same table; sealed columns (payload,
474
+ // lastError) are stored vault-sealed. Indexes target the lease
475
+ // hot-path (queueName + status + availableAt) and lease-expiry
476
+ // sweep (leaseExpiresAt).
477
+ function _jobsDDL(dialect) {
478
+ var t = _types(dialect);
479
+ var name = LOCAL_TO_EXTERNAL._blamejs_jobs;
480
+ return {
481
+ create:
482
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
483
+ " _id TEXT PRIMARY KEY," +
484
+ " queueName TEXT NOT NULL," +
485
+ " payload TEXT," +
486
+ " status TEXT NOT NULL," +
487
+ " enqueuedAt " + t.INT + " NOT NULL," +
488
+ " availableAt " + t.INT + " NOT NULL," +
489
+ " leasedAt " + t.INT + "," +
490
+ " leaseExpiresAt " + t.INT + "," +
491
+ " attempts " + t.INT + " NOT NULL DEFAULT 0," +
492
+ " maxAttempts " + t.INT + " NOT NULL DEFAULT 5," +
493
+ " lastError TEXT," +
494
+ " finishedAt " + t.INT + "," +
495
+ " traceId TEXT," +
496
+ " classification TEXT," +
497
+ " priority " + t.INT + " NOT NULL DEFAULT 0," +
498
+ " repeatCron TEXT," +
499
+ " repeatTimezone TEXT," +
500
+ " flowId TEXT," +
501
+ " flowChildName TEXT," +
502
+ " dependsOn TEXT" +
503
+ ")",
504
+ indexes: [
505
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_lease ON " + name + " (queueName, status, availableAt)",
506
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_priority ON " + name + " (queueName, status, priority, availableAt)",
507
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_flow ON " + name + " (flowId)",
508
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_leaseExpiresAt ON " + name + " (leaseExpiresAt)",
509
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_finishedAt ON " + name + " (finishedAt)",
510
+ ],
511
+ };
512
+ }
513
+
514
+ // _blamejs_seeders — registry of applied seed files for the b.seeders
515
+ // primitive (lib/seeders.js). Composite PK (env, name) so the same
516
+ // filename can apply per env without collision. rerunnable=1 entries
517
+ // have their appliedAt updated in place on each run; non-rerunnable
518
+ // entries are insert-once.
519
+ function _seedersDDL(dialect) {
520
+ var t = _types(dialect);
521
+ var name = LOCAL_TO_EXTERNAL._blamejs_seeders;
522
+ return {
523
+ create:
524
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
525
+ " env TEXT NOT NULL," +
526
+ " name TEXT NOT NULL," +
527
+ " description TEXT," +
528
+ " appliedAt TEXT NOT NULL," +
529
+ " rerunnable " + t.INT + " NOT NULL DEFAULT 0," +
530
+ " PRIMARY KEY (env, name)" +
531
+ ")",
532
+ indexes: [],
533
+ };
534
+ }
535
+
536
+ // _blamejs_seeders_lock — single-row advisory lock matching the
537
+ // _blamejs_migrations_lock pattern. CHECK enforces single row.
538
+ function _seedersLockDDL(dialect) {
539
+ var t = _types(dialect);
540
+ var name = LOCAL_TO_EXTERNAL._blamejs_seeders_lock;
541
+ return {
542
+ create:
543
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
544
+ " scope TEXT PRIMARY KEY CHECK (scope = 'lock')," +
545
+ " lockedAt " + t.INT + " NOT NULL," +
546
+ " lockedBy TEXT NOT NULL" +
547
+ ")",
548
+ indexes: [],
549
+ };
550
+ }
551
+
552
+ // _blamejs_cache — operator-facing cache primitive's cluster backend
553
+ // (lib/cache.js). PRIMARY KEY is the composite "<namespace>:<key>" so a
554
+ // single shared table serves every CacheInstance regardless of namespace
555
+ // without per-namespace table proliferation. valueJson is the
556
+ // JSON-serialized stored value; expiresAt is the unix-ms TTL boundary
557
+ // (Number.MAX_SAFE_INTEGER for never-expiring entries). Indexed on
558
+ // expiresAt for the periodic prune query.
559
+ function _cacheDDL(dialect) {
560
+ var t = _types(dialect);
561
+ var name = LOCAL_TO_EXTERNAL._blamejs_cache;
562
+ return {
563
+ create:
564
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
565
+ " cacheKey TEXT PRIMARY KEY," +
566
+ " valueJson TEXT NOT NULL," +
567
+ " expiresAt " + t.INT + " NOT NULL," +
568
+ " updatedAt " + t.INT + " NOT NULL" +
569
+ ")",
570
+ indexes: [
571
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_expiresAt ON " + name + " (expiresAt)",
572
+ ],
573
+ };
574
+ }
575
+
576
+ // _blamejs_cache_tags — tag→cacheKey junction for cluster-backend
577
+ // tag invalidation. b.cache.invalidateTag(t) finds matching cacheKeys
578
+ // via the indexed `tag` column, deletes them from _blamejs_cache, and
579
+ // drops the junction rows. Cleared on cache.clear() and del() too.
580
+ function _cacheTagsDDL(_dialect) {
581
+ // Junction table is TEXT-only — no dialect-specific INT / BLOB needed.
582
+ var name = LOCAL_TO_EXTERNAL._blamejs_cache_tags;
583
+ return {
584
+ create:
585
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
586
+ " cacheKey TEXT NOT NULL," +
587
+ " tag TEXT NOT NULL," +
588
+ " PRIMARY KEY (cacheKey, tag)" +
589
+ ")",
590
+ indexes: [
591
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_tag ON " + name + " (tag)",
592
+ ],
593
+ };
594
+ }
595
+
596
+ // _blamejs_break_glass_policies — column-level break-glass policy
597
+ // registry. One row per (table) declares which columns are
598
+ // glass-locked + the operator's grant rules. Sealed columns hide
599
+ // column-list / factor-list / bypass config from cleartext browsing.
600
+ function _breakGlassPoliciesDDL(dialect) {
601
+ var t = _types(dialect);
602
+ var name = LOCAL_TO_EXTERNAL._blamejs_break_glass_policies;
603
+ return {
604
+ create:
605
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
606
+ " tableName TEXT PRIMARY KEY," +
607
+ " columnsJson TEXT NOT NULL," +
608
+ " factorsJson TEXT NOT NULL," +
609
+ " cryptographic " + t.INT + " NOT NULL DEFAULT 0," +
610
+ " grantTtlMs " + t.INT + " NOT NULL," +
611
+ " maxRowsPerGrant " + t.INT + " NOT NULL DEFAULT 1," +
612
+ " reasonRequired " + t.INT + " NOT NULL DEFAULT 1," +
613
+ " reasonMinLength " + t.INT + " NOT NULL DEFAULT 12," +
614
+ " pinIp " + t.INT + " NOT NULL DEFAULT 1," +
615
+ " sessionPin " + t.INT + " NOT NULL DEFAULT 1," +
616
+ " onLockedAccess TEXT NOT NULL DEFAULT 'throw'," +
617
+ " requireScope TEXT," +
618
+ " serviceAccountBypassJson TEXT," +
619
+ " dekSealed TEXT," +
620
+ " auditReasonStorage TEXT NOT NULL DEFAULT 'cleartext'," +
621
+ " updatedAt " + t.INT + " NOT NULL" +
622
+ ")",
623
+ indexes: [],
624
+ };
625
+ }
626
+
627
+ // _blamejs_break_glass_grants — issued grants. One row per successful
628
+ // step-up. Default maxRowsPerGrant=1 enforces row-by-row auth per the
629
+ // operator-confirmed shape ("each row access = its own grant").
630
+ function _breakGlassGrantsDDL(dialect) {
631
+ var t = _types(dialect);
632
+ var name = LOCAL_TO_EXTERNAL._blamejs_break_glass_grants;
633
+ return {
634
+ create:
635
+ "CREATE TABLE IF NOT EXISTS " + name + " (" +
636
+ " _id TEXT PRIMARY KEY," +
637
+ " issuedToActorId TEXT NOT NULL," +
638
+ " issuedToActorHash TEXT NOT NULL," +
639
+ " factorType TEXT NOT NULL," +
640
+ " reasonSealed TEXT," +
641
+ " scopeTable TEXT NOT NULL," +
642
+ " scopeColumnsJson TEXT NOT NULL," +
643
+ " issuedAt " + t.INT + " NOT NULL," +
644
+ " expiresAt " + t.INT + " NOT NULL," +
645
+ " maxRowsPerGrant " + t.INT + " NOT NULL," +
646
+ " rowsConsumed " + t.INT + " NOT NULL DEFAULT 0," +
647
+ " revokedAt " + t.INT + "," +
648
+ " sessionId TEXT," +
649
+ " ip TEXT," +
650
+ " kwGrantHalf TEXT" +
651
+ ")",
652
+ indexes: [
653
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_actor ON " + name + " (issuedToActorHash)",
654
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_table ON " + name + " (scopeTable)",
655
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_expires ON " + name + " (expiresAt)",
656
+ "CREATE INDEX IF NOT EXISTS idx_" + name + "_revoked ON " + name + " (revokedAt)",
657
+ ],
658
+ };
659
+ }
660
+
661
+ // ---- ensureSchema ----
662
+
663
+ async function ensureSchema(opts) {
664
+ if (!opts || !opts.externalDbBackend) {
665
+ throw new FrameworkSchemaError(
666
+ "ensureSchema requires { externalDbBackend: <name> }",
667
+ "framework-schema/invalid-config"
668
+ );
669
+ }
670
+ var dialect = (opts.dialect || "postgres").toLowerCase();
671
+ if (dialect !== "postgres" && dialect !== "sqlite") {
672
+ throw new FrameworkSchemaError(
673
+ "unsupported dialect '" + dialect + "' (postgres or sqlite)",
674
+ "framework-schema/unsupported-dialect"
675
+ );
676
+ }
677
+
678
+ var ddls = [
679
+ _auditLogDDL(dialect),
680
+ _consentLogDDL(dialect),
681
+ _auditCheckpointsDDL(dialect),
682
+ _auditTipDDL(dialect),
683
+ _consentTipDDL(dialect),
684
+ _auditPurgeAnchorDDL(dialect),
685
+ _schedulerTicksDDL(dialect),
686
+ _rateLimitCountersDDL(dialect),
687
+ _pubsubMessagesDDL(dialect),
688
+ _apiEncryptNoncesDDL(dialect),
689
+ _apiKeysDDL(dialect),
690
+ _sessionsDDL(dialect),
691
+ _jobsDDL(dialect),
692
+ _cacheDDL(dialect),
693
+ _cacheTagsDDL(dialect),
694
+ _seedersDDL(dialect),
695
+ _seedersLockDDL(dialect),
696
+ _breakGlassPoliciesDDL(dialect),
697
+ _breakGlassGrantsDDL(dialect),
698
+ ];
699
+
700
+ var created = [];
701
+ for (var i = 0; i < ddls.length; i++) {
702
+ var d = ddls[i];
703
+ await externalDb.query(d.create, [], { backend: opts.externalDbBackend });
704
+ for (var j = 0; j < d.indexes.length; j++) {
705
+ await externalDb.query(d.indexes[j], [], { backend: opts.externalDbBackend });
706
+ }
707
+ created.push(d.create.match(/CREATE TABLE IF NOT EXISTS\s+(\S+)/)[1]);
708
+ }
709
+ return { tables: created };
710
+ }
711
+
712
+ module.exports = {
713
+ ensureSchema: ensureSchema,
714
+ tableName: tableName,
715
+ LOCAL_TO_EXTERNAL: LOCAL_TO_EXTERNAL,
716
+ FrameworkSchemaError: FrameworkSchemaError,
717
+ };