leakshield 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,584 @@
1
+ import { createHash, createHmac, randomBytes } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ /**
5
+ * Readonly env query service (opt-in `envQueries` plugin option).
6
+ *
7
+ * Lets an agent ask coarse questions about the files listed in
8
+ * `settings.env_files` — which keys exist, whether a key is missing/empty/
9
+ * nonempty, a coarse lexical shape, and whether two keys hold the same value —
10
+ * without ever exposing raw values, lengths, previews, or fingerprints.
11
+ *
12
+ * Security contract:
13
+ * - Only files in the setup-time `env_files` allowlist, resolved inside the
14
+ * workspace root frozen at construction (canonical path plus device/inode
15
+ * identity). No symlinks on any path component, regular files only, at
16
+ * most 16 files of 1 MiB.
17
+ * - File access is best-effort pathname identity validation, not a sandbox.
18
+ * The root and every ancestor directory are lstat'd before the open and
19
+ * again after the read; the opened descriptor must be the exact inode the
20
+ * pre-open lstat authorized (dev/ino binding); the final component is
21
+ * never followed (O_NOFOLLOW); FIFOs cannot hang the event loop
22
+ * (O_NONBLOCK); and post-read size/mtime, ancestor-identity, and
23
+ * canonical-path checks reject observed changes. Stable symlink
24
+ * substitutions — final component or ancestor, resolving inside or
25
+ * outside the workspace — are rejected.
26
+ * - What pathname checks cannot do, stated honestly: a concurrent
27
+ * same-owner mutation that substitutes a component (root, ancestor, or
28
+ * file) and restores it between the checks — an unobserved ABA race — is
29
+ * not detectable; hardlink provenance is not checked (a hardlink to an
30
+ * outside file is indistinguishable from the original); an in-place
31
+ * rewrite that preserves size and mtime is not distinguishable. This is
32
+ * not a claim of race-proofing against malicious concurrent mutation.
33
+ * - Values are read fresh on every invocation and retained only for the
34
+ * duration of the call; nothing parsed is cached or persisted.
35
+ * - File ids are opaque and session-local (HMAC of a per-setup key); they
36
+ * reveal no path or index and are invalid in other sessions.
37
+ * - The allowlist and its authorization fingerprint come from one
38
+ * configuration read (see `loadConfigWithFingerprint`). If the
39
+ * configuration later changes, queries are disabled with a fixed sanitized
40
+ * error until OpenCode restarts — sticky even if the change is reverted,
41
+ * and never a silent fallback to the old or new authorization.
42
+ * - This is not hostile-agent isolation and not a trusted baseline: the
43
+ * agent can modify the queried files through other tools, so results
44
+ * describe the current file state at query time, never a frozen snapshot
45
+ * that someone vouched for.
46
+ */
47
+ export const MAX_ENV_QUERY_FILES = 16;
48
+ const MAX_ENV_QUERY_FILE_SIZE = 1024 * 1024;
49
+ export const MAX_FILE_ID_LENGTH = 64;
50
+ export const MAX_KEY_NAME_LENGTH = 512;
51
+ // ─── Parser ─────────────────────────────────────────────────────────────────
52
+ /**
53
+ * Unescape a double-quoted env value body. Single-pass scan: `\n` `\r` `\t`
54
+ * `\"` `\\` map to their character; any other backslash sequence stays
55
+ * literal. (Unlike the exact-value scanner's chained replaces, this cannot
56
+ * mis-handle `\\n`; the two services are independent by design.)
57
+ */
58
+ function unescapeDoubleQuoted(body) {
59
+ let out = "";
60
+ for (let i = 0; i < body.length; i++) {
61
+ const char = body[i];
62
+ if (char !== "\\") {
63
+ out += char;
64
+ continue;
65
+ }
66
+ const next = body[++i];
67
+ switch (next) {
68
+ case "n":
69
+ out += "\n";
70
+ break;
71
+ case "r":
72
+ out += "\r";
73
+ break;
74
+ case "t":
75
+ out += "\t";
76
+ break;
77
+ case '"':
78
+ out += '"';
79
+ break;
80
+ case "\\":
81
+ out += "\\";
82
+ break;
83
+ default:
84
+ out += next === undefined ? "\\" : "\\" + next;
85
+ break;
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+ /** Tail after a closing quote: blank, whitespace, or a comment — nothing else. */
91
+ function isValidQuotedTail(tail) {
92
+ return /^\s*(?:#.*)?$/.test(tail);
93
+ }
94
+ /**
95
+ * Unquoted single-line value: an initial `#`, or the first `#` preceded by
96
+ * whitespace, starts a trailing comment; the remainder is trimmed once. The
97
+ * scan is monotonic — the search cursor only moves forward, so every
98
+ * character is examined at most once and whitespace-dense values without a
99
+ * `#` stay linear in the value size.
100
+ */
101
+ function parseUnquotedValue(value) {
102
+ if (value.startsWith("#"))
103
+ return "";
104
+ let cut = value.length;
105
+ let index = 0;
106
+ while (index < value.length) {
107
+ const hash = value.indexOf("#", index);
108
+ if (hash === -1)
109
+ break;
110
+ if (hash > 0 && /\s/.test(value[hash - 1])) {
111
+ cut = hash;
112
+ break;
113
+ }
114
+ index = hash + 1;
115
+ }
116
+ return value.slice(0, cut).trim();
117
+ }
118
+ class QuotedValueScanner {
119
+ #quote;
120
+ #parts = [];
121
+ #pendingEscape = false;
122
+ constructor(quote) {
123
+ this.#quote = quote;
124
+ }
125
+ /**
126
+ * Consumes one chunk (the first line's remainder, then each continuation
127
+ * line prefixed with its joining newline) in a single monotonic pass: the
128
+ * cursor only moves forward and every character is examined at most once
129
+ * (the double-quote form steps over each escape pair in place), so
130
+ * escape-dense values — e.g. a near-1 MiB run of `\x` with the closing
131
+ * quote far away or missing — stay linear in the file size. Body
132
+ * fragments are collected per chunk and joined exactly once at the close.
133
+ */
134
+ append(chunk) {
135
+ let position = 0;
136
+ if (this.#pendingEscape) {
137
+ // A backslash ending the previous chunk escapes the chunk separator
138
+ // newline (or, for the first chunk, ends the line): `\<newline>` and
139
+ // `\<CR>` can never be part of a valid double-quoted body.
140
+ const escaped = chunk[0];
141
+ if (escaped === undefined)
142
+ return { status: "open" };
143
+ if (this.#quote === '"' && (escaped === "\n" || escaped === "\r"))
144
+ return { status: "invalid" };
145
+ this.#parts.push("\\" + escaped);
146
+ position = 1;
147
+ this.#pendingEscape = false;
148
+ }
149
+ const quote = this.#quote;
150
+ let start = position;
151
+ let index = position;
152
+ while (index < chunk.length) {
153
+ const char = chunk[index];
154
+ if (char === quote) {
155
+ this.#parts.push(chunk.slice(start, index));
156
+ if (!isValidQuotedTail(chunk.slice(index + 1)))
157
+ return { status: "invalid" };
158
+ const body = this.#parts.join("");
159
+ return { status: "closed", value: quote === '"' ? unescapeDoubleQuoted(body) : body };
160
+ }
161
+ if (quote === '"' && char === "\\") {
162
+ if (index + 1 >= chunk.length) {
163
+ // Backslash at the very end: the escaped char is the first char of
164
+ // the next chunk (the joining newline) — decide on the next append.
165
+ this.#parts.push(chunk.slice(start, index));
166
+ this.#pendingEscape = true;
167
+ return { status: "open" };
168
+ }
169
+ // Unknown escapes are preserved verbatim in the body (they are
170
+ // resolved by the final unescape); only `\<newline>` and `\<CR>` are
171
+ // rejected outright because they can never be part of a valid value.
172
+ const escaped = chunk[index + 1];
173
+ if (escaped === "\n" || escaped === "\r")
174
+ return { status: "invalid" };
175
+ index += 2;
176
+ continue;
177
+ }
178
+ index++;
179
+ }
180
+ this.#parts.push(chunk.slice(start));
181
+ return { status: "open" };
182
+ }
183
+ }
184
+ function parseEnvValueFromLines(lines, startIndex, rawValue) {
185
+ const value = rawValue.trimStart();
186
+ const quote = value.startsWith('"') ? '"' : value.startsWith("'") ? "'" : undefined;
187
+ if (quote === undefined) {
188
+ return { value: parseUnquotedValue(value), nextIndex: startIndex + 1 };
189
+ }
190
+ const scanner = new QuotedValueScanner(quote);
191
+ let scan = scanner.append(value.slice(1));
192
+ let index = startIndex;
193
+ while (scan.status === "open") {
194
+ index++;
195
+ if (index >= lines.length)
196
+ return undefined; // quote never closed: malformed
197
+ scan = scanner.append("\n" + lines[index]);
198
+ }
199
+ if (scan.status === "invalid")
200
+ return undefined;
201
+ return { value: scan.value, nextIndex: index + 1 };
202
+ }
203
+ /**
204
+ * Strict dotenv parser for the query service. Returns undefined when the file
205
+ * is malformed — the entire file is rejected rather than returning partial,
206
+ * non-authoritative results. Divergences from the exact-value scanner are
207
+ * intentional: all value lengths (including <8) are preserved, and files with
208
+ * stray non-assignment lines or unterminated quotes are rejected wholesale.
209
+ */
210
+ export function parseEnvFileContent(content) {
211
+ const text = content.startsWith("\uFEFF") ? content.slice(1) : content;
212
+ const lines = text.split(/\r?\n/);
213
+ const values = new Map();
214
+ let index = 0;
215
+ while (index < lines.length) {
216
+ const line = lines[index];
217
+ const trimmed = line.trim();
218
+ if (trimmed === "" || trimmed.startsWith("#")) {
219
+ index++;
220
+ continue;
221
+ }
222
+ const assignment = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
223
+ if (!assignment)
224
+ return undefined;
225
+ // Quoted values may span physical lines; quoted scanning consumes whole
226
+ // lines at a time. EOF inside a quote means the whole file is malformed.
227
+ const parsed = parseEnvValueFromLines(lines, index, assignment[2]);
228
+ if (parsed === undefined)
229
+ return undefined;
230
+ values.set(assignment[1], parsed.value);
231
+ index = parsed.nextIndex;
232
+ }
233
+ return values;
234
+ }
235
+ /** Coarse lexical shape of a nonempty value. A shape is a hint, never a claim that the value is a valid boolean or number. */
236
+ export function classifyEnvValueShape(value) {
237
+ if (/[\n\r]/.test(value))
238
+ return "multiline_text";
239
+ if (/^(true|false)$/i.test(value))
240
+ return "boolean_like";
241
+ if (/^[+-]?(0x[0-9a-f]+|\d+(\.\d+)?|\.\d+)(e[+-]?\d+)?$/i.test(value))
242
+ return "number_like";
243
+ return "text";
244
+ }
245
+ // ─── File access ────────────────────────────────────────────────────────────
246
+ function isWithinWorkspace(filePath, workspaceRoot) {
247
+ const relative = path.relative(workspaceRoot, filePath);
248
+ return relative !== "" && !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
249
+ }
250
+ /**
251
+ * lstat one path and require it to currently be a real directory (not a
252
+ * symlink). Returns undefined when it is missing, a symlink, or any other
253
+ * type; callers map that to a fixed sanitized reason code.
254
+ */
255
+ function directoryIdentity(dirPath) {
256
+ let stat;
257
+ try {
258
+ stat = fs.lstatSync(dirPath);
259
+ }
260
+ catch {
261
+ return undefined;
262
+ }
263
+ if (stat.isSymbolicLink() || !stat.isDirectory())
264
+ return undefined;
265
+ return { dev: stat.dev, ino: stat.ino };
266
+ }
267
+ /**
268
+ * Ancestor directories of a workspace-contained `filePath`, from the
269
+ * workspace root (inclusive) down to the file's parent directory.
270
+ */
271
+ function ancestorDirectories(filePath, workspaceRoot) {
272
+ const segments = path.relative(workspaceRoot, filePath).split(path.sep);
273
+ segments.pop(); // drop the file name
274
+ const directories = [workspaceRoot];
275
+ let current = workspaceRoot;
276
+ for (const segment of segments) {
277
+ current = path.join(current, segment);
278
+ directories.push(current);
279
+ }
280
+ return directories;
281
+ }
282
+ /**
283
+ * Fresh, bounded read of one allowlisted env file. No result is cached.
284
+ *
285
+ * Best-effort pathname identity validation, in order:
286
+ * 1. Lexical containment: the entry must resolve, relative to the frozen
287
+ * workspace root, to a path inside the workspace.
288
+ * 2. The final component must lstat as a regular file (symlinks, FIFOs,
289
+ * and directories are rejected by reason code before anything opens).
290
+ * 3. The canonical (realpath-resolved) path must be inside the workspace
291
+ * and must agree with the lexically validated path. Any difference means
292
+ * some component is or became a symlink — including an ancestor
293
+ * directory symlinked to another location inside the workspace, which
294
+ * containment alone would miss.
295
+ * 4. Pre-open walk: the root and every ancestor directory must currently be
296
+ * real directories, the root must still be the device/inode pinned at
297
+ * setup, and every ancestor's identity is snapshotted for step 7.
298
+ * 5. The canonical path is lstat'd again immediately before the open and is
299
+ * opened at that exact path with O_NOFOLLOW|O_NONBLOCK; the descriptor
300
+ * must be the same dev/ino as that lstat (and a regular file in bounds).
301
+ * 6. Post-read metadata: size and mtime must be unchanged by the read.
302
+ * 7. Post-read re-validation: ancestors are re-lstat'd against the pre-open
303
+ * snapshot, the canonical path is re-resolved, and a final lstat of the
304
+ * canonical path must still name the descriptor's inode.
305
+ *
306
+ * Honest limits (also stated in the README): steps 4–7 reject *observed*
307
+ * changes, but a concurrent same-owner attacker who substitutes a component
308
+ * (root, ancestor, or file) and restores it between two checks — an
309
+ * unobserved ABA race — is not detectable by pathname checks alone;
310
+ * hardlinks to files outside the workspace are not distinguished from the
311
+ * original file; and an in-place rewrite preserving size and mtime is not
312
+ * distinguishable. This validates pathname identity; it is not a sandbox
313
+ * and not a trusted baseline.
314
+ */
315
+ function readEnvFileSnapshot(envFile, realWorkspaceRoot, pinnedRoot) {
316
+ if (path.isAbsolute(envFile))
317
+ return { ok: false, reason: "outside_workspace" };
318
+ const candidate = path.resolve(realWorkspaceRoot, envFile);
319
+ if (!isWithinWorkspace(candidate, realWorkspaceRoot))
320
+ return { ok: false, reason: "outside_workspace" };
321
+ let stat;
322
+ try {
323
+ stat = fs.lstatSync(candidate);
324
+ }
325
+ catch {
326
+ return { ok: false, reason: "unreadable" };
327
+ }
328
+ if (stat.isSymbolicLink())
329
+ return { ok: false, reason: "symlink" };
330
+ if (!stat.isFile())
331
+ return { ok: false, reason: "not_regular_file" };
332
+ let canonical;
333
+ try {
334
+ canonical = fs.realpathSync(candidate);
335
+ }
336
+ catch {
337
+ return { ok: false, reason: "unreadable" };
338
+ }
339
+ // Containment plus agreement with the lexically validated path: any
340
+ // difference means a symlink on the path, wherever it resolves.
341
+ if (!isWithinWorkspace(canonical, realWorkspaceRoot))
342
+ return { ok: false, reason: "outside_workspace" };
343
+ if (canonical !== candidate)
344
+ return { ok: false, reason: "symlink" };
345
+ // Pre-open ancestor walk. The root must still be the directory whose
346
+ // identity was pinned at setup; each ancestor is snapshotted so the
347
+ // post-read re-validation below can detect observed substitution.
348
+ const ancestors = ancestorDirectories(canonical, realWorkspaceRoot);
349
+ const ancestorIdentities = [];
350
+ for (let index = 0; index < ancestors.length; index++) {
351
+ const identity = directoryIdentity(ancestors[index]);
352
+ if (!identity)
353
+ return { ok: false, reason: "unreadable" };
354
+ if (index === 0 && (identity.dev !== pinnedRoot.dev || identity.ino !== pinnedRoot.ino)) {
355
+ return { ok: false, reason: "unreadable" };
356
+ }
357
+ ancestorIdentities.push(identity);
358
+ }
359
+ // Re-lstat the canonical path immediately before the open; the descriptor
360
+ // is bound to this stat's dev/ino below.
361
+ try {
362
+ stat = fs.lstatSync(canonical);
363
+ }
364
+ catch {
365
+ return { ok: false, reason: "unreadable" };
366
+ }
367
+ if (stat.isSymbolicLink())
368
+ return { ok: false, reason: "symlink" };
369
+ if (!stat.isFile())
370
+ return { ok: false, reason: "not_regular_file" };
371
+ let fd;
372
+ try {
373
+ // O_NOFOLLOW: a final component swapped to a symlink after the lstat
374
+ // above fails with ELOOP instead of being followed. O_NONBLOCK: a FIFO
375
+ // swapped in cannot hang the event loop (the regular-file check below
376
+ // rejects it). Platforms without the flags fall back to 0; the dev/ino
377
+ // binding below still anchors the descriptor to the lstat'd inode.
378
+ fd = fs.openSync(canonical, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0));
379
+ const fdStat = fs.fstatSync(fd);
380
+ if (!fdStat.isFile())
381
+ return { ok: false, reason: "not_regular_file" };
382
+ // Bind the descriptor to the inode the pre-open lstat authorized: any
383
+ // pathname race (final component or ancestor directory swapped between
384
+ // the lstat and the open) resolves to a different dev/ino and is rejected.
385
+ if (fdStat.dev !== stat.dev || fdStat.ino !== stat.ino)
386
+ return { ok: false, reason: "unreadable" };
387
+ if (fdStat.size > MAX_ENV_QUERY_FILE_SIZE)
388
+ return { ok: false, reason: "oversize" };
389
+ const buffer = Buffer.alloc(fdStat.size);
390
+ let read = 0;
391
+ while (read < fdStat.size) {
392
+ const bytes = fs.readSync(fd, buffer, read, fdStat.size - read, read);
393
+ if (bytes === 0)
394
+ return { ok: false, reason: "unreadable" }; // shrank mid-read: not authoritative
395
+ read += bytes;
396
+ }
397
+ // The snapshot must describe the file it started from: growth or any
398
+ // metadata change during the read voids it (an appended tail would
399
+ // otherwise be silently read as a stale prefix).
400
+ const postStat = fs.fstatSync(fd);
401
+ if (postStat.size !== fdStat.size || postStat.mtimeMs !== fdStat.mtimeMs) {
402
+ return { ok: false, reason: "unreadable" };
403
+ }
404
+ // Post-read re-validation of everything the authorization relied on:
405
+ // the root and every ancestor must still be the same real directories,
406
+ // and the canonical path must still resolve to itself and still name
407
+ // the descriptor's inode. Observed changes void the snapshot; an
408
+ // unobserved ABA substitution between checks is not detectable here.
409
+ for (let index = 0; index < ancestors.length; index++) {
410
+ const identity = directoryIdentity(ancestors[index]);
411
+ if (!identity ||
412
+ identity.dev !== ancestorIdentities[index].dev ||
413
+ identity.ino !== ancestorIdentities[index].ino) {
414
+ return { ok: false, reason: "unreadable" };
415
+ }
416
+ }
417
+ if (fs.realpathSync(canonical) !== canonical)
418
+ return { ok: false, reason: "unreadable" };
419
+ const finalStat = fs.lstatSync(canonical);
420
+ if (!finalStat.isFile() || finalStat.dev !== fdStat.dev || finalStat.ino !== fdStat.ino) {
421
+ return { ok: false, reason: "unreadable" };
422
+ }
423
+ return { ok: true, content: buffer.toString("utf8") };
424
+ }
425
+ catch {
426
+ return { ok: false, reason: "unreadable" };
427
+ }
428
+ finally {
429
+ if (fd !== undefined)
430
+ fs.closeSync(fd);
431
+ }
432
+ }
433
+ // ─── Service ─────────────────────────────────────────────────────────────────
434
+ function hashConfigFile(configPath) {
435
+ if (!configPath)
436
+ return "absent";
437
+ try {
438
+ return createHash("sha256").update(fs.readFileSync(configPath, "utf8")).digest("hex");
439
+ }
440
+ catch {
441
+ return "unreadable";
442
+ }
443
+ }
444
+ export class EnvQueryService {
445
+ #envFiles;
446
+ #realWorkspaceRoot;
447
+ /** dev/ino of the workspace root pinned at construction (with its realpath). */
448
+ #pinnedRoot;
449
+ #setupKey;
450
+ #resolveConfigPath;
451
+ #configFingerprint;
452
+ #revoked = false;
453
+ constructor(options) {
454
+ if (options.envFiles.length > MAX_ENV_QUERY_FILES) {
455
+ throw new Error(`env_files supports at most ${MAX_ENV_QUERY_FILES} files`);
456
+ }
457
+ this.#envFiles = [...options.envFiles];
458
+ // Freezes the workspace at setup; throws (fail-closed setup) if unreadable.
459
+ this.#realWorkspaceRoot = fs.realpathSync(options.workspaceRoot);
460
+ // The root's device/inode identity is pinned alongside its path, so a
461
+ // substituted root (same path, different directory) is rejected on every
462
+ // later read even though the path still lexically matches.
463
+ const rootStat = fs.lstatSync(this.#realWorkspaceRoot);
464
+ if (!rootStat.isDirectory()) {
465
+ throw new Error("workspace root is not a directory");
466
+ }
467
+ this.#pinnedRoot = { dev: rootStat.dev, ino: rootStat.ino };
468
+ this.#setupKey = randomBytes(32);
469
+ this.#resolveConfigPath = options.resolveConfigPath;
470
+ this.#configFingerprint = options.configFingerprint;
471
+ }
472
+ listFiles(sessionID) {
473
+ if (!this.#authorize())
474
+ return { ok: false, code: "disabled" };
475
+ const files = this.#envFiles.map((_, index) => {
476
+ const fileId = this.#fileIdFor(sessionID, index);
477
+ const snapshot = this.#snapshot(index);
478
+ return "unavailable" in snapshot
479
+ ? { file_id: fileId, available: false, reason: snapshot.unavailable }
480
+ : { file_id: fileId, available: true, keys: [...snapshot.values.keys()] };
481
+ });
482
+ return { ok: true, files };
483
+ }
484
+ inspectKey(sessionID, fileId, key) {
485
+ if (typeof sessionID !== "string" || !isValidKeyName(key))
486
+ return { ok: false, code: "invalid_arguments" };
487
+ if (!this.#authorize())
488
+ return { ok: false, code: "disabled" };
489
+ const index = this.#indexOfFileId(sessionID, fileId);
490
+ if (index === undefined)
491
+ return { ok: false, code: "unknown_file_id" };
492
+ const snapshot = this.#snapshot(index);
493
+ if ("unavailable" in snapshot)
494
+ return { ok: true, status: "unavailable", reason: snapshot.unavailable };
495
+ const value = snapshot.values.get(key);
496
+ if (value === undefined)
497
+ return { ok: true, status: "missing" };
498
+ if (value === "")
499
+ return { ok: true, status: "empty" };
500
+ return { ok: true, status: "nonempty", shape: classifyEnvValueShape(value) };
501
+ }
502
+ compareKeys(sessionID, left, right) {
503
+ if (typeof sessionID !== "string" ||
504
+ !isValidKeyName(left.key) ||
505
+ !isValidKeyName(right.key)) {
506
+ return { ok: false, code: "invalid_arguments" };
507
+ }
508
+ if (!this.#authorize())
509
+ return { ok: false, code: "disabled" };
510
+ const leftIndex = this.#indexOfFileId(sessionID, left.fileId);
511
+ if (leftIndex === undefined)
512
+ return { ok: false, code: "unknown_file_id" };
513
+ const rightIndex = this.#indexOfFileId(sessionID, right.fileId);
514
+ if (rightIndex === undefined)
515
+ return { ok: false, code: "unknown_file_id" };
516
+ // Both operands are read within this call (one shared per-call snapshot;
517
+ // the same file is read at most once even when compared with itself).
518
+ const snapshots = new Map();
519
+ const snapshotFor = (index) => {
520
+ const existing = snapshots.get(index);
521
+ if (existing)
522
+ return existing;
523
+ const snapshot = this.#snapshot(index);
524
+ snapshots.set(index, snapshot);
525
+ return snapshot;
526
+ };
527
+ const leftSnapshot = snapshotFor(leftIndex);
528
+ if ("unavailable" in leftSnapshot) {
529
+ return { ok: true, result: "unavailable", reason: leftSnapshot.unavailable };
530
+ }
531
+ const rightSnapshot = snapshotFor(rightIndex);
532
+ if ("unavailable" in rightSnapshot) {
533
+ return { ok: true, result: "unavailable", reason: rightSnapshot.unavailable };
534
+ }
535
+ const leftValue = leftSnapshot.values.get(left.key);
536
+ if (leftValue === undefined)
537
+ return { ok: true, result: "unavailable" };
538
+ const rightValue = rightSnapshot.values.get(right.key);
539
+ if (rightValue === undefined)
540
+ return { ok: true, result: "unavailable" };
541
+ return { ok: true, result: leftValue === rightValue ? "equal" : "different" };
542
+ }
543
+ /**
544
+ * True while the guard configuration still matches the setup fingerprint.
545
+ * Revocation is sticky: once a mismatch is seen, queries stay disabled for
546
+ * the rest of this process even if the file is reverted — an agent must not
547
+ * be able to re-enable authorization by restoring old bytes.
548
+ */
549
+ #authorize() {
550
+ if (this.#revoked)
551
+ return false;
552
+ if (hashConfigFile(this.#resolveConfigPath()) !== this.#configFingerprint) {
553
+ this.#revoked = true;
554
+ return false;
555
+ }
556
+ return true;
557
+ }
558
+ #snapshot(index) {
559
+ const read = readEnvFileSnapshot(this.#envFiles[index], this.#realWorkspaceRoot, this.#pinnedRoot);
560
+ if (!read.ok)
561
+ return { unavailable: read.reason };
562
+ const values = parseEnvFileContent(read.content);
563
+ return values ? { values } : { unavailable: "malformed" };
564
+ }
565
+ #fileIdFor(sessionID, index) {
566
+ return createHmac("sha256", this.#setupKey)
567
+ .update(`session:${sessionID}\0env-file:${index}`)
568
+ .digest("hex")
569
+ .slice(0, 16);
570
+ }
571
+ #indexOfFileId(sessionID, fileId) {
572
+ if (typeof fileId !== "string" || fileId.length === 0 || fileId.length > MAX_FILE_ID_LENGTH) {
573
+ return undefined;
574
+ }
575
+ for (let index = 0; index < this.#envFiles.length; index++) {
576
+ if (this.#fileIdFor(sessionID, index) === fileId)
577
+ return index;
578
+ }
579
+ return undefined;
580
+ }
581
+ }
582
+ function isValidKeyName(key) {
583
+ return typeof key === "string" && key.length > 0 && key.length <= MAX_KEY_NAME_LENGTH;
584
+ }
package/dist/forget.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * W2 (B5) `forget` — the active erasure lever for persisted mappings
3
+ * (decision `docs/plans/2026-10-07-persistence-decision-db-over-t2.md` §4:
4
+ * TTL is the passive bound, forget is the explicit one; dispose never
5
+ * erases). Output is content-free: counts and paths only, never originals.
6
+ *
7
+ * Deletion does not decrypt anything, so the store is opened with a throwaway
8
+ * in-memory key: the real key stays wherever the ladder put it (keychain /
9
+ * keyfile). The key itself holds no data and is retained — removing it is
10
+ * unnecessary and would only force regeneration.
11
+ */
12
+ import { existsSync } from "node:fs";
13
+ import { InMemoryMappingKeyProvider, openMappingStore } from "./decision/mapping-store.js";
14
+ import { defaultStorePath } from "./decision/mapping-key.js";
15
+ /** Process exit code. 0 = success/no-op, 1 = store error, 2 = usage error. */
16
+ export function runForget(options) {
17
+ if (!options.all && options.session === undefined) {
18
+ console.error("specify --all or --session <session-id>");
19
+ return 2;
20
+ }
21
+ const storePath = options.storePath ?? defaultStorePath();
22
+ if (!existsSync(storePath)) {
23
+ console.log(`no mapping store at ${storePath} — nothing to forget`);
24
+ return 0;
25
+ }
26
+ let store;
27
+ try {
28
+ store = openMappingStore({
29
+ path: storePath,
30
+ keyProvider: new InMemoryMappingKeyProvider(),
31
+ ttlDays: 0, // forget must not side-effect TTL sweeps
32
+ readOnly: true, // deletion never decrypts; no key-identity check needed
33
+ });
34
+ }
35
+ catch (error) {
36
+ console.error(`mapping store at ${storePath} is unreadable (${error.message})`);
37
+ console.error("delete the file to reset persistence; conversations are unaffected (memory-only)");
38
+ return 1;
39
+ }
40
+ try {
41
+ if (options.all) {
42
+ const sessions = store.forgetAll();
43
+ console.log(`forgot ${sessions} session(s) from ${storePath}`);
44
+ console.log("old placeholders now degrade per policy: read-only tools see literals, side-effecting calls refuse");
45
+ return 0;
46
+ }
47
+ const removed = store.forgetSession(options.session);
48
+ console.log(removed
49
+ ? `forgot session ${options.session} from ${storePath}`
50
+ : `session ${options.session} not found in ${storePath}`);
51
+ return 0;
52
+ }
53
+ finally {
54
+ store.close();
55
+ }
56
+ }
package/dist/help.js ADDED
@@ -0,0 +1,37 @@
1
+ // ─── CLI help text ───────────────────────────────────────────────────────────
2
+ export const HELP_TEXT = `leakshield — scan text for secrets and PII before sending it to AI
3
+
4
+ Usage:
5
+ leakshield [--cli] [scan options] Scan text, a file, a directory or stdin
6
+ leakshield --web [--port <n>] Start the local Web UI (default port 3000)
7
+ leakshield --doctor Check the OpenCode plugin installation
8
+ leakshield --forget --all Delete all persisted transparent-mode mappings
9
+ leakshield --forget --session <id> Delete persisted mappings for one session
10
+ leakshield --help Show this help
11
+
12
+ Scan input (stdin is read when none is given):
13
+ --text <text> Scan the given text
14
+ --file <path> Scan a single file
15
+ --dir <path> Scan a directory recursively
16
+ --ext <.ext ...> With --dir, only scan these extensions
17
+ --stdin Read text from stdin
18
+ --allow-outside Allow --file/--dir paths outside the working directory
19
+
20
+ Scan options:
21
+ --format json JSON output (CI/CD friendly)
22
+ --min-severity <level> Only report high, medium or low and above (default: low)
23
+ --enable-encoding-detection Also decode Base64/hex/URL-encoded content before scanning
24
+
25
+ Redaction:
26
+ --redact Replace findings with [REDACTED_TYPE] and print to stdout
27
+ --redact --out <path> Write the redacted text to a file
28
+ --redact --dry-run Report what would be redacted without writing output
29
+
30
+ Forget options:
31
+ --path <file> Mapping store location (default: ~/.local/share/leakshield/SGP.db)
32
+
33
+ Exit codes: 0 = safe, 1 = findings detected, 2 = file not found
34
+ `;
35
+ export function isHelpRequest(args) {
36
+ return args.includes("--help") || args.includes("-h");
37
+ }