leakshield 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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +546 -2
  3. package/README.zh-TW.md +565 -0
  4. package/dist/cli.js +61 -0
  5. package/dist/config/loader.js +94 -0
  6. package/dist/decision/deidentify.js +195 -0
  7. package/dist/decision/ingress.js +136 -0
  8. package/dist/decision/mapping-key.js +318 -0
  9. package/dist/decision/mapping-store.js +555 -0
  10. package/dist/decision/model.js +76 -0
  11. package/dist/decision/pseudonymization.js +1230 -0
  12. package/dist/decision/redaction.js +185 -0
  13. package/dist/decision/schema-strings.js +42 -0
  14. package/dist/doctor.js +438 -0
  15. package/dist/env-queries.js +584 -0
  16. package/dist/forget.js +56 -0
  17. package/dist/help.js +37 -0
  18. package/dist/i18n/en.js +71 -0
  19. package/dist/i18n/index.js +28 -0
  20. package/dist/i18n/zh-TW.js +71 -0
  21. package/dist/index.js +12 -0
  22. package/dist/opencode-env-tools.js +243 -0
  23. package/dist/opencode-hooks.js +84 -0
  24. package/dist/opencode-transparent-aisdk.js +100 -0
  25. package/dist/opencode-transparent-http.js +2315 -0
  26. package/dist/opencode-transparent-stream.js +192 -0
  27. package/dist/opencode-transparent-ws.js +298 -0
  28. package/dist/opencode-transparent.js +1492 -0
  29. package/dist/opencode-v2.js +216 -0
  30. package/dist/opencode.js +175 -0
  31. package/dist/plugin-options.js +100 -0
  32. package/dist/rules/builtin.js +283 -0
  33. package/dist/rules/dynamic.js +68 -0
  34. package/dist/scanner/encoding.js +274 -0
  35. package/dist/scanner/engine.js +321 -0
  36. package/dist/scanner/exact-values.js +99 -0
  37. package/dist/scanner/redaction-verifier.js +82 -0
  38. package/dist/scanner/unicode.js +157 -0
  39. package/dist/scanner/utils.js +60 -0
  40. package/dist/transports/cli.js +447 -0
  41. package/dist/transports/web-ui.js +540 -0
  42. package/dist/transports/web.js +200 -0
  43. package/dist/types.js +23 -0
  44. package/dist/utils/files.js +36 -0
  45. package/dist/utils/path-security.js +30 -0
  46. package/dist/utils/win-encoding.js +45 -0
  47. package/package.json +71 -4
