cliprobe 0.0.1 → 0.1.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.
Files changed (4) hide show
  1. package/README.md +106 -21
  2. package/dist/cli.js +1247 -0
  3. package/package.json +87 -44
  4. package/bin/cliprobe.js +0 -225
package/package.json CHANGED
@@ -1,46 +1,89 @@
1
1
  {
2
- "name": "cliprobe",
3
- "version": "0.0.1",
4
- "description": "Black-box test any command-line program for terminal-edge bugs. 0.0.1 checks whether it crashes when its stdout is closed early (| head, grep -q, agents).",
5
- "type": "module",
6
- "bin": {
7
- "cliprobe": "bin/cliprobe.js"
8
- },
9
- "files": [
10
- "bin"
11
- ],
12
- "scripts": {
13
- "test": "node --test test/*.test.js"
14
- },
15
- "keywords": [
16
- "cli",
17
- "testing",
18
- "epipe",
19
- "sigpipe",
20
- "broken-pipe",
21
- "black-box",
22
- "conformance",
23
- "terminal",
24
- "agent-ready"
25
- ],
26
- "author": {
27
- "name": "Khaled Saeed",
28
- "url": "https://github.com/KhaledSaeed18"
29
- },
30
- "license": "MIT",
31
- "engines": {
32
- "node": ">=22.12.0"
33
- },
34
- "os": [
35
- "darwin",
36
- "linux"
37
- ],
38
- "repository": {
39
- "type": "git",
40
- "url": "git+https://github.com/KhaledSaeed18/cliprobe.git"
41
- },
42
- "bugs": {
43
- "url": "https://github.com/KhaledSaeed18/cliprobe/issues"
44
- },
45
- "homepage": "https://github.com/KhaledSaeed18/cliprobe#readme"
2
+ "name": "cliprobe",
3
+ "version": "0.1.0",
4
+ "description": "Black-box test any command-line program for terminal-edge bugs: crashes on a closed pipe (| head), color codes leaking into pipes, broken Ctrl-C handling, and control characters from file names reaching your terminal.",
5
+ "type": "module",
6
+ "bin": {
7
+ "cliprobe": "dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "build": "tsdown",
14
+ "dev": "node src/cli/main.ts",
15
+ "typecheck": "tsc --noEmit",
16
+ "lint": "oxlint --type-aware --deny-warnings",
17
+ "lint:fix": "oxlint --type-aware --fix",
18
+ "format": "prettier --write .",
19
+ "format:check": "prettier --check .",
20
+ "test": "vitest run",
21
+ "check": "pnpm typecheck && pnpm lint && pnpm format:check && pnpm build && pnpm test && pnpm check:package",
22
+ "check:package": "publint --strict",
23
+ "prepublishOnly": "pnpm build",
24
+ "test:watch": "vitest",
25
+ "prepare": "husky"
26
+ },
27
+ "keywords": [
28
+ "cli",
29
+ "testing",
30
+ "epipe",
31
+ "sigpipe",
32
+ "broken-pipe",
33
+ "black-box",
34
+ "conformance",
35
+ "terminal",
36
+ "agent-ready",
37
+ "no-color",
38
+ "sigint",
39
+ "ctrl-c",
40
+ "terminal-injection",
41
+ "pty"
42
+ ],
43
+ "author": {
44
+ "name": "Khaled Saeed",
45
+ "url": "https://github.com/KhaledSaeed18"
46
+ },
47
+ "license": "MIT",
48
+ "engines": {
49
+ "node": ">=22.12.0"
50
+ },
51
+ "os": [
52
+ "darwin",
53
+ "linux"
54
+ ],
55
+ "repository": {
56
+ "type": "git",
57
+ "url": "git+https://github.com/KhaledSaeed18/cliprobe.git"
58
+ },
59
+ "bugs": {
60
+ "url": "https://github.com/KhaledSaeed18/cliprobe/issues"
61
+ },
62
+ "homepage": "https://github.com/KhaledSaeed18/cliprobe#readme",
63
+ "publishConfig": {
64
+ "access": "public",
65
+ "provenance": true
66
+ },
67
+ "devDependencies": {
68
+ "@commitlint/cli": "^21.2.4",
69
+ "@commitlint/config-conventional": "^21.2.4",
70
+ "@semantic-release/changelog": "^7.0.0",
71
+ "@semantic-release/commit-analyzer": "^13.0.1",
72
+ "@semantic-release/git": "^11.0.1",
73
+ "@semantic-release/github": "^12.0.10",
74
+ "@semantic-release/npm": "^13.2.0",
75
+ "@semantic-release/release-notes-generator": "^14.1.1",
76
+ "@types/node": "^22.20.5",
77
+ "conventional-changelog-conventionalcommits": "^9.3.1",
78
+ "husky": "^9.1.7",
79
+ "oxlint": "^1.88.0",
80
+ "oxlint-tsgolint": "^7.0.2004",
81
+ "prettier": "^3.9.10",
82
+ "publint": "^0.3.25",
83
+ "semantic-release": "^25.0.9",
84
+ "tsdown": "^0.23.1",
85
+ "typescript": "^7.0.2",
86
+ "vitest": "^5.1.0"
87
+ },
88
+ "packageManager": "pnpm@12.14.0"
46
89
  }
