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,185 @@
1
+ /**
2
+ * Redaction helpers — deterministic replacement of sensitive spans
3
+ * and safe preview generation.
4
+ *
5
+ * Internal match metadata (match_start, match_end, match_text) is used
6
+ * for replacement but MUST NOT be exposed via transport-facing outputs.
7
+ */
8
+ // ─── Transport-safe types ─────────────────────────────────────────────────────
9
+ /** Keys that are internal-only and must never appear in transport-facing outputs. */
10
+ const INTERNAL_FINDING_KEYS = ["match_start", "match_end", "match_text"];
11
+ // ─── Sanitization API ─────────────────────────────────────────────────────────
12
+ /**
13
+ * Strip internal match metadata from a single finding.
14
+ * The returned object is safe to serialize to transport consumers.
15
+ */
16
+ export function sanitizeFindingForExport(f) {
17
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
18
+ const { match_start: _ms, match_end: _me, match_text: _mt, ...safe } = f;
19
+ return safe;
20
+ }
21
+ /**
22
+ * Strip internal match metadata from an array of findings.
23
+ */
24
+ export function sanitizeFindingsForExport(findings) {
25
+ return findings.map(sanitizeFindingForExport);
26
+ }
27
+ /**
28
+ * Produce a transport-safe copy of a ScanResult by stripping internal
29
+ * match metadata from every finding.
30
+ */
31
+ export function sanitizeScanResultForExport(result) {
32
+ return { ...result, findings: sanitizeFindingsForExport(result.findings) };
33
+ }
34
+ /**
35
+ * Produce a transport-safe copy of a RedactResult by stripping internal
36
+ * match metadata from every finding.
37
+ */
38
+ export function sanitizeRedactResultForExport(result) {
39
+ return { ...result, findings: sanitizeFindingsForExport(result.findings) };
40
+ }
41
+ // ─── Placeholder mapping ─────────────────────────────────────────────────────
42
+ const PLACEHOLDER_MAP = {
43
+ API_KEY: "[REDACTED_API_KEY]",
44
+ SECRET: "[REDACTED_PASSWORD]",
45
+ TOKEN: "[REDACTED_TOKEN]",
46
+ PII_EMAIL: "[REDACTED_EMAIL]",
47
+ PII_PHONE_TW: "[REDACTED_PHONE]",
48
+ PII_PHONE_INTL: "[REDACTED_PHONE]",
49
+ PII_ID_TW: "[REDACTED_ID]",
50
+ DB_CONNECTION: "[REDACTED_DB_CONNECTION]",
51
+ PRIVATE_DOMAIN: "[REDACTED_PRIVATE_DOMAIN]",
52
+ NDA_KEYWORD: "[REDACTED_NDA_TERM]",
53
+ ENV_SECRET: "[REDACTED_ENV_SECRET]",
54
+ // 與 engine.ts 的 `[REDACTED_${type}]` 產生規則保持同形
55
+ PII_CREDIT_CARD: "[REDACTED_PII_CREDIT_CARD]",
56
+ PII_IBAN: "[REDACTED_PII_IBAN]",
57
+ PII_IP: "[REDACTED_PII_IP]",
58
+ PII_URL: "[REDACTED_PII_URL]",
59
+ CUSTOM: "[REDACTED_CUSTOM]",
60
+ };
61
+ // ─── Internal helpers ────────────────────────────────────────────────────────
62
+ /**
63
+ * Validate that all findings carry the match metadata needed for
64
+ * deterministic replacement. Returns the validated spans or undefined
65
+ * if any finding is missing required fields.
66
+ */
67
+ function extractSpans(findings) {
68
+ const spans = [];
69
+ for (const f of findings) {
70
+ if (f.match_start === undefined ||
71
+ f.match_end === undefined ||
72
+ f.match_text === undefined) {
73
+ return undefined;
74
+ }
75
+ spans.push({
76
+ start: f.match_start,
77
+ end: f.match_end,
78
+ placeholder: PLACEHOLDER_MAP[f.type],
79
+ });
80
+ }
81
+ return spans;
82
+ }
83
+ /**
84
+ * Sort spans by start position ascending, then merge overlapping/adjacent spans.
85
+ * When spans overlap, the earlier-starting span wins; for equal starts, the longer span absorbs the shorter one.
86
+ */
87
+ function sortAndMergeSpans(spans) {
88
+ if (spans.length === 0)
89
+ return [];
90
+ const sorted = [...spans].sort((a, b) => a.start - b.start || a.end - b.end);
91
+ const merged = [sorted[0]];
92
+ for (let i = 1; i < sorted.length; i++) {
93
+ const last = merged[merged.length - 1];
94
+ const current = sorted[i];
95
+ if (current.start <= last.end) {
96
+ // Overlapping or adjacent — extend the previous span if needed
97
+ if (current.end > last.end) {
98
+ merged[merged.length - 1] = { ...last, end: current.end };
99
+ }
100
+ // Otherwise the current span is fully contained; skip it
101
+ }
102
+ else {
103
+ merged.push(current);
104
+ }
105
+ }
106
+ return merged;
107
+ }
108
+ /**
109
+ * Apply sorted, non-overlapping spans to the original content,
110
+ * replacing each span with its placeholder.
111
+ */
112
+ function applyReplacements(content, spans) {
113
+ // Build result by walking the content forward
114
+ const parts = [];
115
+ let cursor = 0;
116
+ for (const span of spans) {
117
+ if (span.start < cursor)
118
+ continue; // skip fully contained spans
119
+ parts.push(content.slice(cursor, span.start));
120
+ parts.push(span.placeholder);
121
+ cursor = span.end;
122
+ }
123
+ parts.push(content.slice(cursor));
124
+ return parts.join("");
125
+ }
126
+ // ─── Public API ──────────────────────────────────────────────────────────────
127
+ const DEFAULT_PREVIEW_LENGTH = 60;
128
+ /**
129
+ * Build a safe preview of the original content.
130
+ *
131
+ * Returns a masked excerpt centered around the first finding,
132
+ * respecting `preview_length` from config (default 60).
133
+ * Returns undefined when no findings or no match metadata is available.
134
+ */
135
+ export function buildSafePreview(originalContent, findings, config) {
136
+ if (findings.length === 0)
137
+ return undefined;
138
+ const spans = extractSpans(findings);
139
+ if (spans === undefined || spans.length === 0)
140
+ return undefined;
141
+ const previewLength = config?.settings.preview_length ?? DEFAULT_PREVIEW_LENGTH;
142
+ // Sort and merge for accurate replacement
143
+ const merged = sortAndMergeSpans(spans);
144
+ // Determine the window around the first finding
145
+ const firstSpan = merged[0];
146
+ const contentLength = originalContent.length;
147
+ // Calculate window: try to center around the first finding
148
+ const spanLength = firstSpan.end - firstSpan.start;
149
+ const placeholderLen = firstSpan.placeholder.length;
150
+ const contextBudget = Math.max(0, previewLength - placeholderLen);
151
+ const halfContext = Math.floor(contextBudget / 2);
152
+ let windowStart = Math.max(0, firstSpan.start - halfContext);
153
+ let windowEnd = windowStart + previewLength;
154
+ // Adjust if window exceeds content length
155
+ if (windowEnd > contentLength) {
156
+ windowEnd = contentLength;
157
+ windowStart = Math.max(0, windowEnd - previewLength);
158
+ }
159
+ // Extract window content
160
+ const windowContent = originalContent.slice(windowStart, windowEnd);
161
+ // Adjust spans to be relative to the window
162
+ const windowSpans = merged
163
+ .filter((s) => s.start < windowEnd && s.end > windowStart)
164
+ .map((s) => ({
165
+ ...s,
166
+ start: Math.max(0, s.start - windowStart),
167
+ end: Math.min(windowEnd - windowStart, s.end - windowStart),
168
+ }));
169
+ return applyReplacements(windowContent, windowSpans);
170
+ }
171
+ /**
172
+ * Build a fully redacted version of the original content.
173
+ *
174
+ * Replaces all sensitive spans with semantic placeholders.
175
+ * Returns undefined when no findings or match metadata is missing.
176
+ */
177
+ export function buildRedactedContent(originalContent, findings, _config) {
178
+ if (findings.length === 0)
179
+ return undefined;
180
+ const spans = extractSpans(findings);
181
+ if (spans === undefined)
182
+ return undefined;
183
+ const merged = sortAndMergeSpans(spans);
184
+ return applyReplacements(originalContent, merged);
185
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Structural-string collection for JSON Schema subtrees, shared by the
3
+ * session-layer request guard (src/opencode-transparent.ts) and the wire-layer
4
+ * remaskers (src/opencode-transparent-http.ts) so the pre-mask safety check
5
+ * and the post-mask identity comparison can never drift apart.
6
+ *
7
+ * Structural identifiers (tool names, property keys, enum/const values, regex
8
+ * patterns) must survive masking verbatim: a sensitive or token-bearing one
9
+ * refuses the whole request rather than being silently renamed. Schema
10
+ * ANNOTATION values (`description`, `title` — human prose a provider never
11
+ * dispatches on) are deliberately NOT structural: they are protected as
12
+ * ordinary content leaves, so a scanner hit inside a tool-schema description
13
+ * masks to a pseudonym token instead of failing the request. Fail-closed is
14
+ * unchanged for every identifier position.
15
+ */
16
+ /** JSON Schema annotation keywords whose VALUES are prose, not identifiers. */
17
+ export const SCHEMA_ANNOTATION_KEYS = new Set(["description", "title"]);
18
+ /**
19
+ * Keys and identifier values of a schema/metadata subtree, in stable walk
20
+ * order. Annotation-key VALUES are skipped (the key itself is still pushed so
21
+ * both sides of the before/after comparison see the same collection).
22
+ */
23
+ export function walkSchemaStrings(out, value) {
24
+ if (typeof value === "string") {
25
+ out.push(value);
26
+ return;
27
+ }
28
+ if (value === null || typeof value !== "object")
29
+ return;
30
+ if (Array.isArray(value)) {
31
+ for (const item of value)
32
+ walkSchemaStrings(out, item);
33
+ return;
34
+ }
35
+ const record = value;
36
+ for (const key of Object.keys(record)) {
37
+ out.push(key);
38
+ if (SCHEMA_ANNOTATION_KEYS.has(key))
39
+ continue;
40
+ walkSchemaStrings(out, record[key]);
41
+ }
42
+ }
package/dist/doctor.js ADDED
@@ -0,0 +1,438 @@
1
+ /**
2
+ * `leakshield --doctor` — install-level verification for the OpenCode
3
+ * plugin (Phase 1a of the transparent-hardening plan).
4
+ *
5
+ * The doctor answers one question: "is this machine's OpenCode configured so
6
+ * that LeakShield is actually loaded, with valid options and a working
7
+ * scanner?" It runs OUTSIDE the OpenCode host, so it can verify configuration,
8
+ * registration shape, plugin options, and the local scanner — but it cannot
9
+ * see inside a live session. Runtime registration is proven by the boundary
10
+ * harness (scripts/e2e/run-boundary.mjs) and the documented smoke test.
11
+ *
12
+ * Statuses:
13
+ * - PROTECTED registered + dist present + options valid + config loads + smoke passes
14
+ * - PARTIAL v1 host: session hooks only (no transport layer, no transparent/deidentify)
15
+ * - BROKEN something is registered but would not work (dist missing / invalid options /
16
+ * guard config broken / smoke fails / v2-only mode on v1)
17
+ * - NOT_REGISTERED host found, config found or absent, but LeakShield is not in it
18
+ * - HOST_MISSING no usable `opencode` binary on PATH
19
+ */
20
+ import { spawnSync } from "node:child_process";
21
+ import fs from "node:fs";
22
+ import os from "node:os";
23
+ import path from "node:path";
24
+ import { loadConfig } from "./config/loader.js";
25
+ import { defaultKeyfilePath, defaultStorePath } from "./decision/mapping-key.js";
26
+ import { InMemoryMappingKeyProvider, openMappingStore } from "./decision/mapping-store.js";
27
+ import { validatePluginOptions } from "./plugin-options.js";
28
+ import { scanText } from "./scanner/engine.js";
29
+ const SMOKE_CANARY = "Smoke test only. Do not reveal or use this token: sk-AAAAAAAAAAAAAAAAAAAA";
30
+ export function createDoctorDeps() {
31
+ return {
32
+ opencodeVersion() {
33
+ try {
34
+ const r = spawnSync("opencode", ["--version"], { encoding: "utf8", timeout: 4000 });
35
+ if (r.error || (r.status !== null && r.status !== 0))
36
+ return null;
37
+ return (r.stdout || r.stderr || "").trim() || null;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ },
43
+ readIfExists(filePath) {
44
+ try {
45
+ return fs.readFileSync(filePath, "utf8");
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ },
51
+ existsDir(p) {
52
+ try {
53
+ return fs.statSync(p).isDirectory();
54
+ }
55
+ catch {
56
+ return false;
57
+ }
58
+ },
59
+ existsFile(p) {
60
+ try {
61
+ return fs.statSync(p).isFile();
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ },
67
+ loadGuardConfig(overridePath, workspaceRoot) {
68
+ return loadConfig(overridePath, workspaceRoot);
69
+ },
70
+ smokeScan(text, config) {
71
+ const result = scanText(text, config);
72
+ return { findings: result.findings.filter((f) => f.severity === "HIGH").length };
73
+ },
74
+ cwd: process.cwd(),
75
+ home: os.homedir(),
76
+ xdgConfigHome: process.env.XDG_CONFIG_HOME,
77
+ };
78
+ }
79
+ /** Tolerant JSONC parse: strips line and block comments plus trailing commas,
80
+ * then falls back to plain JSON.parse errors when still invalid. */
81
+ export function parseJsonc(text) {
82
+ try {
83
+ return JSON.parse(text);
84
+ }
85
+ catch {
86
+ const stripped = text
87
+ .replace(/\/\*[\s\S]*?\*\//g, "")
88
+ .replace(/(^|[^:"'\\])\/\/[^\n]*/g, "$1")
89
+ .replace(/,(\s*[}\]])/g, "$1");
90
+ return JSON.parse(stripped);
91
+ }
92
+ }
93
+ function parseHostVersion(raw) {
94
+ if (!raw)
95
+ return null;
96
+ const match = raw.match(/(\d+)\.(\d+)[.\d]*/);
97
+ if (!match)
98
+ return null;
99
+ const major = Number(match[1]);
100
+ if (major >= 2)
101
+ return { generation: "v2", version: raw };
102
+ return { generation: "v1", version: raw };
103
+ }
104
+ function matchesLeakshield(entry) {
105
+ if (entry === "leakshield")
106
+ return true;
107
+ return /\/leakshield(\/dist(\/opencode\.js)?)?$/.test(entry);
108
+ }
109
+ function findRegistration(generation, config) {
110
+ if (!config || typeof config !== "object")
111
+ return null;
112
+ const record = config;
113
+ if (generation === "v2") {
114
+ const plugins = record.plugins;
115
+ if (Array.isArray(plugins)) {
116
+ for (const entry of plugins) {
117
+ if (typeof entry === "string" && matchesLeakshield(entry)) {
118
+ return { packageRef: entry, options: {}, isLocalDistPath: entry.includes("/") };
119
+ }
120
+ if (entry && typeof entry === "object" && !Array.isArray(entry)) {
121
+ const pkg = entry.package;
122
+ if (typeof pkg === "string" && matchesLeakshield(pkg)) {
123
+ const options = entry.options ?? {};
124
+ return { packageRef: pkg, options, isLocalDistPath: pkg.includes("/") };
125
+ }
126
+ }
127
+ }
128
+ }
129
+ return null;
130
+ }
131
+ // v1: legacy `plugin` array of compiled file paths
132
+ const legacy = record.plugin;
133
+ if (Array.isArray(legacy)) {
134
+ for (const entry of legacy) {
135
+ if (typeof entry === "string" && matchesLeakshield(entry)) {
136
+ return { packageRef: entry, options: {}, isLocalDistPath: true };
137
+ }
138
+ }
139
+ }
140
+ return null;
141
+ }
142
+ function registrationSnippet(generation, distDir) {
143
+ if (generation === "v2") {
144
+ return [
145
+ '"plugins": [',
146
+ " {",
147
+ ` "package": "${distDir.replaceAll("\\", "\\\\")}",`,
148
+ ' "options": { "mode": "block" }',
149
+ " }",
150
+ "]",
151
+ ].join("\n");
152
+ }
153
+ return `"plugin": [\n "${distDir.replaceAll("\\", "\\\\")}/opencode.js"\n]`;
154
+ }
155
+ function candidateConfigPaths(deps) {
156
+ const workspace = [
157
+ path.join(deps.cwd, "opencode.json"),
158
+ path.join(deps.cwd, "opencode.jsonc"),
159
+ ];
160
+ const configRoots = [
161
+ deps.xdgConfigHome ?? path.join(deps.home, ".config"),
162
+ path.join(deps.home, "Library", "Application Support"),
163
+ ];
164
+ const global = configRoots.flatMap((root) => [
165
+ path.join(root, "opencode", "opencode.json"),
166
+ path.join(root, "opencode", "opencode.jsonc"),
167
+ ]);
168
+ return [...workspace, ...global];
169
+ }
170
+ /**
171
+ * W2 (B5) persistence status — a warn/ok/skip check, never a status flip:
172
+ * a degraded store weakens nothing (the plugin degrades to memory-only);
173
+ * the check exists so "enabled but silently not working" is visible here
174
+ * instead of only as a setup-time console WARN (decision §4.6).
175
+ */
176
+ export function persistenceCheck(options, deps) {
177
+ const persistence = options.persistence;
178
+ if (!persistence.enabled) {
179
+ return {
180
+ id: "persistence",
181
+ state: "skip",
182
+ detail: "OFF (default) — mappings are memory-only, per process lifetime.",
183
+ };
184
+ }
185
+ const storePath = persistence.path ?? defaultStorePath();
186
+ const keySource = persistence.keyFile
187
+ ? `OS keychain first; keyfile fallback allowed (${persistence.keyfilePath ?? defaultKeyfilePath()})`
188
+ : "OS keychain";
189
+ const base = `CONFIGURED (not runtime-verified); store=${storePath} ttl=${persistence.ttlDays}d cleanup=on-store-open key=${keySource}`;
190
+ if (!deps.existsFile(storePath)) {
191
+ return {
192
+ id: "persistence",
193
+ state: "warn",
194
+ detail: `${base}; store not created yet; activation and key availability are unverified.`,
195
+ fix: "Check the running plugin's persistence active/memory-only log and test restart restoration with synthetic data.",
196
+ };
197
+ }
198
+ const probe = deps.openStoreProbe?.(storePath, persistence.ttlDays) ??
199
+ defaultOpenStoreProbe(storePath, persistence.ttlDays);
200
+ if ("error" in probe) {
201
+ return {
202
+ id: "persistence",
203
+ state: "warn",
204
+ detail: `${base}; store unreadable (${probe.error}) — the plugin degrades to memory-only; conversations are not blocked.`,
205
+ fix: "Run `leakshield --forget --all` to reset the store (erases persisted mappings), or restore the file.",
206
+ };
207
+ }
208
+ return {
209
+ id: "persistence",
210
+ state: "warn",
211
+ // Honesty (R-round F6.2): the doctor counts sessions with a throwaway
212
+ // key — it cannot and does not verify keychain health or decryptability.
213
+ // Runtime setup logs remain the authoritative degradation signal.
214
+ detail: `${base}; ${probe.sessions} persisted session(s) — runtime activation and decryptability not verified from doctor.`,
215
+ fix: "Check the running plugin's persistence active/memory-only log and test restart restoration with synthetic data.",
216
+ };
217
+ }
218
+ function defaultOpenStoreProbe(storePath, ttlDays) {
219
+ try {
220
+ // Throwaway key + readOnly: counting sessions never decrypts rows, and
221
+ // the doctor must never read the user's real keychain (it could prompt).
222
+ const store = openMappingStore({
223
+ path: storePath,
224
+ keyProvider: new InMemoryMappingKeyProvider(),
225
+ ttlDays,
226
+ readOnly: true,
227
+ });
228
+ const sessions = store.sessionCount();
229
+ store.close();
230
+ return { sessions };
231
+ }
232
+ catch (error) {
233
+ return { error: error.message };
234
+ }
235
+ }
236
+ export async function runDoctor(deps) {
237
+ const checks = [];
238
+ const host = parseHostVersion(deps.opencodeVersion());
239
+ if (!host) {
240
+ checks.push({
241
+ id: "host",
242
+ state: "fail",
243
+ detail: "opencode binary not found on PATH (or `opencode --version` failed).",
244
+ fix: "Install OpenCode, or add it to PATH, then rerun `leakshield --doctor`.",
245
+ });
246
+ return { status: "HOST_MISSING", hostVersion: null, hostGeneration: null, configPath: null, checks };
247
+ }
248
+ checks.push({ id: "host", state: "ok", detail: `OpenCode ${host.version.trim()} (${host.generation})` });
249
+ // Config discovery
250
+ let configPath = null;
251
+ let rawConfig = null;
252
+ for (const candidate of candidateConfigPaths(deps)) {
253
+ const text = deps.readIfExists(candidate);
254
+ if (text !== null) {
255
+ configPath = candidate;
256
+ rawConfig = text;
257
+ break;
258
+ }
259
+ }
260
+ let parsedConfig = null;
261
+ if (configPath && rawConfig !== null) {
262
+ try {
263
+ parsedConfig = parseJsonc(rawConfig);
264
+ checks.push({ id: "config", state: "ok", detail: configPath });
265
+ }
266
+ catch (error) {
267
+ checks.push({
268
+ id: "config",
269
+ state: "fail",
270
+ detail: `${configPath} is not parseable JSON/JSONC: ${error.message}`,
271
+ fix: "Fix the syntax error, or remove the file so another candidate can apply.",
272
+ });
273
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
274
+ }
275
+ }
276
+ else {
277
+ checks.push({
278
+ id: "config",
279
+ state: "warn",
280
+ detail: "No opencode.json / opencode.jsonc found (workspace or global).",
281
+ fix: "Create one with the snippet below.",
282
+ });
283
+ }
284
+ const registration = findRegistration(host.generation, parsedConfig);
285
+ const distDir = path.resolve(deps.cwd, "dist");
286
+ if (!registration) {
287
+ checks.push({
288
+ id: "registration",
289
+ state: "fail",
290
+ detail: "LeakShield is not registered in the OpenCode config.",
291
+ fix: "Add it (snippet below), then rerun this doctor.",
292
+ });
293
+ return {
294
+ status: "NOT_REGISTERED",
295
+ hostVersion: host.version,
296
+ hostGeneration: host.generation,
297
+ configPath,
298
+ checks,
299
+ snippet: registrationSnippet(host.generation, distDir),
300
+ };
301
+ }
302
+ checks.push({
303
+ id: "registration",
304
+ state: "ok",
305
+ detail: `Registered as "${registration.packageRef}"${registration.options && Object.keys(registration.options).length > 0 ? " with options" : ""}.`,
306
+ });
307
+ // Local dist presence (silent-skip guard: the host logs and skips a plugin
308
+ // whose entry point cannot be resolved, which looks like "no protection"
309
+ // with no visible failure).
310
+ if (registration.isLocalDistPath && registration.packageRef) {
311
+ const resolved = path.resolve(deps.cwd, registration.packageRef);
312
+ // v2 registers a directory (host resolves index.js); v1 legacy entries
313
+ // point directly at the compiled opencode.js file.
314
+ const entryOk = registration.packageRef.endsWith(".js")
315
+ ? deps.existsFile(resolved)
316
+ : deps.existsDir(resolved) && deps.existsFile(path.join(resolved, "index.js"));
317
+ if (!entryOk) {
318
+ checks.push({
319
+ id: "dist",
320
+ state: "fail",
321
+ detail: `${resolved} is missing or not a loadable entry point — OpenCode will silently log-and-skip this plugin, leaving sessions unprotected.`,
322
+ fix: "Run `npm run build` in the project root (the snippet expects <project>/dist), or point the entry at the built directory.",
323
+ });
324
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
325
+ }
326
+ checks.push({ id: "dist", state: "ok", detail: `${resolved} exists.` });
327
+ }
328
+ else {
329
+ checks.push({
330
+ id: "dist",
331
+ state: "skip",
332
+ detail: "Package-name registration; dist resolution is the host's job at install time.",
333
+ });
334
+ }
335
+ // Options validation (same schema the plugin entry enforces at runtime)
336
+ const optionsValidation = validatePluginOptions(registration.options ?? {}, host.generation);
337
+ if (!optionsValidation.ok) {
338
+ checks.push({
339
+ id: "options",
340
+ state: "fail",
341
+ detail: `Plugin options are invalid — every protected request would fail closed at runtime: ${optionsValidation.error}`,
342
+ fix: "Correct the options in opencode.json (see README for valid combinations).",
343
+ });
344
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
345
+ }
346
+ const options = optionsValidation.options;
347
+ checks.push({
348
+ id: "options",
349
+ state: "ok",
350
+ detail: `mode=${options.mode}${registration.options?.mode === undefined ? " (default)" : ""}${options.mode === "transparent" ? ` wireProtection=${options.wireProtection ?? true}` : ""}${options.attachments === "allow" ? " attachments=allow" : ""}${options.deidentify ? " +deidentify" : ""}${options.envQueries ? " +envQueries" : ""}${options.configPath ? ` configPath=${options.configPath}` : ""}`,
351
+ });
352
+ checks.push(persistenceCheck(options, deps));
353
+ // Guard config load
354
+ let guardConfig;
355
+ try {
356
+ guardConfig = deps.loadGuardConfig(options.configPath, deps.cwd);
357
+ checks.push({
358
+ id: "guard-config",
359
+ state: "ok",
360
+ detail: options.configPath ? `Loaded ${options.configPath}.` : "Default guard config resolved.",
361
+ });
362
+ }
363
+ catch (error) {
364
+ checks.push({
365
+ id: "guard-config",
366
+ state: "fail",
367
+ detail: `Guard config failed to load: ${error.message}`,
368
+ fix: "Fix the config file, or remove configPath to use defaults.",
369
+ });
370
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
371
+ }
372
+ // Smoke: the local scanner must flag a synthetic credential
373
+ const smoke = deps.smokeScan(SMOKE_CANARY, guardConfig);
374
+ if (smoke.findings > 0) {
375
+ checks.push({ id: "smoke", state: "ok", detail: "Synthetic sk- canary detected by the installed scanner." });
376
+ }
377
+ else {
378
+ checks.push({
379
+ id: "smoke",
380
+ state: "fail",
381
+ detail: "Synthetic sk- canary NOT detected — the guard config disables the rules this install relies on.",
382
+ fix: "Restore credential rules in the guard config, or remove configPath to use defaults.",
383
+ });
384
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
385
+ }
386
+ if (host.generation === "v1") {
387
+ checks.push({
388
+ id: "coverage",
389
+ state: "warn",
390
+ detail: "v1 host: session hooks only — no transport egress layer, no transparent pseudonymization, no deidentify.",
391
+ });
392
+ return { status: "PARTIAL", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
393
+ }
394
+ if (options.mode === "transparent") {
395
+ checks.push({
396
+ id: "coverage",
397
+ state: "warn",
398
+ detail: `${options.wireProtection === false ? "transparent hook-only: content hooks protect their snapshots; no outbound HTTP/WS/SDK admission, transport metadata checks, injected-fetch requirement or provider transport transform. Final bodies/frames are not inspected or remasked. Unknown routes, including /alpha/generate, are not gated. Optional incoming HTTP/WS hooks restore known display protocols after successful scoped host preparation for the same session/kind/model; unsupported or unverified replies remain literal. Tool safety remains. Content added after hooks may be unmasked, including late-added attachments." : "transparent mode protects three HTTP protocols by wire shape (Chat Completions, Anthropic Messages, Responses) and native Responses-family WS frames; unknown outbound dialects and intercepted routes, including /alpha/generate, are refused (fail-closed), not passed. AI SDK providers must honor OpenCode's injected HTTP fetch; missing or unsafe fetch options refuse. Bypass transports are outside coverage, not a proven blocked transport."} Both levels stop rewriting on reply-side SG failures and keep literal originals; provider errors and cancellation still propagate. Content-hook masking failures still refuse the affected model call with a safe reason/stage, never silently send raw content. Attachments policy at content hooks: ${options.attachments === "allow" ? "ALLOW — attachments pass through unscanned with a visible notice (you vouch for their content)" : "block — replaced with an omission notice"}. Complete original-history/restart restoration is not verified.`,
399
+ });
400
+ }
401
+ checks.push({
402
+ id: "runtime",
403
+ state: "warn",
404
+ detail: "Install-level checks pass. Live-session proof: run the README smoke test or scripts/e2e/run-boundary.mjs.",
405
+ });
406
+ return { status: options.mode === "transparent" && options.wireProtection === false ? "PARTIAL" : "PROTECTED", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
407
+ }
408
+ export function formatDoctorReport(report) {
409
+ const icon = { ok: "[OK] ", warn: "[WARN]", fail: "[FAIL]", skip: "[SKIP]" };
410
+ const lines = [];
411
+ lines.push(`leakshield doctor — ${new Date().toISOString()}`);
412
+ for (const check of report.checks) {
413
+ lines.push(`${icon[check.state]} ${check.id}: ${check.detail}`);
414
+ if (check.fix)
415
+ lines.push(` fix: ${check.fix}`);
416
+ }
417
+ if (report.snippet) {
418
+ lines.push("");
419
+ lines.push("Registration snippet for your opencode.json:");
420
+ lines.push(report.snippet);
421
+ }
422
+ lines.push("");
423
+ const verdict = report.status === "PROTECTED"
424
+ ? "PROTECTED — install-level checks pass."
425
+ : report.status === "PARTIAL"
426
+ ? report.hostGeneration === "v1"
427
+ ? "PARTIAL — protected within the v1 boundary (session hooks only)."
428
+ : "PARTIAL — hook-first protection; final outbound HTTP bodies are not inspected."
429
+ : report.status === "BROKEN"
430
+ ? "BROKEN — registered but would not protect; fix the [FAIL] items above."
431
+ : report.status === "NOT_REGISTERED"
432
+ ? "NOT REGISTERED — LeakShield is not in the OpenCode config; sessions are unprotected."
433
+ : "HOST MISSING — no OpenCode binary found.";
434
+ lines.push(verdict);
435
+ lines.push("");
436
+ lines.push("Scope: model-conversation leak protection. This is NOT a tool-egress firewall: permitted local tools (curl, remote MCP, …) can still transmit originals. See README.");
437
+ return lines.join("\n");
438
+ }