@misconfig/cli 1.3.2 → 1.5.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/engine/index.js CHANGED
@@ -6,6 +6,7 @@ import { maskSecrets, looksLikeSecret, looksLikeToken, isMasked, isPathLike, des
6
6
  import { parseJSONC, parseTOML, parseYAML, parseCodexRules } from "./parse.js";
7
7
  import { namedInstructions, NAMING_SETTINGS } from "./named.js";
8
8
  import { RULES, CATEGORIES } from "./catalog.js";
9
+ import { TEMPLATES, holds, readers } from "./templates.js";
9
10
  import { explainFile, agentLines, hiddenComments, hiddenTags, hiddenZeroWidth, fenceAt, inCodeSpan, CAN_IMPORT, scopeOf, HOOK_EVENTS, anthropicMarketplace, marketplaceSource } from "./explain.js";
10
11
  import { ignoreRules, isIgnored, globMatch } from "./glob.js";
11
12
  import { HOME_MARKERS, DOWNLOADS_LIKE, TOOL_ROOT, visibleName } from "./paths.js";
@@ -373,7 +374,9 @@ const SHELL_SERVER = /(?:^|[-_/@.])(?:shell|terminal|exec|executor|commands?|cmd
373
374
 
374
375
  // --- Entry point -------------------------------------------------------------
375
376
 
376
- export function analyze(input) {
377
+ // `rules` are a company's own, from readTemplate in templates.js. They can
378
+ // only add findings.
379
+ export function analyze(input, { rules = [] } = {}) {
377
380
  const ctx = buildContext(input ?? {});
378
381
  // A file that trips up a check is reported as unchecked. It can't stop
379
382
  // the rest of the report.
@@ -386,6 +389,9 @@ export function analyze(input) {
386
389
  };
387
390
  for (const f of ctx.files) if (f.content) guard(f, () => collectMcpServers(ctx, f));
388
391
  for (const f of ctx.files) if (f.content) guard(f, () => checkFile(ctx, f));
392
+ // After the built-in checks of every file, so a rule that trips on a file
393
+ // can't cost one of their findings.
394
+ if (rules.length) for (const f of ctx.files) if (f.content) guard(f, () => checkTemplates(ctx, f, rules));
389
395
  for (const f of ctx.files) {
390
396
  if (f.content && f.kind && (f.failed || (/\.(jsonc?|toml)$/i.test(f.path) && parsed(f) == null))) add(ctx, "WS-UNPARSED", { file: f });
391
397
  }
@@ -394,16 +400,22 @@ export function analyze(input) {
394
400
  // to different agents aren't all in front of any one of them.
395
401
  // Agents that read the same file, such as Claude Code and Copilot with
396
402
  // .mcp.json, are reported once.
403
+ // A project can define servers by the hundred thousand, so the lists are
404
+ // added to and compared in place, never copied or joined into one string.
397
405
  const perAgent = new Map();
398
406
  for (const s of ctx.mcpServers) {
399
407
  if (s.disabled) continue;
400
- for (const t of s.file.tools ?? []) perAgent.set(t, [...(perAgent.get(t) ?? []), `${s.file.path}#${s.name}`]);
408
+ for (const t of s.file.tools ?? []) {
409
+ if (!perAgent.has(t)) perAgent.set(t, []);
410
+ perAgent.get(t).push(`${s.file.path}#${s.name}`);
411
+ }
401
412
  }
402
- const reported = new Set();
413
+ const reported = [];
403
414
  for (const [tool, servers] of perAgent) {
404
- const key = servers.sort().join("\n");
405
- if (servers.length <= 12 || reported.has(key)) continue;
406
- reported.add(key);
415
+ if (servers.length <= 12) continue;
416
+ servers.sort();
417
+ if (reported.some((seen) => seen.length === servers.length && seen.every((name, i) => name === servers[i]))) continue;
418
+ reported.push(servers);
407
419
  add(ctx, "MCP-MANY", { tool, vars: { tool, count: servers.length } });
408
420
  }
409
421
  checkWorkspace(ctx);
@@ -441,13 +453,11 @@ function checkFile(ctx, f) {
441
453
  else if (/(^|\/)\.?amazonq\/cli-agents\//i.test(p)) checkAgentFile(ctx, f, "An Amazon Q hook");
442
454
  else if (/(^|\/)\.grok\/hooks\//i.test(p)) checkJsonHooks(ctx, f, "A Grok hook");
443
455
  else if (/(^|\/)\.cursor\/(cli-config|cli)\.json$/i.test(p)) checkCursorCli(ctx, f);
444
- else if (/(^|\/)\.cursor\/sandbox\.json$/i.test(p)) checkCursorSandbox(ctx, f);
456
+ // Cursor's sandbox file and the settings of Zed, Cline and Amp: their rules are templates.
457
+ else if (readers(TEMPLATES, p).length) checkTemplates(ctx, f, TEMPLATES);
445
458
  else if (/(^|\/)(\.vscode|(Code|Code - Insiders|VSCodium|Cursor|Windsurf)\/User)\/settings\.json$/i.test(p)) checkVSCode(ctx, f);
446
459
  else if (/(^|\/)opencode\.jsonc?$/i.test(p)) checkOpenCode(ctx, f);
447
- else if (/(^|\/)(\.zed|zed|Zed)\/settings\.json$/i.test(p)) checkZed(ctx, f);
448
- else if (/(^|\/)\.cline\/data\/globalState\.json$/i.test(p)) checkCline(ctx, f);
449
460
  else if (/(^|\/)\.grok\/config\.toml$/i.test(p)) checkGrok(ctx, f);
450
- else if (/(^|\/)(\.amp|\.config\/amp)\/settings\.json$/i.test(p)) checkAmp(ctx, f);
451
461
  else if (/(^|\/)goose\/config\.ya?ml$/i.test(p)) checkGoose(ctx, f);
452
462
  else if (/(^|\/)\.continue\/(?:.+\/)?[^/]+\.(?:ya?ml|json)$/i.test(p)) checkContinue(ctx, f);
453
463
  else if (f.kind === "Shell profile") checkShellProfile(ctx, f);
@@ -694,6 +704,18 @@ function evidenceLine(file, line) {
694
704
  return line && file.lines ? clip(file.lines[line - 1] ?? "") : undefined;
695
705
  }
696
706
 
707
+ // Rules written as data, from templates.js: for each one that reads this
708
+ // file and applies where the file is, a finding when its match holds.
709
+ function checkTemplates(ctx, f, templates) {
710
+ for (const t of readers(templates, f.path)) {
711
+ if (t.scope && (t.scope === "project") !== inProject(ctx, f)) continue;
712
+ const data = parsed(f);
713
+ if (data === null || typeof data !== "object" || !holds(t.match, data)) continue;
714
+ const line = t.line ? lineOf(f, t.line) : 0;
715
+ add(ctx, t.id, { file: f, line, evidence: evidenceLine(f, line), rule: t.rule });
716
+ }
717
+ }
718
+
697
719
  function add(ctx, id, opts = {}) {
698
720
  const { file, line = 0, vars = {} } = opts;
699
721
  const key = [id, file?.path ?? null, line, ...["server", "key", "rule", "place", "ext", "pkg", "known", "name", "skill", "campaign", "path"].map((k) => vars[k] ?? "")].join("|");
@@ -702,12 +724,14 @@ function add(ctx, id, opts = {}) {
702
724
  ctx.findings.push(makeFinding(id, opts));
703
725
  }
704
726
 
705
- function makeFinding(id, { file, line = 0, evidence, vars = {}, tool } = {}) {
706
- const rule = RULES[id];
727
+ // `own` is the wording of a company's own rule, which isn't in the catalog.
728
+ function makeFinding(id, { file, line = 0, evidence, vars = {}, tool, rule: own } = {}) {
729
+ const rule = own ?? RULES[id];
707
730
  if (!rule) throw new Error(`Unknown rule ${id}`);
708
731
  const filePath = file?.path ?? null;
709
732
  const values = Object.fromEntries(Object.entries({ file: filePath ?? "", ...vars }).map(([k, v]) => [k, String(v ?? "")]));
710
- const fill = (text) => fillTemplate(text, values);
733
+ // A company's rule can quote {file}. Other braces in it are its own words.
734
+ const fill = own ? (text) => text.replaceAll("{file}", () => values.file) : (text) => fillTemplate(text, values);
711
735
  return {
712
736
  id,
713
737
  severity: rule.severity,
@@ -720,6 +744,8 @@ function makeFinding(id, { file, line = 0, evidence, vars = {}, tool } = {}) {
720
744
  line: line || null,
721
745
  evidence: evidence ? describeMasks(clip(evidence, 220)) : null,
722
746
  vars: values,
747
+ // Set for a company's own rule: what it's called and where it's explained.
748
+ ...(own ? { custom: { name: own.name, reference: own.reference } } : {}),
723
749
  };
724
750
  }
725
751
 
@@ -1090,7 +1116,7 @@ function checkShellProfile(ctx, f) {
1090
1116
  }
1091
1117
  }
1092
1118
 
1093
- // --- Gemini, VS Code, OpenCode, Zed, Aider -----------------------------------
1119
+ // --- Gemini, VS Code, OpenCode, Aider ----------------------------------------
1094
1120
 
1095
1121
  function checkGemini(ctx, f) {
1096
1122
  const json = parsed(f);
@@ -1195,19 +1221,6 @@ function checkOpenCode(ctx, f) {
1195
1221
  }
1196
1222
  }
1197
1223
 
1198
- function checkZed(ctx, f) {
1199
- const json = parsed(f);
1200
- if (!isObj(json)) return;
1201
- if (json.agent?.always_allow_tool_actions === true || json.assistant?.always_allow_tool_actions === true || json.agent?.tool_permissions?.default === "allow") {
1202
- const line = lineOf(f, /always_allow_tool_actions|"default"\s*:\s*"allow"/);
1203
- add(ctx, "ZED-ALWAYS-ALLOW", { file: f, line, evidence: evidenceLine(f, line) });
1204
- }
1205
- if (json.session?.trust_all_worktrees === true) {
1206
- const line = lineOf(f, /trust_all_worktrees/);
1207
- add(ctx, "ZED-TRUST-ALL", { file: f, line, evidence: evidenceLine(f, line) });
1208
- }
1209
- }
1210
-
1211
1224
  // --- Trusted folders, hooks and settings of other agents ---------------------
1212
1225
 
1213
1226
  // Gemini CLI: { "/path": "TRUST_FOLDER" | "TRUST_PARENT" | "DO_NOT_TRUST" }.
@@ -1392,26 +1405,6 @@ function checkCursorCli(ctx, f) {
1392
1405
  }
1393
1406
  }
1394
1407
 
1395
- function checkCursorSandbox(ctx, f) {
1396
- if (parsed(f)?.type === "insecure_none") {
1397
- const line = lineOf(f, /insecure_none/);
1398
- add(ctx, "CU-NO-SANDBOX", { file: f, line, evidence: evidenceLine(f, line) });
1399
- }
1400
- }
1401
-
1402
- // Cline keeps its approval settings in ~/.cline/data/globalState.json.
1403
- function checkCline(ctx, f) {
1404
- const json = parsed(f);
1405
- if (!isObj(json)) return;
1406
- if (json.yoloModeToggled === true) {
1407
- const line = lineOf(f, /yoloModeToggled/);
1408
- add(ctx, "CL-YOLO", { file: f, line, evidence: evidenceLine(f, line) });
1409
- } else if (json.autoApprovalSettings?.enabled !== false && json.autoApprovalSettings?.actions?.executeAllCommands === true) {
1410
- const line = lineOf(f, /executeAllCommands/);
1411
- add(ctx, "CL-AUTO-COMMANDS", { file: f, line, evidence: evidenceLine(f, line) });
1412
- }
1413
- }
1414
-
1415
1408
  function checkGrok(ctx, f) {
1416
1409
  const toml = parsed(f);
1417
1410
  for (const command of commandsIn(toml?.ui?.status_line?.command)) checkCommand(ctx, command, f, "Grok's status line command");
@@ -1422,13 +1415,6 @@ function checkGrok(ctx, f) {
1422
1415
  }
1423
1416
  }
1424
1417
 
1425
- function checkAmp(ctx, f) {
1426
- if (parsed(f)?.["amp.dangerouslyAllowAll"] === true) {
1427
- const line = lineOf(f, /dangerouslyAllowAll/);
1428
- add(ctx, "AMP-ALLOW-ALL", { file: f, line, evidence: evidenceLine(f, line) });
1429
- }
1430
- }
1431
-
1432
1418
  // YAML, read line by line: GOOSE_MODE sits at the top level.
1433
1419
  function checkGoose(ctx, f) {
1434
1420
  const line = lineOf(f, /^GOOSE_MODE\s*:\s*["']?auto["']?\s*(#.*)?$/);
@@ -1719,7 +1705,7 @@ function collectMcpServers(ctx, f) {
1719
1705
  }
1720
1706
  }
1721
1707
 
1722
- function normalizeServer(name, def, file) {
1708
+ export function normalizeServer(name, def, file) {
1723
1709
  const d = isObj(def) ? def : {};
1724
1710
  let command = d.command ?? d.cmd;
1725
1711
  let args = scalars(d.args);
@@ -2673,15 +2659,19 @@ export function applyLookup(result, hits) {
2673
2659
  const bySeverity = (a, b) =>
2674
2660
  SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity) || a.category.localeCompare(b.category) || (a.file ?? "").localeCompare(b.file ?? "");
2675
2661
 
2662
+ // The level of a finding's rule. A company's own rule isn't in the catalog,
2663
+ // so its finding says. Null for a finding that names no rule there is.
2664
+ const levelOf = (f) => (Object.hasOwn(RULES, f.id) ? RULES[f.id].severity : f.custom && Object.hasOwn(WEIGHT, f.severity) ? f.severity : null);
2665
+
2676
2666
  // Score, grade and counts from a list of findings, for a check and again
2677
2667
  // after a lookup.
2678
2668
  function scoreFindings(findings, hasControlFiles) {
2679
2669
  const counts = Object.fromEntries(SEVERITIES.map((s) => [s, findings.filter((f) => f.severity === s).length]));
2680
2670
  // Repeats of the same rule count less, so one noisy pattern can't zero the score.
2681
2671
  const byRule = new Map();
2682
- for (const f of findings) byRule.set(f.id, (byRule.get(f.id) ?? 0) + 1);
2672
+ for (const f of findings) byRule.set(f.id, { severity: levelOf(f), n: (byRule.get(f.id)?.n ?? 0) + 1 });
2683
2673
  let penalty = 0;
2684
- for (const [id, n] of byRule) penalty += WEIGHT[RULES[id].severity] * Math.min(2, 1 + 0.25 * (n - 1));
2674
+ for (const { severity, n } of byRule.values()) penalty += WEIGHT[severity] * Math.min(2, 1 + 0.25 * (n - 1));
2685
2675
  const score = Math.max(0, Math.min(100, Math.round(100 - penalty)));
2686
2676
  let grade = GRADES.find(([, min]) => score >= min)?.[0] ?? "F";
2687
2677
  if (counts.critical && "ABC".includes(grade)) grade = "D";
@@ -2694,8 +2684,9 @@ function scoreFindings(findings, hasControlFiles) {
2694
2684
  export function pointsOff(findings) {
2695
2685
  const byRule = new Map();
2696
2686
  for (const f of findings) {
2697
- if (!Object.hasOwn(RULES, f.id)) continue;
2698
- const entry = byRule.get(f.id) ?? { id: f.id, severity: RULES[f.id].severity, findings: [] };
2687
+ const severity = levelOf(f);
2688
+ if (!severity) continue;
2689
+ const entry = byRule.get(f.id) ?? { id: f.id, severity, findings: [] };
2699
2690
  entry.findings.push(f);
2700
2691
  byRule.set(f.id, entry);
2701
2692
  }
@@ -0,0 +1,236 @@
1
+ // Rules written as data. A template names the settings files it reads and
2
+ // what in them makes a finding, and one reader applies them all, so a rule
3
+ // like this needs no code of its own. The rules built in this way are at the
4
+ // end of the file, with their wording in catalog.js. --rules adds a company's
5
+ // own, which bring their wording with them.
6
+ //
7
+ // A template can only add a finding. It can't run anything, read a file or
8
+ // take a finding away. A company's rule holds no regular expression either:
9
+ // its files are paths and its tests compare text, so nothing in a rules file
10
+ // can be written to stall a check on a file from someone else.
11
+
12
+ import { CATEGORIES, LEVELS, RULES } from "./catalog.js";
13
+
14
+ // Capitals, digits and hyphens, as in CC-BYPASS.
15
+ const ID = /^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+){0,6}$/;
16
+ const WORDING = ["name", "title", "severity", "category", "agent", "why", "fix", "reference"];
17
+ // Every key a rule can have, and every test a condition can make.
18
+ export const RULE_KEYS = ["id", ...WORDING, "files", "scope", "match", "line"];
19
+ export const RULE_TESTS = ["equals", "in", "contains", "startsWith", "endsWith", "exists"];
20
+ const MAX = { id: 40, name: 120, text: 600, files: 10, file: 300, stars: 4, line: 200, address: 300, path: 12, key: 200, depth: 6, conditions: 30, values: 50 };
21
+
22
+ const isObj = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
23
+ const isValue = (x) => x === null || typeof x === "boolean" || (typeof x === "number" && Number.isFinite(x)) || (typeof x === "string" && x.length <= MAX.text);
24
+ const oneLine = (x, max) => typeof x === "string" && x.trim() !== "" && x.length <= max && !/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(x);
25
+
26
+ // Where a rule's files are. A pattern is a path: **/ in front of it means in
27
+ // any folder, and * in the file's name stands for any run of characters.
28
+ // Nothing else in it is special, so trying one on a file takes about as long
29
+ // as the pattern and the file's name are, however long a path a project
30
+ // comes up with. Null for text that isn't such a pattern.
31
+ function filePattern(text) {
32
+ if (!oneLine(text, MAX.file)) return null;
33
+ const anywhere = text.startsWith("**/");
34
+ const rest = (anywhere ? text.slice(3) : text).toLowerCase();
35
+ const cut = rest.lastIndexOf("/") + 1;
36
+ const dir = rest.slice(0, cut);
37
+ const parts = rest.slice(cut).split("*");
38
+ if (cut === rest.length || /[*?[\]\\]/.test(dir) || parts.length - 1 > MAX.stars || parts.some((part, i) => /[?[\]\\]/.test(part) || (part === "" && i > 0 && i < parts.length - 1))) return null;
39
+ return { anywhere, dir, under: `/${dir}`, parts };
40
+ }
41
+
42
+ // True when a file's name fits a pattern's name, split where its *s were.
43
+ function named(parts, name) {
44
+ const first = parts[0];
45
+ const last = parts[parts.length - 1];
46
+ if (parts.length === 1) return name === first;
47
+ if (name.length < first.length + last.length || !name.startsWith(first) || !name.endsWith(last)) return false;
48
+ let at = first.length;
49
+ const end = name.length - last.length;
50
+ for (let i = 1; i < parts.length - 1; i++) {
51
+ const found = name.indexOf(parts[i], at);
52
+ if (found < 0 || found + parts[i].length > end) return false;
53
+ at = found + parts[i].length;
54
+ }
55
+ return true;
56
+ }
57
+
58
+ // The templates that read the file at this path, whatever its case, as
59
+ // macOS and Windows open it.
60
+ export function readers(templates, path) {
61
+ const lower = path.toLowerCase();
62
+ const cut = lower.lastIndexOf("/") + 1;
63
+ const dir = lower.slice(0, cut);
64
+ const name = lower.slice(cut);
65
+ return templates.filter((t) => t.files.some((p) => (p.anywhere ? dir === p.dir || dir.endsWith(p.under) : dir === p.dir) && named(p.parts, name)));
66
+ }
67
+
68
+ // A template as the reader uses it, with every key checked, so a mistake is
69
+ // reported when the rules are loaded and not passed over during a check.
70
+ // Throws an Error that says what to change. The message quotes the rule's
71
+ // ID, or a key that's a plain word, and nothing else from the rule, so a
72
+ // rules file can't write to a log in words of its own.
73
+ //
74
+ // A built-in template takes its wording from the catalog, and can point at
75
+ // its line with a regular expression, `linePattern`. Any other brings its
76
+ // own wording and can't use a built-in rule's ID.
77
+ export function readTemplate(raw, { builtIn = false } = {}) {
78
+ const known = isObj(raw) && typeof raw.id === "string" && raw.id.length <= MAX.id && ID.test(raw.id);
79
+ const fail = (message) => {
80
+ throw new Error(`${known ? `${raw.id}: ` : ""}${message}`);
81
+ };
82
+ if (!isObj(raw)) fail("A rule is a set of keys, such as id, files and match.");
83
+ const allowed = builtIn ? ["id", "files", "scope", "match", "line", "linePattern"] : RULE_KEYS;
84
+ for (const key of Object.keys(raw)) {
85
+ if (allowed.includes(key)) continue;
86
+ if (builtIn && WORDING.includes(key)) fail(`A built-in rule's ${key} is in the catalog.`);
87
+ fail(`${/^[\w-]{1,30}$/.test(key) ? `“${key}”` : "One of its keys"} isn't a key a rule can have. The keys are ${allowed.join(", ")}.`);
88
+ }
89
+ if (!known) fail("id needs capitals, digits and hyphens, such as ACME-NO-YOLO.");
90
+
91
+ const files = Array.isArray(raw.files) && raw.files.length && raw.files.length <= MAX.files ? raw.files.map(filePattern) : [null];
92
+ if (files.includes(null)) fail(`files needs a list of 1 to ${MAX.files} paths, such as **/.claude/settings.json. **/ in front means in any folder, and * in the file's name, up to ${MAX.stars} times, means any run of characters.`);
93
+ if (raw.scope !== undefined && raw.scope !== "project" && raw.scope !== "computer") fail("scope is project, for files in the checked folder, or computer, for the settings outside it.");
94
+
95
+ let conditions = 0;
96
+ const condition = (node, depth) => {
97
+ if (depth > MAX.depth) fail(`match is nested more than ${MAX.depth} deep.`);
98
+ // A list on its own means all of them.
99
+ if (Array.isArray(node)) {
100
+ if (!node.length) fail("A list in match needs at least one condition.");
101
+ node = { all: node };
102
+ }
103
+ if (!isObj(node)) fail("Each part of match is a condition with a path, or all, any or not.");
104
+ const keys = Object.keys(node);
105
+ for (const group of ["all", "any"]) {
106
+ if (!Object.hasOwn(node, group)) continue;
107
+ if (keys.length !== 1 || !Array.isArray(node[group]) || !node[group].length) fail(`${group} needs a list of conditions and nothing beside it.`);
108
+ return { [group]: node[group].map((n) => condition(n, depth + 1)) };
109
+ }
110
+ if (Object.hasOwn(node, "not")) {
111
+ if (keys.length !== 1) fail("not needs one condition and nothing beside it.");
112
+ return { not: condition(node.not, depth + 1) };
113
+ }
114
+ if (++conditions > MAX.conditions) fail(`match has more than ${MAX.conditions} conditions.`);
115
+ // A path is keys joined by dots, or a list of keys for a key that has
116
+ // a dot in it. * stands for every key, or every item of a list.
117
+ const path = typeof node.path === "string" ? node.path.split(".") : node.path;
118
+ if (!Array.isArray(path) || !path.length || path.length > MAX.path || !path.every((key) => typeof key === "string" && key !== "" && key.length <= MAX.key)) {
119
+ fail("path needs keys joined by dots, such as permissions.defaultMode, or a list of keys.");
120
+ }
121
+ const tests = keys.filter((key) => key !== "path");
122
+ if (tests.length !== 1 || !RULE_TESTS.includes(tests[0])) fail(`A condition needs a path and one of ${RULE_TESTS.join(", ")}.`);
123
+ const [test] = tests;
124
+ const value = node[test];
125
+ if (test === "exists" && typeof value !== "boolean") fail("exists is true or false.");
126
+ if (test === "equals" && !isValue(value)) fail("equals needs text, a number, true, false or null.");
127
+ if (test === "in" && !(Array.isArray(value) && value.length && value.length <= MAX.values && value.every(isValue))) fail(`in needs a list of up to ${MAX.values} values. Each is text, a number, true, false or null.`);
128
+ if (["contains", "startsWith", "endsWith"].includes(test) && !(typeof value === "string" && value !== "" && value.length <= MAX.text)) fail(`${test} needs text of up to ${MAX.text} characters.`);
129
+ return { path, test, value };
130
+ };
131
+ if (raw.match === undefined) fail("match says what in the file makes a finding. It needs at least one condition.");
132
+ const match = condition(raw.match, 0);
133
+
134
+ // The line a finding points at is the first one that has this text.
135
+ // Without `line`, that's the last key of the first path.
136
+ const firstPath = (node) => node.path ?? firstPath((node.all ?? node.any ?? [node.not])[0]);
137
+ if (raw.line !== undefined && !oneLine(raw.line, MAX.line)) fail(`line needs text of up to ${MAX.line} characters that's on the line a finding should point at.`);
138
+ const line = raw.line ?? firstPath(match).filter((key) => key !== "*").pop() ?? null;
139
+
140
+ const template = { id: raw.id, files, scope: raw.scope ?? null, match, line, rule: null };
141
+ if (builtIn) {
142
+ if (!Object.hasOwn(RULES, raw.id)) fail("A built-in rule needs its wording in the catalog.");
143
+ return raw.linePattern === undefined ? template : { ...template, line: new RegExp(raw.linePattern) };
144
+ }
145
+
146
+ if (Object.hasOwn(RULES, raw.id)) fail("That ID belongs to a built-in rule. Choose another, such as one that starts with your company's name.");
147
+ if (!oneLine(raw.name, MAX.name) || raw.name.includes("{file}")) fail(`name says what the rule finds, in one line of up to ${MAX.name} characters, without {file}.`);
148
+ if (raw.title !== undefined && !oneLine(raw.title, MAX.name)) fail(`title needs one line of up to ${MAX.name} characters.`);
149
+ for (const word of ["why", "fix"]) if (!oneLine(raw[word], MAX.text)) fail(`${word} needs one line of up to ${MAX.text} characters.`);
150
+ if (!Object.hasOwn(LEVELS, raw.severity)) fail(`severity is one of ${Object.keys(LEVELS).join(", ")}.`);
151
+ if (!Object.hasOwn(CATEGORIES, raw.category)) fail(`category is one of ${Object.keys(CATEGORIES).join(", ")}.`);
152
+ if (raw.agent !== undefined && !oneLine(raw.agent, 40)) fail("agent names the agent the setting belongs to, such as Claude Code, in up to 40 characters.");
153
+ let reference = null;
154
+ if (raw.reference !== undefined) {
155
+ try {
156
+ const url = new URL(oneLine(raw.reference, MAX.address) && !/\s/.test(raw.reference) ? raw.reference : "");
157
+ if (url.protocol !== "https:" || url.username || url.password) throw new Error();
158
+ reference = url.href;
159
+ } catch {
160
+ fail("reference needs an https address where the rule is explained.");
161
+ }
162
+ }
163
+ return {
164
+ ...template,
165
+ rule: { severity: raw.severity, category: raw.category, ...(raw.agent ? { tool: raw.agent } : {}), title: raw.title ?? raw.name, name: raw.name, why: raw.why, fix: raw.fix, reference },
166
+ };
167
+ }
168
+
169
+ // Every value a path leads to in a parsed settings file, however many: a
170
+ // list padded with harmless items can't keep the last one from a rule. Only
171
+ // a file's own keys count, so a path can't lead to what every object carries.
172
+ function valuesAt(data, path) {
173
+ let found = [data];
174
+ for (const key of path) {
175
+ const next = [];
176
+ for (const value of found) {
177
+ if (key !== "*") {
178
+ if (isObj(value) && Object.hasOwn(value, key)) next.push(value[key]);
179
+ continue;
180
+ }
181
+ const items = Array.isArray(value) ? value : isObj(value) ? Object.values(value) : [];
182
+ for (const item of items) next.push(item);
183
+ }
184
+ found = next;
185
+ if (!found.length) break;
186
+ }
187
+ return found;
188
+ }
189
+
190
+ // A number and its spelling as text are the same value: settings written in
191
+ // YAML are read as text.
192
+ const same = (a, b) => a === b || (typeof a === "number" && typeof b === "string" && String(a) === b) || (typeof a === "string" && typeof b === "number" && a === String(b));
193
+ const spelled = (v) => (typeof v === "string" ? v : typeof v === "number" ? String(v) : null);
194
+
195
+ // True when a template's match holds for a parsed settings file. A condition
196
+ // holds when a value its path leads to passes its test. Text is compared
197
+ // whole, so padding around a value can't hide the rest of it.
198
+ export function holds(node, data) {
199
+ if (node.all) return node.all.every((n) => holds(n, data));
200
+ if (node.any) return node.any.some((n) => holds(n, data));
201
+ if (node.not) return !holds(node.not, data);
202
+ const found = valuesAt(data, node.path);
203
+ if (node.test === "exists") return found.length > 0 === node.value;
204
+ if (node.test === "equals") return found.some((v) => same(v, node.value));
205
+ if (node.test === "in") return found.some((v) => node.value.some((w) => same(v, w)));
206
+ if (node.test === "contains") return found.some((v) => spelled(v)?.includes(node.value) === true);
207
+ if (node.test === "startsWith") return found.some((v) => spelled(v)?.startsWith(node.value) === true);
208
+ return found.some((v) => spelled(v)?.endsWith(node.value) === true);
209
+ }
210
+
211
+ // --- Built-in rules ----------------------------------------------------------------
212
+
213
+ // Zed's own folder is named .zed in a project and zed or Zed on a computer.
214
+ const ZED = ["**/.zed/settings.json", "**/zed/settings.json"];
215
+ // Cline keeps its approval settings in ~/.cline/data/globalState.json.
216
+ const CLINE = ["**/.cline/data/globalState.json"];
217
+
218
+ export const TEMPLATES = [
219
+ { id: "CU-NO-SANDBOX", files: ["**/.cursor/sandbox.json"], match: [{ path: "type", equals: "insecure_none" }], line: "insecure_none" },
220
+ {
221
+ id: "ZED-ALWAYS-ALLOW",
222
+ files: ZED,
223
+ match: { any: [{ path: "agent.always_allow_tool_actions", equals: true }, { path: "assistant.always_allow_tool_actions", equals: true }, { path: "agent.tool_permissions.default", equals: "allow" }] },
224
+ linePattern: 'always_allow_tool_actions|"default"\\s*:\\s*"allow"',
225
+ },
226
+ { id: "ZED-TRUST-ALL", files: ZED, match: [{ path: "session.trust_all_worktrees", equals: true }] },
227
+ { id: "CL-YOLO", files: CLINE, match: [{ path: "yoloModeToggled", equals: true }] },
228
+ // YOLO mode already approves everything, so this is for when it's off.
229
+ {
230
+ id: "CL-AUTO-COMMANDS",
231
+ files: CLINE,
232
+ match: [{ not: { path: "yoloModeToggled", equals: true } }, { not: { path: "autoApprovalSettings.enabled", equals: false } }, { path: "autoApprovalSettings.actions.executeAllCommands", equals: true }],
233
+ line: "executeAllCommands",
234
+ },
235
+ { id: "AMP-ALLOW-ALL", files: ["**/.amp/settings.json", "**/.config/amp/settings.json"], match: [{ path: ["amp.dangerouslyAllowAll"], equals: true }], line: "dangerouslyAllowAll" },
236
+ ].map((raw) => readTemplate(raw, { builtIn: true }));
@@ -0,0 +1,173 @@
1
+ import { fingerprint } from "./computer-snapshot.js";
2
+ import { changeEvent, changeValue, earlierBuildNote, editorText, historyLine, linkEditors, localAccount, riskEvent } from "./review-history.js";
3
+
4
+ function differences(secret, before, after, uncertain) {
5
+ const rows = [];
6
+ for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
7
+ const a = before[key], b = after[key], entry = b ?? a;
8
+ if (a?.hash === b?.hash || uncertain.has(entry.file)) continue;
9
+ const kind = !a ? "added" : !b ? "removed" : "changed";
10
+ const fields = new Set([...Object.keys(a?.parts ?? {}), ...Object.keys(b?.parts ?? {})]);
11
+ const changedFields = [...fields].filter((k) => a?.parts?.[k] !== b?.parts?.[k]).sort();
12
+ rows.push({
13
+ key, id: "c-" + fingerprint(secret, [key, a?.hash ?? null, b?.hash ?? null]).slice(0, 20),
14
+ kind, file: entry.file, label: entry.label, before: a?.summary ?? null, after: b?.summary ?? null, changedFields,
15
+ });
16
+ }
17
+ return rows.sort((a,b) => a.file.localeCompare(b.file) || a.label.localeCompare(b.label) || a.key.localeCompare(b.key));
18
+ }
19
+
20
+ export function observe(state, snapshot, findings) {
21
+ const previousScanAt = state.scannedAt;
22
+ const seen = { ...snapshot.items };
23
+ for (const [key, item] of Object.entries(state.seen)) {
24
+ if (snapshot.uncertain.has(item.file)) seen[key] = item;
25
+ }
26
+ const changes = previousScanAt === null ? [] : differences(state.key, state.seen, seen, snapshot.uncertain);
27
+ for (const row of changes) {
28
+ if (row.kind === "removed" && !state.approved[row.key] && !state.receipts[row.key]) state.removedPending[row.key] = state.seen[row.key];
29
+ else if (row.kind !== "removed") delete state.removedPending[row.key];
30
+ }
31
+ state.seen = seen;
32
+ state.uncertain = [...snapshot.uncertain].sort();
33
+ state.scannedAt = Date.now();
34
+ if (previousScanAt === null) state.history.events.push({ action: "baseline", at: state.scannedAt, actor: null, count: Object.keys(seen).length });
35
+ for (const row of changes) {
36
+ state.history.events.push({ ...changeEvent("observed", row, state.scannedAt), id: "e-" + (state.history.events.length + 1),
37
+ since: previousScanAt, subject: row.key, transition: row.id, editor: null,
38
+ ...(state.fileRevisions ? { priorFile: state.fileRevisions[row.file] ?? null } : {}),
39
+ nextFile: snapshot.fileRevisions.get(row.file) ?? null });
40
+ }
41
+ const revisions = Object.fromEntries(snapshot.fileRevisions);
42
+ for (const file of snapshot.uncertain) if (state.fileRevisions?.[file]) revisions[file] = state.fileRevisions[file];
43
+ state.fileRevisions = revisions;
44
+
45
+ const byFile = new Map();
46
+ for (const [key, item] of Object.entries(seen).sort(([a],[b]) => a.localeCompare(b))) {
47
+ if (!byFile.has(item.file)) byFile.set(item.file, []);
48
+ byFile.get(item.file).push([key, item]);
49
+ }
50
+ state.offeredRisks = {};
51
+ const risks = new Map();
52
+ for (const finding of findings) {
53
+ if (finding.severity === "info" || (!snapshot.verified.has(finding.file) && !snapshot.riskSources.has(finding.file))) continue;
54
+ const entries = byFile.get(finding.file) ?? [];
55
+ const server = finding.vars?.server;
56
+ const owners = server ? entries.filter(([,v]) => v.subject === fingerprint(state.key, ["server", server])) : [];
57
+ const scope = owners.length ? owners : entries;
58
+ const revision = snapshot.riskSources.get(finding.file)
59
+ ?? (!owners.length && finding.evidence ? finding.evidence.trim() : scope.map(([k,v]) => [k,v.hash]));
60
+ const id = "r-" + fingerprint(state.key, [finding.file, finding.id, finding.severity, finding.title, finding.vars, revision]).slice(0, 20);
61
+ state.offeredRisks[id] = { file: finding.file, rule: finding.id, severity: finding.severity, label: owners.length === 1 ? owners[0][1].label : null };
62
+ const accepted = state.acceptedRisks[id];
63
+ finding.review = { id, acceptedAt: accepted?.at ?? null, acceptedBy: accepted?.by ?? null };
64
+ risks.set(id, { ...finding.review, file: finding.file, rule: finding.id, title: finding.title, severity: finding.severity });
65
+ }
66
+ const awaiting = pending(state);
67
+ linkEditors(state.history, [...changes, ...awaiting]);
68
+ const approvalIds = new Map(awaiting.map((r) => [r.key, r.id]));
69
+ for (const row of changes) row.id = approvalIds.get(row.key) ?? null;
70
+ const earlierRisks = Object.entries(state.acceptedRisks).filter(([id]) => !risks.has(id)).map(([id, r]) => ({
71
+ id, file: r.file, rule: r.rule, severity: r.severity, label: r.label, acceptedAt: r.at, acceptedBy: r.by ?? null,
72
+ status: snapshot.uncertain.has(r.file) ? "unverified" : "not observed on this scan",
73
+ }));
74
+ return { previousScanAt, changes, pending: awaiting, unverified: state.uncertain, risks: [...risks.values()], earlierRisks, history: state.history };
75
+ }
76
+
77
+ function pending(state) {
78
+ return differences(state.key, { ...state.removedPending, ...state.approved }, state.seen, new Set(state.uncertain));
79
+ }
80
+
81
+ export function approve(state, id, account = localAccount()) {
82
+ const row = pending(state).find((r) => r.id === id);
83
+ if (row) {
84
+ linkEditors(state.history, [row]);
85
+ if (row.kind === "removed") {
86
+ delete state.approved[row.key];
87
+ delete state.removedPending[row.key];
88
+ }
89
+ else state.approved[row.key] = state.seen[row.key];
90
+ state.receipts[row.key] = id;
91
+ const event = changeEvent("approved", row, Date.now(), account);
92
+ if (row.observationId) Object.assign(event, { observationId: row.observationId, editor: row.editor, editorScope: row.editorScope });
93
+ state.history.events.push(event);
94
+ return { id, kind: "change", history: state.history };
95
+ }
96
+ if (Object.hasOwn(state.offeredRisks, id)) {
97
+ if (!state.acceptedRisks[id]) {
98
+ const risk = { at: Date.now(), by: account, ...state.offeredRisks[id] };
99
+ state.acceptedRisks[id] = risk;
100
+ state.history.events.push(riskEvent(id, risk));
101
+ }
102
+ const risk = state.acceptedRisks[id];
103
+ return { id, kind: "risk", acceptedAt: risk.at, acceptedBy: risk.by ?? null, history: state.history };
104
+ }
105
+ for (const [key, receipt] of Object.entries(state.receipts)) {
106
+ if (receipt !== id || state.approved[key]?.hash !== state.seen[key]?.hash) continue;
107
+ if (state.uncertain.includes(state.approved[key]?.file)) break;
108
+ return { id, kind: "change", history: state.history };
109
+ }
110
+ throw new Error("That review ID is no longer current. Scan again and choose the ID beside the change or risk you just reviewed.");
111
+ }
112
+
113
+ export function showApproval(review, findings, decision) {
114
+ review.history = decision.history;
115
+ if (decision.kind === "risk") {
116
+ const accepted = { acceptedAt: decision.acceptedAt, acceptedBy: decision.acceptedBy };
117
+ for (const risk of review.risks) if (risk.id === decision.id) Object.assign(risk, accepted);
118
+ for (const f of findings) if (f.review?.id === decision.id) Object.assign(f.review, accepted);
119
+ review.confirmation = "Risk accepted. Its severity, score and fix are still shown.";
120
+ } else {
121
+ review.pending = review.pending.filter((r) => r.id !== decision.id);
122
+ for (const row of review.changes) if (row.id === decision.id) row.id = null;
123
+ review.confirmation = "Change approved.";
124
+ }
125
+ }
126
+
127
+ export function changeLabel(row, existing = false) {
128
+ const action = existing ? "Existing" : row.kind[0].toUpperCase() + row.kind.slice(1);
129
+ return action + " " + row.label;
130
+ }
131
+
132
+ export function changeText(row, existing = false) {
133
+ return [changeLabel(row, existing), changeValue(row), row.file, row.observationId ? editorText(row.editor, row.editorScope) + " · " + row.observationId : null].filter(Boolean).join(" · ");
134
+ }
135
+
136
+ export function reviewLines(review, demo = false) {
137
+ const lines = [];
138
+ const displayedIds = new Set();
139
+ if (review.previousScanAt === null) lines.push("First scan on this computer. Review the settings you want to keep.");
140
+ else {
141
+ lines.push(review.changes.length ? "Since your last scan" : review.unverified.length ? "No changes in the settings we could verify." : "No changes since your last scan.");
142
+ for (const row of review.changes) {
143
+ lines.push(" " + changeText(row) + (row.id ? " · awaiting approval " + row.id : ""));
144
+ if (row.id) displayedIds.add(row.id);
145
+ }
146
+ }
147
+ const outstanding = review.pending.filter((r) => !displayedIds.has(r.id));
148
+ if (outstanding.length) lines.push("Awaiting your approval (" + outstanding.length + ")");
149
+ else if (!review.pending.length) lines.push(review.unverified.length ? "Approval is paused for the unverified sources below." : "No computer changes awaiting approval.");
150
+ for (const row of outstanding) lines.push(" " + row.id + " " + changeText(row, review.previousScanAt === null));
151
+ for (const file of review.unverified) lines.push("Could not fully verify " + file + ". Any earlier decision is kept.");
152
+ const accepted = review.risks.filter((r) => r.acceptedAt).length;
153
+ if (accepted) lines.push(accepted + (accepted === 1 ? " accepted risk is" : " accepted risks are") + " still present. See Findings.");
154
+ if (review.earlierRisks.length) {
155
+ lines.push("Earlier risk decisions");
156
+ for (const r of review.earlierRisks) lines.push(" " + [r.rule, r.label, r.file, "accepted " + new Date(r.acceptedAt).toISOString().slice(0, 10) + " by " + (r.acceptedBy ?? "an unknown account"), r.status].filter(Boolean).join(" · "));
157
+ }
158
+ if (!demo && (review.pending.length || review.risks.some((r) => !r.acceptedAt))) lines.push("Run again with --review to decide one at a time, or --approve ID to choose one.");
159
+ if (review.confirmation) lines.push(review.confirmation);
160
+ if (review.attribution && !demo) {
161
+ const { matchedEdits, filesRead, limited } = review.attribution;
162
+ lines.push("Tool records matched " + matchedEdits + " observed edit(s) across " + filesRead + " local session file(s)." + (limited ? " Session coverage was partial." : ""));
163
+ }
164
+ if (demo) {
165
+ lines.push("", "Sample computer history (newest first)", ...review.history.events.slice().reverse().map(historyLine));
166
+ } else {
167
+ if (review.history?.incomplete) lines.push(earlierBuildNote);
168
+ lines.push("Run --history to see changes, approvals and accepted risks on this computer.");
169
+ const unknown = [...review.changes, ...review.pending].find((row) => row.observationId && !row.editor);
170
+ if (unknown) lines.push("Use --attribute to check local tool records. If you made this edit, use --i-edited " + unknown.observationId + ".");
171
+ }
172
+ return lines;
173
+ }