debabble 0.0.0 → 0.1.1
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/LICENSE +21 -0
- package/README.md +187 -2
- package/bin/debabble.mjs +35 -0
- package/package.json +27 -3
- package/src/cli.mjs +211 -0
- package/src/default-wrap.json +8 -0
- package/src/hook.mjs +469 -0
- package/src/index.mjs +8 -0
- package/src/list.mjs +163 -0
- package/src/logs.mjs +138 -0
- package/src/redact.mjs +88 -0
- package/src/run.mjs +96 -0
- package/src/scan.mjs +207 -0
package/src/hook.mjs
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
// The Claude Code hook: rewrites a noisy Bash call on the wrap list to `debabble [--show excerpt] -- <original>`, and leaves every other call alone.
|
|
2
|
+
// In the app: bin/debabble.mjs runs `hookMain` for `debabble hook claude [--list <file>]`; Claude Code runs that as a PreToolUse hook on `Bash`.
|
|
3
|
+
// Run: Claude Code pipes the hook JSON on stdin; settings entry: `{"type":"command","command":"debabble hook claude","timeout":5}` under PreToolUse, matcher `Bash`.
|
|
4
|
+
// When: every Bash call in a project that wires it.
|
|
5
|
+
// Env: DEBABBLE=off (no rewrite); CLAUDE_PROJECT_DIR (where project settings are read; else the hook JSON's `cwd`); HOME; CLAUDE_CONFIG_DIR (the user
|
|
6
|
+
// settings folder, else ~/.claude); PATH (where `debabble` is looked up); any RULE_ENV variable set (no rewrite).
|
|
7
|
+
// Writes: nothing but stdout: either nothing (no rewrite) or one JSON line with `updatedInput`. Never a `permissionDecision`.
|
|
8
|
+
// Exit: 0 always (a usage error prints one line on stderr). Any other error prints nothing, so Claude Code runs the original command (costs tokens, never safety).
|
|
9
|
+
// Used by: bin/debabble.mjs; tested by test/hook.test.mjs.
|
|
10
|
+
// Uses: node builtins only; src/list.mjs (the shipped default under the user file) when no `--list` is given; `ps` (not on Linux) to read the argv of the processes above the hook,
|
|
11
|
+
// up to the nearest `claude` (CLAUDE_HOST).
|
|
12
|
+
// Exports: readLine(line), wordPrefix(words, match), matchRule(pattern, line, mode), decide(line, list, env, facts), processInfo(pid), claudeHost(args),
|
|
13
|
+
// flaggedAncestor(start, stop, info, { atHost }), blindSpot(env, configDir, system), ancestorBlindSpot(system, stop, env), gatherFacts(input, env, system), hookOutput(input, command),
|
|
14
|
+
// hookMain(argv, { stdin, env, system, stopPid }) (system and stopPid: tests only).
|
|
15
|
+
//
|
|
16
|
+
// A rewrite needs every one of these (anything else, or any doubt: no rewrite):
|
|
17
|
+
// - the line is one simple command: no `;` `&&` `||` `|` `&`, redirection, subshell, heredoc, `$(…)` or backticks, newline, comment, or leading `VAR=x`,
|
|
18
|
+
// and it starts with a program, not a shell builtin or keyword (`cd`, `time`, `export`, `source`, `exec`, …);
|
|
19
|
+
// - its words start with a list entry's `match` words, and it is not already a debabble line;
|
|
20
|
+
// - DEBABBLE is not `off`; the call is not `run_in_background`;
|
|
21
|
+
// - `debabble` is on PATH (version from its package.json, else `--version`), at or past its pin in the list's `requires` (a missing pin counts as not met);
|
|
22
|
+
// - an allow rule in the user or project settings matches the rewritten line (the mirror), and no deny or ask rule matches either line;
|
|
23
|
+
// - every place Claude Code may take a deny or ask rule from is one the hook reads (blindSpot, ancestorBlindSpot): Claude Code checks its rules against the rewritten
|
|
24
|
+
// line only, so a deny the hook cannot see (`Bash(git push:*)` in an MDM profile or `--settings`) would not match `debabble -- git push …`.
|
|
25
|
+
// The rewrite is the prefix plus the exact original bytes, so the line any other PreToolUse hook judged is the line that runs inside the wrapper.
|
|
26
|
+
|
|
27
|
+
import { execFileSync } from "node:child_process";
|
|
28
|
+
import { readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
29
|
+
import { homedir, userInfo } from "node:os";
|
|
30
|
+
import { delimiter, dirname, join, resolve } from "node:path";
|
|
31
|
+
import { NOT_PROGRAMS, readLayered } from "./list.mjs";
|
|
32
|
+
|
|
33
|
+
export { NOT_PROGRAMS };
|
|
34
|
+
|
|
35
|
+
// The program whose version gates a rewrite, and its npm package (to find its package.json from the bin on PATH).
|
|
36
|
+
export const REQUIRED = { debabble: "debabble" };
|
|
37
|
+
const PACKAGE_DEPTH = 6;
|
|
38
|
+
// The fallback `<bin> --version` (only when no package.json is found, as behind a pnpm, Volta or asdf shim) gives up after this long: no version, no rewrite.
|
|
39
|
+
const VERSION_TIMEOUT_MS = 1000;
|
|
40
|
+
const USAGE = "usage: debabble hook claude [--list <file>]";
|
|
41
|
+
// Where Claude Code reads managed settings files (`managed-settings.json` and `managed-settings.d/*.json`), per platform. Elsewhere (Windows,
|
|
42
|
+
// whose policy also sits in the registry): no rewrite.
|
|
43
|
+
const MANAGED_DIRS = { darwin: "/Library/Application Support/ClaudeCode", linux: "/etc/claude-code" };
|
|
44
|
+
// A macOS MDM profile for Claude Code, machine-wide or per user. A plist needs a process to read, so one existing is enough for no rewrite.
|
|
45
|
+
const MDM_DOMAIN = "com.anthropic.claudecode.plist";
|
|
46
|
+
// Flags on a process the walk reads (the hook's ancestors up to the `claude` that runs it; all of them when none is recognized) that bring rules or a judge the hook cannot read,
|
|
47
|
+
// from `claude --help` and the flags claude 2.1.285 parses (hidden ones included). Any of them, alone or as `--flag=value`: no rewrite.
|
|
48
|
+
// - settings: `--settings`; `--managed-settings` (hidden; policy-tier settings from an SDK host); `--client-data-url` (a signed configuration
|
|
49
|
+
// document); `--project-config-root` (project settings read from another folder than the one the hook reads).
|
|
50
|
+
// - tool lists: `--allowedTools`, `--disallowedTools` (either spelling) and `--tools`, which Claude Code groups with them.
|
|
51
|
+
// - agents and plugins: `--agents`, `--agent`, `--plugin-dir`, `--plugin-dir-no-mcp`, `--plugin-url` bring definitions the hook doesn't read,
|
|
52
|
+
// and an agent definition carries its own tool denies.
|
|
53
|
+
// - a judge of the rewritten line: `--input-format` (an SDK host, which can also pass settings on stdin), `--permission-prompt-tool`, `--permission-prompts`.
|
|
54
|
+
// - a background session: `--bg`, `--background`, and the workers that run it (`--daemon-worker`, `--bg-spare`, `--bg-pty-host`), which take
|
|
55
|
+
// the session's flags over a socket, not argv.
|
|
56
|
+
// Not rule flags: `--setting-sources` (only narrows what is read), `--permission-mode` (a deny rule holds in every mode), `--restricted` (drops
|
|
57
|
+
// the user, project and local files, keeps managed settings and `--settings`), `--add-dir` (2.1.285 reads no settings file from an added folder).
|
|
58
|
+
const RULE_FLAG_NAMES = [
|
|
59
|
+
"settings", "managed-settings", "client-data-url", "project-config-root",
|
|
60
|
+
"allowedTools", "allowed-tools", "disallowedTools", "disallowed-tools", "tools",
|
|
61
|
+
"agents", "agent", "plugin-dir", "plugin-dir-no-mcp", "plugin-url",
|
|
62
|
+
"input-format", "permission-prompt-tool", "permission-prompts",
|
|
63
|
+
"bg", "background", "daemon-worker", "bg-spare", "bg-pty-host",
|
|
64
|
+
];
|
|
65
|
+
const RULE_FLAGS = new RegExp(`(?:^|\\s)--(?:${RULE_FLAG_NAMES.join("|")})(?=[=\\s]|$)`);
|
|
66
|
+
// Variables in the hook's env (it inherits claude's) that point Claude Code at settings the hook doesn't read: a managed settings path, a
|
|
67
|
+
// server-managed settings file or mock, a signed configuration document, settings handed down by a bridge host, plugin folders (as
|
|
68
|
+
// `--plugin-dir`). Any of them set: no rewrite.
|
|
69
|
+
const RULE_ENV = [
|
|
70
|
+
"CLAUDE_CODE_MANAGED_SETTINGS_PATH", "CLAUDE_CODE_REMOTE_SETTINGS_PATH", "CLAUDE_CODE_MOCK_REMOTE_SETTINGS", "CLAUDE_CODE_CLIENT_DATA_URL",
|
|
71
|
+
"CLAUDE_CODE_BRIDGE_CHILD_MACHINE_SETTINGS", "CLAUDE_CODE_PLUGIN_DIRS",
|
|
72
|
+
];
|
|
73
|
+
// The ancestor walk gives up (no rewrite) past this many processes, and each `ps` after this long.
|
|
74
|
+
const MAX_ANCESTORS = 64;
|
|
75
|
+
// The `claude` host process, by its argv as `ps -o args=` (or /proc cmdline) joins it: the walk stops there, since its flags govern this
|
|
76
|
+
// session's tool calls and what sits above it (a parent claude, an IDE, a shell, a desktop app) does not. Observed on macOS, 2026-11-23:
|
|
77
|
+
// claude 2.1.285 from a terminal runs a hook's shell as its direct child, argv0 as typed (`/opt/homebrew/bin/claude -p …`, or bare `claude`);
|
|
78
|
+
// the desktop app runs `<…>/Application Support/Claude/claude-code/<version>/<id>/claude.app/Contents/MacOS/claude <flags>` (2.1.326) under
|
|
79
|
+
// `disclaimer --pgroup -- <that path> <flags>`, which the strict patterns below don't take for claude. Each pattern reads argv0 with no
|
|
80
|
+
// space in it (the desktop path's one `Application Support` aside), so an argument that merely names claude never matches. An npm install
|
|
81
|
+
// run through its bin link (`node /usr/local/bin/claude`) is not recognized: the walk then goes to the top, as before.
|
|
82
|
+
const CLAUDE_HOST = [
|
|
83
|
+
/^(?:[^ ]*\/)?claude(?: |$)/,
|
|
84
|
+
/^\/[^ ]*(?:\/Application Support\/[^ ]*)?\/claude\.app\/Contents\/MacOS\/claude(?: |$)/,
|
|
85
|
+
/^(?:[^ ]*\/)?(?:node|bun) (?:[^ ]*\/)?node_modules\/@anthropic-ai\/claude-code\/(?:cli\.js|bin\/claude)(?: |$)/,
|
|
86
|
+
];
|
|
87
|
+
// A background session (`claude --bg`). Measured 2026-11-23, claude 2.1.285, a real `claude --bg --settings <deny>` session: the session's host
|
|
88
|
+
// argv carries `--bg-spare` and the pty host's carries `--bg-pty-host`, both rule flags, so the walk finds them and the hook skips the rewrite.
|
|
89
|
+
// claude strips CLAUDE_CODE_SESSION_KIND, CLAUDE_BG_BACKEND, CLAUDE_BG_SOURCE and CLAUDE_BG_SESSION_PERMISSION_RULES from the env it gives hooks;
|
|
90
|
+
// CLAUDE_JOB_DIR is the one that survives. Set, the walk ignores the claude host and goes to the top.
|
|
91
|
+
const BACKGROUND_ENV = ["CLAUDE_JOB_DIR"];
|
|
92
|
+
const PS_TIMEOUT_MS = 1000;
|
|
93
|
+
|
|
94
|
+
// Reads a shell line as one simple command: its words, unquoted, or null when it is anything else (or when in doubt).
|
|
95
|
+
export const readLine = (line) => {
|
|
96
|
+
// A newline anywhere (two commands, a continuation, a quoted multi-line argument) is doubt enough.
|
|
97
|
+
// So are other line or paragraph separators and control characters (tab aside): what a reader shows as one line must be one line.
|
|
98
|
+
if (typeof line !== "string" || /[\n\r\u0085\u2028\u2029\u0000-\u0008\u000b-\u001f\u007f]/.test(line)) return null;
|
|
99
|
+
const words = [];
|
|
100
|
+
const raw = [];
|
|
101
|
+
let word = null; // the unquoted text of the word being read; null between words
|
|
102
|
+
let start = 0;
|
|
103
|
+
const begin = (at) => {
|
|
104
|
+
if (word === null) {
|
|
105
|
+
word = "";
|
|
106
|
+
start = at;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
for (let i = 0; i < line.length; i += 1) {
|
|
110
|
+
const ch = line[i];
|
|
111
|
+
if (ch === " " || ch === "\t") {
|
|
112
|
+
if (word !== null) {
|
|
113
|
+
words.push(word);
|
|
114
|
+
raw.push(line.slice(start, i));
|
|
115
|
+
word = null;
|
|
116
|
+
}
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (";&|<>()`\n\r".includes(ch)) return null;
|
|
120
|
+
if (ch === "#" && word === null) return null;
|
|
121
|
+
if (ch === "$" && line[i + 1] === "(") return null;
|
|
122
|
+
begin(i);
|
|
123
|
+
if (ch === "\\") {
|
|
124
|
+
if (i + 1 >= line.length) return null;
|
|
125
|
+
word += line[(i += 1)];
|
|
126
|
+
} else if (ch === "'") {
|
|
127
|
+
const end = line.indexOf("'", i + 1);
|
|
128
|
+
if (end === -1) return null;
|
|
129
|
+
word += line.slice(i + 1, end);
|
|
130
|
+
i = end;
|
|
131
|
+
} else if (ch === '"') {
|
|
132
|
+
let j = i + 1;
|
|
133
|
+
for (; j < line.length && line[j] !== '"'; j += 1) {
|
|
134
|
+
const c = line[j];
|
|
135
|
+
if (c === "`" || (c === "$" && line[j + 1] === "(")) return null;
|
|
136
|
+
if (c === "\\") {
|
|
137
|
+
if (j + 1 >= line.length) return null;
|
|
138
|
+
j += 1;
|
|
139
|
+
word += '$`"\\\n'.includes(line[j]) ? line[j] : `\\${line[j]}`;
|
|
140
|
+
} else word += c;
|
|
141
|
+
}
|
|
142
|
+
if (j >= line.length) return null;
|
|
143
|
+
i = j;
|
|
144
|
+
} else word += ch;
|
|
145
|
+
}
|
|
146
|
+
if (word !== null) {
|
|
147
|
+
words.push(word);
|
|
148
|
+
raw.push(line.slice(start));
|
|
149
|
+
}
|
|
150
|
+
if (words.length === 0) return null;
|
|
151
|
+
// A leading assignment would be run by debabble as a program name (no shell), so the line is not one it can wrap.
|
|
152
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(raw[0])) return null;
|
|
153
|
+
return words;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// Whether `words` start with the words of `match` (`pnpm test` matches `pnpm test --run x`, not `pnpm testx`).
|
|
157
|
+
export const wordPrefix = (words, match) => {
|
|
158
|
+
const want = match.trim().split(/\s+/);
|
|
159
|
+
return want.length > 0 && want[0] !== "" && want.length <= words.length && want.every((w, i) => words[i] === w);
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
// Whether a permission rule's content (the text inside `Bash(…)`) matches a command line.
|
|
163
|
+
// mode "strict" (for allow: a false match would send a line the rules then deny) or "loose" (for deny and ask: a false match only skips a rewrite).
|
|
164
|
+
export const matchRule = (pattern, line, mode) => {
|
|
165
|
+
if (pattern.endsWith(":*")) {
|
|
166
|
+
const prefix = pattern.slice(0, -2);
|
|
167
|
+
return mode === "strict" ? line === prefix || line.startsWith(`${prefix} `) : line.startsWith(prefix);
|
|
168
|
+
}
|
|
169
|
+
if (!pattern.includes("*")) return line === pattern;
|
|
170
|
+
let source = pattern
|
|
171
|
+
.split("*")
|
|
172
|
+
.map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
|
|
173
|
+
.join(".*");
|
|
174
|
+
// `Bash(ls *)` may also match a bare `ls`; count that only where a false match is harmless.
|
|
175
|
+
if (mode === "loose") source = source.replace(/ \.\*$/, "(?: .*)?");
|
|
176
|
+
return new RegExp(`^${source}$`, "s").test(line);
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
// Compares dotted versions with an optional prerelease (`1.2.3-pre.1` < `1.2.3`): negative, zero, or positive; NaN when either is not a version.
|
|
180
|
+
const VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
181
|
+
export const compareVersions = (a, b) => {
|
|
182
|
+
const [x, y] = [VERSION.exec(String(a ?? "")), VERSION.exec(String(b ?? ""))];
|
|
183
|
+
if (!x || !y) return Number.NaN;
|
|
184
|
+
for (let i = 1; i <= 3; i += 1) if (Number(x[i]) !== Number(y[i])) return Number(x[i]) - Number(y[i]);
|
|
185
|
+
if (!x[4] || !y[4]) return (x[4] ? -1 : 0) - (y[4] ? -1 : 0);
|
|
186
|
+
const [p, q] = [x[4].split("."), y[4].split(".")];
|
|
187
|
+
for (let i = 0; i < Math.max(p.length, q.length); i += 1) {
|
|
188
|
+
if (p[i] === undefined || q[i] === undefined) return p[i] === undefined ? -1 : 1;
|
|
189
|
+
const [n, m] = [/^\d+$/.test(p[i]), /^\d+$/.test(q[i])];
|
|
190
|
+
if (n && m && Number(p[i]) !== Number(q[i])) return Number(p[i]) - Number(q[i]);
|
|
191
|
+
if (n !== m) return n ? -1 : 1;
|
|
192
|
+
if (p[i] !== q[i]) return p[i] < q[i] ? -1 : 1;
|
|
193
|
+
}
|
|
194
|
+
return 0;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const isDebabble = (word) => word === "debabble" || word.endsWith("/debabble");
|
|
198
|
+
|
|
199
|
+
// The pure core: the rewritten command, or null for no rewrite.
|
|
200
|
+
// facts: { background, versions: { debabble }, rules: { allow, deny, ask } (rule contents of `Bash(…)` entries), blind (a reason, or null) }.
|
|
201
|
+
export const decide = (line, list, env, facts) => {
|
|
202
|
+
if (env.DEBABBLE === "off" || facts.background !== false || facts.blind !== null) return null;
|
|
203
|
+
const words = readLine(line);
|
|
204
|
+
if (!words || isDebabble(words[0]) || NOT_PROGRAMS.has(words[0])) return null;
|
|
205
|
+
const entry = (list?.wrap ?? []).find((e) => typeof e?.match === "string" && e.enabled !== false && wordPrefix(words, e.match));
|
|
206
|
+
if (!entry) return null;
|
|
207
|
+
for (const bin of Object.keys(REQUIRED)) if (!(compareVersions(facts.versions?.[bin], list.requires?.[bin]) >= 0)) return null;
|
|
208
|
+
const command = `debabble ${entry.show === "excerpt" ? "--show excerpt " : ""}-- ${line}`;
|
|
209
|
+
const { allow = [], deny = [], ask = [] } = facts.rules ?? {};
|
|
210
|
+
// A deny or ask rule on either line keeps the original, so Claude Code judges it as written (an allow on the rewrite must never outrank a deny on the original).
|
|
211
|
+
// The original is matched as written and as its words joined by one space, so a respelling (`ssh 'prod' x`) cannot slip past `Bash(ssh prod:*)`.
|
|
212
|
+
const spellings = [command, line, line.trim(), words.join(" ")];
|
|
213
|
+
if ([...deny, ...ask].some((p) => spellings.some((text) => matchRule(p, text, "loose")))) return null;
|
|
214
|
+
return allow.some((p) => matchRule(p, command, "strict")) ? command : null;
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const readJson = (path) => {
|
|
218
|
+
try {
|
|
219
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
220
|
+
} catch {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// The version of the package that owns `bin` on PATH, read from its package.json (no process started), or null.
|
|
226
|
+
const versionOnPath = (bin, pkgName, env) => {
|
|
227
|
+
for (const dir of (env.PATH ?? "").split(delimiter)) {
|
|
228
|
+
if (!dir) continue;
|
|
229
|
+
const candidate = join(dir, bin);
|
|
230
|
+
try {
|
|
231
|
+
if (!statSync(candidate).isFile()) continue;
|
|
232
|
+
let at = dirname(realpathSync(candidate));
|
|
233
|
+
for (let i = 0; i < PACKAGE_DEPTH; i += 1) {
|
|
234
|
+
const pkg = readJson(join(at, "package.json"));
|
|
235
|
+
if (pkg?.name === pkgName) return typeof pkg.version === "string" ? pkg.version : null;
|
|
236
|
+
at = dirname(at);
|
|
237
|
+
}
|
|
238
|
+
return versionFromRun(candidate);
|
|
239
|
+
} catch {}
|
|
240
|
+
}
|
|
241
|
+
return null;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
// `<path> --version`, first line, when it is a version; null on anything else (a timeout included).
|
|
245
|
+
const versionFromRun = (path) => {
|
|
246
|
+
try {
|
|
247
|
+
const out = execFileSync(path, ["--version"], { encoding: "utf8", timeout: VERSION_TIMEOUT_MS, stdio: ["ignore", "pipe", "ignore"] });
|
|
248
|
+
const first = out.trim().split("\n")[0].trim().replace(/^v/, "");
|
|
249
|
+
return Number.isNaN(compareVersions(first, "0.0.0")) ? null : first;
|
|
250
|
+
} catch {
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
// A settings file as Claude Code reads it: null when it is not there, else its JSON object, a leading UTF-8 BOM dropped (Claude Code drops
|
|
256
|
+
// it and applies the rules). Throws when the file exists but can't be read, isn't JSON or isn't an object, so the caller skips the rewrite.
|
|
257
|
+
// Claude Code 2.1.285 ignores a file with comments or trailing commas, so "no rules" would also be safe there; skipping is safe either way.
|
|
258
|
+
const readSettings = (path) => {
|
|
259
|
+
let text;
|
|
260
|
+
try {
|
|
261
|
+
text = readFileSync(path, "utf8");
|
|
262
|
+
} catch (error) {
|
|
263
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
|
|
264
|
+
throw error;
|
|
265
|
+
}
|
|
266
|
+
const json = JSON.parse(text.replace(/^\uFEFF/, ""));
|
|
267
|
+
if (json === null || typeof json !== "object" || Array.isArray(json)) throw new Error(`${path} is not a settings object`);
|
|
268
|
+
return json;
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
// `Bash(…)` rule contents from the settings files, by kind; throws (readSettings) when one exists but can't be read.
|
|
272
|
+
const bashRules = (files) => {
|
|
273
|
+
const rules = { allow: [], deny: [], ask: [] };
|
|
274
|
+
for (const file of files) {
|
|
275
|
+
const perms = readSettings(file)?.permissions;
|
|
276
|
+
for (const kind of Object.keys(rules)) {
|
|
277
|
+
for (const rule of Array.isArray(perms?.[kind]) ? perms[kind] : []) {
|
|
278
|
+
const m = typeof rule === "string" ? /^Bash\((.*)\)$/s.exec(rule.trim()) : null;
|
|
279
|
+
if (m) rules[kind].push(m[1]);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return rules;
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
// Whether `path` exists: false only when it is not there; any other failure (no permission) throws, so the caller treats it as unread.
|
|
287
|
+
const present = (path) => {
|
|
288
|
+
try {
|
|
289
|
+
statSync(path);
|
|
290
|
+
return true;
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR") return false;
|
|
293
|
+
throw error;
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
// One process: { ppid, args } (args joined by spaces), or null. Linux reads /proc (no process started); elsewhere one `ps` per process.
|
|
298
|
+
export const processInfo = (pid) => {
|
|
299
|
+
try {
|
|
300
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
301
|
+
// `pid (comm) state ppid …`; comm may hold spaces and parentheses, so read from the last `)`.
|
|
302
|
+
return { ppid: Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]), args: readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").join(" ") };
|
|
303
|
+
} catch {}
|
|
304
|
+
try {
|
|
305
|
+
const out = execFileSync("ps", ["-ww", "-o", "ppid=,args=", "-p", String(pid)], { encoding: "utf8", timeout: PS_TIMEOUT_MS, stdio: ["ignore", "pipe", "ignore"] });
|
|
306
|
+
const match = /^\s*(\d+)\s?([\s\S]*)$/.exec(out);
|
|
307
|
+
return match ? { ppid: Number(match[1]), args: match[2] } : null;
|
|
308
|
+
} catch {
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
// Whether a process's args (argv joined by spaces) are the `claude` host's (CLAUDE_HOST).
|
|
314
|
+
export const claudeHost = (args) => CLAUDE_HOST.some((pattern) => pattern.test(args));
|
|
315
|
+
|
|
316
|
+
// Why a process from `start` up to the nearest claude host (CLAUDE_HOST; to pid 1 when none is recognized, or `atHost` is false; stopping
|
|
317
|
+
// before `stop`) may hold rules the hook cannot read: a RULE_FLAGS flag on it, or a walk that could not finish (a process that cannot be
|
|
318
|
+
// read, a loop, too many). Null when every one was read and none has such a flag. The host's own flags count; a claude inside a claude
|
|
319
|
+
// (`claude -p` from a session's Bash) is the nearest, so its flags govern and the outer one's are not read.
|
|
320
|
+
// `info(pid)` → { ppid, args } or null.
|
|
321
|
+
export const flaggedAncestor = (start, stop, info, { atHost = true } = {}) => {
|
|
322
|
+
const seen = new Set();
|
|
323
|
+
for (let pid = start; pid >= 1 && pid !== stop; ) {
|
|
324
|
+
if (seen.has(pid) || seen.size >= MAX_ANCESTORS) return "the process tree above the hook could not be walked";
|
|
325
|
+
seen.add(pid);
|
|
326
|
+
const proc = info(pid);
|
|
327
|
+
if (!proc || !Number.isInteger(proc.ppid) || typeof proc.args !== "string") return `process ${pid} could not be read`;
|
|
328
|
+
if (RULE_FLAGS.test(proc.args)) return `process ${pid} was started with a rule flag`;
|
|
329
|
+
if (pid === 1 || (atHost && claudeHost(proc.args))) break;
|
|
330
|
+
pid = proc.ppid;
|
|
331
|
+
}
|
|
332
|
+
return null;
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
// The managed settings files Claude Code reads in `dir`, in its order; throws when one can't be listed.
|
|
336
|
+
const managedDocs = (dir) => {
|
|
337
|
+
const docs = present(join(dir, "managed-settings.json")) ? [join(dir, "managed-settings.json")] : [];
|
|
338
|
+
const dropIns = join(dir, "managed-settings.d");
|
|
339
|
+
if (present(dropIns)) for (const name of readdirSync(dropIns).toSorted()) if (name.endsWith(".json")) docs.push(join(dropIns, name));
|
|
340
|
+
return docs;
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
// The machine as gatherFacts() reads it; tests pass their own.
|
|
344
|
+
const SYSTEM = {
|
|
345
|
+
platform: process.platform,
|
|
346
|
+
managedDir: MANAGED_DIRS[process.platform],
|
|
347
|
+
mdmProfiles: () => (process.platform === "darwin" ? [join("/Library/Managed Preferences", MDM_DOMAIN), join("/Library/Managed Preferences", userInfo().username, MDM_DOMAIN)] : []),
|
|
348
|
+
// WSL can take the Windows policy (registry or a file on the Windows side), which the hook can't read.
|
|
349
|
+
wsl: () => process.platform === "linux" && /microsoft/i.test(readFileSync("/proc/version", "utf8")),
|
|
350
|
+
ppid: process.ppid,
|
|
351
|
+
processInfo,
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
// Why this hook call may not see every deny or ask rule Claude Code applies, or null; file checks only (ancestorBlindSpot walks the processes).
|
|
355
|
+
// Seen sources (read by gatherFacts): the user, project and project-local files and the managed settings files. Unseen ones: an MDM profile,
|
|
356
|
+
// a managed file that can't be read or that runs a policy helper (`policyHelper`, or `policyHelpers`: per-platform helpers and a default),
|
|
357
|
+
// server-managed settings (their cache file exists), WSL's Windows policy, and settings named by a RULE_ENV variable.
|
|
358
|
+
export const blindSpot = (env, configDir, system = SYSTEM) => {
|
|
359
|
+
try {
|
|
360
|
+
const variable = RULE_ENV.find((name) => (env[name] ?? "") !== "");
|
|
361
|
+
if (variable) return `${variable} is set`;
|
|
362
|
+
if (!system.managedDir) return `managed settings on ${system.platform} are not read`;
|
|
363
|
+
if (system.wsl()) return "WSL can take the Windows policy";
|
|
364
|
+
const profile = system.mdmProfiles().find(present);
|
|
365
|
+
if (profile) return `MDM profile ${profile}`;
|
|
366
|
+
for (const doc of managedDocs(system.managedDir)) {
|
|
367
|
+
let json;
|
|
368
|
+
try {
|
|
369
|
+
json = readSettings(doc);
|
|
370
|
+
} catch {
|
|
371
|
+
return `${doc} could not be read`;
|
|
372
|
+
}
|
|
373
|
+
if (json === null) return `${doc} could not be read`;
|
|
374
|
+
if ("policyHelper" in json || "policyHelpers" in json) return `${doc} names a policy helper`;
|
|
375
|
+
}
|
|
376
|
+
if (present(join(configDir, "remote-settings.json"))) return "server-managed settings";
|
|
377
|
+
return null;
|
|
378
|
+
} catch (error) {
|
|
379
|
+
return `a settings source could not be read (${error.code ?? error.name})`;
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
// Why the processes above the hook may hold rules it cannot read (RULE_FLAGS on one, or a walk that could not finish), or null; never throws.
|
|
384
|
+
// Run only for a line that would otherwise be rewritten: on macOS it costs one `ps` per ancestor (about 1.3 ms each on an Apple silicon Mac),
|
|
385
|
+
// up to the claude host (usually the hook's parent or grandparent). One `ps -A` listing instead measured slower there: 11 ms without args,
|
|
386
|
+
// 26 ms with them (843 processes), so the walk stays per process. `env`: the hook's (claude's); a BACKGROUND_ENV variable set walks to the top.
|
|
387
|
+
// `stop` (tests only): the walk ends before this pid.
|
|
388
|
+
export const ancestorBlindSpot = (system = SYSTEM, stop = 0, env = process.env) => {
|
|
389
|
+
try {
|
|
390
|
+
const atHost = !BACKGROUND_ENV.some((name) => (env[name] ?? "") !== "");
|
|
391
|
+
return flaggedAncestor(system.ppid, stop, system.processInfo, { atHost });
|
|
392
|
+
} catch (error) {
|
|
393
|
+
return `the processes above the hook could not be read (${error.code ?? error.name})`;
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
// The folders whose `.claude/settings.local.json` Claude Code may read: the project folder (older versions), the repo root (2.1.211 on), and
|
|
398
|
+
// for a worktree the main checkout's root. Reading one Claude Code skips only adds rules, and extra deny rules only skip a rewrite.
|
|
399
|
+
const localRoots = (project) => {
|
|
400
|
+
const roots = [project];
|
|
401
|
+
for (let dir = resolve(project); ; dir = dirname(dir)) {
|
|
402
|
+
const git = join(dir, ".git");
|
|
403
|
+
if (present(git)) {
|
|
404
|
+
roots.push(dir);
|
|
405
|
+
const gitdir = statSync(git).isFile() ? /^gitdir: (.+)$/m.exec(readFileSync(git, "utf8"))?.[1]?.trim() : undefined;
|
|
406
|
+
if (gitdir) {
|
|
407
|
+
const own = resolve(dir, gitdir);
|
|
408
|
+
let common = own;
|
|
409
|
+
try {
|
|
410
|
+
common = resolve(own, readFileSync(join(own, "commondir"), "utf8").trim());
|
|
411
|
+
} catch {}
|
|
412
|
+
roots.push(dirname(common));
|
|
413
|
+
}
|
|
414
|
+
return roots;
|
|
415
|
+
}
|
|
416
|
+
if (dirname(dir) === dir) return roots;
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
// The I/O edge: what decide() needs from the machine for this hook call, the ancestor walk aside (hookMain runs it last). Any failure
|
|
421
|
+
// reading a rule source (a settings file that exists but can't be read or parsed included) is a blind spot (no rewrite).
|
|
422
|
+
// Project settings: `settings.json` from the project folder only (claude 2.1.285 started in a repo's subfolder reads the subfolder's, not the
|
|
423
|
+
// root's, and passes the subfolder as CLAUDE_PROJECT_DIR); `settings.local.json` also from the roots localRoots() names.
|
|
424
|
+
export const gatherFacts = (input, env, system = SYSTEM) => {
|
|
425
|
+
const project = env.CLAUDE_PROJECT_DIR || input.cwd || ".";
|
|
426
|
+
const configDir = env.CLAUDE_CONFIG_DIR || join(env.HOME || homedir(), ".claude");
|
|
427
|
+
let blind = blindSpot(env, configDir, system);
|
|
428
|
+
let rules = { allow: [], deny: [], ask: [] };
|
|
429
|
+
try {
|
|
430
|
+
const locals = [...new Set(localRoots(project))].map((root) => join(root, ".claude", "settings.local.json"));
|
|
431
|
+
rules = bashRules([join(configDir, "settings.json"), join(project, ".claude", "settings.json"), ...locals, ...(blind === null ? managedDocs(system.managedDir) : [])]);
|
|
432
|
+
} catch (error) {
|
|
433
|
+
blind ??= `a settings source could not be read (${error.code ?? error.name})`;
|
|
434
|
+
}
|
|
435
|
+
return {
|
|
436
|
+
// Anything but a missing or false flag counts as backgrounded (a string "true" included): on doubt, no rewrite.
|
|
437
|
+
background: !(input.tool_input?.run_in_background === undefined || input.tool_input?.run_in_background === false),
|
|
438
|
+
versions: Object.fromEntries(Object.entries(REQUIRED).map(([bin, pkg]) => [bin, versionOnPath(bin, pkg, env)])),
|
|
439
|
+
rules,
|
|
440
|
+
blind,
|
|
441
|
+
};
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
// The hook's stdout for a rewrite: every original tool_input field kept (run_in_background, timeout, description), the command replaced.
|
|
445
|
+
export const hookOutput = (input, command) =>
|
|
446
|
+
JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", updatedInput: { ...input.tool_input, command } } });
|
|
447
|
+
|
|
448
|
+
// `debabble hook claude [--list <file>]`: reads the layered wrap list (src/list.mjs) unless `--list` names one file; returns { code, stdout, stderr }. Always code 0; a usage error has one stderr line, and any failure is no output.
|
|
449
|
+
// Tests only: `system` stands in for the machine, and the ancestor walk stops before `stopPid` (the test runner's own ancestors may pass rule flags).
|
|
450
|
+
// `defaultList` stands in for the shipped default under the user file (tests only).
|
|
451
|
+
export const hookMain = (argv, { stdin, env = process.env, system = SYSTEM, stopPid = 0, defaultList } = {}) => {
|
|
452
|
+
const [agent, ...rest] = argv;
|
|
453
|
+
const listPath = rest[0] === "--list" && rest.length === 2 ? rest[1] : rest.length === 0 ? null : undefined;
|
|
454
|
+
// Exit 0 even here: a hook that exits non-zero shows Claude Code an error on every Bash call; the line on stderr is enough.
|
|
455
|
+
if (agent !== "claude" || listPath === undefined) return { code: 0, stdout: "", stderr: `debabble: ${USAGE}` };
|
|
456
|
+
try {
|
|
457
|
+
const input = JSON.parse(stdin());
|
|
458
|
+
if (input?.tool_name !== "Bash" || typeof input.tool_input?.command !== "string") return { code: 0, stdout: "", stderr: "" };
|
|
459
|
+
// No `--list`: the shipped default under the user file. A bad user file means no rewrite (the command runs unwrapped).
|
|
460
|
+
const list = listPath === null ? readLayered(env, defaultList).list : readJson(resolve(listPath));
|
|
461
|
+
if (!list || !Array.isArray(list.wrap)) return { code: 0, stdout: "", stderr: "" };
|
|
462
|
+
let command = decide(input.tool_input.command, list, env, gatherFacts(input, env, system));
|
|
463
|
+
// The walk last: a line that is not rewritten anyway starts no `ps`.
|
|
464
|
+
if (command !== null && ancestorBlindSpot(system, stopPid, env) !== null) command = null;
|
|
465
|
+
return { code: 0, stdout: command === null ? "" : hookOutput(input, command), stderr: "" };
|
|
466
|
+
} catch {
|
|
467
|
+
return { code: 0, stdout: "", stderr: "" };
|
|
468
|
+
}
|
|
469
|
+
};
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// The library entry: the pieces debabble is built from, for a project that vendors them or tests against them.
|
|
2
|
+
// In the app: `import { run, scan, excerpt } from "debabble"`; the CLI (bin/debabble.mjs) uses the same modules. Additive only after 1.0.
|
|
3
|
+
// Used by: package consumers; tested by test/index.test.mjs.
|
|
4
|
+
// Uses: src/scan.mjs, src/run.mjs.
|
|
5
|
+
// Exports: run (command → promise of its result, output to a log file), scan (log file → counts and kept lines), excerpt (scan → lines to show).
|
|
6
|
+
|
|
7
|
+
export { run } from "./run.mjs";
|
|
8
|
+
export { scanLog as scan, excerptLines as excerpt } from "./scan.mjs";
|
package/src/list.mjs
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// `debabble list`: show, add, disable and enable entries of the wrap list, so nobody hand-edits JSON; and the layered read the hook uses.
|
|
2
|
+
// In the app: bin/debabble.mjs runs `listMain` for `debabble list …`; src/hook.mjs calls `readLayered` when no `--list <file>` is given.
|
|
3
|
+
// Run: `debabble list show`, `debabble list add <match> --show verdict|excerpt`, `debabble list disable <match>`, `debabble list enable <match>`.
|
|
4
|
+
// Env: XDG_CONFIG_HOME (else $HOME/.config) holds `debabble/wrap.json`, the user file.
|
|
5
|
+
// Writes: the user file only, atomically (temp file in the same folder, then rename); file 0600, a folder it creates 0700. A malformed user file is reported and never touched.
|
|
6
|
+
// Exit: 0 done; 1 refused or not found or a bad user file; 125 usage error.
|
|
7
|
+
// Layering: the shipped default (src/default-wrap.json) with the user file over it by `match`: a user entry replaces the default entry with the same match, in place;
|
|
8
|
+
// user-only entries follow. `requires` always comes from the shipped default. There is no remove: `disable` writes `enabled: false`; absent means enabled.
|
|
9
|
+
// Exports: NOT_PROGRAMS, userListPath(env), layer(base, user), readLayered(env, base), refusal(match), listMain(argv, { env, base }).
|
|
10
|
+
// Uses: node builtins only. Imported by src/hook.mjs on every Bash call, so keep it small.
|
|
11
|
+
|
|
12
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { homedir } from "node:os";
|
|
14
|
+
import { dirname, join } from "node:path";
|
|
15
|
+
|
|
16
|
+
const DEFAULT_LIST = new URL("./default-wrap.json", import.meta.url);
|
|
17
|
+
const USAGE = "usage: debabble list show | add <match> --show verdict|excerpt | disable <match> | enable <match>";
|
|
18
|
+
|
|
19
|
+
// Shell builtins, keywords and wrappers that change how or where the rest runs. debabble execs argv with no shell, so a line (or list entry) starting with one is never wrapped.
|
|
20
|
+
export const NOT_PROGRAMS = new Set([
|
|
21
|
+
".", ":", "[[", "]]", "!", "{", "}", "alias", "bg", "bind", "break", "builtin", "caller", "case", "cd", "command", "compgen", "complete", "continue", "coproc",
|
|
22
|
+
"declare", "dirs", "disown", "do", "done", "elif", "else", "enable", "esac", "eval", "exec", "exit", "export", "fc", "fg", "fi", "for", "function", "getopts",
|
|
23
|
+
"hash", "help", "history", "if", "in", "jobs", "let", "local", "logout", "mapfile", "popd", "pushd", "read", "readarray", "readonly", "return", "select", "set",
|
|
24
|
+
"shift", "shopt", "source", "suspend", "then", "time", "times", "trap", "type", "typeset", "ulimit", "umask", "unalias", "unset", "until", "wait", "while",
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
// `$XDG_CONFIG_HOME/debabble/wrap.json`, else `$HOME/.config/debabble/wrap.json` (an empty variable counts as unset).
|
|
28
|
+
export const userListPath = (env = process.env) => join(env.XDG_CONFIG_HOME || join(env.HOME || homedir(), ".config"), "debabble", "wrap.json");
|
|
29
|
+
|
|
30
|
+
// A match is compared as its words joined by one space.
|
|
31
|
+
const norm = (match) => match.trim().split(/\s+/).join(" ");
|
|
32
|
+
|
|
33
|
+
// The shipped entries with each replaced by the user entry of the same match, then the user-only entries. `requires` is the base's.
|
|
34
|
+
export const layer = (base, user) => {
|
|
35
|
+
const mine = new Map();
|
|
36
|
+
for (const e of user?.wrap ?? []) if (typeof e?.match === "string") mine.set(norm(e.match), e);
|
|
37
|
+
const used = new Set();
|
|
38
|
+
const wrap = (base?.wrap ?? []).map((e) => {
|
|
39
|
+
const key = typeof e?.match === "string" ? norm(e.match) : null;
|
|
40
|
+
if (key === null || !mine.has(key)) return e;
|
|
41
|
+
used.add(key);
|
|
42
|
+
return mine.get(key);
|
|
43
|
+
});
|
|
44
|
+
for (const [key, e] of mine) if (!used.has(key)) wrap.push(e);
|
|
45
|
+
return { ...base, wrap };
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const readBase = (base) => base ?? JSON.parse(readFileSync(DEFAULT_LIST, "utf8"));
|
|
49
|
+
|
|
50
|
+
// Reads the user file. { user: null } when it does not exist; { error } when it can't be read or isn't `{ "wrap": [...] }`.
|
|
51
|
+
const readUser = (path) => {
|
|
52
|
+
let text;
|
|
53
|
+
try {
|
|
54
|
+
text = readFileSync(path, "utf8");
|
|
55
|
+
} catch (error) {
|
|
56
|
+
return error.code === "ENOENT" ? { user: null } : { error: `${path}: ${error.message}` };
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const user = JSON.parse(text);
|
|
60
|
+
if (user === null || typeof user !== "object" || Array.isArray(user) || !Array.isArray(user.wrap)) return { error: `${path}: not a wrap list (expected {"wrap": [...]})` };
|
|
61
|
+
return { user };
|
|
62
|
+
} catch (error) {
|
|
63
|
+
return { error: `${path}: malformed JSON (${error.message}); left untouched` };
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// The list the hook reads: shipped default under the user file. { list } or { error } (a bad user file; the hook then rewrites nothing).
|
|
68
|
+
export const readLayered = (env = process.env, base) => {
|
|
69
|
+
const { user, error } = readUser(userListPath(env));
|
|
70
|
+
return error ? { error } : { list: layer(readBase(base), user) };
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
// A reason `match` can't be added, or null. The hook wraps simple commands only.
|
|
74
|
+
export const refusal = (match) => {
|
|
75
|
+
const words = norm(match).split(" ");
|
|
76
|
+
if (words[0] === "") return "match is empty";
|
|
77
|
+
if (NOT_PROGRAMS.has(words[0])) return `"${words[0]}" is a shell builtin or keyword, not a program`;
|
|
78
|
+
const op = /;|&|\||<|>|\$\(|`|\n|\r/.exec(match);
|
|
79
|
+
return op ? `match contains a shell operator (${JSON.stringify(op[0])})` : null;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// Temp file in the same folder, then rename. The folder is made 0700 when new; the file is 0600.
|
|
83
|
+
const writeAtomic = (path, data) => {
|
|
84
|
+
const dir = dirname(path);
|
|
85
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
86
|
+
const temp = join(dir, `.wrap.json.${process.pid}.${Date.now()}.tmp`);
|
|
87
|
+
try {
|
|
88
|
+
writeFileSync(temp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
89
|
+
chmodSync(temp, 0o600);
|
|
90
|
+
renameSync(temp, path);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
rmSync(temp, { force: true });
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const out = (code, stdout = "", stderr = "") => ({ code, stdout, stderr });
|
|
98
|
+
const fail = (message) => out(1, "", `debabble: ${message}`);
|
|
99
|
+
const usage = () => out(125, "", `debabble: ${USAGE}`);
|
|
100
|
+
const pad = (text, width) => text.padEnd(width);
|
|
101
|
+
|
|
102
|
+
// `debabble list …`: returns { code, stdout, stderr }. `base` is for tests (a stand-in for the shipped default).
|
|
103
|
+
export const listMain = (argv, { env = process.env, base } = {}) => {
|
|
104
|
+
const [sub, ...rest] = argv;
|
|
105
|
+
const path = userListPath(env);
|
|
106
|
+
const baseList = readBase(base);
|
|
107
|
+
const { user, error } = readUser(path);
|
|
108
|
+
if (!["show", "add", "disable", "enable"].includes(sub)) return usage();
|
|
109
|
+
if (error) return fail(error);
|
|
110
|
+
const userWrap = user?.wrap ?? [];
|
|
111
|
+
const baseKeys = new Set((baseList.wrap ?? []).filter((e) => typeof e?.match === "string").map((e) => norm(e.match)));
|
|
112
|
+
const userKeys = new Map(userWrap.filter((e) => typeof e?.match === "string").map((e) => [norm(e.match), e]));
|
|
113
|
+
|
|
114
|
+
if (sub === "show") {
|
|
115
|
+
if (rest.length) return usage();
|
|
116
|
+
const merged = layer(baseList, user);
|
|
117
|
+
const rows = merged.wrap
|
|
118
|
+
.filter((e) => typeof e?.match === "string")
|
|
119
|
+
.map((e) => [e.match, e.show === "excerpt" ? "excerpt" : "verdict", userKeys.has(norm(e.match)) ? "user" : "default", e.enabled === false ? "disabled" : "enabled"]);
|
|
120
|
+
const width = Math.max(5, ...rows.map((r) => r[0].length));
|
|
121
|
+
const lines = [[pad("match", width), "show ", "source ", "state"].join(" "), ...rows.map((r) => [pad(r[0], width), pad(r[1], 7), pad(r[2], 7), r[3]].join(" "))];
|
|
122
|
+
return out(0, lines.join("\n"));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
let match;
|
|
126
|
+
let showMode;
|
|
127
|
+
if (sub === "add") {
|
|
128
|
+
if (rest.length !== 3 || rest[1] !== "--show" || !["verdict", "excerpt"].includes(rest[2])) return usage();
|
|
129
|
+
[match, , showMode] = rest;
|
|
130
|
+
const reason = refusal(match);
|
|
131
|
+
if (reason) return fail(`refused: ${reason}`);
|
|
132
|
+
} else {
|
|
133
|
+
if (rest.length !== 1) return usage();
|
|
134
|
+
[match] = rest;
|
|
135
|
+
}
|
|
136
|
+
const key = norm(match);
|
|
137
|
+
|
|
138
|
+
let next;
|
|
139
|
+
let message;
|
|
140
|
+
if (sub === "add") {
|
|
141
|
+
if (baseKeys.has(key) || userKeys.has(key)) return fail(`"${key}" is already on the list (use enable or disable)`);
|
|
142
|
+
next = [...userWrap, { match: key, show: showMode }];
|
|
143
|
+
message = `added ${key} (${showMode})`;
|
|
144
|
+
} else {
|
|
145
|
+
const flag = sub === "enable";
|
|
146
|
+
const own = userKeys.get(key);
|
|
147
|
+
const shipped = (baseList.wrap ?? []).find((e) => typeof e?.match === "string" && norm(e.match) === key);
|
|
148
|
+
if (!own && !shipped) return fail(`"${key}" is not on the list`);
|
|
149
|
+
const entry = { ...(own ?? shipped), match: own ? own.match : shipped.match };
|
|
150
|
+
if (flag) delete entry.enabled;
|
|
151
|
+
else entry.enabled = false;
|
|
152
|
+
// Enabling a default that has no user entry: nothing to write.
|
|
153
|
+
if (!own && flag) return out(0, `${key} already enabled`);
|
|
154
|
+
next = own ? userWrap.map((e) => (e === own ? entry : e)) : [...userWrap, entry];
|
|
155
|
+
message = `${flag ? "enabled" : "disabled"} ${key}`;
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
writeAtomic(path, { ...user, wrap: next });
|
|
159
|
+
} catch (error) {
|
|
160
|
+
return fail(`could not write ${path}: ${error.message}`);
|
|
161
|
+
}
|
|
162
|
+
return out(0, message);
|
|
163
|
+
};
|