leakshield 0.1.2 → 0.2.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.
package/dist/doctor.js CHANGED
@@ -11,9 +11,10 @@
11
11
  *
12
12
  * Statuses:
13
13
  * - PROTECTED registered + dist present + options valid + config loads + smoke passes
14
- * - PARTIAL v1 host: session hooks only (no transport layer, no transparent/deidentify)
14
+ * - PARTIAL transparent hook-only mode (wireProtection=false): no final-body inspection
15
15
  * - BROKEN something is registered but would not work (dist missing / invalid options /
16
- * guard config broken / smoke fails / v2-only mode on v1)
16
+ * guard config broken / smoke fails), or the host is OpenCode v1, which is
17
+ * no longer supported (the package only blocks its model requests)
17
18
  * - NOT_REGISTERED host found, config found or absent, but LeakShield is not in it
18
19
  * - HOST_MISSING no usable `opencode` binary on PATH
19
20
  */
@@ -21,13 +22,33 @@ import { spawnSync } from "node:child_process";
21
22
  import fs from "node:fs";
22
23
  import os from "node:os";
23
24
  import path from "node:path";
25
+ import { fileURLToPath } from "node:url";
24
26
  import { loadConfig } from "./config/loader.js";
25
27
  import { defaultKeyfilePath, defaultStorePath } from "./decision/mapping-key.js";
26
28
  import { InMemoryMappingKeyProvider, openMappingStore } from "./decision/mapping-store.js";
27
29
  import { validatePluginOptions } from "./plugin-options.js";
28
- import { skippedCustomRules } from "./rules/dynamic.js";
30
+ import { BUILTIN_RULE_IDS } from "./rules/builtin.js";
31
+ import { skippedCustomRules, customRuleBoundaries } from "./rules/dynamic.js";
32
+ import { allowlistSuppressions } from "./scanner/allowlist.js";
29
33
  import { scanText } from "./scanner/engine.js";
30
34
  const SMOKE_CANARY = "Smoke test only. Do not reveal or use this token: sk-AAAAAAAAAAAAAAAAAAAA";