package/bin/cliprobe.js DELETED
@@ -1,225 +0,0 @@
1
- #!/usr/bin/env node
2
- // cliprobe: black-box tests a command-line program for terminal-edge bugs.
3
- // 0.0.1 ships one check: does the program crash when its stdout is closed?
4
- import { spawn, execFileSync } from "node:child_process";
5
- import { closeSync, constants, mkdtempSync, openSync, readFileSync, rmSync } from "node:fs";
6
- import { tmpdir } from "node:os";
7
- import { join } from "node:path";
8
-
9
- const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
10
- const STDERR_CAP = 64 * 1024;
11
- // Signs that a program reported a write failure or crashed with a stack trace.
12
- const ERROR_RE = /EPIPE|broken ?pipe|BrokenPipeError|Unhandled 'error' event|^\s+at .+:\d+:\d+\)?$/im;
13
-
14
- const HELP = `cliprobe ${VERSION}: test a command-line program for terminal-edge bugs
15
-
16
- Usage:
17
- cliprobe [options] -- <command> [args...]
18
-
19
- With no args after <command>, cliprobe probes "<command> --version" and
20
- "<command> --help". With args, it probes exactly that invocation.
21
-
22
- Checks (0.0.1):
23
- closed-pipe Runs the command with stdout already closed, as when output is
24
- piped into a reader that quits early (head, grep -q, an agent).
25
- A well-behaved program exits quietly; a buggy one crashes with
26
- an EPIPE error and a stack trace.
27
-
28
- Options:
29
- --json Print results as JSON
30
- --timeout <ms> Kill a probe after this long (default 15000)
31
- -h, --help Show this help
32
- -v, --version Show the version
33
-
34
- Exit codes: 0 no failures, 1 a check failed, 2 usage error or could not run.
35
- Runs the target in the current directory without a shell, with stdin closed,
36
- a temporary HOME and a minimal environment. Only run programs you trust.`;
37
-
38
- function parseArgs(argv) {
39
- const opts = { json: false, timeout: 15000, command: null, args: [] };
40
- for (let i = 0; i < argv.length; i++) {
41
- const a = argv[i];
42
- if (a === "--") {
43
- [opts.command, ...opts.args] = argv.slice(i + 1);
44
- break;
45
- }
46
- if (a === "--json") opts.json = true;
47
- else if (a === "-h" || a === "--help") opts.help = true;
48
- else if (a === "-v" || a === "--version") opts.version = true;
49
- else if (a === "--timeout" || a.startsWith("--timeout=")) {
50
- const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
51
- opts.timeout = Number(value);
52
- if (!Number.isInteger(opts.timeout) || opts.timeout <= 0) throw new UsageError(`--timeout needs a positive whole number of milliseconds, got "${value}"`);
53
- } else if (a.startsWith("-")) throw new UsageError(`unknown option "${a}"`);
54
- else {
55
- // No "--": the first bare argument starts the command.
56
- [opts.command, ...opts.args] = argv.slice(i);
57
- break;
58
- }
59
- }
60
- return opts;
61
- }
62
-
63
- class UsageError extends Error {}
64
-
65
- /** Escapes control characters so a target's output cannot drive our terminal. */
66
- function safe(text) {
67
- return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, (c) => `\\x${c.charCodeAt(0).toString(16).padStart(2, "0")}`);
68
- }
69
-
70
- function sandbox() {
71
- const dir = mkdtempSync(join(tmpdir(), "cliprobe-"));
72
- const env = {
73
- PATH: process.env.PATH ?? "/usr/bin:/bin",
74
- LANG: process.env.LANG ?? "C.UTF-8",
75
- HOME: dir,
76
- TMPDIR: dir,
77
- TERM: "dumb",
78
- CI: "1",
79
- NO_UPDATE_NOTIFIER: "1",
80
- };
81
- return { dir, env };
82
- }
83
-
84
- /**
85
- * Runs one invocation. With `closedStdout`, stdout is the write end of a FIFO
86
- * whose read end is closed before the program starts, so its first write to
87
- * stdout fails (EPIPE, or SIGPIPE for programs that keep the default handler).
88
- */
89
- function run(command, args, { closedStdout, timeout }) {
90
- const { dir, env } = sandbox();
91
- let stdoutFd = "pipe";
92
- if (closedStdout) {
93
- const fifo = join(dir, "stdout.fifo");
94
- execFileSync("mkfifo", [fifo]);
95
- const reader = openSync(fifo, constants.O_RDONLY | constants.O_NONBLOCK);
96
- stdoutFd = openSync(fifo, constants.O_WRONLY | constants.O_NONBLOCK);
97
- closeSync(reader);
98
- }
99
-
100
- return new Promise((resolve) => {
101
- let stdoutBytes = 0;
102
- let stderr = "";
103
- let timedOut = false;
104
- let child;
105
- let finished = false;
106
- // A failed spawn emits both "error" and "close"; clean up and resolve once.
107
- const finish = (result) => {
108
- if (finished) return;
109
- finished = true;
110
- if (typeof stdoutFd === "number") closeSync(stdoutFd);
111
- rmSync(dir, { recursive: true, force: true });
112
- resolve({ stdoutBytes, stderr, timedOut, ...result });
113
- };
114
- try {
115
- // Runs in the caller's directory, as if typed there, so relative paths such as
116
- // `node ./dist/cli.js` work. HOME and TMPDIR point at a throwaway directory.
117
- child = spawn(command, args, { env, stdio: ["ignore", stdoutFd, "pipe"], detached: true });
118
- } catch (error) {
119
- return finish({ spawnError: error.message });
120
- }
121
- const timer = setTimeout(() => {
122
- timedOut = true;
123
- try { process.kill(-child.pid, "SIGKILL"); } catch {}
124
- }, timeout);
125
- child.stdout?.on("data", (chunk) => { stdoutBytes += chunk.length; });
126
- child.stderr.on("data", (chunk) => { if (stderr.length < STDERR_CAP) stderr += chunk.toString("utf8"); });
127
- child.on("error", (error) => { clearTimeout(timer); finish({ spawnError: error.message }); });
128
- child.on("close", (exitCode, signal) => { clearTimeout(timer); finish({ exitCode, signal }); });
129
- });
130
- }
131
-
132
- /**
133
- * Picks the most useful evidence from a crash: the error message plus the first
134
- * stack frame in the program's own code (not Node internals), which usually
135
- * points at the unguarded write.
136
- */
137
- function crashEvidence(stderr) {
138
- const lines = stderr.split("\n").map((l) => l.trim()).filter(Boolean);
139
- const message = lines.find((l) => /^(\w*Error\b|panic:)/.test(l)) ?? lines.find((l) => ERROR_RE.test(l)) ?? lines[0] ?? "";
140
- const frame = lines.find((l) => l.startsWith("at ") && !/\bnode:/.test(l))?.match(/(?:file:\/\/)?(\/[^\s()]+:\d+:\d+)/)?.[1];
141
- if (!frame) return message;
142
- const cwd = process.cwd() + "/";
143
- return `${message} (at ${frame.startsWith(cwd) ? frame.slice(cwd.length) : frame})`;
144
- }
145
-
146
- function judge(base, closed) {
147
- if (base.spawnError) return { verdict: "error", reason: `could not start: ${base.spawnError}` };
148
- if (base.timedOut) return { verdict: "error", reason: "timed out on a normal run" };
149
- if (base.stdoutBytes === 0) return { verdict: "skip", reason: "wrote nothing to stdout, so a closed stdout is never touched" };
150
- if (closed.timedOut) return { verdict: "fail", reason: "hung after stdout was closed" };
151
- if (closed.signal === "SIGPIPE") return { verdict: "pass", reason: "stopped by SIGPIPE, the conventional exit" };
152
- const newError = ERROR_RE.test(closed.stderr) && !ERROR_RE.test(base.stderr);
153
- if (newError && closed.exitCode !== base.exitCode) {
154
- return { verdict: "fail", reason: `crashed when stdout was closed (exit ${base.exitCode} -> ${closed.exitCode})`, evidence: crashEvidence(closed.stderr) };
155
- }
156
- if (newError) return { verdict: "warn", reason: "printed a write error but kept its exit code", evidence: crashEvidence(closed.stderr) };
157
- if (closed.exitCode !== base.exitCode) return { verdict: "pass", reason: `exited quietly with code ${closed.exitCode}` };
158
- return { verdict: "pass", reason: "exited quietly" };
159
- }
160
-
161
- async function probe(command, args, timeout) {
162
- const base = await run(command, args, { closedStdout: false, timeout });
163
- const closed = await run(command, args, { closedStdout: true, timeout });
164
- return {
165
- check: "closed-pipe",
166
- invocation: [command, ...args],
167
- ...judge(base, closed),
168
- baseline: { exitCode: base.exitCode ?? null, signal: base.signal ?? null, stdoutBytes: base.stdoutBytes },
169
- closed: { exitCode: closed.exitCode ?? null, signal: closed.signal ?? null, timedOut: closed.timedOut, stderr: closed.stderr.slice(-2000) },
170
- };
171
- }
172
-
173
- const COLORS = { pass: 32, fail: 31, warn: 33, skip: 90, error: 35 };
174
-
175
- function printHuman(command, results, useColor) {
176
- const paint = (verdict) => {
177
- const label = verdict.toUpperCase().padEnd(5);
178
- return useColor ? `\x1b[${COLORS[verdict]}m${label}\x1b[0m` : label;
179
- };
180
- const width = Math.max(...results.map((r) => safe(r.invocation.join(" ")).length));
181
- console.log(`cliprobe ${VERSION}: closed-pipe check for ${safe(command)}\n`);
182
- for (const r of results) {
183
- console.log(` ${paint(r.verdict)} ${safe(r.invocation.join(" ")).padEnd(width)} ${r.reason}`);
184
- if (r.evidence) console.log(` ${" ".repeat(5)} ${" ".repeat(width)} ${safe(r.evidence).slice(0, 200)}`);
185
- }
186
- const count = (v) => results.filter((r) => r.verdict === v).length;
187
- console.log(`\n${count("fail")} failed, ${count("warn")} warned, ${count("pass")} passed, ${count("skip")} skipped${count("error") ? `, ${count("error")} could not run` : ""}`);
188
- }
189
-
190
- async function main() {
191
- let opts;
192
- try {
193
- opts = parseArgs(process.argv.slice(2));
194
- } catch (error) {
195
- if (!(error instanceof UsageError)) throw error;
196
- console.error(`cliprobe: ${error.message}\nRun "cliprobe --help" for usage.`);
197
- return 2;
198
- }
199
- if (opts.help) { console.log(HELP); return 0; }
200
- if (opts.version) { console.log(VERSION); return 0; }
201
- if (!opts.command) { console.error(`cliprobe: no command given\nUsage: cliprobe [options] -- <command> [args...]`); return 2; }
202
- if (process.platform === "win32") { console.error("cliprobe: Windows is not supported yet (the closed-pipe check needs mkfifo)."); return 2; }
203
-
204
- const invocations = opts.args.length ? [opts.args] : [["--version"], ["--help"]];
205
- const results = [];
206
- for (const args of invocations) results.push(await probe(opts.command, args, opts.timeout));
207
-
208
- if (opts.json) {
209
- console.log(JSON.stringify({ tool: "cliprobe", version: VERSION, command: opts.command, results }, null, 2));
210
- } else {
211
- const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
212
- printHuman(opts.command, results, useColor);
213
- }
214
- if (results.some((r) => r.verdict === "fail")) return 1;
215
- if (results.every((r) => r.verdict === "error")) return 2;
216
- return 0;
217
- }
218
-
219
- // cliprobe practises what it checks: a closed stdout ends it quietly.
220
- process.stdout.on("error", (error) => {
221
- if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
222
- throw error;
223
- });
224
-
225
- process.exitCode = await main();