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,318 @@
1
+ /**
2
+ * W2 (B2) mapping-key providers — key custody for the encrypted mapping
3
+ * store (decision `docs/plans/2026-10-07-persistence-decision-db-over-t2.md`
4
+ * §10: keychain is the local-first equivalent of mainstream key custody;
5
+ * none of the four reference integrations ship one).
6
+ *
7
+ * Resolution ladder (decision §4.6/§8 — degrade, never fail-closed):
8
+ * 1. OS keychain — macOS Keychain (`security`), Linux libsecret
9
+ * (`secret-tool`), Windows DPAPI (ProtectedData, CurrentUser scope).
10
+ * 2. 0600 keyfile — ONLY when explicitly opted in; documented weaker
11
+ * (a stolen directory/backup carries both secrets).
12
+ * 3. null — the caller degrades that process to memory-only operation;
13
+ * conversations are never blocked.
14
+ *
15
+ * Threat-model boundary (documented in the decision and README): the
16
+ * keychain defends OFFLINE file theft (disk, backups, a stolen SGP.db); it
17
+ * does not defend malware already running inside the user's login session
18
+ * (macOS authorization prompts can be social-engineered; DPAPI/libsecret
19
+ * decrypt for the same user). This is the common OS-protection boundary,
20
+ * not unique to this design.
21
+ */
22
+ import { spawnSync } from "node:child_process";
23
+ import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync, writeFileSync, } from "node:fs";
24
+ import { homedir } from "node:os";
25
+ import { dirname, join } from "node:path";
26
+ import { randomBytes } from "node:crypto";
27
+ const SERVICE = "leakshield";
28
+ const ACCOUNT = "sgp-mapping-key";
29
+ const HEX_KEY = /^[0-9a-f]{64}$/;
30
+ function run(command, args, input) {
31
+ return spawnSync(command, args, {
32
+ input,
33
+ encoding: "utf8",
34
+ stdio: ["pipe", "pipe", "pipe"],
35
+ timeout: 10_000,
36
+ });
37
+ }
38
+ /** macOS Keychain generic-password probe. Exit 44 = item not found (null). */
39
+ export function createMacKeychainProbe() {
40
+ if (process.platform !== "darwin")
41
+ return null;
42
+ return {
43
+ read() {
44
+ const result = run("security", [
45
+ "find-generic-password", "-a", ACCOUNT, "-s", SERVICE, "-w",
46
+ ]);
47
+ if (result.status === 44)
48
+ return null;
49
+ if (result.status !== 0 || typeof result.stdout !== "string") {
50
+ throw new Error("macOS keychain read failed");
51
+ }
52
+ // R3-F5: rc=0 with EMPTY output means the item EXISTS but is empty —
53
+ // surface that as "" (the resolver refuses malformed/empty values);
54
+ // returning null here would make `add -U` overwrite a corrupt item.
55
+ return result.stdout.trim();
56
+ },
57
+ write(hexKey) {
58
+ const result = run("security", [
59
+ "add-generic-password", "-U", "-a", ACCOUNT, "-s", SERVICE, "-w", hexKey,
60
+ ]);
61
+ if (result.status !== 0)
62
+ throw new Error("macOS keychain write failed");
63
+ },
64
+ };
65
+ }
66
+ /**
67
+ * Linux libsecret probe via secret-tool.
68
+ *
69
+ * Exit-code semantics (R2-4): `secret-tool lookup` exits 1 BOTH when no item
70
+ * matches (silent, empty stdout AND stderr) and on real errors (message on
71
+ * stderr). Only the silent variant is "absent"; a read failure must never be
72
+ * mistaken for absence, or the ladder would create/overwrite a key over an
73
+ * unreadable keychain. ENOENT means secret-tool is not installed.
74
+ */
75
+ export function interpretSecretToolLookup(result) {
76
+ if (result.error !== undefined && result.error.code === "ENOENT") {
77
+ throw new Error("secret-tool not installed");
78
+ }
79
+ if (result.status === 0) {
80
+ // R3-F5: rc=0 with empty output is a present-but-empty item, not absence.
81
+ if (result.stdout.length === 0)
82
+ throw new Error("keychain item present but empty");
83
+ return result.stdout;
84
+ }
85
+ if (result.status === 1 && result.stdout.length === 0 && (result.stderr ?? "").length === 0) {
86
+ return null; // absent — the only silent-nonzero case
87
+ }
88
+ throw new Error("libsecret lookup failed");
89
+ }
90
+ export function createLinuxSecretProbe() {
91
+ if (process.platform !== "linux")
92
+ return null;
93
+ const attrs = ["attribute", "service", SERVICE, "attribute", "account", ACCOUNT];
94
+ return {
95
+ read() {
96
+ const result = run("secret-tool", ["lookup", ...attrs]);
97
+ return interpretSecretToolLookup({
98
+ status: result.status,
99
+ stdout: typeof result.stdout === "string" ? result.stdout : "",
100
+ stderr: typeof result.stderr === "string" ? result.stderr : "",
101
+ error: result.error,
102
+ });
103
+ },
104
+ write(hexKey) {
105
+ const result = run("secret-tool", ["store", "--label=leakshield mappings", ...attrs], hexKey ?? "");
106
+ if (result.status !== 0)
107
+ throw new Error("libsecret store failed");
108
+ },
109
+ };
110
+ }
111
+ /**
112
+ * Windows DPAPI probe. DPAPI protects data, not storage, so the encrypted
113
+ * key blob lives in a 0600 file under the user's profile; it is decryptable
114
+ * only by the same user on the same machine (offline theft fails).
115
+ */
116
+ export function createWindowsDpapiProbe() {
117
+ if (process.platform !== "win32")
118
+ return null;
119
+ const blobPath = join(homedir(), "AppData", "Local", "leakshield", "sgp.key.dpapi");
120
+ const ps = (script) => run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
121
+ return {
122
+ read() {
123
+ if (!existsSync(blobPath))
124
+ return null;
125
+ const base64 = readFileSync(blobPath, "utf8").trim();
126
+ // R3-F5: an existing-but-empty blob is corruption, not absence.
127
+ if (base64.length === 0)
128
+ throw new Error("DPAPI key blob present but empty");
129
+ const result = ps(`[System.Text.Encoding]::UTF8.GetString([System.Security.Cryptography.ProtectedData]::Unprotect([Convert]::FromBase64String('${base64}'),$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser))`);
130
+ if (result.status !== 0)
131
+ throw new Error("DPAPI unprotect failed");
132
+ return result.stdout.trim();
133
+ },
134
+ write(hexKey) {
135
+ // R-round: Set-Content does not create parent directories.
136
+ mkdirSync(dirname(blobPath), { recursive: true, mode: 0o700 });
137
+ const result = ps(`[Convert]::ToBase64String([System.Security.Cryptography.ProtectedData]::Protect([System.Text.Encoding]::UTF8.GetBytes('${hexKey}'),$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser)) | Set-Content -NoNewline -Path '${blobPath}'`);
138
+ if (result.status !== 0)
139
+ throw new Error("DPAPI protect failed");
140
+ },
141
+ };
142
+ }
143
+ /** The platform's keychain probe, or null when unsupported. */
144
+ export function createPlatformKeychainProbe() {
145
+ return createMacKeychainProbe() ?? createLinuxSecretProbe() ?? createWindowsDpapiProbe();
146
+ }
147
+ /**
148
+ * 0600 keyfile provider — the documented-weaker ladder step. The key sits
149
+ * next to the data's directory tree, so directory/backup theft carries both
150
+ * secrets; it still enforces the two-file bar and never prompts.
151
+ *
152
+ * R-round guarantees:
153
+ * - Creation uses exclusive (`wx`) semantics: two processes racing the first
154
+ * create converge on ONE key (the loser adopts the winner's file) instead
155
+ * of silently forking keys.
156
+ * - An existing file with group/other permission bits is tightened to 0600;
157
+ * if tightening fails the provider refuses (ladder degrades, memory-only)
158
+ * rather than silently accepting a world-readable key.
159
+ */
160
+ export class KeyfileMappingKeyProvider {
161
+ path;
162
+ source = "keyfile";
163
+ key;
164
+ constructor(path) {
165
+ this.path = path;
166
+ const existing = readKeyfile(this.path);
167
+ if (existing !== null) {
168
+ assertKeyfilePrivate(this.path);
169
+ this.key = Buffer.from(existing, "hex");
170
+ return;
171
+ }
172
+ const fresh = randomBytes(32);
173
+ try {
174
+ // Exclusive create: EEXIST means a concurrent creator won the race.
175
+ const fd = openSync(this.path, "wx", 0o600);
176
+ try {
177
+ writeFileSync(fd, fresh.toString("hex"));
178
+ }
179
+ finally {
180
+ // R2-6: writeFileSync(fd, …) does NOT close the descriptor.
181
+ closeSync(fd);
182
+ }
183
+ try {
184
+ chmodSync(this.path, 0o600);
185
+ }
186
+ catch {
187
+ // Best effort on exotic filesystems; creation mode already applied.
188
+ }
189
+ }
190
+ catch (error) {
191
+ if (error.code !== "EEXIST")
192
+ throw error;
193
+ // Lost the race: adopt the winner's key. The winner may still be
194
+ // mid-write — retry briefly until the file holds a complete key.
195
+ const winner = waitForKeyfile(this.path);
196
+ if (winner === null) {
197
+ throw new Error(`keyfile race at ${this.path}: concurrent creator did not finish`);
198
+ }
199
+ assertKeyfilePrivate(this.path);
200
+ this.key = Buffer.from(winner, "hex");
201
+ return;
202
+ }
203
+ this.key = fresh;
204
+ }
205
+ getOrCreateKey() {
206
+ return this.key;
207
+ }
208
+ }
209
+ /** Existing keyfile with loose permissions must tighten or refuse. */
210
+ function assertKeyfilePrivate(path) {
211
+ let mode;
212
+ try {
213
+ mode = statSync(path).mode;
214
+ }
215
+ catch {
216
+ throw new Error(`keyfile disappeared: ${path}`);
217
+ }
218
+ if ((mode & 0o077) === 0)
219
+ return;
220
+ try {
221
+ chmodSync(path, 0o600);
222
+ }
223
+ catch {
224
+ throw new Error(`keyfile ${path} is group/other readable and could not be tightened to 0600`);
225
+ }
226
+ if ((statSync(path).mode & 0o077) !== 0) {
227
+ throw new Error(`keyfile ${path} remains group/other readable after chmod 0600`);
228
+ }
229
+ }
230
+ /** Retry-loop for a concurrent creator's partial write (~100ms budget). */
231
+ function waitForKeyfile(path) {
232
+ for (let attempt = 0; attempt < 10; attempt++) {
233
+ const content = readKeyfile(path);
234
+ if (content !== null)
235
+ return content;
236
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
237
+ }
238
+ return null;
239
+ }
240
+ function readKeyfile(path) {
241
+ try {
242
+ const content = readFileSync(path, "utf8").trim();
243
+ return HEX_KEY.test(content) ? content : null;
244
+ }
245
+ catch {
246
+ return null;
247
+ }
248
+ }
249
+ /** Overridable for tests. */
250
+ export function resolveMappingKeyWithProbe(probe, options) {
251
+ if (probe !== null) {
252
+ try {
253
+ const existing = probe.read();
254
+ if (existing !== null && !HEX_KEY.test(existing)) {
255
+ // R2-5: a PRESENT but malformed item is corruption, not absence —
256
+ // overwriting it would silently re-key (and orphan every persisted
257
+ // mapping behind a keyId mismatch). Refuse; the ladder steps down.
258
+ throw new Error("keychain item present but malformed or empty (not 64-hex)");
259
+ }
260
+ if (existing !== null) {
261
+ const key = Buffer.from(existing, "hex");
262
+ return { source: "os-keychain", getOrCreateKey: () => key };
263
+ }
264
+ // First creation. Keychains have no atomic create-if-absent across
265
+ // processes, so: write, then ALWAYS read back and adopt what the
266
+ // keychain actually holds. A concurrent creator that wrote after us
267
+ // wins the store; both processes converge on the same key instead of
268
+ // forking. (A write-vs-read window remains — documented residual,
269
+ // narrowed from "always fork" to "last write wins + read-back".)
270
+ const fresh = randomBytes(32).toString("hex");
271
+ try {
272
+ probe.write(fresh);
273
+ }
274
+ catch {
275
+ // We may have lost the race or the write failed; the read-back below
276
+ // is the arbiter — no key there means the ladder steps down.
277
+ }
278
+ const confirmed = probe.read();
279
+ const confirmedHex = confirmed !== null && HEX_KEY.test(confirmed)
280
+ ? confirmed
281
+ : null;
282
+ if (confirmedHex === null)
283
+ throw new Error("keychain create failed");
284
+ const key = Buffer.from(confirmedHex, "hex");
285
+ return { source: "os-keychain", getOrCreateKey: () => key };
286
+ }
287
+ catch {
288
+ options.warn("persistence: keychain unavailable, stepping down the key ladder");
289
+ }
290
+ }
291
+ if (options.keyFile) {
292
+ const path = options.keyfilePath ?? defaultKeyfilePath();
293
+ try {
294
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
295
+ return new KeyfileMappingKeyProvider(path);
296
+ }
297
+ catch {
298
+ options.warn("persistence: keyfile unreadable or unwritable, degrading to memory-only");
299
+ return null;
300
+ }
301
+ }
302
+ options.warn("persistence: no key provider available, degrading to memory-only");
303
+ return null;
304
+ }
305
+ /** Ladder entry point for production callers. */
306
+ export function resolveMappingKey(options) {
307
+ return resolveMappingKeyWithProbe(createPlatformKeychainProbe(), options);
308
+ }
309
+ export function defaultKeyfilePath() {
310
+ return join(defaultDataDir(), "sgp.key");
311
+ }
312
+ /** Decision §8: global store location, owner-specified file name. */
313
+ export function defaultStorePath() {
314
+ return join(defaultDataDir(), "SGP.db");
315
+ }
316
+ function defaultDataDir() {
317
+ return join(homedir(), ".local", "share", "leakshield");
318
+ }