35
+ /**
36
+ * Severity-agnostic probe for the allowlist diagnostics: every finding, plus
37
+ * the ones whose matched text is exactly the input. Findings carrying
38
+ * `unicode_detected` are tagged because an allowlist cannot suppress them.
39
+ */
40
+ function defaultProbeScan(text, config) {
41
+ const result = scanText(text, config);
42
+ return {
43
+ findings: result.findings.length,
44
+ exact: result.findings
45
+ .filter((finding) => finding.match_text === text)
46
+ .map((finding) => ({
47
+ description: finding.description ?? null,
48
+ unicodeWarning: finding.unicode_detected !== undefined,
49
+ })),
50
+ };
51
+ }
31
52
  export function createDoctorDeps() {
32
53
  return {
33
54
  opencodeVersion() {
@@ -72,6 +93,9 @@ export function createDoctorDeps() {
72
93
  const result = scanText(text, config);
73
94
  return { findings: result.findings.filter((f) => f.severity === "HIGH").length };
74
95
  },
96
+ probeScan(text, config) {
97
+ return defaultProbeScan(text, config);
98
+ },
75
99
  cwd: process.cwd(),
76
100
  home: os.homedir(),
77
101
  xdgConfigHome: process.env.XDG_CONFIG_HOME,
@@ -102,58 +126,152 @@ function parseHostVersion(raw) {
102
126
  return { generation: "v2", version: raw };
103
127
  return { generation: "v1", version: raw };
104
128
  }
105
- function matchesLeakshield(entry) {
106
- if (entry === "leakshield")
129
+ /** An npm name without its version or tag, so `leakshield@1.2.0` and `leakshield` agree. */
130
+ function packageName(ref) {
131
+ const at = ref.indexOf("@", 1); // keep a leading @scope
132
+ return at === -1 ? ref : ref.slice(0, at);
133
+ }
134
+ /**
135
+ * A reference the host resolves on disk rather than through npm. The host only
136
+ * rebases `./` and `../`; a bare `.`, `..` or a backslash-relative string goes
137
+ * to package resolution, and only `file://` is converted as a URL. Windows
138
+ * drive and UNC forms are local only on Windows, where they are separators.
139
+ */
140
+ function isLocalRef(ref) {
141
+ if (ref.startsWith("./") || ref.startsWith("../"))
142
+ return true;
143
+ if (ref.startsWith("file://"))
144
+ return true;
145
+ if (path.isAbsolute(ref))
107
146
  return true;
108
- return /\/leakshield(\/dist(\/opencode\.js)?)?$/.test(entry);
147
+ return path.sep === "\\" && (/^[A-Za-z]:[\\/]/.test(ref) || ref.startsWith("\\\\"));
109
148
  }
110
- function findRegistration(generation, config) {
111
- if (!config || typeof config !== "object")
149
+ /**
150
+ * The path a `file://` reference names, or null when the URL cannot become a
151
+ * path on this platform (an encoded separator, a remote host). The host cannot
152
+ * load such an entry either, so doctor reports it instead of crashing on it.
153
+ */
154
+ function filePathOf(ref) {
155
+ try {
156
+ return fileURLToPath(ref);
157
+ }
158
+ catch {
112
159
  return null;
113
- const record = config;
114
- if (generation === "v2") {
115
- const plugins = record.plugins;
116
- if (Array.isArray(plugins)) {
117
- for (const entry of plugins) {
118
- if (typeof entry === "string" && matchesLeakshield(entry)) {
119
- return { packageRef: entry, options: {}, isLocalDistPath: entry.includes("/") };
120
- }
121
- if (entry && typeof entry === "object" && !Array.isArray(entry)) {
122
- const pkg = entry.package;
123
- if (typeof pkg === "string" && matchesLeakshield(pkg)) {
124
- const options = entry.options ?? {};
125
- return { packageRef: pkg, options, isLocalDistPath: pkg.includes("/") };
126
- }
127
- }
128
- }
129
- }
160
+ }
161
+ }
162
+ /**
163
+ * Absolute path for a reference the host resolves on disk, or null for a
164
+ * package. An invalid `file://` URL is local but its `path` is null.
165
+ */
166
+ function localPathOf(ref, baseDir) {
167
+ if (!isLocalRef(ref))
130
168
  return null;
169
+ if (ref.startsWith("file://"))
170
+ return { path: filePathOf(ref) };
171
+ return { path: path.resolve(baseDir, ref) };
172
+ }
173
+ /**
174
+ * LeakShield's own package or dist directory. Split on the platform separator
175
+ * only: on POSIX a backslash is an ordinary filename character, so treating it
176
+ * as a separator would identify an unrelated plugin directory as LeakShield.
177
+ */
178
+ function isLeakshieldPath(resolved) {
179
+ return isLeakshieldParts(resolved.replace(/[\\/]+$/, "").split(path.sep).filter(Boolean));
180
+ }
181
+ /**
182
+ * Best-effort id for a `file://` URL that has no path on this platform. A
183
+ * `leakshield` path segment anywhere means the entry is LeakShield's and must be
184
+ * reported as unloadable rather than skipped — a heuristic, since the reference
185
+ * cannot be resolved. Literal tab/CR/LF are removed first, as URL parsing does,
186
+ * and encoded separators are split so one broken escape cannot hide the rest of
187
+ * the path; the parsed pathname is preferred because it also normalises dot
188
+ * segments.
189
+ */
190
+ function invalidFileUrlId(ref) {
191
+ const cleaned = ref.replace(/[\t\n\r]/g, "");
192
+ let pathname = null;
193
+ try {
194
+ pathname = new URL(cleaned).pathname;
131
195
  }
132
- // v1: legacy `plugin` array of compiled file paths
133
- const legacy = record.plugin;
134
- if (Array.isArray(legacy)) {
135
- for (const entry of legacy) {
136
- if (typeof entry === "string" && matchesLeakshield(entry)) {
137
- return { packageRef: entry, options: {}, isLocalDistPath: true };
138
- }
196
+ catch {
197
+ pathname = null;
198
+ }
199
+ const text = (pathname ?? cleaned.replace(/^file:\/\//, "").split(/[?#]/)[0] ?? "")
200
+ // An encoded separator cannot appear in a loadable path, which is why this
201
+ // reference is here; splitting on it keeps the segments identifiable.
202
+ .replace(/%2f|%5c/gi, "/");
203
+ const parts = text
204
+ .split("/")
205
+ .filter(Boolean)
206
+ .map((part) => {
207
+ try {
208
+ return decodeURIComponent(part);
139
209
  }
210
+ catch {
211
+ return part;
212
+ }
213
+ });
214
+ // Case-insensitive here only: this runs for references that cannot become a
215
+ // path, and a case-insensitive filesystem makes `/LeakShield/dist` the same
216
+ // directory. Identification of a usable path stays exact.
217
+ const isLeakshieldSegment = (part) => part.toLowerCase() === "leakshield" ||
218
+ part.split(/[\\/]/).some((segment) => segment.toLowerCase() === "leakshield");
219
+ if (parts.some(isLeakshieldSegment))
220
+ return "leakshield";
221
+ return parts[parts.length - 1] ?? ref;
222
+ }
223
+ function isLeakshieldParts(parts) {
224
+ const tail = parts[parts.length - 1];
225
+ const parent = parts[parts.length - 2];
226
+ const grand = parts[parts.length - 3];
227
+ if (tail === "leakshield")
228
+ return true;
229
+ if (tail === "dist" && parent === "leakshield")
230
+ return true;
231
+ return tail === "opencode.js" && parent === "dist" && grand === "leakshield";
232
+ }
233
+ /**
234
+ * The ID a plugin entry registers under, which is what `-id` and `-prefix.*`
235
+ * removals match. LeakShield resolves to `leakshield` (the id its entry declares
236
+ * in src/opencode.ts) whatever form the entry was written in — package name,
237
+ * pinned name, `./dir`, an absolute dist path, or a `file://` URL — and every
238
+ * other entry keeps its package name without the `@version`.
239
+ */
240
+ function pluginIdOf(ref, baseDir) {
241
+ const local = localPathOf(ref, baseDir);
242
+ if (local !== null) {
243
+ if (local.path === null)
244
+ return invalidFileUrlId(ref);
245
+ return isLeakshieldPath(local.path) ? "leakshield" : path.basename(local.path);
140
246
  }
141
- return null;
247
+ return packageName(ref);
142
248
  }
143
- function registrationSnippet(generation, distDir) {
144
- if (generation === "v2") {
145
- return [
146
- '"plugins": [',
147
- " {",
148
- ` "package": "${distDir.replaceAll("\\", "\\\\")}",`,
149
- ' "options": { "mode": "block" }',
150
- " }",
151
- "]",
152
- ].join("\n");
153
- }
154
- return `"plugin": [\n "${distDir.replaceAll("\\", "\\\\")}/opencode.js"\n]`;
249
+ function registrationSnippet(distDir) {
250
+ return [
251
+ '"plugins": [',
252
+ " {",
253
+ ` "package": "${distDir.replaceAll("\\", "\\\\")}",`,
254
+ ' "options": { "mode": "block" }',
255
+ " }",
256
+ "]",
257
+ ].join("\n");
155
258
  }
156
- function candidateConfigPaths(deps) {
259
+ /**
260
+ * Config locations grouped by precedence, highest first.
261
+ *
262
+ * OpenCode applies `plugins` from the user config dir, the project root and
263
+ * `.opencode/`, lowest precedence first (https://opencode.ai/v2/docs/plugins/#configure
264
+ * lists exactly those three). The two global roots are alternatives rather
265
+ * than two merged files: the docs name `~/.config/opencode` as the user config
266
+ * directory, so `~/Library/Application Support/opencode` is only a fallback for
267
+ * a host that keeps its user config there. Within a root, `.json` wins over
268
+ * `.jsonc`.
269
+ */
270
+ function configRootGroups(deps) {
271
+ const dotOpencode = [
272
+ path.join(deps.cwd, ".opencode", "opencode.json"),
273
+ path.join(deps.cwd, ".opencode", "opencode.jsonc"),
274
+ ];
157
275
  const workspace = [
158
276
  path.join(deps.cwd, "opencode.json"),
159
277
  path.join(deps.cwd, "opencode.jsonc"),
@@ -162,11 +280,154 @@ function candidateConfigPaths(deps) {
162
280
  deps.xdgConfigHome ?? path.join(deps.home, ".config"),
163
281
  path.join(deps.home, "Library", "Application Support"),
164
282
  ];
165
- const global = configRoots.flatMap((root) => [
166
- path.join(root, "opencode", "opencode.json"),
167
- path.join(root, "opencode", "opencode.jsonc"),
168
- ]);
169
- return [...workspace, ...global];
283
+ return [
284
+ dotOpencode,
285
+ workspace,
286
+ ...configRoots.map((root) => [
287
+ path.join(root, "opencode", "opencode.json"),
288
+ path.join(root, "opencode", "opencode.jsonc"),
289
+ ]),
290
+ ];
291
+ }
292
+ function readConfigFile(deps, candidates) {
293
+ for (const candidate of candidates) {
294
+ const text = deps.readIfExists(candidate);
295
+ if (text !== null)
296
+ return { path: candidate, text };
297
+ }
298
+ return null;
299
+ }
300
+ /**
301
+ * Config files doctor reads, highest precedence first: `.opencode/`, the
302
+ * workspace file, and the one active global root. A stale file in the inactive
303
+ * fallback root is not read, so it cannot turn a working install into a failure.
304
+ */
305
+ function loadConfigSources(deps) {
306
+ const [dotOpencodeGroup, workspaceGroup, ...globalGroups] = configRootGroups(deps);
307
+ const chosen = [readConfigFile(deps, dotOpencodeGroup), readConfigFile(deps, workspaceGroup)];
308
+ for (const group of globalGroups) {
309
+ const file = readConfigFile(deps, group);
310
+ if (!file)
311
+ continue;
312
+ chosen.push(file);
313
+ break; // the global roots are alternatives, not additional files
314
+ }
315
+ const sources = [];
316
+ for (const file of chosen) {
317
+ if (!file)
318
+ continue;
319
+ try {
320
+ sources.push({ path: file.path, config: parseJsonc(file.text) });
321
+ }
322
+ catch (error) {
323
+ return { sources, broken: { path: file.path, error: error.message } };
324
+ }
325
+ }
326
+ return { sources, broken: null };
327
+ }
328
+ /**
329
+ * Apply every `plugins` array doctor can read, lowest precedence first, the way
330
+ * the host does: entries accumulate across files instead of replacing one
331
+ * another, `-id` / `-prefix.*` / `-*` remove an entry, `*` restores every entry
332
+ * seen so far, and a later entry re-enables it
333
+ * (https://opencode.ai/v2/docs/plugins/#configure, #control).
334
+ *
335
+ * Two lists come back, because doctor does not try to predict which of several
336
+ * references to one id the host keeps loaded (#67). `registrations` is what is
337
+ * enabled now, which decides whether the plugin loads; `considered` is every
338
+ * reference configured for the id, which drives the option and path checks so a
339
+ * weaker entry can never be hidden by a stronger one.
340
+ */
341
+ function applyPluginLists(sourcesLowToHigh) {
342
+ const known = new Map(); // key: reference as written
343
+ const enabled = new Map();
344
+ /** Every entry as the config wrote it, including a reference applied twice. */
345
+ const occurrences = [];
346
+ let anyEnabled = false;
347
+ let disabled = null;
348
+ const enable = (applied) => {
349
+ known.set(applied.ref, applied);
350
+ enabled.set(applied.ref, applied);
351
+ occurrences.push(applied);
352
+ if (applied.id === "leakshield") {
353
+ anyEnabled = true;
354
+ disabled = null;
355
+ }
356
+ };
357
+ const removeWhere = (source, entry, matches) => {
358
+ for (const [ref, applied] of [...enabled.entries()]) {
359
+ if (!matches(applied.id))
360
+ continue;
361
+ enabled.delete(ref);
362
+ if (applied.id === "leakshield") {
363
+ anyEnabled = false;
364
+ disabled = { source, entry };
365
+ }
366
+ }
367
+ };
368
+ /** Apply one entry as written. Re-applying a reference replaces its enabled
369
+ * state but keeps the earlier occurrence for the conservative checks. */
370
+ const applyEntry = (source, ref, options) => {
371
+ enable({ id: pluginIdOf(ref, path.dirname(source.path)), ref, options, source: source.path });
372
+ };
373
+ for (const source of sourcesLowToHigh) {
374
+ const config = source.config;
375
+ if (!config || typeof config !== "object")
376
+ continue;
377
+ const list = config.plugins;
378
+ if (!Array.isArray(list))
379
+ continue;
380
+ for (const entry of list) {
381
+ if (typeof entry === "string") {
382
+ if (entry.startsWith("-")) {
383
+ const pattern = entry.slice(1);
384
+ const prefix = pattern.endsWith(".*") ? pattern.slice(0, -2) : null;
385
+ removeWhere(source.path, entry, (id) => pattern === "*"
386
+ ? true
387
+ : prefix !== null
388
+ ? id.startsWith(`${prefix}.`)
389
+ : id === pattern);
390
+ continue;
391
+ }
392
+ if (entry === "*") {
393
+ // Restores what earlier files configured: only the enabled state
394
+ // changes, so this records no new occurrence.
395
+ for (const knownEntry of known.values()) {
396
+ enabled.set(knownEntry.ref, knownEntry);
397
+ if (knownEntry.id === "leakshield") {
398
+ anyEnabled = true;
399
+ disabled = null;
400
+ }
401
+ }
402
+ continue;
403
+ }
404
+ applyEntry(source, entry, {});
405
+ continue;
406
+ }
407
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
408
+ continue;
409
+ const record = entry;
410
+ const ref = record.package;
411
+ if (typeof ref !== "string")
412
+ continue;
413
+ applyEntry(source, ref, record.options ?? {});
414
+ }
415
+ }
416
+ const seen = new Set();
417
+ const considered = occurrences.filter((applied) => {
418
+ if (applied.id !== "leakshield")
419
+ return false;
420
+ const key = `${applied.ref}\u0000${applied.source}\u0000${JSON.stringify(applied.options)}`;
421
+ if (seen.has(key))
422
+ return false;
423
+ seen.add(key);
424
+ return true;
425
+ });
426
+ return {
427
+ registrations: [...enabled.values()].filter((applied) => applied.id === "leakshield"),
428
+ considered,
429
+ disabled: anyEnabled ? null : disabled,
430
+ };
170
431
  }
171
432
  /**
172
433
  * W2 (B5) persistence status — a warn/ok/skip check, never a status flip:
@@ -246,35 +507,30 @@ export async function runDoctor(deps) {
246
507
  });
247
508
  return { status: "HOST_MISSING", hostVersion: null, hostGeneration: null, configPath: null, checks };
248
509
  }
249
- checks.push({ id: "host", state: "ok", detail: `OpenCode ${host.version.trim()} (${host.generation})` });
250
- // Config discovery
251
- let configPath = null;
252
- let rawConfig = null;
253
- for (const candidate of candidateConfigPaths(deps)) {
254
- const text = deps.readIfExists(candidate);
255
- if (text !== null) {
256
- configPath = candidate;
257
- rawConfig = text;
258
- break;
259
- }
510
+ if (host.generation === "v1") {
511
+ checks.push({
512
+ id: "host",
513
+ state: "fail",
514
+ detail: `OpenCode ${host.version.trim()} (v1) is no longer supported. LeakShield only blocks model requests on a v1 host.`,
515
+ fix: "Upgrade to OpenCode v2, then rerun `leakshield --doctor`.",
516
+ });
517
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath: null, checks };
260
518
  }
261
- let parsedConfig = null;
262
- if (configPath && rawConfig !== null) {
263
- try {
264
- parsedConfig = parseJsonc(rawConfig);
265
- checks.push({ id: "config", state: "ok", detail: configPath });
266
- }
267
- catch (error) {
268
- checks.push({
269
- id: "config",
270
- state: "fail",
271
- detail: `${configPath} is not parseable JSON/JSONC: ${error.message}`,
272
- fix: "Fix the syntax error, or remove the file so another candidate can apply.",
273
- });
274
- return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
275
- }
519
+ checks.push({ id: "host", state: "ok", detail: `OpenCode ${host.version.trim()} (${host.generation})` });
520
+ // Config discovery across every file OpenCode merges
521
+ const { sources, broken } = loadConfigSources(deps);
522
+ const configPaths = sources.map((source) => source.path);
523
+ const configPath = broken?.path ?? configPaths[0] ?? null;
524
+ if (broken) {
525
+ checks.push({
526
+ id: "config",
527
+ state: "fail",
528
+ detail: `${broken.path} is not parseable JSON/JSONC: ${broken.error}`,
529
+ fix: "Fix the syntax error; doctor reads every config file OpenCode merges, so one broken file hides the rest.",
530
+ });
531
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
276
532
  }
277
- else {
533
+ if (sources.length === 0) {
278
534
  checks.push({
279
535
  id: "config",
280
536
  state: "warn",
@@ -282,13 +538,19 @@ export async function runDoctor(deps) {
282
538
  fix: "Create one with the snippet below.",
283
539
  });
284
540
  }
285
- const registration = findRegistration(host.generation, parsedConfig);
541
+ else {
542
+ checks.push({ id: "config", state: "ok", detail: configPaths.join(", ") });
543
+ }
544
+ const applied = applyPluginLists([...sources].reverse());
545
+ const configured = applied.considered;
286
546
  const distDir = path.resolve(deps.cwd, "dist");
287
- if (!registration) {
547
+ if (applied.registrations.length === 0) {
288
548
  checks.push({
289
549
  id: "registration",
290
550
  state: "fail",
291
- detail: "LeakShield is not registered in the OpenCode config.",
551
+ detail: applied.disabled
552
+ ? `LeakShield is disabled by "${applied.disabled.entry}" in ${applied.disabled.source}, so the host does not load it.`
553
+ : "LeakShield is not registered in the OpenCode config.",
292
554
  fix: "Add it (snippet below), then rerun this doctor.",
293
555
  });
294
556
  return {
@@ -297,34 +559,61 @@ export async function runDoctor(deps) {
297
559
  hostGeneration: host.generation,
298
560
  configPath,
299
561
  checks,
300
- snippet: registrationSnippet(host.generation, distDir),
562
+ snippet: registrationSnippet(distDir),
301
563
  };
302
564
  }
565
+ const registrationRefs = applied.registrations.map((entry) => `"${entry.ref}"`).join(", ");
566
+ const registrationSources = [...new Set(applied.registrations.map((entry) => entry.source))];
567
+ const registrationHasOptions = applied.registrations.some((entry) => entry.options && Object.keys(entry.options).length > 0);
568
+ const fromSource = sources.length > 1 ? ` (from ${registrationSources.join(", ")})` : "";
303
569
  checks.push({
304
570
  id: "registration",
305
571
  state: "ok",
306
- detail: `Registered as "${registration.packageRef}"${registration.options && Object.keys(registration.options).length > 0 ? " with options" : ""}.`,
572
+ detail: `Registered as ${registrationRefs}${registrationHasOptions ? " with options" : ""}${fromSource}.`,
307
573
  });
308
574
  // Local dist presence (silent-skip guard: the host logs and skips a plugin
309
575
  // whose entry point cannot be resolved, which looks like "no protection"
310
- // with no visible failure).
311
- if (registration.isLocalDistPath && registration.packageRef) {
312
- const resolved = path.resolve(deps.cwd, registration.packageRef);
313
- // v2 registers a directory (host resolves index.js); v1 legacy entries
314
- // point directly at the compiled opencode.js file.
315
- const entryOk = registration.packageRef.endsWith(".js")
316
- ? deps.existsFile(resolved)
317
- : deps.existsDir(resolved) && deps.existsFile(path.join(resolved, "index.js"));
318
- if (!entryOk) {
576
+ // with no visible failure). Every configured reference is checked, not only
577
+ // the one doctor would pick as the winner (#67).
578
+ const localEntries = configured
579
+ .filter((entry) => isLocalRef(entry.ref))
580
+ .map((entry) => {
581
+ // A relative path resolves from the config file that declared it, and a
582
+ // `file://` URL is decoded rather than used literally
583
+ // (https://opencode.ai/v2/docs/plugins/#configure).
584
+ const local = localPathOf(entry.ref, path.dirname(entry.source));
585
+ if (local?.path == null) {
586
+ return { entry, resolved: entry.ref, isSingleFile: false, invalidUrl: true, ok: false };
587
+ }
588
+ const resolved = local.path;
589
+ // Configured local paths must be directories; the host skips a path that
590
+ // points at a single file.
591
+ const isSingleFile = deps.existsFile(resolved);
592
+ const ok = !isSingleFile && deps.existsDir(resolved) && deps.existsFile(path.join(resolved, "index.js"));
593
+ return { entry, resolved, isSingleFile, invalidUrl: false, ok };
594
+ });
595
+ if (localEntries.length > 0) {
596
+ const broken = localEntries.find((local) => !local.ok);
597
+ if (broken) {
319
598
  checks.push({
320
599
  id: "dist",
321
600
  state: "fail",
322
- detail: `${resolved} is missing or not a loadable entry point — OpenCode will silently log-and-skip this plugin, leaving sessions unprotected.`,
323
- fix: "Run `npm run build` in the project root (the snippet expects <project>/dist), or point the entry at the built directory.",
601
+ detail: broken.invalidUrl
602
+ ? `"${broken.entry.ref}" (${broken.entry.source}) is not a file URL this platform can turn into a path, so the host cannot load it and sessions are left unprotected.`
603
+ : broken.isSingleFile
604
+ ? `${broken.resolved} (from "${broken.entry.ref}") is a single file; the host skips configured file paths and loads only plugin directories.`
605
+ : `${broken.resolved} (from "${broken.entry.ref}") is missing or not a loadable entry point — OpenCode will silently log-and-skip this plugin, leaving sessions unprotected.`,
606
+ fix: broken.invalidUrl
607
+ ? "Write the entry as a plain absolute path or a local file:// URL without encoded separators."
608
+ : "Run `npm run build` in the project root (the snippet expects <project>/dist), or point the entry at the built directory.",
324
609
  });
325
610
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
326
611
  }
327
- checks.push({ id: "dist", state: "ok", detail: `${resolved} exists.` });
612
+ checks.push({
613
+ id: "dist",
614
+ state: "ok",
615
+ detail: `${localEntries.map((local) => local.resolved).join(", ")} ${localEntries.length === 1 ? "exists" : "exist"}.`,
616
+ });
328
617
  }
329
618
  else {
330
619
  checks.push({
@@ -333,43 +622,80 @@ export async function runDoctor(deps) {
333
622
  detail: "Package-name registration; dist resolution is the host's job at install time.",
334
623
  });
335
624
  }
336
- // Options validation (same schema the plugin entry enforces at runtime)
337
- const optionsValidation = validatePluginOptions(registration.options ?? {}, host.generation);
338
- if (!optionsValidation.ok) {
339
- checks.push({
340
- id: "options",
341
- state: "fail",
342
- detail: `Plugin options are invalid — every protected request would fail closed at runtime: ${optionsValidation.error}`,
343
- fix: "Correct the options in opencode.json (see README for valid combinations).",
344
- });
345
- return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
625
+ // Options validation (same schema the plugin entry enforces at runtime). Every
626
+ // configured entry is validated and the weakest decides the verdict: a
627
+ // stronger entry must not hide a weaker one when both reach the host (#67).
628
+ const validated = [];
629
+ for (const entry of configured) {
630
+ const validation = validatePluginOptions(entry.options ?? {});
631
+ if (!validation.ok) {
632
+ checks.push({
633
+ id: "options",
634
+ state: "fail",
635
+ detail: `Plugin options are invalid for "${entry.ref}" (${entry.source}) — every protected request would fail closed at runtime: ${validation.error}`,
636
+ fix: "Correct the options in opencode.json (see README for valid combinations).",
637
+ });
638
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
639
+ }
640
+ validated.push({ entry, options: validation.options });
346
641
  }
347
- const options = optionsValidation.options;
642
+ const weakness = (candidate) => candidate.mode === "transparent" ? (candidate.wireProtection === false ? 0 : 1) : 2;
643
+ const weakest = [...validated].sort((a, b) => weakness(a.options) - weakness(b.options))[0];
644
+ const options = weakest.options;
645
+ // Attachments are reported conservatively too: any transparent entry that
646
+ // lets them through unscanned outranks a stricter tied entry (#67).
647
+ if (options.mode === "transparent" &&
648
+ validated.some((candidate) => candidate.options.mode === "transparent" && candidate.options.attachments === "allow")) {
649
+ options.attachments = "allow";
650
+ }
651
+ const across = configured.length > 1 ? ` (weakest of ${configured.length} configured entries)` : "";
348
652
  checks.push({
349
653
  id: "options",
350
654
  state: "ok",
351
- 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}` : ""}`,
655
+ detail: `mode=${options.mode}${weakest.entry.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}` : ""}${across}`,
352
656
  });
353
657
  checks.push(persistenceCheck(options, deps));
354
- // Guard config load
658
+ // Guard config load. Every configured entry's guard config must load: the
659
+ // weakest entry supplies the summary, but a broken configPath in another
660
+ // entry still breaks the install it would run under (#67).
355
661
  let guardConfig;
356
- try {
357
- guardConfig = deps.loadGuardConfig(options.configPath, deps.cwd);
358
- checks.push({
359
- id: "guard-config",
360
- state: "ok",
361
- detail: options.configPath ? `Loaded ${options.configPath}.` : "Default guard config resolved.",
362
- });
662
+ const loadedConfigs = [];
663
+ const guardPaths = [...new Set(validated.map((candidate) => candidate.options.configPath))];
664
+ for (const guardPath of guardPaths) {
665
+ try {
666
+ const loaded = deps.loadGuardConfig(guardPath, deps.cwd);
667
+ loadedConfigs.push({ path: guardPath, config: loaded });
668
+ if (guardPath === options.configPath)
669
+ guardConfig = loaded;
670
+ }
671
+ catch (error) {
672
+ checks.push({
673
+ id: "guard-config",
674
+ state: "fail",
675
+ detail: `Guard config failed to load${guardPath ? ` for ${guardPath}` : ""}: ${error.message}`,
676
+ fix: "Fix the config file, or remove configPath to use defaults.",
677
+ });
678
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
679
+ }
363
680
  }
364
- catch (error) {
681
+ if (!guardConfig) {
365
682
  checks.push({
366
683
  id: "guard-config",
367
684
  state: "fail",
368
- detail: `Guard config failed to load: ${error.message}`,
369
- fix: "Fix the config file, or remove configPath to use defaults.",
685
+ detail: "Guard config did not load for the entry that decides the verdict.",
686
+ fix: "Rerun the doctor; if it repeats, report the configuration.",
370
687
  });
371
688
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
372
689
  }
690
+ checks.push({
691
+ id: "guard-config",
692
+ state: "ok",
693
+ detail: options.configPath
694
+ ? `Loaded ${options.configPath}.`
695
+ : validated.length > 1
696
+ ? `Guard configs resolved for ${validated.length} entries.`
697
+ : "Default guard config resolved.",
698
+ });
373
699
  // Custom rules the scanner skips (the ReDoS timing heuristic; uncompileable
374
700
  // patterns already failed the load above). Descriptions only, never patterns.
375
701
  const skipped = skippedCustomRules(guardConfig);
@@ -381,27 +707,149 @@ export async function runDoctor(deps) {
381
707
  fix: "Rewrite the pattern without nested or overlapping quantifiers, such as (a+)+ or (a|a)*.",
382
708
  });
383
709
  }
384
- // Smoke: the local scanner must flag a synthetic credential
385
- const smoke = deps.smokeScan(SMOKE_CANARY, guardConfig);
386
- if (smoke.findings > 0) {
710
+ // Allowlists (issue #32) are an exact-match bypass, so they are surfaced
711
+ // rather than silent: which entries exist, whether each still suppresses the
712
+ // literal it names, and how many suppressions this process counted.
713
+ const globalAllow = guardConfig.settings?.allowlist ?? [];
714
+ const customRules = guardConfig.custom_rules ?? [];
715
+ const ruleAllow = customRules.flatMap((rule) => rule.allow ?? []);
716
+ const entries = [];
717
+ const seenEntry = new Set();
718
+ for (const value of globalAllow) {
719
+ const key = `global\u0000${value}`;
720
+ if (seenEntry.has(key))
721
+ continue;
722
+ seenEntry.add(key);
723
+ entries.push({ value, ruleIndex: -1 });
724
+ }
725
+ customRules.forEach((rule, ruleIndex) => {
726
+ for (const value of rule.allow ?? []) {
727
+ const key = `rule${ruleIndex}\u0000${value}`;
728
+ if (seenEntry.has(key))
729
+ continue;
730
+ seenEntry.add(key);
731
+ entries.push({ value, ruleIndex });
732
+ }
733
+ });
734
+ if (entries.length > 0) {
735
+ const scan = deps.probeScan ?? defaultProbeScan;
736
+ // An allowlist only suppresses a rule's own finding or an exact env value.
737
+ // A Unicode evasion warning (zero-width or look-alike letters) is not a rule match,
738
+ // so it must neither count as suppression nor as a broken filter.
739
+ const suppressible = (exact, ruleDescription) => exact.filter((finding) => !finding.unicodeWarning && (ruleDescription === undefined || finding.description === ruleDescription));
740
+ const withoutAllowlists = (config) => ({
741
+ ...config,
742
+ settings: { ...(config.settings ?? {}), allowlist: [] },
743
+ custom_rules: (config.custom_rules ?? []).map((rule) => ({ ...rule, allow: undefined })),
744
+ });
745
+ const sample = entries.slice(0, 8);
746
+ let broken = 0;
747
+ let exercised = 0;
748
+ let unverified = 0;
749
+ // A per-rule entry must be judged against that rule alone: leaving built-in
750
+ // detectors in place would report a correct suppression as BROKEN when the
751
+ // same literal is also an email, a keyword or an env value.
752
+ const isolateRule = (ruleIndex) => ({
753
+ nda_keywords: [],
754
+ private_domains: [],
755
+ custom_rules: [customRules[ruleIndex]],
756
+ exact_value_detector: undefined,
757
+ settings: {
758
+ ...(guardConfig.settings ?? {}),
759
+ allowlist: [],
760
+ env_files: [],
761
+ encoding_detection: false,
762
+ private_cidrs: [],
763
+ rule_overrides: Object.fromEntries([...BUILTIN_RULE_IDS].map((id) => [id, false])),
764
+ },
765
+ });
766
+ for (const entry of sample) {
767
+ const scope = entry.ruleIndex < 0 ? guardConfig : isolateRule(entry.ruleIndex);
768
+ const ruleDescription = entry.ruleIndex < 0 ? undefined : customRules[entry.ruleIndex].description;
769
+ // Only an exact matched span can be suppressed, so the baseline must ask
770
+ // for one: a rule matching a substring of the entry says nothing about it.
771
+ const baseline = scan(entry.value, withoutAllowlists(scope));
772
+ const withAllow = scan(entry.value, scope);
773
+ if (suppressible(withAllow.exact, ruleDescription).length > 0)
774
+ broken += 1;
775
+ else if (suppressible(baseline.exact, ruleDescription).length > 0)
776
+ exercised += 1;
777
+ else
778
+ unverified += 1;
779
+ }
780
+ const entryCount = entries.length === 1 ? "1 allowlist entry" : `${entries.length} allowlist entries`;
781
+ const coverage = sample.length === entries.length ? "all" : `${sample.length} of them`;
782
+ const counter = `${allowlistSuppressions()} suppression(s) counted in this process`;
783
+ if (broken > 0) {
784
+ checks.push({
785
+ id: "allowlist",
786
+ state: "fail",
787
+ detail: `${broken} allowlisted literal(s) still produce a finding under their own scope. The exact-match filter is not working, so those values are not actually quiet. ${entryCount} total; ${counter}.`,
788
+ fix: "Do not rely on those entries. Re-run the scanner with `--text` on the exact value and report it: an allowlisted literal must produce no rule or env finding (a standing Unicode warning is separate).",
789
+ });
790
+ }
791
+ else if (unverified > 0) {
792
+ checks.push({
793
+ id: "allowlist",
794
+ state: "warn",
795
+ detail: `${entryCount} (global ${globalAllow.length}, per-rule ${ruleAllow.length}), exact match only; ${exercised} suppress when exercised, ${unverified} could not be exercised as a bare literal (a context-dependent pattern is judged only in place). ${coverage} exercised; ${counter}.`,
796
+ fix: "Review the entries that doctor could not exercise; it cannot prove a context-dependent entry, and an entry that no longer matches anything is only risk.",
797
+ });
798
+ }
799
+ else {
800
+ checks.push({
801
+ id: "allowlist",
802
+ state: "ok",
803
+ detail: `${entryCount} (global ${globalAllow.length}, per-rule ${ruleAllow.length}), exact match only; ${coverage} exercised, all suppress; ${counter}.`,
804
+ });
805
+ }
806
+ }
807
+ // `word_boundary` can only add \b at literal ASCII word edges. Where the edge
808
+ // is a group/class/quantifier the rule is looser than it looks; say so.
809
+ const boundaryHidden = customRules.filter((rule) => {
810
+ if (rule.word_boundary !== true)
811
+ return false;
812
+ const edges = customRuleBoundaries(rule);
813
+ return edges.lead === "hidden" || edges.trail === "hidden";
814
+ });
815
+ if (boundaryHidden.length > 0) {
816
+ checks.push({
817
+ id: "custom-rule-boundaries",
818
+ state: "warn",
819
+ detail: `${boundaryHidden.length} custom rule(s) set word_boundary but end or start with a group, class, quantifier or escape, where no \\b can be added: ${boundaryHidden.map((rule) => `"${rule.description}"`).join(", ")}. Those edges match inside larger words.`,
820
+ fix: "Write \\b in the pattern yourself, e.g. \\bEMP-\\d{6}\\b, or finish the pattern with a literal word character.",
821
+ });
822
+ }
823
+ // `path` is accepted but not implemented: the scanner has no source path for
824
+ // chat or tool text. Say so instead of letting a rule look scoped when it is not.
825
+ const pathRules = customRules.filter((rule) => (rule.path ?? []).length > 0);
826
+ if (pathRules.length > 0) {
827
+ checks.push({
828
+ id: "custom-rule-paths",
829
+ state: "warn",
830
+ detail: `${pathRules.length} custom rule(s) set \`path\`, but path scoping is not implemented: they apply to every scanned text, including prompts and tool output.`,
831
+ fix: "Remove `path` from those rules, or rely on the rule's pattern alone, until path scoping ships.",
832
+ });
833
+ }
834
+ // Smoke: the local scanner must flag a synthetic credential under every
835
+ // configured guard config, not only the one that decides the summary (#67).
836
+ const smokeFailures = loadedConfigs.filter((candidate) => deps.smokeScan(SMOKE_CANARY, candidate.config).findings === 0);
837
+ if (smokeFailures.length === 0) {
387
838
  checks.push({ id: "smoke", state: "ok", detail: "Synthetic sk- canary detected by the installed scanner." });
388
839
  }
389
840
  else {
390
841
  checks.push({
391
842
  id: "smoke",
392
843
  state: "fail",
393
- detail: "Synthetic sk- canary NOT detected — the guard config disables the rules this install relies on.",
844
+ detail: `Synthetic sk- canary NOT detected${smokeFailures[0].path ? ` under ${smokeFailures[0].path}` : ""} — that guard config disables the rules this install relies on.`,
394
845
  fix: "Restore credential rules in the guard config, or remove configPath to use defaults.",
395
846
  });
396
847
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
397
848
  }
398
- if (host.generation === "v1") {
399
- checks.push({
400
- id: "coverage",
401
- state: "warn",
402
- detail: "v1 host: session hooks only — no transport egress layer, no transparent pseudonymization, no deidentify.",
403
- });
404
- return { status: "PARTIAL", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
849
+ // A failed check must not still read as PARTIAL or PROTECTED: an allowlist
850
+ // failure is a "do not trust this install" signal, like a missing canary.
851
+ if (checks.some((check) => check.state === "fail")) {
852
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
405
853
  }
406
854
  if (options.mode === "transparent") {
407
855
  checks.push({
@@ -435,9 +883,7 @@ export function formatDoctorReport(report) {
435
883
  const verdict = report.status === "PROTECTED"
436
884
  ? "PROTECTED — install-level checks pass."
437
885
  : report.status === "PARTIAL"
438
- ? report.hostGeneration === "v1"
439
- ? "PARTIAL — protected within the v1 boundary (session hooks only)."
440
- : "PARTIAL — hook-first protection; final outbound HTTP bodies are not inspected."
886
+ ? "PARTIAL — hook-first protection; final outbound HTTP bodies are not inspected."
441
887
  : report.status === "BROKEN"
442
888
  ? "BROKEN — registered but would not protect; fix the [FAIL] items above."
443
889
  : report.status === "NOT_REGISTERED"