leakshield 0.1.3 → 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,6 +22,7 @@ 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";
@@ -124,58 +126,152 @@ function parseHostVersion(raw) {
124
126
  return { generation: "v2", version: raw };
125
127
  return { generation: "v1", version: raw };
126
128
  }
127
- function matchesLeakshield(entry) {
128
- 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))
129
146
  return true;
130
- return /\/leakshield(\/dist(\/opencode\.js)?)?$/.test(entry);
147
+ return path.sep === "\\" && (/^[A-Za-z]:[\\/]/.test(ref) || ref.startsWith("\\\\"));
131
148
  }
132
- function findRegistration(generation, config) {
133
- 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 {
134
159
  return null;
135
- const record = config;
136
- if (generation === "v2") {
137
- const plugins = record.plugins;
138
- if (Array.isArray(plugins)) {
139
- for (const entry of plugins) {
140
- if (typeof entry === "string" && matchesLeakshield(entry)) {
141
- return { packageRef: entry, options: {}, isLocalDistPath: entry.includes("/") };
142
- }
143
- if (entry && typeof entry === "object" && !Array.isArray(entry)) {
144
- const pkg = entry.package;
145
- if (typeof pkg === "string" && matchesLeakshield(pkg)) {
146
- const options = entry.options ?? {};
147
- return { packageRef: pkg, options, isLocalDistPath: pkg.includes("/") };
148
- }
149
- }
150
- }
151
- }
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))
152
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;
153
195
  }
154
- // v1: legacy `plugin` array of compiled file paths
155
- const legacy = record.plugin;
156
- if (Array.isArray(legacy)) {
157
- for (const entry of legacy) {
158
- if (typeof entry === "string" && matchesLeakshield(entry)) {
159
- return { packageRef: entry, options: {}, isLocalDistPath: true };
160
- }
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);
161
209
  }
162
- }
163
- return null;
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);
246
+ }
247
+ return packageName(ref);
164
248
  }
165
- function registrationSnippet(generation, distDir) {
166
- if (generation === "v2") {
167
- return [
168
- '"plugins": [',
169
- " {",
170
- ` "package": "${distDir.replaceAll("\\", "\\\\")}",`,
171
- ' "options": { "mode": "block" }',
172
- " }",
173
- "]",
174
- ].join("\n");
175
- }
176
- 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");
177
258
  }
178
- 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
+ ];
179
275
  const workspace = [
180
276
  path.join(deps.cwd, "opencode.json"),
181
277
  path.join(deps.cwd, "opencode.jsonc"),
@@ -184,11 +280,154 @@ function candidateConfigPaths(deps) {
184
280
  deps.xdgConfigHome ?? path.join(deps.home, ".config"),
185
281
  path.join(deps.home, "Library", "Application Support"),
186
282
  ];
187
- const global = configRoots.flatMap((root) => [
188
- path.join(root, "opencode", "opencode.json"),
189
- path.join(root, "opencode", "opencode.jsonc"),
190
- ]);
191
- 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
+ };
192
431
  }