@@ -0,0 +1,555 @@
1
+ /**
2
+ * W2 (B1, R2 2026-10-07) encrypted SQLite mapping store — the persistence
3
+ * adapter for the transparent pseudonymization core (decision
4
+ * `docs/plans/2026-10-07-persistence-decision-db-over-t2.md`).
5
+ *
6
+ * Design constraints (decision §4 + external-review R1/R2 rounds):
7
+ * - Per-entry AES-256-GCM; AAD binds `sessionId || token` so a row moved
8
+ * between sessions/tokens fails authentication instead of decrypting.
9
+ * - Originals NEVER appear in plaintext anywhere in the file (tokens do —
10
+ * they are non-sensitive by design: they ride transcripts already).
11
+ * - Dual-secret custody: this module needs BOTH the DB file and the key
12
+ * provider's key; either alone exposes nothing.
13
+ * - Degrade, never fail-closed: unreadable DB → the caller falls back to
14
+ * memory-only; undecryptable rows are skipped (treated as absent).
15
+ * - WAL journal; writes are single transactions; lazy TTL sweep on open
16
+ * (writer handles only — readOnly handles never write).
17
+ * - Pure storage: no OpenCode imports, no config coupling. The core stays
18
+ * fs/db-free; this adapter feeds it via seedSession (B3).
19
+ *
20
+ * Concurrency & lifecycle invariants (R1+R2):
21
+ * - Lazy `node:sqlite` load: a runtime without the driver must not break
22
+ * plugin load when persistence is OFF (zero-diff default path).
23
+ * - Initialization (DDL, version upgrade, meta bootstrap, key pinning) runs
24
+ * in ONE BEGIN IMMEDIATE transaction with ON CONFLICT DO NOTHING inserts:
25
+ * two first-openers can never clobber each other's key identity (R2-3).
26
+ * - Key identity pinning: sha256(key) prefix recorded in meta. Opening with
27
+ * a DIFFERENT key throws MappingKeyMismatchError (memory-only degrade),
28
+ * never silently re-keys. `forgetAll` clears the pin so a mismatched store
29
+ * can be deliberately reset with `forget --all` (R2-13). readOnly handles
30
+ * never pin anything (R2-12).
31
+ * - Optimistic concurrency with absent-sentinel and tombstones:
32
+ * - expectedVersion === 0 means "the row was ABSENT when this handle last
33
+ * looked" — writing then requires the row to still be absent (R2-1).
34
+ * - every delete (forget / TTL sweep / LRU eviction) records the row's
35
+ * version in session_tombstones; re-creation CONTINUES the numbering, so
36
+ * a stale writer's remembered version can never match a re-created row
37
+ * (no ABA resurrection, R2-2).
38
+ * - Bounded retention: a single snapshot larger than maxEntries is refused
39
+ * outright (R2-10); beyond that, maxSessions / maxEntries evict
40
+ * least-recently-used sessions inside the write transaction.
41
+ * - Erasure honesty: `PRAGMA secure_delete = ON` zeroes deleted pages,
42
+ * forgetAll additionally VACUUMs and truncates the WAL. Logical +
43
+ * best-effort in-file erasure — physical media residue is out of scope.
44
+ */
45
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
46
+ import { createRequire } from "node:module";
47
+ import { mkdirSync } from "node:fs";
48
+ import { dirname } from "node:path";
49
+ /** In-memory key provider for tests and throwaway stores. */
50
+ export class InMemoryMappingKeyProvider {
51
+ key;
52
+ constructor(seed) {
53
+ this.key = seed !== undefined && seed.length === 32 ? Buffer.from(seed) : randomBytes(32);
54
+ }
55
+ getOrCreateKey() {
56
+ return this.key;
57
+ }
58
+ }
59
+ /** CAS failure: another process holds a newer (or simply different-lineage)
60
+ * snapshot for this session; the stale writer is refused. */
61
+ export class MappingStoreConflictError extends Error {
62
+ constructor(sessionId) {
63
+ super(`mapping store version conflict for session ${sessionId}: a newer snapshot exists; write skipped`);
64
+ this.name = "MappingStoreConflictError";
65
+ }
66
+ }
67
+ /** A forget ran under this handle; persisting now would resurrect erased data. */
68
+ export class MappingForgottenError extends Error {
69
+ constructor() {
70
+ super("mappings were forgotten while this process was running; persistence disabled for this process");
71
+ this.name = "MappingForgottenError";
72
+ }
73
+ }
74
+ /** The resolved key does not match the key identity pinned in this store. */
75
+ export class MappingKeyMismatchError extends Error {
76
+ constructor() {
77
+ super("resolved key does not match this store's pinned key identity (key source changed?); " +
78
+ "degrading to memory-only — run `leakshield --forget --all` to reset, or restore the original key source");
79
+ this.name = "MappingKeyMismatchError";
80
+ }
81
+ }
82
+ /** The single snapshot exceeds the store-wide entry cap; refused outright. */
83
+ export class MappingSnapshotTooLargeError extends Error {
84
+ constructor(sessionId, entries, cap) {
85
+ super(`session ${sessionId} snapshot (${entries} entries) exceeds the store entry cap (${cap}); write refused`);
86
+ this.name = "MappingSnapshotTooLargeError";
87
+ }
88
+ }
89
+ /**
90
+ * Stable identity for a key: sha256 prefix. The key is 256-bit random, so
91
+ * publishing this digest inside the (plaintext) meta row leaks nothing about
92
+ * the key material; it exists to detect key-source drift before any write.
93
+ */
94
+ export function deriveKeyId(key) {
95
+ return createHash("sha256").update(key).digest("hex").slice(0, 16);
96
+ }
97
+ const SCHEMA_VERSION = "3";
98
+ const KNOWN_SCHEMA_VERSIONS = new Set(["1", "2", "3"]);
99
+ const NONCE_BYTES = 12;
100
+ const TAG_BYTES = 16;
101
+ const DAY_MS = 86_400_000;
102
+ const DEFAULT_MAX_SESSIONS = 256;
103
+ const DEFAULT_MAX_ENTRIES = 50_000;
104
+ // ─── R-round: lazy driver load (zero-diff for persistence-off users) ───────
105
+ // A static `import { DatabaseSync } from "node:sqlite"` would crash module
106
+ // load on runtimes without the driver (Node < 22.5, or 22.x without the
107
+ // experimental flag) — even for users who never enabled persistence. Loading
108
+ // via createRequire keeps the public API synchronous and confines the failure
109
+ // to openMappingStore, which callers already translate into memory-only
110
+ // degradation.
111
+ const nodeRequire = createRequire(import.meta.url);
112
+ let sqliteModule = null;
113
+ function loadSqlite() {
114
+ if (sqliteModule === null) {
115
+ try {
116
+ sqliteModule = nodeRequire("node:sqlite");
117
+ }
118
+ catch (error) {
119
+ throw new Error(`node:sqlite is unavailable on this runtime (${error.message}); ` +
120
+ "persistence requires Node 22.5+ (24+ recommended) or Bun — degrading to memory-only");
121
+ }
122
+ }
123
+ return sqliteModule;
124
+ }
125
+ function encryptOriginal(key, sessionId, token, original) {
126
+ const nonce = randomBytes(NONCE_BYTES);
127
+ const cipher = createCipheriv("aes-256-gcm", key, nonce, { authTagLength: TAG_BYTES });
128
+ cipher.setAAD(Buffer.from(`${sessionId}\u0000${token}`, "utf8"));
129
+ const ciphertext = Buffer.concat([cipher.update(original, "utf8"), cipher.final()]);
130
+ return Buffer.concat([nonce, cipher.getAuthTag(), ciphertext]);
131
+ }
132
+ function decryptOriginal(key, sessionId, token, blob) {
133
+ try {
134
+ if (blob.length <= NONCE_BYTES + TAG_BYTES)
135
+ return null;
136
+ const nonce = blob.subarray(0, NONCE_BYTES);
137
+ const tag = blob.subarray(NONCE_BYTES, NONCE_BYTES + TAG_BYTES);
138
+ const ciphertext = blob.subarray(NONCE_BYTES + TAG_BYTES);
139
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce, { authTagLength: TAG_BYTES });
140
+ decipher.setAAD(Buffer.from(`${sessionId}\u0000${token}`, "utf8"));
141
+ decipher.setAuthTag(tag);
142
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
143
+ }
144
+ catch {
145
+ return null; // wrong key, tampered AAD, or corrupted row: treat as absent
146
+ }
147
+ }
148
+ /** readOnly handle for an uninitialized file: counts zero, writes refuse. */
149
+ function stubStore() {
150
+ return {
151
+ loadSession: () => null,
152
+ absentGeneration: () => 0,
153
+ putSession: () => {
154
+ throw new Error("read-only mapping store handle cannot persist");
155
+ },
156
+ forgetSession: () => false,
157
+ forgetAll: () => 0,
158
+ sessionCount: () => 0,
159
+ close: () => undefined,
160
+ };
161
+ }
162
+ /**
163
+ * Opens (creating when needed) the encrypted mapping store. Throws only on
164
+ * unreadable/uncreatable files or key-identity mismatch — callers translate
165
+ * that into a memory-only degradation, never a conversation failure
166
+ * (decision §4.6).
167
+ */
168
+ export function openMappingStore(options) {
169
+ const ttlDays = options.ttlDays ?? 7;
170
+ const maxSessions = options.maxSessions ?? DEFAULT_MAX_SESSIONS;
171
+ const maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;
172
+ const now = options.now ?? Date.now;
173
+ const key = options.keyProvider.getOrCreateKey();
174
+ if (key.length !== 32)
175
+ throw new Error("mapping key must be 32 bytes");
176
+ mkdirSync(dirname(options.path), { recursive: true, mode: 0o700 });
177
+ const { DatabaseSync } = loadSqlite();
178
+ const db = new DatabaseSync(options.path);
179
+ // R3-F1/F3: connection-local pragmas on EVERY handle — secure_delete
180
+ // zeroes freed pages for any deleting handle (writer or erase), busy_timeout
181
+ // bounds lock waits instead of instant SQLITE_BUSY. journal_mode is a FILE
182
+ // property: only writers may set it (a probe must never write the header).
183
+ let epochAtOpen = 0;
184
+ try {
185
+ // Inside the close-on-failure boundary: a corrupt/non-SQLite file or a
186
+ // filesystem error here must not leak the handle (fd/lock) either.
187
+ db.exec("PRAGMA foreign_keys = ON");
188
+ db.exec("PRAGMA secure_delete = ON");
189
+ db.exec("PRAGMA busy_timeout = 5000");
190
+ if (!options.readOnly)
191
+ db.exec("PRAGMA journal_mode = WAL");
192
+ const metaTable = db
193
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'")
194
+ .get();
195
+ const initialized = metaTable !== undefined;
196
+ if (options.readOnly) {
197
+ // R2-12: an observation handle NEVER initializes, upgrades, pins, or
198
+ // sweeps. An uninitialized file (or one missing its schema marker)
199
+ // yields an empty stub rather than a side-effecting bootstrap.
200
+ if (!initialized) {
201
+ db.close();
202
+ return stubStore();
203
+ }
204
+ const versionRow = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
205
+ if (versionRow === undefined) {
206
+ db.close();
207
+ return stubStore();
208
+ }
209
+ if (versionRow.value !== SCHEMA_VERSION) {
210
+ throw new Error(`mapping store schema version ${versionRow.value} needs a writer open to upgrade to ${SCHEMA_VERSION} (run the plugin once)`);
211
+ }
212
+ const epochRow = db.prepare("SELECT value FROM meta WHERE key = 'forget_epoch'").get();
213
+ epochAtOpen = epochRow !== undefined ? Number.parseInt(epochRow.value, 10) : 0;
214
+ }
215
+ else {
216
+ // Writer initialization: ONE immediate transaction so two first-openers
217
+ // serialize; meta inserts never replace (R2-3), upgrades from v1/v2
218
+ // complete inside the same transaction (R2-11).
219
+ db.exec("BEGIN IMMEDIATE");
220
+ try {
221
+ db.exec(`
222
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
223
+ CREATE TABLE IF NOT EXISTS sessions (
224
+ session_id TEXT PRIMARY KEY,
225
+ epoch TEXT NOT NULL,
226
+ created_at INTEGER NOT NULL,
227
+ last_used_at INTEGER NOT NULL,
228
+ expires_at INTEGER NOT NULL,
229
+ version INTEGER NOT NULL DEFAULT 1
230
+ );
231
+ CREATE TABLE IF NOT EXISTS session_tombstones (
232
+ session_id TEXT PRIMARY KEY,
233
+ last_version INTEGER NOT NULL
234
+ );
235
+ CREATE TABLE IF NOT EXISTS mappings (
236
+ session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
237
+ token TEXT NOT NULL,
238
+ enc_value BLOB NOT NULL,
239
+ PRIMARY KEY (session_id, token)
240
+ ) WITHOUT ROWID;
241
+ `);
242
+ try {
243
+ db.exec("ALTER TABLE sessions ADD COLUMN version INTEGER NOT NULL DEFAULT 1");
244
+ }
245
+ catch {
246
+ // column already present (fresh create or v2+ store)
247
+ }
248
+ const versionRow = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
249
+ if (versionRow !== undefined && !KNOWN_SCHEMA_VERSIONS.has(versionRow.value)) {
250
+ throw new Error(`unsupported mapping store schema version ${versionRow.value}`);
251
+ }
252
+ const seedMeta = db.prepare("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO NOTHING");
253
+ seedMeta.run("schema_version", SCHEMA_VERSION);
254
+ seedMeta.run("forget_epoch", "0");
255
+ seedMeta.run("version_counter", "0");
256
+ // Key pinning: first writer wins; later openers must match. For v1/v2
257
+ // stores (never released; no pinned identity) the first opener is
258
+ // trusted — EXCEPT when the store already holds mapping rows: a wrong
259
+ // key would silently upgrade into an empty-reading store and then pin
260
+ // itself against the RIGHT key (R3-F8). Verify AEAD before pinning.
261
+ if (pinnedIsNull(db) && mappingRowCount(db) > 0) {
262
+ const row = db
263
+ .prepare("SELECT session_id, token, enc_value FROM mappings LIMIT 1")
264
+ .get();
265
+ if (decryptOriginal(key, row.session_id, row.token, Buffer.from(row.enc_value)) === null) {
266
+ throw new Error("legacy mapping store exists but is not decryptable under this key (wrong key or corrupt); degrading to memory-only");
267
+ }
268
+ }
269
+ seedMeta.run("key_id", deriveKeyId(key));
270
+ if (versionRow !== undefined && versionRow.value !== SCHEMA_VERSION) {
271
+ db.prepare("UPDATE meta SET value = ? WHERE key = 'schema_version'").run(SCHEMA_VERSION);
272
+ }
273
+ const pinned = db.prepare("SELECT value FROM meta WHERE key = 'key_id'").get();
274
+ const pinnedId = pinned !== undefined ? pinned.value : deriveKeyId(key);
275
+ if (pinnedId !== deriveKeyId(key)) {
276
+ throw new MappingKeyMismatchError();
277
+ }
278
+ const epochRow = db.prepare("SELECT value FROM meta WHERE key = 'forget_epoch'").get();
279
+ epochAtOpen = epochRow !== undefined ? Number.parseInt(epochRow.value, 10) : 0;
280
+ db.exec("COMMIT");
281
+ }
282
+ catch (error) {
283
+ db.exec("ROLLBACK");
284
+ throw error;
285
+ }
286
+ // Lazy TTL sweep (writer handles only; tombstones continue versions).
287
+ if (ttlDays > 0) {
288
+ db.exec("BEGIN");
289
+ try {
290
+ tombstoneAndDelete(db, "expires_at <= ?", [`${now()}`]);
291
+ db.exec("COMMIT");
292
+ }
293
+ catch (error) {
294
+ db.exec("ROLLBACK");
295
+ throw error;
296
+ }
297
+ }
298
+ }
299
+ }
300
+ catch (error) {
301
+ // R1/R2: any init failure must not leak the handle.
302
+ db.close();
303
+ throw error;
304
+ }
305
+ // ─── Prepared statements — same close-on-failure boundary as init (R3-F4)
306
+ try {
307
+ const stmtCount = db.prepare("SELECT COUNT(*) AS n FROM sessions");
308
+ const stmtEntryCount = db.prepare("SELECT COUNT(*) AS n FROM mappings");
309
+ const stmtGet = db.prepare("SELECT epoch, version FROM sessions WHERE session_id = ?");
310
+ const stmtTouch = db.prepare("UPDATE sessions SET last_used_at = ? WHERE session_id = ?");
311
+ const stmtEntries = db.prepare("SELECT token, enc_value FROM mappings WHERE session_id = ? ORDER BY token");
312
+ const stmtInsertSession = db.prepare("INSERT INTO sessions (session_id, epoch, created_at, last_used_at, expires_at, version) VALUES (?, ?, ?, ?, ?, ?)");
313
+ const stmtUpdateSession = db.prepare("UPDATE sessions SET epoch = ?, last_used_at = ?, expires_at = ?, version = ? " +
314
+ "WHERE session_id = ? AND version = ?");
315
+ const stmtBumpVersionCounter = db.prepare("UPDATE meta SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT) WHERE key = 'version_counter'");
316
+ const stmtReadVersionCounter = db.prepare("SELECT value FROM meta WHERE key = 'version_counter'");
317
+ const stmtAbsentGeneration = db.prepare("SELECT last_version FROM session_tombstones WHERE session_id = ?");
318
+ const stmtTombstoneCount = db.prepare("SELECT COUNT(*) AS n FROM session_tombstones");
319
+ const stmtPruneTombstones = db.prepare("DELETE FROM session_tombstones WHERE session_id IN " +
320
+ "(SELECT session_id FROM (SELECT session_id FROM session_tombstones ORDER BY last_version ASC LIMIT ?))");
321
+ const stmtClearMappings = db.prepare("DELETE FROM mappings WHERE session_id = ?");
322
+ const stmtPutMapping = db.prepare("INSERT INTO mappings (session_id, token, enc_value) VALUES (?, ?, ?)");
323
+ const stmtDropAll = db.prepare("DELETE FROM sessions");
324
+ const stmtBumpEpoch = db.prepare("UPDATE meta SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT) WHERE key = 'forget_epoch'");
325
+ const stmtClearKeyId = db.prepare("DELETE FROM meta WHERE key = 'key_id'");
326
+ const stmtReadEpoch = db.prepare("SELECT value FROM meta WHERE key = 'forget_epoch'");
327
+ // Eviction victims: oldest first, never the session being written. The
328
+ // tombstone insert must select the SAME victim set (deterministic ORDER BY
329
+ // with session_id tiebreak) inside the same transaction. Every
330
+ // upsert-select carries `WHERE true` so SQLite's ON CONFLICT parses as an
331
+ // upsert clause, not a join constraint.
332
+ const EVICT_ORDER = "ORDER BY last_used_at ASC, session_id ASC";
333
+ const stmtEvictOverflow = db.prepare(`DELETE FROM sessions WHERE session_id IN (` +
334
+ `SELECT session_id FROM (SELECT session_id FROM sessions WHERE session_id != ? ${EVICT_ORDER} LIMIT ?))`);
335
+ const stmtEvictOldest = db.prepare(`DELETE FROM sessions WHERE session_id = (` +
336
+ `SELECT session_id FROM (SELECT session_id FROM sessions WHERE session_id != ? ${EVICT_ORDER} LIMIT 1))`);
337
+ const stmtTombstoneOverflow = db.prepare(`INSERT INTO session_tombstones (session_id, last_version) ` +
338
+ `SELECT session_id, version FROM (SELECT session_id, version FROM sessions WHERE session_id != ? ${EVICT_ORDER} LIMIT ?) ` +
339
+ `WHERE true ` +
340
+ `ON CONFLICT (session_id) DO UPDATE SET last_version = MAX(last_version, excluded.last_version)`);
341
+ const stmtTombstoneOldest = db.prepare(`INSERT INTO session_tombstones (session_id, last_version) ` +
342
+ `SELECT session_id, version FROM (SELECT session_id, version FROM sessions WHERE session_id != ? ${EVICT_ORDER} LIMIT 1) ` +
343
+ `WHERE true ` +
344
+ `ON CONFLICT (session_id) DO UPDATE SET last_version = MAX(last_version, excluded.last_version)`);
345
+ /** Read the live forget epoch (inside the caller's transaction). */
346
+ const liveEpoch = () => {
347
+ const row = stmtReadEpoch.get();
348
+ return row !== undefined ? Number.parseInt(row.value, 10) : 0;
349
+ };
350
+ /**
351
+ * R3-F6: versions come from a GLOBAL monotonic counter — never reused, so a
352
+ * re-created session can never collide with a pre-delete version (belt to
353
+ * the tombstone suspenders), and pruning tombstones stays safe: a pruned
354
+ * lineage re-starts at a fresh, globally-unique version anyway.
355
+ */
356
+ const nextVersion = () => {
357
+ stmtBumpVersionCounter.run();
358
+ const row = stmtReadVersionCounter.get();
359
+ return row !== undefined ? Number.parseInt(row.value, 10) : 1;
360
+ };
361
+ /** Tombstone retention ceiling (R3-F6): bounded, generously above the
362
+ * session cap so live-ish lineages are never pruned in practice. */
363
+ const tombstoneCeiling = () => Math.max(1000, maxSessions * 2);
364
+ return {
365
+ loadSession(sessionId) {
366
+ const session = stmtGet.get(sessionId);
367
+ if (session === undefined)
368
+ return null;
369
+ // Hydration counts as use (writer handles only — readOnly never writes).
370
+ if (!options.readOnly)
371
+ stmtTouch.run(now(), sessionId);
372
+ const entries = [];
373
+ for (const row of stmtEntries.iterate(sessionId)) {
374
+ const original = decryptOriginal(key, sessionId, row.token, Buffer.from(row.enc_value));
375
+ if (original === null)
376
+ continue; // decision §4.6: skip, never throw
377
+ entries.push({ token: row.token, original });
378
+ }
379
+ return { sessionId, epoch: session.epoch, entries, version: session.version };
380
+ },
381
+ absentGeneration(sessionId) {
382
+ const tomb = stmtAbsentGeneration.get(sessionId);
383
+ return tomb !== undefined ? tomb.last_version : 0;
384
+ },
385
+ putSession(seed, expectedVersion) {
386
+ if (options.readOnly)
387
+ throw new Error("read-only mapping store handle cannot persist");
388
+ // R2-10: the snapshot itself must fit the cap — evicting others can
389
+ // never satisfy a cap the current session alone exceeds.
390
+ if (seed.entries.length > maxEntries) {
391
+ throw new MappingSnapshotTooLargeError(seed.sessionId, seed.entries.length, maxEntries);
392
+ }
393
+ const expiresAt = ttlDays > 0 ? now() + ttlDays * DAY_MS : Number.MAX_SAFE_INTEGER;
394
+ db.exec("BEGIN");
395
+ try {
396
+ // Forget tombstone: if anything was erased through another handle
397
+ // since this one opened, refuse to write (no resurrection).
398
+ if (liveEpoch() !== epochAtOpen)
399
+ throw new MappingForgottenError();
400
+ const existing = stmtGet.get(seed.sessionId);
401
+ let storedVersion;
402
+ if (existing !== undefined) {
403
+ // R2-1: a writer holding a remembered version must CAS against it
404
+ // exactly; an absent-token (<= 0) can never blind-write a live row.
405
+ if (expectedVersion <= 0 || existing.version !== expectedVersion) {
406
+ throw new MappingStoreConflictError(seed.sessionId);
407
+ }
408
+ storedVersion = nextVersion();
409
+ const updated = stmtUpdateSession.run(seed.epoch, now(), expiresAt, storedVersion, seed.sessionId, expectedVersion);
410
+ if (updated.changes === 0)
411
+ throw new MappingStoreConflictError(seed.sessionId);
412
+ }
413
+ else if (expectedVersion > 0) {
414
+ // The row vanished since this handle observed it (external
415
+ // forgetSession / TTL sweep / LRU eviction): refuse rather than
416
+ // resurrect or ABA-match a re-created row (re-created rows take a
417
+ // fresh globally-unique version, so a remembered version can never
418
+ // match anyway; this branch is the absent-row guard).
419
+ throw new MappingStoreConflictError(seed.sessionId);
420
+ }
421
+ else {
422
+ // R3-F2: absent-writer CAS. The token encodes the tombstone
423
+ // generation the writer saw (0 ≡ never-deleted). An unchanged
424
+ // generation is required to insert — a delete that happened since
425
+ // (create→forget, sweep, eviction) must not be resurrected over.
426
+ const rememberedGeneration = expectedVersion < 0 ? -expectedVersion - 1 : 0;
427
+ const tombRow = stmtAbsentGeneration.get(seed.sessionId);
428
+ const currentGeneration = tombRow !== undefined ? tombRow.last_version : 0;
429
+ if (rememberedGeneration !== currentGeneration) {
430
+ throw new MappingStoreConflictError(seed.sessionId);
431
+ }
432
+ storedVersion = nextVersion();
433
+ stmtInsertSession.run(seed.sessionId, seed.epoch, now(), now(), expiresAt, storedVersion);
434
+ }
435
+ stmtClearMappings.run(seed.sessionId);
436
+ for (const entry of seed.entries) {
437
+ stmtPutMapping.run(seed.sessionId, entry.token, encryptOriginal(key, seed.sessionId, entry.token, entry.original));
438
+ }
439
+ // R-round bounded retention (§4.5): evict LRU sessions beyond the
440
+ // session cap, then beyond the total-entries cap, inside the txn —
441
+ // tombstoning every eviction so its version lineage survives.
442
+ const overflow = stmtCount.get().n - maxSessions;
443
+ if (overflow > 0) {
444
+ stmtTombstoneOverflow.run(seed.sessionId, overflow);
445
+ stmtEvictOverflow.run(seed.sessionId, overflow);
446
+ }
447
+ let total = stmtEntryCount.get().n;
448
+ while (total > maxEntries) {
449
+ const before = stmtCount.get().n;
450
+ stmtTombstoneOldest.run(seed.sessionId);
451
+ stmtEvictOldest.run(seed.sessionId);
452
+ if (stmtCount.get().n === before)
453
+ break; // only us left
454
+ total = stmtEntryCount.get().n;
455
+ }
456
+ // R3-F6: tombstones are bounded — prune the oldest lineages past the
457
+ // ceiling. A pruned id re-starts at a fresh global version, so this
458
+ // cannot reopen a version collision, only (theoretically) an
459
+ // absent-generation look ≥ ceiling sessions later — bounded residual.
460
+ const tombstoneExcess = stmtTombstoneCount.get().n - tombstoneCeiling();
461
+ if (tombstoneExcess > 0)
462
+ stmtPruneTombstones.run(tombstoneExcess);
463
+ db.exec("COMMIT");
464
+ return storedVersion;
465
+ }
466
+ catch (error) {
467
+ db.exec("ROLLBACK");
468
+ throw error;
469
+ }
470
+ },
471
+ forgetSession(sessionId) {
472
+ // Targeted forget (erase handles included): tombstone the version
473
+ // lineage (no ABA), delete the row. Per-session forgets are guarded by
474
+ // the absent-row CAS in putSession, so other sessions' write-behind
475
+ // keeps flowing.
476
+ db.exec("BEGIN");
477
+ try {
478
+ const changed = tombstoneAndDelete(db, "session_id = ?", [sessionId]);
479
+ db.exec("COMMIT");
480
+ return changed;
481
+ }
482
+ catch (error) {
483
+ db.exec("ROLLBACK");
484
+ throw error;
485
+ }
486
+ },
487
+ forgetAll() {
488
+ let removed = 0;
489
+ db.exec("BEGIN");
490
+ try {
491
+ tombstoneAll(db);
492
+ removed = stmtCount.get().n;
493
+ stmtDropAll.run();
494
+ stmtBumpEpoch.run();
495
+ stmtClearKeyId.run(); // R2-13: forget --all resets identity mismatches
496
+ db.exec("COMMIT");
497
+ }
498
+ catch (error) {
499
+ db.exec("ROLLBACK");
500
+ throw error;
501
+ }
502
+ // Best-effort physical compaction: rebuild the file (collapses the
503
+ // freelist secure_delete already zeroed) and truncate the WAL.
504
+ try {
505
+ db.exec("VACUUM");
506
+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
507
+ }
508
+ catch {
509
+ // A concurrent reader can block these; logical erasure already
510
+ // committed — the next open retries the sweep/checkpoint path.
511
+ }
512
+ return removed;
513
+ },
514
+ sessionCount() {
515
+ return stmtCount.get().n;
516
+ },
517
+ close() {
518
+ db.close();
519
+ },
520
+ };
521
+ }
522
+ catch (error) {
523
+ // R3-F4: a prepare failure (e.g. legacy/foreign schema shape) must not
524
+ // leak the handle.
525
+ db.close();
526
+ throw error;
527
+ }
528
+ }
529
+ /** Whether the store has no pinned key identity yet (v1/v2-era). */
530
+ function pinnedIsNull(db) {
531
+ return db.prepare("SELECT value FROM meta WHERE key = 'key_id'").get() === undefined;
532
+ }
533
+ /** Total mapping rows — used by the legacy-upgrade AEAD verification. */
534
+ function mappingRowCount(db) {
535
+ return db.prepare("SELECT COUNT(*) AS n FROM mappings").get().n;
536
+ }
537
+ /** Tombstones then deletes the matching sessions in the caller's transaction. */
538
+ function tombstoneAndDelete(db, where, params) {
539
+ db.prepare(`INSERT INTO session_tombstones (session_id, last_version) ` +
540
+ `SELECT s.session_id, MAX(COALESCE(t.last_version, 0), s.version) ` +
541
+ `FROM sessions s LEFT JOIN session_tombstones t ON t.session_id = s.session_id ` +
542
+ `WHERE s.${where} ` +
543
+ `GROUP BY s.session_id ` +
544
+ `ON CONFLICT (session_id) DO UPDATE SET last_version = MAX(last_version, excluded.last_version)`).run(...params);
545
+ return db.prepare(`DELETE FROM sessions WHERE ${where}`).run(...params).changes > 0;
546
+ }
547
+ /** Tombstones every existing session (caller's transaction). */
548
+ function tombstoneAll(db) {
549
+ db.prepare(`INSERT INTO session_tombstones (session_id, last_version) ` +
550
+ `SELECT s.session_id, MAX(COALESCE(t.last_version, 0), s.version) ` +
551
+ `FROM sessions s LEFT JOIN session_tombstones t ON t.session_id = s.session_id ` +
552
+ `WHERE true ` +
553
+ `GROUP BY s.session_id ` +
554
+ `ON CONFLICT (session_id) DO UPDATE SET last_version = MAX(last_version, excluded.last_version)`).run();
555
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Decision model — translates a ScanResult into a GuardDecisionResult
3
+ * that the reminder / confirmation UI layer can consume.
4
+ */
5
+ import { buildSafePreview, buildRedactedContent } from "./redaction.js";
6
+ // ─── Helpers ────────────────────────────────────────────────────────────────
7
+ function hasHigh(findings) {
8
+ return findings.some((f) => f.severity === "HIGH");
9
+ }
10
+ function hasMediumOrHigher(findings) {
11
+ return findings.some((f) => f.severity === "HIGH" || f.severity === "MEDIUM");
12
+ }
13
+ function toGuardFinding(f) {
14
+ return {
15
+ type: f.type,
16
+ severity: f.severity,
17
+ description: f.description,
18
+ preview: f.preview,
19
+ line: f.line,
20
+ };
21
+ }
22
+ // ─── Core ───────────────────────────────────────────────────────────────────
23
+ /**
24
+ * Translate a ScanResult into a GuardDecisionResult.
25
+ *
26
+ * | Findings | decision | riskLevel | recommendedAction |
27
+ * |-------------------|----------|-----------|-------------------|
28
+ * | none | ALLOW | LOW | — |
29
+ * | LOW only | WARN | MEDIUM | — |
30
+ * | MEDIUM (no HIGH) | CONFIRM | HIGH | REVIEW |
31
+ * | any HIGH | CONFIRM | CRITICAL | BLOCK |
32
+ */
33
+ export function toDecisionResult(scan, originalContent, config) {
34
+ const findings = scan.findings.map(toGuardFinding);
35
+ if (scan.safe || scan.total_findings === 0) {
36
+ return {
37
+ decision: "ALLOW",
38
+ riskLevel: "LOW",
39
+ summary: scan.summary,
40
+ findings,
41
+ originalContent,
42
+ };
43
+ }
44
+ if (hasHigh(scan.findings)) {
45
+ return {
46
+ decision: "CONFIRM",
47
+ riskLevel: "CRITICAL",
48
+ summary: scan.summary,
49
+ findings,
50
+ recommendedAction: "BLOCK",
51
+ safePreview: buildSafePreview(originalContent, scan.findings, config),
52
+ redactedContent: buildRedactedContent(originalContent, scan.findings, config),
53
+ originalContent,
54
+ };
55
+ }
56
+ if (hasMediumOrHigher(scan.findings)) {
57
+ return {
58
+ decision: "CONFIRM",
59
+ riskLevel: "HIGH",
60
+ summary: scan.summary,
61
+ findings,
62
+ recommendedAction: "REVIEW",
63
+ safePreview: buildSafePreview(originalContent, scan.findings, config),
64
+ redactedContent: buildRedactedContent(originalContent, scan.findings, config),
65
+ originalContent,
66
+ };
67
+ }
68
+ // LOW-only
69
+ return {
70
+ decision: "WARN",
71
+ riskLevel: "MEDIUM",
72
+ summary: scan.summary,
73
+ findings,
74
+ originalContent,
75
+ };
76
+ }