@nabasolution/database-postgres 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,1077 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir } from "node:fs/promises";
3
+ import { hostname } from "node:os";
4
+ import { NabaError } from "@nabasolution/core";
5
+ export const POSTGRES_SCHEMA_VERSION = 1;
6
+ export const POSTGRES_RUNTIME_SCHEMA_VERSION = 5;
7
+ export const NABA_WRITER_LEASE_NAME = "naba-writer";
8
+ const DEFAULT_DATA_DIR = ".naba/data";
9
+ const DEFAULT_LEASE_TTL_MS = 30_000;
10
+ const DEFAULT_AUDIT_RETENTION_DAYS = 90;
11
+ /** Stable advisory-lock key serializing audit-chain appends and purges. */
12
+ export const AUDIT_CHAIN_LOCK_KEY = 7_314_005_001;
13
+ const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,200}$/;
14
+ function invalidKey(key) {
15
+ return new NabaError("INVALID_STORE_KEY", "State keys must be 1-200 characters of letters, digits, dot, underscore or hyphen", { status: 400 });
16
+ }
17
+ function assertKey(key) {
18
+ if (typeof key !== "string" || !KEY_PATTERN.test(key) || key === "." || key === "..") {
19
+ throw invalidKey(key);
20
+ }
21
+ return key;
22
+ }
23
+ function unavailable(cause) {
24
+ // Never include the connection string (or any credential) in the error.
25
+ const code = sanitizeCauseCode(cause);
26
+ return new NabaError("STORE_UNAVAILABLE", "PostgreSQL state store is unavailable", {
27
+ status: 503,
28
+ ...(code ? { details: { code } } : {})
29
+ });
30
+ }
31
+ function sanitizeCauseCode(cause) {
32
+ if (typeof cause !== "object" || cause === null)
33
+ return undefined;
34
+ const code = cause.code;
35
+ if (typeof code === "string" && /^[A-Z0-9_]{2,32}$/.test(code))
36
+ return code;
37
+ return undefined;
38
+ }
39
+ function corrupt(key) {
40
+ return new NabaError("STORE_CORRUPT", `Stored value for "${key}" is not valid JSON`, {
41
+ status: 500,
42
+ details: { key }
43
+ });
44
+ }
45
+ function serialize(value) {
46
+ if (value === undefined) {
47
+ throw new NabaError("INVALID_STORE_VALUE", "Cannot persist undefined", { status: 400 });
48
+ }
49
+ try {
50
+ const json = JSON.stringify(value);
51
+ if (json === undefined) {
52
+ throw new Error("JSON.stringify returned undefined");
53
+ }
54
+ return json;
55
+ }
56
+ catch (error) {
57
+ throw new NabaError("INVALID_STORE_VALUE", "State value must be JSON-serializable data", {
58
+ status: 400,
59
+ details: { cause: error instanceof Error ? error.message : String(error) }
60
+ });
61
+ }
62
+ }
63
+ async function createPgliteDriver(dataDir) {
64
+ const { PGlite } = await import("@electric-sql/pglite");
65
+ let database;
66
+ try {
67
+ // PGlite creates the leaf directory but not missing parents. A fresh
68
+ // checkout has no `.naba/`, so create the whole path first.
69
+ await mkdir(dataDir, { recursive: true });
70
+ database = new PGlite(dataDir);
71
+ await database.waitReady;
72
+ }
73
+ catch (error) {
74
+ throw unavailable(error);
75
+ }
76
+ return {
77
+ kind: "pglite",
78
+ async query(sql, params) {
79
+ const result = await database.query(sql, params);
80
+ return result.rows;
81
+ },
82
+ async transaction(fn) {
83
+ return database.transaction(async (transaction) => {
84
+ const query = async (sql, params) => {
85
+ const result = await transaction.query(sql, params);
86
+ return result.rows;
87
+ };
88
+ return fn({ query });
89
+ });
90
+ },
91
+ async close() {
92
+ await database.close();
93
+ }
94
+ };
95
+ }
96
+ async function createPgDriver(connectionString) {
97
+ const module = (await import("pg"));
98
+ const PoolCtor = module.default?.Pool ?? module.Pool;
99
+ if (!PoolCtor)
100
+ throw unavailable(new Error("pg Pool constructor unavailable"));
101
+ const pool = new PoolCtor({ connectionString });
102
+ return {
103
+ kind: "pg",
104
+ async query(sql, params) {
105
+ const result = await pool.query(sql, params);
106
+ return result.rows;
107
+ },
108
+ async transaction(fn) {
109
+ const client = await pool.connect();
110
+ try {
111
+ await client.query("begin");
112
+ const query = async (sql, params) => {
113
+ const result = await client.query(sql, params);
114
+ return result.rows;
115
+ };
116
+ const result = await fn({ query });
117
+ await client.query("commit");
118
+ return result;
119
+ }
120
+ catch (error) {
121
+ await client.query("rollback").catch(() => undefined);
122
+ throw error;
123
+ }
124
+ finally {
125
+ client.release();
126
+ }
127
+ },
128
+ async close() {
129
+ await pool.end();
130
+ }
131
+ };
132
+ }
133
+ async function openDriver(options) {
134
+ const connectionString = typeof options.connectionString === "string" && options.connectionString.trim()
135
+ ? options.connectionString.trim()
136
+ : undefined;
137
+ const dataDir = typeof options.dataDir === "string" && options.dataDir.trim()
138
+ ? options.dataDir.trim()
139
+ : DEFAULT_DATA_DIR;
140
+ try {
141
+ return connectionString
142
+ ? await createPgDriver(connectionString)
143
+ : await createPgliteDriver(dataDir);
144
+ }
145
+ catch (error) {
146
+ throw error instanceof NabaError ? error : unavailable(error);
147
+ }
148
+ }
149
+ /* -------------------------------------------------------------------------- */
150
+ /* State store */
151
+ /* -------------------------------------------------------------------------- */
152
+ class PostgresStateStore {
153
+ provider = "postgres";
154
+ driver;
155
+ keyPrefix;
156
+ queue = Promise.resolve();
157
+ pending = 0;
158
+ initializing;
159
+ closed = false;
160
+ writeGuard;
161
+ constructor(driver, keyPrefix) {
162
+ this.driver = driver;
163
+ this.keyPrefix = keyPrefix;
164
+ }
165
+ /** Runtime-only gate: called before each mutation while a writer lease is held. */
166
+ setWriteGuard(guard) {
167
+ this.writeGuard = guard;
168
+ }
169
+ async init() {
170
+ this.assertOpen();
171
+ if (!this.initializing) {
172
+ this.initializing = this.runInit().catch((error) => {
173
+ this.initializing = undefined;
174
+ throw error instanceof NabaError ? error : unavailable(error);
175
+ });
176
+ }
177
+ return this.initializing;
178
+ }
179
+ async load(key) {
180
+ this.assertOpen();
181
+ const fullKey = this.fullKey(assertKey(key));
182
+ await this.init();
183
+ await this.queue;
184
+ let rows;
185
+ try {
186
+ rows = await this.driver.query("select value from naba_state where key = $1 limit 1", [
187
+ fullKey
188
+ ]);
189
+ }
190
+ catch (error) {
191
+ throw error instanceof NabaError ? error : unavailable(error);
192
+ }
193
+ const row = rows[0];
194
+ if (!row)
195
+ return undefined;
196
+ if (typeof row.value === "string") {
197
+ try {
198
+ return JSON.parse(row.value);
199
+ }
200
+ catch {
201
+ throw corrupt(key);
202
+ }
203
+ }
204
+ return row.value;
205
+ }
206
+ async save(key, value) {
207
+ this.assertOpen();
208
+ const fullKey = this.fullKey(assertKey(key));
209
+ const payload = serialize(value);
210
+ return this.enqueue(async () => {
211
+ await this.init();
212
+ try {
213
+ await this.writeGuard?.();
214
+ await this.driver.query(`insert into naba_state (key, value, updated_at)
215
+ values ($1, $2::jsonb, now())
216
+ on conflict (key) do update set value = excluded.value, updated_at = now()`, [fullKey, payload]);
217
+ }
218
+ catch (error) {
219
+ throw error instanceof NabaError ? error : unavailable(error);
220
+ }
221
+ });
222
+ }
223
+ async delete(key) {
224
+ this.assertOpen();
225
+ const fullKey = this.fullKey(assertKey(key));
226
+ return this.enqueue(async () => {
227
+ await this.init();
228
+ try {
229
+ await this.writeGuard?.();
230
+ await this.driver.query("delete from naba_state where key = $1", [fullKey]);
231
+ }
232
+ catch (error) {
233
+ throw error instanceof NabaError ? error : unavailable(error);
234
+ }
235
+ });
236
+ }
237
+ async flush() {
238
+ await this.queue;
239
+ }
240
+ async close() {
241
+ if (this.closed)
242
+ return;
243
+ await this.queue;
244
+ this.closed = true;
245
+ try {
246
+ await this.driver.close();
247
+ }
248
+ catch (error) {
249
+ throw error instanceof NabaError ? error : unavailable(error);
250
+ }
251
+ }
252
+ /** Number of writes queued but not yet committed (diagnostics/tests). */
253
+ get pendingWrites() {
254
+ return this.pending;
255
+ }
256
+ async runInit() {
257
+ try {
258
+ await this.driver.query(`create table if not exists naba_migrations (
259
+ version integer primary key,
260
+ name text not null,
261
+ applied_at timestamptz not null default now()
262
+ )`);
263
+ await this.driver.query(`create table if not exists naba_state (
264
+ key text primary key,
265
+ value jsonb not null,
266
+ updated_at timestamptz not null default now()
267
+ )`);
268
+ await this.driver.query(`insert into naba_migrations (version, name)
269
+ values ($1, $2)
270
+ on conflict (version) do nothing`, [POSTGRES_SCHEMA_VERSION, "initial_state"]);
271
+ }
272
+ catch (error) {
273
+ throw error instanceof NabaError ? error : unavailable(error);
274
+ }
275
+ }
276
+ enqueue(task) {
277
+ this.pending += 1;
278
+ const run = this.queue.then(task, task);
279
+ this.queue = run.then(() => undefined, () => undefined);
280
+ return run.finally(() => {
281
+ this.pending -= 1;
282
+ });
283
+ }
284
+ fullKey(key) {
285
+ return this.keyPrefix ? `${this.keyPrefix}${key}` : key;
286
+ }
287
+ assertOpen() {
288
+ if (this.closed) {
289
+ throw new NabaError("STORE_CLOSED", "State store has been closed", { status: 409 });
290
+ }
291
+ }
292
+ }
293
+ /* -------------------------------------------------------------------------- */
294
+ /* Runtime schema */
295
+ /* -------------------------------------------------------------------------- */
296
+ const RUNTIME_MIGRATIONS = [
297
+ {
298
+ version: 2,
299
+ name: "rate_limits",
300
+ statements: [
301
+ `create table if not exists naba_rate_limits (
302
+ key text primary key,
303
+ window_start bigint not null,
304
+ count integer not null
305
+ )`
306
+ ]
307
+ },
308
+ {
309
+ version: 3,
310
+ name: "audit_log",
311
+ statements: [
312
+ `create table if not exists naba_audit (
313
+ id bigserial primary key,
314
+ timestamp timestamptz not null,
315
+ request_id text not null,
316
+ method text not null,
317
+ path text not null,
318
+ status integer not null,
319
+ duration_ms double precision not null,
320
+ client_key text not null,
321
+ tenant_id text not null,
322
+ entry jsonb not null
323
+ )`
324
+ ]
325
+ },
326
+ {
327
+ version: 4,
328
+ name: "writer_lease",
329
+ statements: [
330
+ `create table if not exists naba_writer_leases (
331
+ name text primary key,
332
+ owner_id text not null,
333
+ expires_at timestamptz not null
334
+ )`
335
+ ]
336
+ },
337
+ {
338
+ version: 5,
339
+ name: "audit_chain",
340
+ statements: [
341
+ `alter table naba_audit add column if not exists prev_hash text not null default ''`,
342
+ `alter table naba_audit add column if not exists hash text not null default ''`,
343
+ `create table if not exists naba_audit_archive (
344
+ id bigint primary key,
345
+ timestamp timestamptz not null,
346
+ request_id text not null,
347
+ method text not null,
348
+ path text not null,
349
+ status integer not null,
350
+ duration_ms double precision not null,
351
+ client_key text not null,
352
+ tenant_id text not null,
353
+ entry jsonb not null,
354
+ prev_hash text not null default '',
355
+ hash text not null default ''
356
+ )`,
357
+ `create table if not exists naba_audit_anchors (
358
+ id integer primary key check (id = 1),
359
+ last_hash text not null default '',
360
+ cutoff timestamptz,
361
+ updated_at timestamptz not null default now()
362
+ )`,
363
+ `insert into naba_audit_anchors (id, last_hash) values (1, '')
364
+ on conflict (id) do nothing`,
365
+ `create table if not exists naba_audit_heads (
366
+ id integer primary key check (id = 1),
367
+ head_hash text not null default '',
368
+ updated_at timestamptz not null default now()
369
+ )`,
370
+ `insert into naba_audit_heads (id, head_hash)
371
+ select 1, coalesce(
372
+ (select hash from naba_audit order by id desc limit 1),
373
+ (select last_hash from naba_audit_anchors where id = 1),
374
+ ''
375
+ )
376
+ on conflict (id) do update
377
+ set head_hash = excluded.head_hash, updated_at = now()
378
+ where naba_audit_heads.head_hash = ''`
379
+ ]
380
+ }
381
+ ];
382
+ async function ensureRuntimeSchema(driver) {
383
+ try {
384
+ for (const migration of RUNTIME_MIGRATIONS) {
385
+ for (const statement of migration.statements) {
386
+ await driver.query(statement);
387
+ }
388
+ await driver.query(`insert into naba_migrations (version, name)
389
+ values ($1, $2)
390
+ on conflict (version) do nothing`, [migration.version, migration.name]);
391
+ }
392
+ }
393
+ catch (error) {
394
+ throw error instanceof NabaError ? error : unavailable(error);
395
+ }
396
+ await backfillAuditChain(driver);
397
+ }
398
+ /**
399
+ * v3 databases already have audit rows without hashes. Chain them once, starting
400
+ * from the anchor (or the last hashed predecessor), so verification does not
401
+ * reject a legitimate upgrade.
402
+ */
403
+ async function backfillAuditChain(driver) {
404
+ try {
405
+ await driver.transaction(async (tx) => {
406
+ await tx.query("select pg_advisory_xact_lock($1)", [AUDIT_CHAIN_LOCK_KEY]);
407
+ const firstRows = await tx.query("select min(id) as id from naba_audit where hash = ''");
408
+ const first = firstRows[0]?.id;
409
+ if (first === null || first === undefined)
410
+ return;
411
+ const firstId = Number(first);
412
+ if (!Number.isFinite(firstId))
413
+ return;
414
+ const priorRows = await tx.query("select hash from naba_audit where id < $1 order by id desc limit 1", [firstId]);
415
+ const anchorRows = await tx.query("select last_hash from naba_audit_anchors where id = 1");
416
+ let head = priorRows[0]?.hash !== undefined
417
+ ? String(priorRows[0].hash)
418
+ : String(anchorRows[0]?.last_hash ?? "");
419
+ const rows = await tx.query("select id, entry, prev_hash, hash from naba_audit where id >= $1 order by id asc", [firstId]);
420
+ for (const row of rows) {
421
+ const entry = entryFromStored(row.entry);
422
+ if (!entry) {
423
+ throw new NabaError("STORE_CORRUPT", "Audit row is not a valid entry", {
424
+ status: 500,
425
+ details: { id: Number(row.id) }
426
+ });
427
+ }
428
+ const hash = hashAuditEntry(entry, head);
429
+ await tx.query("update naba_audit set prev_hash = $2, hash = $3 where id = $1", [row.id, head, hash]);
430
+ head = hash;
431
+ }
432
+ await tx.query(`update naba_audit_heads
433
+ set head_hash = coalesce(
434
+ (select hash from naba_audit order by id desc limit 1),
435
+ (select last_hash from naba_audit_anchors where id = 1),
436
+ ''
437
+ ), updated_at = now()
438
+ where id = 1`);
439
+ });
440
+ }
441
+ catch (error) {
442
+ throw error instanceof NabaError ? error : unavailable(error);
443
+ }
444
+ }
445
+ /* -------------------------------------------------------------------------- */
446
+ /* Rate limiter */
447
+ /* -------------------------------------------------------------------------- */
448
+ class PostgresRateLimiterImpl {
449
+ driver;
450
+ options;
451
+ lastPrune = 0;
452
+ constructor(driver, options) {
453
+ this.driver = driver;
454
+ this.options = options;
455
+ }
456
+ async consume(key, now = Date.now()) {
457
+ if (typeof key !== "string" || key.trim() === "" || key.length > 256) {
458
+ throw new NabaError("INVALID_RATE_LIMIT_KEY", "A rate-limit key is required", {
459
+ status: 400
460
+ });
461
+ }
462
+ if (typeof now !== "number" || !Number.isFinite(now) || now < 0) {
463
+ throw new NabaError("INVALID_RATE_LIMIT_TIME", "now must be a non-negative timestamp", {
464
+ status: 400
465
+ });
466
+ }
467
+ const { windowMs, max } = this.options;
468
+ const windowStart = Math.floor(now / windowMs) * windowMs;
469
+ let rows;
470
+ try {
471
+ rows = await this.driver.query(`insert into naba_rate_limits (key, window_start, count)
472
+ values ($1, $2, 1)
473
+ on conflict (key) do update
474
+ set count = case
475
+ when naba_rate_limits.window_start = excluded.window_start
476
+ then naba_rate_limits.count + 1
477
+ else 1
478
+ end,
479
+ window_start = case
480
+ when naba_rate_limits.window_start = excluded.window_start
481
+ then naba_rate_limits.window_start
482
+ else excluded.window_start
483
+ end
484
+ returning window_start, count`, [key.trim(), windowStart]);
485
+ }
486
+ catch (error) {
487
+ throw error instanceof NabaError ? error : unavailable(error);
488
+ }
489
+ if (now - this.lastPrune >= 60_000) {
490
+ this.lastPrune = now;
491
+ try {
492
+ // Opportunistic retention: rate-limit rows only need to survive the
493
+ // current window. Keep an hour for diagnostics.
494
+ await this.driver.query("delete from naba_rate_limits where window_start < $1", [now - 60 * 60 * 1000]);
495
+ }
496
+ catch {
497
+ // Cleanup failure must not reject legitimate traffic.
498
+ }
499
+ }
500
+ const row = rows[0];
501
+ if (!row)
502
+ throw unavailable();
503
+ const count = Number(row.count ?? 0);
504
+ const start = Number(row.window_start ?? windowStart);
505
+ const allowed = count <= max;
506
+ return {
507
+ allowed,
508
+ retryAfter: Math.max(1, Math.ceil((start + windowMs - now) / 1000)),
509
+ remaining: Math.max(0, max - count),
510
+ limit: max
511
+ };
512
+ }
513
+ }
514
+ /* -------------------------------------------------------------------------- */
515
+ /* Audit sink + hash chain */
516
+ /* -------------------------------------------------------------------------- */
517
+ const AUDIT_TEXT_LIMITS = {
518
+ requestId: 128,
519
+ method: 16,
520
+ path: 2048,
521
+ clientKey: 128,
522
+ tenantId: 64
523
+ };
524
+ function auditText(value, limit) {
525
+ const text = typeof value === "string" ? value : String(value ?? "");
526
+ return text.length > limit ? text.slice(0, limit) : text;
527
+ }
528
+ /** Whitelist the audit shape so bodies/headers/tokens can never be persisted. */
529
+ function sanitizeAuditEntry(entry) {
530
+ const parsed = typeof entry?.timestamp === "string" ? Date.parse(entry.timestamp) : Number.NaN;
531
+ return {
532
+ timestamp: Number.isFinite(parsed) ? new Date(parsed).toISOString() : new Date().toISOString(),
533
+ requestId: auditText(entry?.requestId, AUDIT_TEXT_LIMITS.requestId),
534
+ method: auditText(entry?.method, AUDIT_TEXT_LIMITS.method).toUpperCase(),
535
+ path: auditText(entry?.path, AUDIT_TEXT_LIMITS.path),
536
+ status: Number.isFinite(entry?.status) ? Math.trunc(Number(entry.status)) : 0,
537
+ durationMs: Number.isFinite(entry?.durationMs) ? Number(entry.durationMs) : 0,
538
+ clientKey: auditText(entry?.clientKey, AUDIT_TEXT_LIMITS.clientKey),
539
+ tenantId: auditText(entry?.tenantId, AUDIT_TEXT_LIMITS.tenantId)
540
+ };
541
+ }
542
+ /**
543
+ * Canonical SHA-256 link: hash = sha256(JSON({prevHash, entry})). Field order is
544
+ * explicit, so JSONB key ordering and property insertion order cannot change
545
+ * the digest. Input must be a sanitized entry.
546
+ */
547
+ export function hashAuditEntry(entry, prevHash) {
548
+ const canonical = JSON.stringify({
549
+ prevHash,
550
+ entry: {
551
+ timestamp: entry.timestamp,
552
+ requestId: entry.requestId,
553
+ method: entry.method,
554
+ path: entry.path,
555
+ status: entry.status,
556
+ durationMs: entry.durationMs,
557
+ clientKey: entry.clientKey,
558
+ tenantId: entry.tenantId
559
+ }
560
+ });
561
+ return createHash("sha256").update(canonical, "utf8").digest("hex");
562
+ }
563
+ function isRecord(value) {
564
+ return typeof value === "object" && value !== null && !Array.isArray(value);
565
+ }
566
+ /** Reconstruct a stored entry without normalizing it (tamper detection). */
567
+ function entryFromStored(value) {
568
+ let raw = value;
569
+ if (typeof raw === "string") {
570
+ try {
571
+ raw = JSON.parse(raw);
572
+ }
573
+ catch {
574
+ return null;
575
+ }
576
+ }
577
+ if (!isRecord(raw))
578
+ return null;
579
+ const timestamp = raw.timestamp;
580
+ const requestId = raw.requestId;
581
+ const method = raw.method;
582
+ const path = raw.path;
583
+ const status = raw.status;
584
+ const durationMs = raw.durationMs;
585
+ const clientKey = raw.clientKey;
586
+ const tenantId = raw.tenantId;
587
+ if (typeof timestamp !== "string" ||
588
+ typeof requestId !== "string" ||
589
+ typeof method !== "string" ||
590
+ typeof path !== "string" ||
591
+ typeof status !== "number" ||
592
+ typeof durationMs !== "number" ||
593
+ typeof clientKey !== "string" ||
594
+ typeof tenantId !== "string" ||
595
+ !Number.isFinite(status) ||
596
+ !Number.isFinite(durationMs)) {
597
+ return null;
598
+ }
599
+ return { timestamp, requestId, method, path, status, durationMs, clientKey, tenantId };
600
+ }
601
+ /** Current chain head: last live row hash, else the anchor (genesis ""). */
602
+ async function readAuditHead(queryable) {
603
+ const rows = await queryable.query(`select coalesce(
604
+ (select hash from naba_audit order by id desc limit 1),
605
+ (select last_hash from naba_audit_anchors where id = 1),
606
+ ''
607
+ ) as head`);
608
+ return String(rows[0]?.head ?? "");
609
+ }
610
+ class PostgresAuditSinkImpl {
611
+ driver;
612
+ queue = Promise.resolve();
613
+ writeError;
614
+ closed = false;
615
+ lastHash = "";
616
+ initialized = false;
617
+ constructor(driver) {
618
+ this.driver = driver;
619
+ }
620
+ /** Read the current head so the first append chains onto existing history. */
621
+ async init() {
622
+ if (this.initialized)
623
+ return;
624
+ try {
625
+ this.lastHash = await readAuditHead(this.driver);
626
+ this.initialized = true;
627
+ }
628
+ catch (error) {
629
+ throw error instanceof NabaError ? error : unavailable(error);
630
+ }
631
+ }
632
+ record(entry) {
633
+ if (this.closed)
634
+ return;
635
+ const sanitized = sanitizeAuditEntry(entry);
636
+ const payload = JSON.stringify(sanitized);
637
+ this.queue = this.queue.then(async () => {
638
+ try {
639
+ await this.driver.transaction(async (tx) => {
640
+ // Serializes appends across replicas so the chain cannot fork.
641
+ await tx.query("select pg_advisory_xact_lock($1)", [AUDIT_CHAIN_LOCK_KEY]);
642
+ const prevHash = await readAuditHead(tx);
643
+ const hash = hashAuditEntry(sanitized, prevHash);
644
+ await tx.query(`insert into naba_audit
645
+ (timestamp, request_id, method, path, status, duration_ms, client_key, tenant_id,
646
+ entry, prev_hash, hash)
647
+ values ($1::timestamptz, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11)`, [
648
+ sanitized.timestamp,
649
+ sanitized.requestId,
650
+ sanitized.method,
651
+ sanitized.path,
652
+ sanitized.status,
653
+ sanitized.durationMs,
654
+ sanitized.clientKey,
655
+ sanitized.tenantId,
656
+ payload,
657
+ prevHash,
658
+ hash
659
+ ]);
660
+ await tx.query("update naba_audit_heads set head_hash = $1, updated_at = now() where id = 1", [hash]);
661
+ this.lastHash = hash;
662
+ });
663
+ }
664
+ catch (error) {
665
+ this.writeError ??= error instanceof Error ? error : new Error("audit insert failed");
666
+ }
667
+ });
668
+ }
669
+ async flush() {
670
+ await this.queue;
671
+ if (this.writeError) {
672
+ throw new NabaError("STORE_UNAVAILABLE", "PostgreSQL audit sink write failed", {
673
+ status: 503
674
+ });
675
+ }
676
+ }
677
+ async close() {
678
+ if (this.closed)
679
+ return;
680
+ this.closed = true;
681
+ await this.flush();
682
+ }
683
+ /** Last hash written by this sink (diagnostics; the DB head is authoritative). */
684
+ get head() {
685
+ return this.lastHash;
686
+ }
687
+ }
688
+ /** Verify live rows in id order, starting from the anchor. */
689
+ async function verifyChain(queryable) {
690
+ const anchorRows = await queryable.query("select last_hash from naba_audit_anchors where id = 1");
691
+ let expected = String(anchorRows[0]?.last_hash ?? "");
692
+ const rows = await queryable.query("select id, entry, prev_hash, hash from naba_audit order by id asc");
693
+ let checked = 0;
694
+ for (const row of rows) {
695
+ checked += 1;
696
+ const id = Number(row.id);
697
+ if (String(row.prev_hash ?? "") !== expected) {
698
+ return { valid: false, checked, brokenAt: id };
699
+ }
700
+ const entry = entryFromStored(row.entry);
701
+ if (!entry) {
702
+ return { valid: false, checked, brokenAt: id };
703
+ }
704
+ const expectedHash = hashAuditEntry(entry, expected);
705
+ if (String(row.hash ?? "") !== expectedHash) {
706
+ return { valid: false, checked, brokenAt: id };
707
+ }
708
+ expected = expectedHash;
709
+ }
710
+ const headRows = await queryable.query(`select h.head_hash,
711
+ (select count(*) from naba_audit_heads where id = 1) as guaranteed
712
+ from (select 1) as one
713
+ left join naba_audit_heads h on h.id = 1`);
714
+ const guaranteed = Number(headRows[0]?.guaranteed ?? 0) > 0;
715
+ if (guaranteed) {
716
+ const head = String(headRows[0]?.head_hash ?? "");
717
+ if (head !== expected) {
718
+ const last = rows.at(-1);
719
+ return {
720
+ valid: false,
721
+ checked: checked + 1,
722
+ brokenAt: last ? Number(last.id) + 1 : 0
723
+ };
724
+ }
725
+ }
726
+ return { valid: true, checked };
727
+ }
728
+ /** Archive and delete the longest all-older prefix, then advance the anchor. */
729
+ async function purgeAuditRows(driver, retentionDays, now = Date.now()) {
730
+ if (retentionDays === 0) {
731
+ return { archived: 0, deleted: 0, cutoff: null, lastHash: null };
732
+ }
733
+ const cutoff = new Date(now - retentionDays * 86_400_000).toISOString();
734
+ try {
735
+ return await driver.transaction(async (tx) => {
736
+ await tx.query("select pg_advisory_xact_lock($1)", [AUDIT_CHAIN_LOCK_KEY]);
737
+ // Longest id-prefix whose rows are all older than the cutoff. This keeps
738
+ // the remaining live chain contiguous even with clock skew.
739
+ const boundaryRows = await tx.query(`select coalesce(
740
+ (select min(id) - 1 from naba_audit where timestamp >= $1::timestamptz),
741
+ (select max(id) from naba_audit)
742
+ ) as boundary`, [cutoff]);
743
+ const rawBoundary = boundaryRows[0]?.boundary;
744
+ const boundary = rawBoundary === null || rawBoundary === undefined ? Number.NaN : Number(rawBoundary);
745
+ if (!Number.isFinite(boundary) || boundary <= 0) {
746
+ return { archived: 0, deleted: 0, cutoff, lastHash: null };
747
+ }
748
+ const lastRows = await tx.query("select hash from naba_audit where id = $1", [boundary]);
749
+ if (lastRows.length === 0) {
750
+ return { archived: 0, deleted: 0, cutoff, lastHash: null };
751
+ }
752
+ const lastHash = String(lastRows[0]?.hash ?? "");
753
+ await tx.query(`insert into naba_audit_archive
754
+ (id, timestamp, request_id, method, path, status, duration_ms, client_key, tenant_id,
755
+ entry, prev_hash, hash)
756
+ select id, timestamp, request_id, method, path, status, duration_ms, client_key, tenant_id,
757
+ entry, prev_hash, hash
758
+ from naba_audit
759
+ where id <= $1
760
+ on conflict (id) do nothing`, [boundary]);
761
+ const deleted = await tx.query("delete from naba_audit where id <= $1 returning id", [boundary]);
762
+ if (deleted.length === 0) {
763
+ return { archived: 0, deleted: 0, cutoff, lastHash: null };
764
+ }
765
+ await tx.query(`update naba_audit_anchors
766
+ set last_hash = $1, cutoff = $2::timestamptz, updated_at = now()
767
+ where id = 1`, [lastHash, cutoff]);
768
+ await tx.query(`update naba_audit_heads
769
+ set head_hash = coalesce(
770
+ (select hash from naba_audit order by id desc limit 1),
771
+ $1
772
+ ), updated_at = now()
773
+ where id = 1`, [lastHash]);
774
+ return {
775
+ archived: deleted.length,
776
+ deleted: deleted.length,
777
+ cutoff,
778
+ lastHash
779
+ };
780
+ });
781
+ }
782
+ catch (error) {
783
+ throw error instanceof NabaError ? error : unavailable(error);
784
+ }
785
+ }
786
+ /* -------------------------------------------------------------------------- */
787
+ /* Writer lease */
788
+ /* -------------------------------------------------------------------------- */
789
+ function leaseHeld() {
790
+ return new NabaError("STORE_WRITER_LEASE_HELD", "Another NABA writer owns this database", {
791
+ status: 409
792
+ });
793
+ }
794
+ class WriterLease {
795
+ driver;
796
+ name;
797
+ ownerId;
798
+ ttlMs;
799
+ timer;
800
+ acquired = false;
801
+ constructor(driver, name, ownerId, ttlMs) {
802
+ this.driver = driver;
803
+ this.name = name;
804
+ this.ownerId = ownerId;
805
+ this.ttlMs = ttlMs;
806
+ }
807
+ async acquire() {
808
+ let rows;
809
+ try {
810
+ rows = await this.driver.query(`insert into naba_writer_leases (name, owner_id, expires_at)
811
+ values ($1, $2, now() + ($3::bigint * interval '1 millisecond'))
812
+ on conflict (name) do update
813
+ set owner_id = excluded.owner_id, expires_at = excluded.expires_at
814
+ where naba_writer_leases.owner_id = excluded.owner_id
815
+ or naba_writer_leases.expires_at < now()
816
+ returning owner_id`, [this.name, this.ownerId, this.ttlMs]);
817
+ }
818
+ catch (error) {
819
+ throw error instanceof NabaError ? error : unavailable(error);
820
+ }
821
+ if (rows.length === 0)
822
+ throw leaseHeld();
823
+ this.acquired = true;
824
+ }
825
+ async heartbeat() {
826
+ try {
827
+ const rows = await this.driver.query(`update naba_writer_leases
828
+ set expires_at = now() + ($3::bigint * interval '1 millisecond')
829
+ where name = $1 and owner_id = $2
830
+ returning owner_id`, [this.name, this.ownerId, this.ttlMs]);
831
+ return rows.length > 0;
832
+ }
833
+ catch (error) {
834
+ throw error instanceof NabaError ? error : unavailable(error);
835
+ }
836
+ }
837
+ async assertActive() {
838
+ let rows;
839
+ try {
840
+ rows = await this.driver.query(`select 1 as ok from naba_writer_leases
841
+ where name = $1 and owner_id = $2 and expires_at > now()
842
+ limit 1`, [this.name, this.ownerId]);
843
+ }
844
+ catch (error) {
845
+ throw error instanceof NabaError ? error : unavailable(error);
846
+ }
847
+ if (rows.length === 0) {
848
+ throw new NabaError("STORE_WRITER_LEASE_LOST", "The NABA writer lease is no longer held; refusing to write", { status: 409 });
849
+ }
850
+ }
851
+ startHeartbeat() {
852
+ if (this.timer)
853
+ return;
854
+ const interval = Math.max(200, Math.floor(this.ttlMs / 3));
855
+ this.timer = setInterval(() => {
856
+ void this.heartbeat().catch(() => {
857
+ // A missed heartbeat is retried on the next tick. The lease expiring is
858
+ // the safety mechanism; never take the process down for it.
859
+ });
860
+ }, interval);
861
+ this.timer.unref?.();
862
+ }
863
+ stopHeartbeat() {
864
+ if (this.timer) {
865
+ clearInterval(this.timer);
866
+ this.timer = undefined;
867
+ }
868
+ }
869
+ async release() {
870
+ if (!this.acquired)
871
+ return;
872
+ this.acquired = false;
873
+ try {
874
+ await this.driver.query("delete from naba_writer_leases where name = $1 and owner_id = $2", [this.name, this.ownerId]);
875
+ }
876
+ catch (error) {
877
+ throw error instanceof NabaError ? error : unavailable(error);
878
+ }
879
+ }
880
+ async expiresAt() {
881
+ try {
882
+ const rows = await this.driver.query(`select (extract(epoch from expires_at) * 1000)::bigint as expires_ms
883
+ from naba_writer_leases
884
+ where name = $1 and owner_id = $2`, [this.name, this.ownerId]);
885
+ const value = rows[0]?.expires_ms;
886
+ if (value === undefined || value === null)
887
+ return null;
888
+ const parsed = Number(value);
889
+ return Number.isFinite(parsed) ? parsed : null;
890
+ }
891
+ catch (error) {
892
+ throw error instanceof NabaError ? error : unavailable(error);
893
+ }
894
+ }
895
+ }
896
+ /* -------------------------------------------------------------------------- */
897
+ /* Public factories */
898
+ /* -------------------------------------------------------------------------- */
899
+ function normalizePrefix(keyPrefix) {
900
+ if (keyPrefix === undefined || keyPrefix === null)
901
+ return "";
902
+ if (typeof keyPrefix !== "string") {
903
+ throw new NabaError("INVALID_KEY_PREFIX", "keyPrefix must be a string", { status: 400 });
904
+ }
905
+ const trimmed = keyPrefix.trim();
906
+ if (!trimmed)
907
+ return "";
908
+ return trimmed.endsWith(":") ? trimmed : `${trimmed}:`;
909
+ }
910
+ export async function createPostgresStateStore(options = {}) {
911
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
912
+ throw new NabaError("INVALID_STORE_OPTIONS", "Postgres state store options must be an object", {
913
+ status: 400
914
+ });
915
+ }
916
+ const keyPrefix = normalizePrefix(options.keyPrefix);
917
+ const driver = await openDriver(options);
918
+ return new PostgresStateStore(driver, keyPrefix);
919
+ }
920
+ function defaultOwnerId() {
921
+ let host = "host";
922
+ try {
923
+ host = hostname() || host;
924
+ }
925
+ catch {
926
+ /* hostname is best-effort only */
927
+ }
928
+ return `${host}:${process.pid}:${randomUUID().slice(0, 8)}`;
929
+ }
930
+ function validateRateLimit(rateLimit) {
931
+ if (!rateLimit ||
932
+ typeof rateLimit !== "object" ||
933
+ typeof rateLimit.windowMs !== "number" ||
934
+ !Number.isFinite(rateLimit.windowMs) ||
935
+ rateLimit.windowMs <= 0 ||
936
+ !Number.isInteger(rateLimit.max) ||
937
+ rateLimit.max < 1) {
938
+ throw new NabaError("INVALID_RATE_LIMIT", "rateLimit requires a positive windowMs and a positive integer max", { status: 400 });
939
+ }
940
+ }
941
+ /** Offline verification against a database/data directory (opens its own driver). */
942
+ export async function verifyAuditChain(options = {}) {
943
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
944
+ throw new NabaError("INVALID_STORE_OPTIONS", "Verification options must be an object", {
945
+ status: 400
946
+ });
947
+ }
948
+ const driver = await openDriver(options);
949
+ try {
950
+ return await verifyChain(driver);
951
+ }
952
+ catch (error) {
953
+ throw error instanceof NabaError ? error : unavailable(error);
954
+ }
955
+ finally {
956
+ await driver.close().catch(() => undefined);
957
+ }
958
+ }
959
+ export async function createPostgresRuntime(options = {}) {
960
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
961
+ throw new NabaError("INVALID_RUNTIME_OPTIONS", "Postgres runtime options must be an object", {
962
+ status: 400
963
+ });
964
+ }
965
+ const rateLimit = options.rateLimit;
966
+ if (rateLimit !== undefined)
967
+ validateRateLimit(rateLimit);
968
+ const ttlMs = options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS;
969
+ if (!Number.isInteger(ttlMs) || ttlMs < 300 || ttlMs > 86_400_000) {
970
+ throw new NabaError("INVALID_LEASE_TTL", "leaseTtlMs must be an integer between 300 and 86400000", { status: 400 });
971
+ }
972
+ const ownerId = typeof options.ownerId === "string" && options.ownerId.trim()
973
+ ? options.ownerId.trim()
974
+ : defaultOwnerId();
975
+ if (ownerId.length > 200) {
976
+ throw new NabaError("INVALID_OWNER_ID", "ownerId must be at most 200 characters", {
977
+ status: 400
978
+ });
979
+ }
980
+ const auditRetentionDays = options.auditRetentionDays ?? DEFAULT_AUDIT_RETENTION_DAYS;
981
+ if (!Number.isInteger(auditRetentionDays) || auditRetentionDays < 0) {
982
+ throw new NabaError("INVALID_AUDIT_RETENTION", "auditRetentionDays must be a non-negative integer (0 keeps rows forever)", { status: 400 });
983
+ }
984
+ const singleWriter = options.singleWriter !== false;
985
+ const driver = await openDriver(options);
986
+ const store = new PostgresStateStore(driver, "");
987
+ try {
988
+ await store.init();
989
+ await ensureRuntimeSchema(driver);
990
+ }
991
+ catch (error) {
992
+ await driver.close().catch(() => undefined);
993
+ throw error instanceof NabaError ? error : unavailable(error);
994
+ }
995
+ const auditSink = new PostgresAuditSinkImpl(driver);
996
+ try {
997
+ await auditSink.init();
998
+ }
999
+ catch (error) {
1000
+ await driver.close().catch(() => undefined);
1001
+ throw error instanceof NabaError ? error : unavailable(error);
1002
+ }
1003
+ const rateLimiter = rateLimit
1004
+ ? new PostgresRateLimiterImpl(driver, { windowMs: rateLimit.windowMs, max: rateLimit.max })
1005
+ : undefined;
1006
+ let lease;
1007
+ if (singleWriter) {
1008
+ lease = new WriterLease(driver, NABA_WRITER_LEASE_NAME, ownerId, ttlMs);
1009
+ try {
1010
+ await lease.acquire();
1011
+ }
1012
+ catch (error) {
1013
+ lease.stopHeartbeat();
1014
+ await auditSink.close().catch(() => undefined);
1015
+ await store.close().catch(() => undefined);
1016
+ throw error instanceof NabaError ? error : unavailable(error);
1017
+ }
1018
+ lease.startHeartbeat();
1019
+ store.setWriteGuard(() => lease.assertActive());
1020
+ }
1021
+ let closed = false;
1022
+ return {
1023
+ store,
1024
+ rateLimiter,
1025
+ auditSink,
1026
+ ownerId,
1027
+ auditRetentionDays,
1028
+ verifyAuditChain: async () => {
1029
+ try {
1030
+ return await verifyChain(driver);
1031
+ }
1032
+ catch (error) {
1033
+ throw error instanceof NabaError ? error : unavailable(error);
1034
+ }
1035
+ },
1036
+ purgeAudit: async (retentionDays) => {
1037
+ const retention = retentionDays ?? auditRetentionDays;
1038
+ if (!Number.isInteger(retention) || retention < 0) {
1039
+ throw new NabaError("INVALID_AUDIT_RETENTION", "auditRetentionDays must be a non-negative integer (0 keeps rows forever)", { status: 400 });
1040
+ }
1041
+ return purgeAuditRows(driver, retention);
1042
+ },
1043
+ ...(lease
1044
+ ? {
1045
+ lease: {
1046
+ name: NABA_WRITER_LEASE_NAME,
1047
+ ownerId,
1048
+ expiresAt: () => lease.expiresAt(),
1049
+ heartbeat: async () => {
1050
+ const held = await lease.heartbeat();
1051
+ if (!held) {
1052
+ throw new NabaError("STORE_WRITER_LEASE_LOST", "The NABA writer lease is no longer held", { status: 409 });
1053
+ }
1054
+ }
1055
+ }
1056
+ }
1057
+ : {}),
1058
+ async close() {
1059
+ if (closed)
1060
+ return;
1061
+ closed = true;
1062
+ lease?.stopHeartbeat();
1063
+ try {
1064
+ await auditSink.close();
1065
+ }
1066
+ finally {
1067
+ try {
1068
+ await lease?.release();
1069
+ }
1070
+ finally {
1071
+ await store.close();
1072
+ }
1073
+ }
1074
+ }
1075
+ };
1076
+ }
1077
+ //# sourceMappingURL=index.js.map