193
432
  /**
194
433
  * W2 (B5) persistence status — a warn/ok/skip check, never a status flip:
@@ -268,35 +507,30 @@ export async function runDoctor(deps) {
268
507
  });
269
508
  return { status: "HOST_MISSING", hostVersion: null, hostGeneration: null, configPath: null, checks };
270
509
  }
271
- checks.push({ id: "host", state: "ok", detail: `OpenCode ${host.version.trim()} (${host.generation})` });
272
- // Config discovery
273
- let configPath = null;
274
- let rawConfig = null;
275
- for (const candidate of candidateConfigPaths(deps)) {
276
- const text = deps.readIfExists(candidate);
277
- if (text !== null) {
278
- configPath = candidate;
279
- rawConfig = text;
280
- break;
281
- }
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 };
282
518
  }
283
- let parsedConfig = null;
284
- if (configPath && rawConfig !== null) {
285
- try {
286
- parsedConfig = parseJsonc(rawConfig);
287
- checks.push({ id: "config", state: "ok", detail: configPath });
288
- }
289
- catch (error) {
290
- checks.push({
291
- id: "config",
292
- state: "fail",
293
- detail: `${configPath} is not parseable JSON/JSONC: ${error.message}`,
294
- fix: "Fix the syntax error, or remove the file so another candidate can apply.",
295
- });
296
- return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
297
- }
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 };
298
532
  }
299
- else {
533
+ if (sources.length === 0) {
300
534
  checks.push({
301
535
  id: "config",
302
536
  state: "warn",
@@ -304,13 +538,19 @@ export async function runDoctor(deps) {
304
538
  fix: "Create one with the snippet below.",
305
539
  });
306
540
  }
307
- 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;
308
546
  const distDir = path.resolve(deps.cwd, "dist");
309
- if (!registration) {
547
+ if (applied.registrations.length === 0) {
310
548
  checks.push({
311
549
  id: "registration",
312
550
  state: "fail",
313
- 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.",
314
554
  fix: "Add it (snippet below), then rerun this doctor.",
315
555
  });
316
556
  return {
@@ -319,34 +559,61 @@ export async function runDoctor(deps) {
319
559
  hostGeneration: host.generation,
320
560
  configPath,
321
561
  checks,
322
- snippet: registrationSnippet(host.generation, distDir),
562
+ snippet: registrationSnippet(distDir),
323
563
  };
324
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(", ")})` : "";
325
569
  checks.push({
326
570
  id: "registration",
327
571
  state: "ok",
328
- detail: `Registered as "${registration.packageRef}"${registration.options && Object.keys(registration.options).length > 0 ? " with options" : ""}.`,
572
+ detail: `Registered as ${registrationRefs}${registrationHasOptions ? " with options" : ""}${fromSource}.`,
329
573
  });
330
574
  // Local dist presence (silent-skip guard: the host logs and skips a plugin
331
575
  // whose entry point cannot be resolved, which looks like "no protection"
332
- // with no visible failure).
333
- if (registration.isLocalDistPath && registration.packageRef) {
334
- const resolved = path.resolve(deps.cwd, registration.packageRef);
335
- // v2 registers a directory (host resolves index.js); v1 legacy entries
336
- // point directly at the compiled opencode.js file.
337
- const entryOk = registration.packageRef.endsWith(".js")
338
- ? deps.existsFile(resolved)
339
- : deps.existsDir(resolved) && deps.existsFile(path.join(resolved, "index.js"));
340
- 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) {
341
598
  checks.push({
342
599
  id: "dist",
343
600
  state: "fail",
344
- detail: `${resolved} is missing or not a loadable entry point — OpenCode will silently log-and-skip this plugin, leaving sessions unprotected.`,
345
- 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.",
346
609
  });
347
610
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
348
611
  }
349
- 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
+ });
350
617
  }
351
618
  else {
352
619
  checks.push({
@@ -355,43 +622,80 @@ export async function runDoctor(deps) {
355
622
  detail: "Package-name registration; dist resolution is the host's job at install time.",
356
623
  });
357
624
  }
358
- // Options validation (same schema the plugin entry enforces at runtime)
359
- const optionsValidation = validatePluginOptions(registration.options ?? {}, host.generation);
360
- if (!optionsValidation.ok) {
361
- checks.push({
362
- id: "options",
363
- state: "fail",
364
- detail: `Plugin options are invalid — every protected request would fail closed at runtime: ${optionsValidation.error}`,
365
- fix: "Correct the options in opencode.json (see README for valid combinations).",
366
- });
367
- return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
368
- }
369
- const options = optionsValidation.options;
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 });
641
+ }
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)` : "";
370
652
  checks.push({
371
653
  id: "options",
372
654
  state: "ok",
373
- 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}`,
374
656
  });
375
657
  checks.push(persistenceCheck(options, deps));
376
- // 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).
377
661
  let guardConfig;
378
- try {
379
- guardConfig = deps.loadGuardConfig(options.configPath, deps.cwd);
380
- checks.push({
381
- id: "guard-config",
382
- state: "ok",
383
- detail: options.configPath ? `Loaded ${options.configPath}.` : "Default guard config resolved.",
384
- });
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
+ }
385
680
  }
386
- catch (error) {
681
+ if (!guardConfig) {
387
682
  checks.push({
388
683
  id: "guard-config",
389
684
  state: "fail",
390
- detail: `Guard config failed to load: ${error.message}`,
391
- 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.",
392
687
  });
393
688
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
394
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
+ });
395
699
  // Custom rules the scanner skips (the ReDoS timing heuristic; uncompileable
396
700
  // patterns already failed the load above). Descriptions only, never patterns.
397
701
  const skipped = skippedCustomRules(guardConfig);
@@ -527,34 +831,26 @@ export async function runDoctor(deps) {
527
831
  fix: "Remove `path` from those rules, or rely on the rule's pattern alone, until path scoping ships.",
528
832
  });
529
833
  }
530
- // Smoke: the local scanner must flag a synthetic credential
531
- const smoke = deps.smokeScan(SMOKE_CANARY, guardConfig);
532
- if (smoke.findings > 0) {
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) {
533
838
  checks.push({ id: "smoke", state: "ok", detail: "Synthetic sk- canary detected by the installed scanner." });
534
839
  }
535
840
  else {
536
841
  checks.push({
537
842
  id: "smoke",
538
843
  state: "fail",
539
- 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.`,
540
845
  fix: "Restore credential rules in the guard config, or remove configPath to use defaults.",
541
846
  });
542
847
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
543
848
  }
544
849
  // A failed check must not still read as PARTIAL or PROTECTED: an allowlist
545
850
  // failure is a "do not trust this install" signal, like a missing canary.
546
- // This runs before the v1 early return so a v1 host cannot mask it either.
547
851
  if (checks.some((check) => check.state === "fail")) {
548
852
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
549
853
  }
550
- if (host.generation === "v1") {
551
- checks.push({
552
- id: "coverage",
553
- state: "warn",
554
- detail: "v1 host: session hooks only — no transport egress layer, no transparent pseudonymization, no deidentify.",
555
- });
556
- return { status: "PARTIAL", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
557
- }
558
854
  if (options.mode === "transparent") {
559
855
  checks.push({
560
856
  id: "coverage",
@@ -562,9 +858,6 @@ export async function runDoctor(deps) {
562
858
  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.`,
563
859
  });
564
860
  }
565
- // A failed check must not still read as PROTECTED: the allowlist failure is a
566
- // real "do not trust this install" signal, like a missing smoke canary.
567
- // (Handled before the v1 return above.)
568
861
  checks.push({
569
862
  id: "runtime",
570
863
  state: "warn",
@@ -590,9 +883,7 @@ export function formatDoctorReport(report) {
590
883
  const verdict = report.status === "PROTECTED"
591
884
  ? "PROTECTED — install-level checks pass."
592
885
  : report.status === "PARTIAL"
593
- ? report.hostGeneration === "v1"
594
- ? "PARTIAL — protected within the v1 boundary (session hooks only)."
595
- : "PARTIAL — hook-first protection; final outbound HTTP bodies are not inspected."
886
+ ? "PARTIAL — hook-first protection; final outbound HTTP bodies are not inspected."
596
887
  : report.status === "BROKEN"
597
888
  ? "BROKEN — registered but would not protect; fix the [FAIL] items above."
598
889
  : report.status === "NOT_REGISTERED"