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/logs.mjs
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Where a run's log lives: the per-repo log folder, the file name, permissions, and pruning of old logs.
|
|
2
|
+
// In the app: a library module; cli.mjs asks for a log file at the start of every run. Logs can hold secrets a command printed, so they never leave the machine.
|
|
3
|
+
// Used by: src/cli.mjs, src/index.mjs; tested by test/logs.test.mjs.
|
|
4
|
+
// Uses: node builtins only; the repo root is the nearest parent holding `.git` (falls back to the working directory).
|
|
5
|
+
// Exports: MAX_LOGS, MAX_AGE_DAYS, logBase(env, flag), repoRoot(cwd), logDirFor(cwd, env, flag), pruneLogs(dir, { now }), openLog(dir, label, { now, tmp }), slug(text).
|
|
6
|
+
//
|
|
7
|
+
// Layout: `<base>/<repo-basename>-<hash>/<YYYYMMDD-HHMMSS>-<label-slug>.log`, where <base> is `--log-dir`, else `DEBABBLE_LOG_DIR`, else
|
|
8
|
+
// `$XDG_STATE_HOME/debabble`, else `~/.local/state/debabble`. The folder is 0700 and each file 0600. Pruning runs at the start of each run:
|
|
9
|
+
// logs older than MAX_AGE_DAYS go, then the oldest past MAX_LOGS - 1 (the run about to start takes the last slot). Deleting old logs is this
|
|
10
|
+
// tool's documented retention; it only ever removes files whose names match its own pattern.
|
|
11
|
+
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
|
|
14
|
+
import { homedir, tmpdir } from "node:os";
|
|
15
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
16
|
+
|
|
17
|
+
// Most logs kept per folder, and how old a log may get, in days.
|
|
18
|
+
export const MAX_LOGS = 200;
|
|
19
|
+
export const MAX_AGE_DAYS = 7;
|
|
20
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
21
|
+
// A log written by this tool: `20261121-142201-pnpm-test.log`, with an optional `-2` counter when two runs share a second and a label.
|
|
22
|
+
const LOG_NAME = /^\d{8}-\d{6}-.+\.log$/;
|
|
23
|
+
|
|
24
|
+
// A label as a file name part: letters, digits, . _ - only; at most 60 characters so the name stays short.
|
|
25
|
+
export const slug = (text) => text.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/g, "") || "run";
|
|
26
|
+
|
|
27
|
+
// The base folder for all repos' logs.
|
|
28
|
+
export const logBase = (env = process.env, flag) => {
|
|
29
|
+
if (flag) return resolve(flag);
|
|
30
|
+
if ((env.DEBABBLE_LOG_DIR ?? "") !== "") return resolve(env.DEBABBLE_LOG_DIR);
|
|
31
|
+
const state = (env.XDG_STATE_HOME ?? "") !== "" ? env.XDG_STATE_HOME : join(homedir(), ".local", "state");
|
|
32
|
+
return join(state, "debabble");
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// The repo's top folder: the nearest parent holding `.git` (a folder, or a file for a worktree), else `cwd`. Walked in JS: a `git` process
|
|
36
|
+
// would add about 10 ms to every run.
|
|
37
|
+
export const repoRoot = (cwd) => {
|
|
38
|
+
for (let dir = resolve(cwd); ; dir = dirname(dir)) {
|
|
39
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
40
|
+
if (dirname(dir) === dir) return cwd;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
// `<base>/<repo-basename>-<4 hex of the real path's hash>`: two repos named alike get different folders.
|
|
45
|
+
export const logDirFor = (cwd, env = process.env, flag) => {
|
|
46
|
+
const root = repoRoot(cwd);
|
|
47
|
+
let real = root;
|
|
48
|
+
try {
|
|
49
|
+
real = realpathSync(root);
|
|
50
|
+
} catch {
|
|
51
|
+
// A root that vanished: hash the name as given.
|
|
52
|
+
}
|
|
53
|
+
const hash = createHash("sha256").update(real).digest("hex").slice(0, 4);
|
|
54
|
+
return join(logBase(env, flag), `${slug(basename(real)) || "root"}-${hash}`);
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// Makes the folder (0700, parents included) and refuses a symlink or a folder someone else owns: a planted link would send logs elsewhere.
|
|
58
|
+
const ensureDir = (dir) => {
|
|
59
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
60
|
+
const info = lstatSync(dir);
|
|
61
|
+
if (!info.isDirectory()) throw new Error(`${dir} is not a folder`);
|
|
62
|
+
if (typeof process.getuid === "function" && info.uid !== process.getuid()) throw new Error(`${dir} belongs to another user`);
|
|
63
|
+
// mkdir's mode is cut by the umask and skipped for a folder that already exists.
|
|
64
|
+
chmodSync(dir, 0o700);
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// Deletes this tool's logs in `dir` older than MAX_AGE_DAYS, then the oldest ones past MAX_LOGS - 1. Returns how many it removed.
|
|
68
|
+
// `now` is passed in so a test needs no clock. A folder that cannot be read or a file that cannot be removed is skipped, never an error.
|
|
69
|
+
export const pruneLogs = (dir, { now = Date.now(), maxLogs = MAX_LOGS, maxAgeDays = MAX_AGE_DAYS } = {}) => {
|
|
70
|
+
let removed = 0;
|
|
71
|
+
let logs = [];
|
|
72
|
+
try {
|
|
73
|
+
for (const name of readdirSync(dir)) {
|
|
74
|
+
if (!LOG_NAME.test(name)) continue;
|
|
75
|
+
try {
|
|
76
|
+
const info = statSync(join(dir, name));
|
|
77
|
+
if (info.isFile()) logs.push({ name, at: info.mtimeMs });
|
|
78
|
+
} catch {
|
|
79
|
+
// Gone already.
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
} catch {
|
|
83
|
+
return 0;
|
|
84
|
+
}
|
|
85
|
+
const drop = (entry) => {
|
|
86
|
+
try {
|
|
87
|
+
rmSync(join(dir, entry.name), { force: true });
|
|
88
|
+
removed += 1;
|
|
89
|
+
} catch {
|
|
90
|
+
// Read-only or busy: left for next time.
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
const [old, fresh] = [logs.filter((e) => now - e.at > maxAgeDays * DAY_MS), logs.filter((e) => now - e.at <= maxAgeDays * DAY_MS)];
|
|
94
|
+
for (const entry of old) drop(entry);
|
|
95
|
+
logs = fresh.toSorted((a, b) => a.at - b.at || (a.name < b.name ? -1 : 1));
|
|
96
|
+
for (const entry of logs.slice(0, Math.max(0, logs.length - (maxLogs - 1)))) drop(entry);
|
|
97
|
+
return removed;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const two = (n) => String(n).padStart(2, "0");
|
|
101
|
+
// `20261121-142201`, local time, so the name sorts the way a person reads the clock.
|
|
102
|
+
const stamp = (now) => {
|
|
103
|
+
const d = new Date(now);
|
|
104
|
+
return `${d.getFullYear()}${two(d.getMonth() + 1)}${two(d.getDate())}-${two(d.getHours())}${two(d.getMinutes())}${two(d.getSeconds())}`;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// Prunes, then creates a new empty log (0600, never overwriting) for `label` in `dir`. Returns { logFile, dir, fallback }.
|
|
108
|
+
// If `dir` cannot be made or written, falls back rather than fail the run (the verdict matters more than where the log sits): to one reused
|
|
109
|
+
// folder per user in `tmp`, made and pruned like any log folder, else (someone else owns it) a fresh private one. `fallback` is then
|
|
110
|
+
// { dir: the folder it could not use, error: why } for the caller to say so; otherwise null.
|
|
111
|
+
export const openLog = (dir, label, { now = Date.now(), tmp = tmpdir() } = {}) => {
|
|
112
|
+
let target = dir;
|
|
113
|
+
let fallback = null;
|
|
114
|
+
try {
|
|
115
|
+
ensureDir(dir);
|
|
116
|
+
pruneLogs(dir, { now });
|
|
117
|
+
} catch (error) {
|
|
118
|
+
fallback = { dir, error: error.code ?? error.message };
|
|
119
|
+
target = join(tmp, `debabble-${typeof process.getuid === "function" ? process.getuid() : "logs"}`);
|
|
120
|
+
try {
|
|
121
|
+
ensureDir(target);
|
|
122
|
+
pruneLogs(target, { now });
|
|
123
|
+
} catch {
|
|
124
|
+
target = mkdtempSync(join(tmp, "debabble-"));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
for (let n = 1; n < 1000; n += 1) {
|
|
128
|
+
const logFile = join(target, `${stamp(now)}-${slug(label)}${n === 1 ? "" : `-${n}`}.log`);
|
|
129
|
+
try {
|
|
130
|
+
// "wx": two runs in the same second never share a file.
|
|
131
|
+
closeSync(openSync(logFile, "wx", 0o600));
|
|
132
|
+
return { logFile, dir: target, fallback };
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (error.code !== "EEXIST") throw error;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
throw new Error(`no free log name in ${target}`);
|
|
138
|
+
};
|
package/src/redact.mjs
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Masks secret-shaped text in what debabble prints (the label, verdict line and excerpt), never in the log file.
|
|
2
|
+
// In the app: a library module; cli.mjs passes a line redactor to scanLog and runs the label and error text through redactText.
|
|
3
|
+
// Used by: src/cli.mjs, src/index.mjs; tested by test/redact.test.mjs.
|
|
4
|
+
// Uses: nothing.
|
|
5
|
+
// Exports: SHAPES (names, in the order they are tried), redactText(text), lineRedactor().
|
|
6
|
+
//
|
|
7
|
+
// Shapes (high precision only; each hit becomes `<redacted:<shape>>`):
|
|
8
|
+
// pem-private-key `-----BEGIN … PRIVATE KEY-----` through its END line (a missing END masks to the end of the text)
|
|
9
|
+
// github-token `gh[pousr]_` + 20 or more letters and digits
|
|
10
|
+
// sk-key `sk-` + 20 or more letters, digits, `-` or `_` (not inside a longer word, so `task-…` is left alone)
|
|
11
|
+
// aws-access-key `AKIA` + 16 capitals and digits
|
|
12
|
+
// slack-token `xox[abprs]-` + 10 or more letters, digits or `-`
|
|
13
|
+
// jwt `eyJ…` header, `eyJ…` payload, then the signature (may be empty)
|
|
14
|
+
// url-credentials the `user:pass` of `scheme://user:pass@host` (scheme and host stay; `$VAR`, `{…}`, `<…>` and `%s` passwords are templates, not secrets)
|
|
15
|
+
// Not masked on purpose: `secret=…`, `token: …`, `Authorization: Bearer …`, `.env`-style lines. In a 14-day scan they matched source and docs far
|
|
16
|
+
// more often than secrets.
|
|
17
|
+
//
|
|
18
|
+
// Two ways in. redactText masks a whole string (a PEM block may span lines). lineRedactor() returns a function for one line at a time, in
|
|
19
|
+
// order, that remembers whether it is inside a PEM block, so a block is masked line by line even when an excerpt shows only some of its lines.
|
|
20
|
+
|
|
21
|
+
const PEM_HEAD = String.raw`-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?)-----`;
|
|
22
|
+
const PEM_BEGIN = new RegExp(PEM_HEAD);
|
|
23
|
+
const PEM_BLOCK = new RegExp(String.raw`${PEM_HEAD}[\s\S]*?(?:-----END \1-----|$)`, "g");
|
|
24
|
+
|
|
25
|
+
// The shapes that sit on one line, as [name, pattern, replacement].
|
|
26
|
+
const LINE_SHAPES = [
|
|
27
|
+
["github-token", /(?<![A-Za-z0-9])gh[pousr]_[A-Za-z0-9]{20,}/g, "<redacted:github-token>"],
|
|
28
|
+
["sk-key", /(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{20,}/g, "<redacted:sk-key>"],
|
|
29
|
+
["aws-access-key", /(?<![A-Z0-9])AKIA[A-Z0-9]{16}(?![A-Z0-9])/g, "<redacted:aws-access-key>"],
|
|
30
|
+
["slack-token", /(?<![A-Za-z0-9])xox[abprs]-[A-Za-z0-9-]{10,}/g, "<redacted:slack-token>"],
|
|
31
|
+
["jwt", /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g, "<redacted:jwt>"],
|
|
32
|
+
["url-credentials", /(?<=\b[A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/:@'"<>]+:(?![$<{%])[^\s/@'"<>]+@/g, "<redacted:url-credentials>@"],
|
|
33
|
+
];
|
|
34
|
+
export const SHAPES = ["pem-private-key", ...LINE_SHAPES.map(([name]) => name)];
|
|
35
|
+
|
|
36
|
+
// A line with none of these can hold no shape: one scan decides, so the many lines of a long log pay for one regex, not seven.
|
|
37
|
+
const ANCHOR = /-----|gh[pousr]_|sk-|AKIA|xox[abprs]-|eyJ|:\/\//;
|
|
38
|
+
|
|
39
|
+
const PEM_MASK = "<redacted:pem-private-key>";
|
|
40
|
+
// A line that can sit inside a PEM block: base64, a `Proc-Type: 4,ENCRYPTED` style header, or a blank. Anything else (code, a sentence with
|
|
41
|
+
// quotes or brackets) ends a block that never closed.
|
|
42
|
+
const PEM_BODY = /^[A-Za-z0-9+/=:,. \t-]*$/;
|
|
43
|
+
// A key is under 100 lines (4096-bit RSA is about 52); a block that stays open longer is not one.
|
|
44
|
+
const PEM_MAX_LINES = 100;
|
|
45
|
+
|
|
46
|
+
const maskLineShapes = (text) => {
|
|
47
|
+
if (!ANCHOR.test(text)) return text;
|
|
48
|
+
let out = text;
|
|
49
|
+
for (const [, pattern, mask] of LINE_SHAPES) out = out.replace(pattern, mask);
|
|
50
|
+
return out;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// `text` with every shape masked. Idempotent: a mask matches no shape.
|
|
54
|
+
export const redactText = (text) => {
|
|
55
|
+
if (typeof text !== "string" || !ANCHOR.test(text)) return text;
|
|
56
|
+
return maskLineShapes(text.replace(PEM_BLOCK, PEM_MASK));
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// A function that masks one line at a time; call it on the lines of one output in order. Inside a PEM block every line is the mask.
|
|
60
|
+
export const lineRedactor = () => {
|
|
61
|
+
let inKey = false;
|
|
62
|
+
let left = 0;
|
|
63
|
+
return (line) => {
|
|
64
|
+
if (inKey) {
|
|
65
|
+
const end = /-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----/.exec(line);
|
|
66
|
+
if (end) {
|
|
67
|
+
inKey = false;
|
|
68
|
+
return `${PEM_MASK}${maskLineShapes(line.slice(end.index + end[0].length))}`;
|
|
69
|
+
}
|
|
70
|
+
left -= 1;
|
|
71
|
+
if (left > 0 && PEM_BODY.test(line)) return PEM_MASK;
|
|
72
|
+
inKey = false; // never closed: this line is ordinary output
|
|
73
|
+
}
|
|
74
|
+
if (!ANCHOR.test(line)) return line;
|
|
75
|
+
const begin = PEM_BEGIN.exec(line);
|
|
76
|
+
if (!begin) return maskLineShapes(line);
|
|
77
|
+
const before = maskLineShapes(line.slice(0, begin.index));
|
|
78
|
+
const rest = line.slice(begin.index);
|
|
79
|
+
const closed = new RegExp(`${PEM_HEAD}[\\s\\S]*?-----END \\1-----`).exec(rest);
|
|
80
|
+
if (closed) return `${before}${PEM_MASK}${lineRedactorTail(rest.slice(closed[0].length))}`;
|
|
81
|
+
inKey = true;
|
|
82
|
+
left = PEM_MAX_LINES;
|
|
83
|
+
return `${before}${PEM_MASK}`;
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// What follows a block's END on its line may hold a second block or another shape.
|
|
88
|
+
const lineRedactorTail = (text) => lineRedactor()(text);
|
package/src/run.mjs
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Runs one command with its whole output (stdout and stderr, in order) sent to a log file, and stops its process tree on timeout or kill.
|
|
2
|
+
// In the app: the I/O edge of the library; cli.mjs is the only caller that matters.
|
|
3
|
+
// Used by: src/cli.mjs, src/index.mjs; tested by test/run.test.mjs.
|
|
4
|
+
// Uses: node builtins only; `ps` to walk a process tree (without it, only the root is stopped).
|
|
5
|
+
// Exports: DEFAULT_TIMEOUT_MS, MAX_TIMER_MS, signalTree(root, signal), stopTree(root), run({ command, args, cwd, logFile, env, timeoutMs }).
|
|
6
|
+
//
|
|
7
|
+
// Why the child writes the file itself: stdout and stderr are the same open file, handed to the command as fd 1 and fd 2. The kernel orders
|
|
8
|
+
// the writes, so `2>&1` order is kept exactly, and nothing sits in a pipe or a buffer of ours, so a command that writes megabytes and calls
|
|
9
|
+
// `process.exit` loses nothing. A relay in between (a tee) broke both; this is the shape that doesn't.
|
|
10
|
+
//
|
|
11
|
+
// A command that outlives its limit is stopped with everything it started: on timeout the tree is frozen (SIGSTOP, walked until it stops
|
|
12
|
+
// growing) and SIGKILLed. Not a process group: a new session would take the command's controlling terminal (/dev/tty) away. No supervisor
|
|
13
|
+
// process sits between debabble and the command, so a run costs one process start, not two. Limit: a process already handed to init (its
|
|
14
|
+
// parent exited) before the timeout is out of reach.
|
|
15
|
+
|
|
16
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
17
|
+
import { closeSync, openSync } from "node:fs";
|
|
18
|
+
|
|
19
|
+
// A command that runs longer than this is killed and reported as timed out.
|
|
20
|
+
export const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
|
|
21
|
+
// The most a timer can wait: setTimeout treats a longer delay as 1 ms, which would kill every command at once.
|
|
22
|
+
export const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
23
|
+
// How many times stopTree walks the tree looking for processes started since the last walk, at most.
|
|
24
|
+
const MAX_WALKS = 200;
|
|
25
|
+
|
|
26
|
+
// The ids of `root` and everything it started, as `ps` lists them now. Without `ps` (Windows), just the root.
|
|
27
|
+
const treeOf = (root) => {
|
|
28
|
+
const listed = spawnSync("ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8" });
|
|
29
|
+
if (listed.status !== 0 || typeof listed.stdout !== "string") return [root];
|
|
30
|
+
const children = new Map();
|
|
31
|
+
for (const row of listed.stdout.split("\n")) {
|
|
32
|
+
const [pid, ppid] = row.trim().split(/\s+/).map(Number);
|
|
33
|
+
if (Number.isInteger(pid) && Number.isInteger(ppid)) children.set(ppid, [...(children.get(ppid) ?? []), pid]);
|
|
34
|
+
}
|
|
35
|
+
const found = [];
|
|
36
|
+
for (const queue = [root]; queue.length > 0; ) {
|
|
37
|
+
const pid = queue.shift();
|
|
38
|
+
found.push(pid);
|
|
39
|
+
queue.push(...(children.get(pid) ?? []));
|
|
40
|
+
}
|
|
41
|
+
return found;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const signalAll = (pids, signal) => {
|
|
45
|
+
for (const pid of pids) {
|
|
46
|
+
try {
|
|
47
|
+
process.kill(pid, signal);
|
|
48
|
+
} catch {
|
|
49
|
+
// Already gone.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// Sends `signal` to `root` and every process it started, as `ps` lists them now (the passthrough's graceful stop; stopTree follows).
|
|
55
|
+
export const signalTree = (root, signal) => signalAll(treeOf(root), signal);
|
|
56
|
+
|
|
57
|
+
// Stops `root` and every process it started that is still attached to it: SIGSTOP the tree, walk it again, and repeat until a walk finds
|
|
58
|
+
// nothing new, then SIGKILL all of it. A stopped process cannot fork, so a spawner forking every few milliseconds cannot outrun the walk
|
|
59
|
+
// (killing first would leave the children it forked between the listing and its own death). No SIGTERM first: a process that has
|
|
60
|
+
// been told to clean up would keep forking while it does.
|
|
61
|
+
export const stopTree = (root) => {
|
|
62
|
+
const seen = new Set();
|
|
63
|
+
for (let walk = 0; walk < MAX_WALKS; walk += 1) {
|
|
64
|
+
const fresh = treeOf(root).filter((pid) => !seen.has(pid));
|
|
65
|
+
if (fresh.length === 0) break;
|
|
66
|
+
signalAll(fresh, "SIGSTOP");
|
|
67
|
+
for (const pid of fresh) seen.add(pid);
|
|
68
|
+
}
|
|
69
|
+
signalAll([...seen], "SIGKILL");
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
// Runs `command args` in `cwd` with stdout and stderr both appended to `logFile` (which must exist); the command reads no input. With no
|
|
73
|
+
// `logFile`, the command shares debabble's stdin, stdout and stderr instead (the passthrough).
|
|
74
|
+
// Returns a promise of { status, signal, timedOut, error, ms }: status is the exit code (null when a signal ended it). The promise has a
|
|
75
|
+
// `child` property (the command's process), so a caller can stop the tree on a kill (stopTree(promise.child.pid)).
|
|
76
|
+
export const run = ({ command, args = [], cwd, logFile, env = process.env, timeoutMs = DEFAULT_TIMEOUT_MS }) => {
|
|
77
|
+
const fd = logFile === undefined ? null : openSync(logFile, "a");
|
|
78
|
+
const started = Date.now();
|
|
79
|
+
const child = spawn(command, args, { cwd, env, stdio: fd === null ? "inherit" : ["ignore", fd, fd] });
|
|
80
|
+
if (fd !== null) closeSync(fd);
|
|
81
|
+
let timedOut = false;
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
timedOut = true;
|
|
84
|
+
stopTree(child.pid);
|
|
85
|
+
}, Math.min(timeoutMs, MAX_TIMER_MS));
|
|
86
|
+
const done = new Promise((resolve) => {
|
|
87
|
+
const finish = (result) => {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
resolve({ timedOut, ...result, ms: Date.now() - started });
|
|
90
|
+
};
|
|
91
|
+
// A command that could not start (not found, not executable) emits `error` and never `exit`.
|
|
92
|
+
child.on("error", (error) => finish({ status: null, signal: null, error: timedOut ? undefined : error }));
|
|
93
|
+
child.on("exit", (status, signal) => finish({ status, signal }));
|
|
94
|
+
});
|
|
95
|
+
return Object.assign(done, { child });
|
|
96
|
+
};
|
package/src/scan.mjs
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// Reads a command's log in one pass and cuts the lines worth showing: failure blocks, the tail, counts of errors, warnings and progress.
|
|
2
|
+
// In the app: a library module; run.mjs's caller (cli.mjs) prints what this returns. Pure over a file path, fixed memory.
|
|
3
|
+
// Used by: src/cli.mjs, src/index.mjs; tested by test/scan.test.mjs.
|
|
4
|
+
// Uses: node builtins only.
|
|
5
|
+
// Exports: TAIL_LINES, EXCERPT_MAX_LINES, isProgressLine(line), scanLog(logFile, knobs?), excerptLines(scan).
|
|
6
|
+
//
|
|
7
|
+
// What a red run prints is cut from the file after the run is over: the lines that name a failure (each with a line before and a few after;
|
|
8
|
+
// the cap is split so the first failures and the last ones both show), then the last lines, in file order, with a marker where lines were left
|
|
9
|
+
// out. A short log prints whole. Progress lines (a test runner's dots, per-file pass lines, `ok pkg`) are never shown: PROGRESS_LINE lists
|
|
10
|
+
// every shape, and a line that names a failure is never one of them. The log is the record; the exit code is the verdict.
|
|
11
|
+
|
|
12
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
13
|
+
import { StringDecoder } from "node:string_decoder";
|
|
14
|
+
|
|
15
|
+
// The most lines an excerpt may have, markers included: 100 block + 30 tail, with a hard cut if the markers push it past.
|
|
16
|
+
export const EXCERPT_MAX_LINES = 130;
|
|
17
|
+
// A log of at most this many lines is printed whole when its command fails.
|
|
18
|
+
const FULL_LOG_LINES = 60;
|
|
19
|
+
// Around a failure-shaped line: lines kept before and after it, and the most lines all such blocks may keep.
|
|
20
|
+
const LINES_BEFORE = 1;
|
|
21
|
+
const LINES_AFTER = 5;
|
|
22
|
+
const MAX_BLOCK_LINES = 100;
|
|
23
|
+
// The last lines of a long failed log are always shown, whatever they say.
|
|
24
|
+
export const TAIL_LINES = 30;
|
|
25
|
+
// A line longer than this is cut when shown (a minified bundle, a progress bar); the log keeps it whole.
|
|
26
|
+
const LINE_CHARS = 1000;
|
|
27
|
+
|
|
28
|
+
// A line that names a failure. "0 errors" and "no failures" are blanked first, so "2 failed, 0 errors" still counts.
|
|
29
|
+
// A word that is part of a hyphenated name, path, or identifier ("quick-error", "wait-timeout", "src/error.ts") is not a failure.
|
|
30
|
+
const FAILURE_LINE = /(?<![-/])\b(error|errors|fail|failed|failure|failing|fatal|panic|exception|traceback|assertion|not ok|cannot|can't|unable|denied|refused|timed? ?out)\b(?!-|\.\w)|✗|✖|×/i;
|
|
31
|
+
// An exception or error class by name (`TypeError`, `ReferenceError`, `RuntimeError`, `ModuleNotFoundError`, `AssertionError`,
|
|
32
|
+
// `java.lang.NullPointerException`): the `\b` in FAILURE_LINE sees no word break inside a CamelCase name. Case-sensitive on purpose, so
|
|
33
|
+
// "noerror" or "errors" never match here; a name inside a hyphenated or slashed path ("src/TypeError.ts", "quick-Error") is not a failure.
|
|
34
|
+
const ERROR_NAME = /(?<![\w/-])[A-Z][A-Za-z0-9_]*(?:Error|Exception)(?![\w-]|\.\w)/;
|
|
35
|
+
// The start of a failure report, as opposed to an error-shaped line anywhere: kept in a window of its own, so a flood of generic lines
|
|
36
|
+
// after it (a stack trace, a retry log) cannot push it out.
|
|
37
|
+
const FAILURE_START = /^\s*(FAIL(ED)?\b|--- FAIL|not ok\b|✗|✖|×|Traceback|thread '.*' panicked|panic:|\w*Assertion\w*)/;
|
|
38
|
+
// A test runner's progress line: it says "still going", never what went wrong, so a failure report is better without it. One shape per
|
|
39
|
+
// common runner (measured 2026-10-29):
|
|
40
|
+
// dots node:test `--test-reporter=dot` and other dot reporters (`.` and `·`), unittest and `pytest -q` without a %:
|
|
41
|
+
// a line of nothing but those marks, starting in column 0 (an indented `...` is diff context or a report's own text, so it stays).
|
|
42
|
+
// A line with an `X`, `F` or `E` in it is NOT progress: it marks the failure.
|
|
43
|
+
// pytest `tests/test_a.py ....s. [ 40%]` and, with -q, `.... [ 40%]`: marks of pass/skip/xfail only, then the percent.
|
|
44
|
+
// file totals a passing file, `✓ tests/a (12 tests) 34ms`. (Failures print `❯` and `×`.)
|
|
45
|
+
// node:test the spec reporter's passing test, `✔ name (1.2ms)`.
|
|
46
|
+
// go test `ok \tpkg\t0.3s`, `? \tpkg\t[no test files]`; with -v also `=== RUN`, `=== PAUSE`, `=== CONT`, `--- PASS:`, `--- SKIP:`.
|
|
47
|
+
// nextest `PASS [ 0.01s] crate test`, `START`, `SLOW`, `SKIP` (shown only when the status level is raised), and cargo's `Compiling x v1`.
|
|
48
|
+
// unittest -v `test_a (mod.Class) ... ok`.
|
|
49
|
+
const PROGRESS_LINE = new RegExp(
|
|
50
|
+
[
|
|
51
|
+
String.raw`^[.·]+\s*$`,
|
|
52
|
+
String.raw`^\s*(?:\S+\.py\s+)?[.sx]+\s+\[\s*\d+%\]\s*$`,
|
|
53
|
+
String.raw`^\s*✓ \S.* \(\d+ tests?(?: [|] \d+ skipped)?\)(?: \d+ms)?\s*$`,
|
|
54
|
+
String.raw`^\s*✔ .* \([\d.]+m?s\)\s*$`,
|
|
55
|
+
String.raw`^ok\s+\S+\s+(?:[\d.]+s|\(cached\))`,
|
|
56
|
+
String.raw`^\?\s+\S+\s+\[no test files\]\s*$`,
|
|
57
|
+
String.raw`^\s*=== (?:RUN|PAUSE|CONT|NAME)\b`,
|
|
58
|
+
String.raw`^\s*--- (?:PASS|SKIP): `,
|
|
59
|
+
String.raw`^\s*(?:PASS|START|SLOW|SKIP) +\[ *[\d.]+s\]`,
|
|
60
|
+
String.raw`^\s*Compiling \S+ v\d`,
|
|
61
|
+
String.raw`^\S.* \.\.\. ok\s*$`,
|
|
62
|
+
].join("|"),
|
|
63
|
+
);
|
|
64
|
+
const NOT_A_FAILURE = /\b(0|no|zero) (errors?|failures?|failed|failing)\b|\b(errors?|failures?|failed)[:=] ?0\b/gi;
|
|
65
|
+
const WARNING_LINE = /\bwarn(ing|ings)?\b|‼|⚠/i;
|
|
66
|
+
const NOT_A_WARNING = /\b(0|no|zero) warnings?\b|\bwarnings?[:=] ?0\b/gi;
|
|
67
|
+
// Colors and cursor moves (CSI), and operating-system commands (OSC: window titles, hyperlinks), which end in BEL or ESC \.
|
|
68
|
+
const ESC = String.fromCharCode(27);
|
|
69
|
+
const ANSI = new RegExp(`${ESC}\\[[0-9;?]*[ -/]*[@-~]|${ESC}\\][^${String.fromCharCode(7)}${ESC}]*(?:${String.fromCharCode(7)}|${ESC}\\\\)`, "g");
|
|
70
|
+
|
|
71
|
+
const isFailureLine = (line) => {
|
|
72
|
+
const text = line.replaceAll(NOT_A_FAILURE, " ");
|
|
73
|
+
return FAILURE_LINE.test(text) || ERROR_NAME.test(text);
|
|
74
|
+
};
|
|
75
|
+
// Whether a line is progress (PROGRESS_LINE) and names no failure: the failure test goes first, so no pattern can hide an error.
|
|
76
|
+
export const isProgressLine = (line) => {
|
|
77
|
+
const plain = line.replace(ANSI, "");
|
|
78
|
+
return PROGRESS_LINE.test(plain) && !isFailureLine(plain);
|
|
79
|
+
};
|
|
80
|
+
const isWarningLine = (line) => WARNING_LINE.test(line.replaceAll(NOT_A_WARNING, " "));
|
|
81
|
+
|
|
82
|
+
// One pass over the log in fixed memory. Returns what a report needs:
|
|
83
|
+
// total lines (progress lines included, so line numbers match the file), how many of them were progress, the first FULL_LOG_LINES (for a
|
|
84
|
+
// short log), the lines kept around failure-shaped ones, the last TAIL_LINES (none of these hold a progress line),
|
|
85
|
+
// how many failure-shaped lines there were with the first of them, and how many warning lines with the first of them.
|
|
86
|
+
// `redact` (default: none) masks each line as it is kept, so a line cut at lineChars never shows half a secret.
|
|
87
|
+
// The kept lines have two halves of maxBlock/2: the first failures' lines, and a rolling window of the latest, so a real failure after a
|
|
88
|
+
// flood of early noise still shows.
|
|
89
|
+
export const scanLog = (logFile, { redact = (text) => text, lineChars = LINE_CHARS, fullLines = FULL_LOG_LINES, before = LINES_BEFORE, after = LINES_AFTER, maxBlock = MAX_BLOCK_LINES, tail = TAIL_LINES } = {}) => {
|
|
90
|
+
const out = { total: 0, bytes: 0, progress: 0, head: [], blocks: new Map(), tail: [], failures: 0, firstFailure: "", warnings: 0, firstWarning: "" };
|
|
91
|
+
// The kept lines: the first half of the cap to whatever fails first, then two rolling windows of a quarter each, one for the starts of
|
|
92
|
+
// failure reports and one for every other error-shaped line.
|
|
93
|
+
const half = Math.ceil(maxBlock / 2);
|
|
94
|
+
const quarter = Math.floor((maxBlock - half) / 2);
|
|
95
|
+
const early = new Map();
|
|
96
|
+
const late = { start: new Map(), other: new Map() };
|
|
97
|
+
let bucket = "other";
|
|
98
|
+
const fd = openSync(logFile, "r");
|
|
99
|
+
const decoder = new StringDecoder("utf8");
|
|
100
|
+
const chunk = Buffer.alloc(64 * 1024);
|
|
101
|
+
let carry = "";
|
|
102
|
+
let carryCut = 0;
|
|
103
|
+
let recent = [];
|
|
104
|
+
let afterLeft = 0;
|
|
105
|
+
|
|
106
|
+
const keep = (e) => {
|
|
107
|
+
if (early.size < half) {
|
|
108
|
+
early.set(e.n, e.text);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const window = late[bucket];
|
|
112
|
+
if (early.has(e.n) || late.start.has(e.n) || late.other.has(e.n)) return;
|
|
113
|
+
window.set(e.n, e.text);
|
|
114
|
+
if (window.size > quarter) window.delete(window.keys().next().value);
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const line = (raw, cut) => {
|
|
118
|
+
out.total += 1;
|
|
119
|
+
const plain = raw.replace(ANSI, "");
|
|
120
|
+
// What is kept for display passes through `redact` (a line function, called on every line in order); what a line means is judged on `plain`.
|
|
121
|
+
const shown = redact(plain);
|
|
122
|
+
// Progress is counted and left out of everything shown; it never starts or extends a failure block.
|
|
123
|
+
if (PROGRESS_LINE.test(plain) && !isFailureLine(plain)) {
|
|
124
|
+
out.progress += 1;
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const text = cut > 0 || shown.length > lineChars ? `${shown.slice(0, lineChars)} […${cut + Math.max(0, shown.length - lineChars)} more characters]` : shown;
|
|
128
|
+
const entry = { n: out.total, text };
|
|
129
|
+
if (out.total <= fullLines) out.head.push(entry);
|
|
130
|
+
out.tail.push(entry);
|
|
131
|
+
if (out.tail.length > tail) out.tail.shift();
|
|
132
|
+
if (isWarningLine(plain)) {
|
|
133
|
+
out.warnings += 1;
|
|
134
|
+
if (out.firstWarning === "") out.firstWarning = text;
|
|
135
|
+
}
|
|
136
|
+
if (isFailureLine(plain)) {
|
|
137
|
+
out.failures += 1;
|
|
138
|
+
if (out.firstFailure === "") out.firstFailure = text;
|
|
139
|
+
bucket = FAILURE_START.test(plain) ? "start" : "other";
|
|
140
|
+
for (const e of recent) keep(e);
|
|
141
|
+
keep(entry);
|
|
142
|
+
afterLeft = after;
|
|
143
|
+
} else if (afterLeft > 0) {
|
|
144
|
+
keep(entry);
|
|
145
|
+
afterLeft -= 1;
|
|
146
|
+
}
|
|
147
|
+
recent = [...recent, entry].slice(-before);
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
// Text arrives in pieces; a bare carriage return is a progress bar redrawing, so it ends a line like a newline does.
|
|
151
|
+
let endedInCr = false;
|
|
152
|
+
const feed = (piece) => {
|
|
153
|
+
// A \r\n split between two pieces is one line break, not two.
|
|
154
|
+
const text = endedInCr && piece.startsWith("\n") ? piece.slice(1) : piece;
|
|
155
|
+
endedInCr = piece.endsWith("\r");
|
|
156
|
+
const parts = (carry + text).replace(/\r\n/g, "\n").split(/[\n\r]/);
|
|
157
|
+
carry = parts.pop() ?? "";
|
|
158
|
+
for (const part of parts) {
|
|
159
|
+
line(part, carryCut);
|
|
160
|
+
carryCut = 0;
|
|
161
|
+
}
|
|
162
|
+
// Memory is fixed: a line that never ends is kept to its first lineChars characters and the rest is only counted.
|
|
163
|
+
if (carry.length > lineChars * 2) {
|
|
164
|
+
carryCut += carry.length - lineChars;
|
|
165
|
+
carry = carry.slice(0, lineChars);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
try {
|
|
170
|
+
out.bytes = fstatSync(fd).size;
|
|
171
|
+
for (let n = readSync(fd, chunk, 0, chunk.length, null); n > 0; n = readSync(fd, chunk, 0, chunk.length, null)) feed(decoder.write(chunk.subarray(0, n)));
|
|
172
|
+
feed(decoder.end());
|
|
173
|
+
if (carry !== "") line(carry, carryCut);
|
|
174
|
+
} finally {
|
|
175
|
+
closeSync(fd);
|
|
176
|
+
}
|
|
177
|
+
out.blocks = new Map([...early, ...late.start, ...late.other]);
|
|
178
|
+
return out;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// The lines to show for a failed command, in file order, as strings. A short log is whole; a long one is the failure blocks plus the tail,
|
|
182
|
+
// with a marker where lines are missing.
|
|
183
|
+
export const excerptLines = (scan) => {
|
|
184
|
+
if (scan.total === 0) return ["(the command printed nothing)"];
|
|
185
|
+
if (scan.total <= FULL_LOG_LINES) {
|
|
186
|
+
const whole = scan.head.map((e) => e.text);
|
|
187
|
+
return scan.progress > 0 ? [...whole, `… ${scan.progress} progress line${scan.progress === 1 ? "" : "s"} not shown …`] : whole;
|
|
188
|
+
}
|
|
189
|
+
const shown = new Map(scan.blocks);
|
|
190
|
+
for (const e of scan.tail) shown.set(e.n, e.text);
|
|
191
|
+
const numbers = [...shown.keys()].toSorted((a, b) => a - b);
|
|
192
|
+
const lines = [];
|
|
193
|
+
let last = 0;
|
|
194
|
+
for (const n of numbers) {
|
|
195
|
+
if (n > last + 1) lines.push(`… ${n - last - 1} line${n - last - 1 === 1 ? "" : "s"} not shown …`);
|
|
196
|
+
lines.push(shown.get(n));
|
|
197
|
+
last = n;
|
|
198
|
+
}
|
|
199
|
+
if (scan.total > last) lines.push(`… ${scan.total - last} line${scan.total - last === 1 ? "" : "s"} not shown …`);
|
|
200
|
+
if (scan.failures === 0) lines.unshift("(no line names an error; the end of the output:)");
|
|
201
|
+
// Markers add lines the 100 + 30 caps don't count; cut the middle (the first and last halves are the most useful) if they overflow.
|
|
202
|
+
if (lines.length > EXCERPT_MAX_LINES) {
|
|
203
|
+
const half = Math.floor((EXCERPT_MAX_LINES - 1) / 2);
|
|
204
|
+
return [...lines.slice(0, half), `… ${lines.length - 2 * half} more lines not shown …`, ...lines.slice(-half)];
|
|
205
|
+
}
|
|
206
|
+
return lines;
|
|
207
|
+
};
|