返回 CodeWhale
install-safety.test.js
根目录 / scripts / release / install-safety.test.js
1 #!/usr/bin/env node
2
3 // Offline shell proofs. Every destination and download is a disposable fixture;
4 // curl, uname, and sudo are intercepted so no real installation or network runs.
5 const assert = require("node:assert/strict");
6 const { spawnSync } = require("node:child_process");
7 const crypto = require("node:crypto");
8 const fs = require("node:fs");
9 const os = require("node:os");
10 const path = require("node:path");
11 const test = require("node:test");
12
13 const repo = path.resolve(__dirname, "../..");
14 const bytes = '#!/bin/sh\necho "executed $*" >> "$INSTALL_TEST_EXECUTED"\n[ "$1" = doctor ] && echo "telemetry=${CODEWHALE_TELEMETRY-unset} update_check=${CODEWHALE_NO_UPDATE_CHECK-unset}" >> "$INSTALL_TEST_DOCTOR_ENV"\ncase "$1" in --help) printf \'%s\\n\' "${INSTALL_TEST_HELP:-}" ;; *) echo "codewhale 0.9.11" ;; esac\n';
15
16 function executable(file, body) {
17 fs.writeFileSync(file, body, { mode: 0o755 });
18 }
19
20 function fixture(t, kind) {
21 const root = fs.mkdtempSync(path.join(os.tmpdir(), "cw-install-safety-"));
22 t.after(() => fs.rmSync(root, { recursive: true, force: true }));
23 const home = path.join(root, "home");
24 const bin = path.join(root, "tools");
25 const archive = path.join(root, "archive");
26 const assets = path.join(root, "assets");
27 for (const dir of [home, bin, archive, assets]) fs.mkdirSync(dir);
28 fs.copyFileSync(path.join(repo, "scripts/release/install.sh"), path.join(archive, "install.sh"));
29 for (const name of ["codewhale", "codew"]) {
30 executable(path.join(archive, name), bytes);
31 executable(path.join(assets, `${name}-macos-arm64`), bytes);
32 }
33 const hash = crypto.createHash("sha256").update(bytes).digest("hex");
34 fs.writeFileSync(path.join(assets, "codewhale-artifacts-sha256.txt"),
35 `${hash} codewhale-macos-arm64\n${hash} codew-macos-arm64\n`);
36 executable(path.join(bin, "uname"), '#!/bin/sh\ncase "$1" in -s) echo Darwin ;; -m) echo arm64 ;; esac\n');
37 executable(path.join(bin, "sudo"), '#!/bin/sh\necho sudo >> "$INSTALL_TEST_EXECUTED"\nexit 97\n');
38 executable(path.join(bin, "codewhale"), '#!/bin/sh\necho shadow >> "$INSTALL_TEST_EXECUTED"\nexit 98\n');
39 executable(path.join(bin, "curl"), `#!/bin/sh
40 url=""; output=""
41 while [ "$#" -gt 0 ]; do
42 case "$1" in
43 -o) shift; output="$1" ;;
44 http*) url="$1" ;;
45 esac
46 shift
47 done
48 printf '%s\n' "$url" >> "$INSTALL_TEST_DOWNLOADS"
49 asset="$(basename "$url")"
50 cp "$INSTALL_TEST_ASSETS/$asset" "$output"
51 `);
52 const destination = path.join(home, ".local", "bin");
53 fs.mkdirSync(destination, { recursive: true });
54 fs.chmodSync(destination, 0o755);
55 const env = { ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}`, CI: "1",
56 CODEWHALE_VERSION: "v0.9.11", CODEWHALE_INSTALL_DIR: destination,
57 PREFIX: path.dirname(destination), INSTALL_TEST_ASSETS: assets,
58 INSTALL_TEST_EXECUTED: path.join(root, "executed"),
59 INSTALL_TEST_DOCTOR_ENV: path.join(root, "doctor-env"),
60 INSTALL_TEST_DOWNLOADS: path.join(root, "downloads") };
61 for (const key of ["CODEWHALE_RELEASE_BASE_URL", "DEEPSEEK_TUI_RELEASE_BASE_URL", "CODEWHALE_SKIP_GLIBC_CHECK", "DEEPSEEK_TUI_SKIP_GLIBC_CHECK", "DEEPSEEK_SKIP_GLIBC_CHECK", "TERMUX_VERSION", "CODEWHALE_HOME", "CODEWHALE_FORCE_REINSTALL", "CODEWHALE_INSTALL_COMPILED_HOST", "SHELL", "ZDOTDIR"]) delete env[key];
62 function run(args = []) {
63 const script = kind === "website" ? path.join(repo, "web/public/install.sh") : path.join(archive, "install.sh");
64 return spawnSync(kind === "website" ? "sh" : "bash", [script, ...args], { env, encoding: "utf8", timeout: 10000 });
65 }
66 function prepare() { fs.mkdirSync(env.CODEWHALE_INSTALL_DIR, { recursive: true }); }
67 function untouched() {
68 const runs = fs.existsSync(env.INSTALL_TEST_EXECUTED) ? fs.readFileSync(env.INSTALL_TEST_EXECUTED, "utf8").trim().split("\n") : [];
69 assert.ok(runs.every(line => line === "executed doctor --installs --brief" || line === "executed --help"), `installers must not execute existing files or sudo: ${runs.join(", ")}`);
70 }
71 return { root, home, bin, archive, assets, destination, env, run, prepare, untouched };
72 }
73
74 function flakyCurl(f, failures) {
75 const counter = path.join(f.root, "curl-calls");
76 const real = fs.readFileSync(path.join(f.bin, "curl"), "utf8");
77 executable(path.join(f.bin, "curl"), `#!/bin/sh
78 n=$(cat "${counter}" 2>/dev/null || echo 0)
79 n=$((n + 1))
80 echo "$n" > "${counter}"
81 if [ "$n" -le ${failures} ]; then echo "curl: (35) SSL_connect: SSL_ERROR_SYSCALL" >&2; exit 35; fi
82 ${real.replace("#!/bin/sh\n", "")}`);
83 f.env.CODEWHALE_INSTALL_RETRY_DELAY = "0";
84 return counter;
85 }
86
87 test("website: a download that fails twice with a connection error is retried and the install succeeds", t => {
88 const f = fixture(t, "website");
89 const counter = flakyCurl(f, 2);
90 const result = f.run();
91 assert.equal(result.status, 0, result.stderr);
92 assert.equal(fs.readFileSync(counter, "utf8").trim(), "4");
93 assert.equal(fs.readFileSync(path.join(f.destination, "codewhale"), "utf8"), bytes);
94 });
95
96 test("website: three failed attempts end with the retry hint and install nothing", t => {
97 const f = fixture(t, "website");
98 const counter = flakyCurl(f, 99);
99 const result = f.run();
100 assert.notEqual(result.status, 0);
101 assert.equal(fs.readFileSync(counter, "utf8").trim(), "3");
102 assert.ok(result.stderr.includes("Download failed. This is usually a network blip; run the same command again."), result.stderr);
103 assert.equal(fs.existsSync(path.join(f.destination, "codewhale")), false);
104 });
105
106 for (const kind of ["website", "archive"]) {
107 test(`${kind}: fresh installation verifies bytes, executable modes, and PATH shadowing`, t => {
108 const f = fixture(t, kind);
109 const result = f.run();
110 assert.equal(result.status, 0, result.stderr);
111 for (const name of ["codewhale", "codew"]) {
112 const installed = path.join(f.destination, name);
113 assert.equal(fs.readFileSync(installed, "utf8"), bytes);
114 assert.ok(fs.statSync(installed).mode & 0o111);
115 }
116 assert.equal(
117 fs.statSync(path.join(f.destination, "codewhale")).ino,
118 fs.statSync(path.join(f.destination, "codew")).ino,
119 "codew should be hard-linked to codewhale"
120 );
121 const receipt = fs.readFileSync(path.join(f.destination, ".codewhale-install.sha256"), "utf8");
122 const hash = crypto.createHash("sha256").update(bytes).digest("hex");
123 assert.equal(receipt, `${hash} codewhale
124 ${hash} codew
125 `);
126 assert.match(result.stdout, /PATH selects/);
127 assert.ok(result.stdout.includes(`"${fs.realpathSync(f.destination)}/codewhale" update`), result.stdout);
128 if (kind === "website") {
129 const downloads = fs.readFileSync(f.env.INSTALL_TEST_DOWNLOADS, "utf8").trim().split("\n");
130 assert.equal(downloads.length, 2);
131 assert.ok(downloads.some(url => url.endsWith("/codewhale-macos-arm64")));
132 assert.ok(!downloads.some(url => url.endsWith("/codew-macos-arm64")));
133 assert.ok(downloads.every(url => url.startsWith("https://github.com/codewhale-hq/CodeWhale/releases/download/v0.9.11/")));
134 }
135 f.untouched();
136 });
137
138 test(`${kind}: the installer's own doctor run is made with usage reporting forced off`, t => {
139 for (const inherited of [undefined, "1"]) {
140 const f = fixture(t, kind);
141 if (inherited !== undefined) f.env.CODEWHALE_TELEMETRY = inherited;
142 else delete f.env.CODEWHALE_TELEMETRY;
143 const result = f.run();
144 assert.equal(result.status, 0, result.stderr);
145 const seen = fs.readFileSync(f.env.INSTALL_TEST_DOCTOR_ENV, "utf8").trim().split("\n");
146 assert.deepEqual(seen, ["telemetry=0 update_check=1"], `inherited=${inherited}`);
147 assert.ok(result.stdout.includes("config set telemetry false"), result.stdout);
148 assert.ok(!result.stdout.includes("telemetry=0"), result.stdout);
149 }
150 });
151
152 test(`${kind}: the output ends with the PATH command and the verify command`, t => {
153 const f = fixture(t, kind);
154 f.env.SHELL = "/bin/bash";
155 const result = f.run();
156 assert.equal(result.status, 0, result.stderr);
157 const lines = result.stdout.split("\n").map(line => line.trim()).filter(Boolean);
158 assert.equal(lines.at(-1), "codewhale --version", result.stdout);
159 assert.equal(lines.at(-2), "Then check it:", result.stdout);
160 assert.ok(lines.at(-3).startsWith("export PATH="), result.stdout);
161 assert.ok(lines.at(-3).endsWith("hash -r"), result.stdout);
162 f.untouched();
163 });
164
165 test(`${kind}: install output never mentions Computer Use or Node.js 20`, t => {
166 const f = fixture(t, kind);
167 const noNode = ["/usr/bin", "/bin"].every(dir => !fs.existsSync(path.join(dir, "node")));
168 if (noNode) f.env.PATH = `${f.bin}:/usr/bin:/bin`;
169 const result = f.run();
170 assert.equal(result.status, 0, result.stderr);
171 assert.ok(!result.stdout.includes("Computer Use"), result.stdout);
172 assert.ok(!result.stdout.includes("Node.js 20"), result.stdout);
173 f.untouched();
174 });
175
176 test(`${kind}: rerunning an identical installation preserves its files`, t => {
177 const f = fixture(t, kind);
178 assert.equal(f.run().status, 0);
179 const file = path.join(f.destination, "codewhale");
180 const alias = path.join(f.destination, "codew");
181 const before = fs.statSync(file);
182 assert.equal(fs.statSync(alias).ino, before.ino);
183 const result = f.run();
184 assert.equal(result.status, 0, result.stderr);
185 assert.equal(fs.statSync(file).ino, before.ino);
186 assert.equal(fs.statSync(alias).ino, before.ino);
187 assert.equal(fs.readFileSync(file, "utf8"), bytes);
188 f.untouched();
189 });
190
191 test(`${kind}: hard-link fallback copies codew when staging link from codewhale fails`, t => {
192 const f = fixture(t, kind);
193 executable(path.join(f.bin, "ln"), `#!/bin/sh
194 case "$1:$2" in
195 */codewhale:*/.codewhale-install.*/codew) exit 1 ;;
196 esac
197 exec /bin/ln "$@"
198 `);
199 const result = f.run();
200 assert.equal(result.status, 0, result.stderr);
201 const primary = path.join(f.destination, "codewhale");
202 const alias = path.join(f.destination, "codew");
203 assert.equal(fs.readFileSync(primary, "utf8"), bytes);
204 assert.equal(fs.readFileSync(alias, "utf8"), bytes);
205 assert.notEqual(fs.statSync(primary).ino, fs.statSync(alias).ino);
206 assert.ok(fs.statSync(alias).mode & 0o111);
207 f.untouched();
208 });
209
210 test(`${kind}: upgrading a hard-linked Codewhale binary moves old entries to recovery and links the new pair`, t => {
211 const f = fixture(t, kind);
212 f.prepare();
213 const olderBytes = `${bytes}# codewhale-updater old-build\n`;
214 const primary = path.join(f.destination, "codewhale");
215 const alias = path.join(f.destination, "codew");
216 executable(primary, olderBytes);
217 fs.linkSync(primary, alias);
218 const oldIno = fs.statSync(primary).ino;
219 assert.equal(fs.statSync(alias).ino, oldIno);
220
221 const result = f.run();
222 assert.equal(result.status, 0, result.stderr);
223 assert.equal(fs.readFileSync(primary, "utf8"), bytes);
224 assert.equal(fs.readFileSync(alias, "utf8"), bytes);
225 const newIno = fs.statSync(primary).ino;
226 assert.notEqual(newIno, oldIno);
227 assert.equal(fs.statSync(alias).ino, newIno);
228 const recoveryRoot = path.join(f.home, ".codewhale", "recovery");
229 const batches = fs.readdirSync(recoveryRoot);
230 assert.equal(batches.length, 1);
231 const manifest = fs.readFileSync(path.join(recoveryRoot, batches[0], "manifest.tsv"), "utf8");
232 assert.ok(manifest.includes("001-codewhale"), manifest);
233 assert.ok(manifest.includes("002-codew"), manifest);
234 f.untouched();
235 });
236
237 test(`${kind}: refuses a non-Codewhale file at the destination without executing it`, t => {
238 const f = fixture(t, kind); f.prepare();
239 const primary = path.join(f.destination, "codewhale");
240 const newer = bytes.replace("0.9.11", "0.9.12");
241 executable(primary, newer);
242 const result = f.run();
243 assert.notEqual(result.status, 0);
244 assert.ok(result.stderr.includes(primary), result.stderr);
245 assert.match(result.stderr, /fresh (directory|prefix)/);
246 assert.equal(fs.readFileSync(primary, "utf8"), newer);
247 assert.equal(fs.existsSync(path.join(f.destination, "codew")), false);
248 f.untouched();
249 });
250
251 for (const name of ["codew", "codewhale-tui"]) {
252 test(`${kind}: existing ${name} follows current command ownership`, t => {
253 const f = fixture(t, kind); f.prepare();
254 const file = path.join(f.destination, name);
255 executable(file, "unrelated bytes");
256 const result = f.run();
257 assert.equal(fs.readFileSync(file, "utf8"), "unrelated bytes");
258 if (name === "codewhale-tui") {
259 assert.equal(result.status, 0, result.stderr);
260 assert.equal(fs.readFileSync(path.join(f.destination, "codewhale"), "utf8"), bytes);
261 } else {
262 assert.notEqual(result.status, 0);
263 assert.ok(result.stderr.includes(file), result.stderr);
264 assert.equal(fs.existsSync(path.join(f.destination, "codewhale")), false);
265 }
266 f.untouched();
267 });
268 }
269
270 test(`${kind}: refuses a symlink destination and preserves its target`, t => {
271 const f = fixture(t, kind); f.prepare();
272 const target = path.join(f.root, "foreign");
273 executable(target, "unrelated bytes");
274 const alias = path.join(f.destination, "codew");
275 fs.symlinkSync(target, alias);
276 assert.notEqual(f.run().status, 0);
277 assert.ok(fs.lstatSync(alias).isSymbolicLink());
278 assert.equal(fs.readFileSync(target, "utf8"), "unrelated bytes");
279 assert.equal(fs.existsSync(path.join(f.destination, "codewhale")), false);
280 f.untouched();
281 });
282
283 test(`${kind}: managed directories are refused without invoking sudo`, t => {
284 const f = fixture(t, kind);
285 f.env.PREFIX = path.join(f.home, ".cargo");
286 f.env.CODEWHALE_INSTALL_DIR = path.join(f.env.PREFIX, "bin");
287 const result = f.run();
288 assert.notEqual(result.status, 0);
289 assert.match(result.stderr, /managed\/system/);
290 assert.equal(fs.existsSync(path.join(f.env.CODEWHALE_INSTALL_DIR, "codewhale")), false);
291 f.untouched();
292 });
293
294 for (const [label, file, record, accepted] of [
295 ["an unrelated Cargo record", ".crates.toml", '[v1]\n"ripgrep 14.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = ["rg"]\n"codewhale-tui 0.10.3 (registry+https://github.com/rust-lang/crates.io-index)" = ["codewhale-tui"]\n', true],
296 ["a Cargo record listing codewhale", ".crates.toml", '[v1]\n"codewhale-cli 0.10.3 (registry+https://github.com/rust-lang/crates.io-index)" = ["codewhale"]\n', false],
297 ["a Cargo record listing codew", ".crates2.json", '{"installs":{"codewhale-cli 0.10.3":{"bins":["codew"]}}}\n', false],
298 ["an unreadable Cargo record", ".crates.toml", null, false],
299 ]) {
300 test(`${kind}: ${label} beside the install directory is ${accepted ? "accepted" : "refused"}`, t => {
301 const f = fixture(t, kind); f.prepare();
302 const receipt = path.join(path.dirname(f.destination), file);
303 if (record === null) {
304 if (process.getuid && process.getuid() === 0) return t.skip("root can read any file");
305 fs.writeFileSync(receipt, '"codewhale" ', { mode: 0o000 });
306 } else {
307 fs.writeFileSync(receipt, record);
308 }
309 const result = f.run();
310 if (accepted) {
311 assert.equal(result.status, 0, result.stderr);
312 assert.equal(fs.readFileSync(path.join(f.destination, "codewhale"), "utf8"), bytes);
313 } else {
314 assert.notEqual(result.status, 0);
315 assert.match(result.stderr, /cargo uninstall/);
316 assert.equal(fs.existsSync(path.join(f.destination, "codewhale")), false);
317 }
318 f.untouched();
319 });
320 }
321
322 test(`${kind}: a destination created during publication is never overwritten`, t => {
323 const f = fixture(t, kind);
324 executable(path.join(f.bin, "ln"), `#!/bin/sh
325 destination="$2$(basename "$1")"
326 printf 'another writer' > "$destination"
327 exec /bin/ln "$@"
328 `);
329 assert.notEqual(f.run().status, 0);
330 assert.equal(fs.readFileSync(path.join(f.destination, "codewhale"), "utf8"), "another writer");
331 assert.equal(fs.existsSync(path.join(f.destination, "codew")), false);
332 assert.equal(fs.readdirSync(f.destination).some(name => name.startsWith(".codewhale-install.")), false);
333 f.untouched();
334 });
335
336 test(`${kind}: a failed second publication removes the command this run published`, t => {
337 const f = fixture(t, kind);
338 // Another writer claims codew between preflight and its publication.
339 executable(path.join(f.bin, "ln"), `#!/bin/sh
340 case "$(basename "$1")" in codew) printf 'another writer' > "$2codew" ;; esac
341 exec /bin/ln "$@"
342 `);
343 const result = f.run();
344 assert.notEqual(result.status, 0, result.stdout);
345 assert.equal(fs.existsSync(path.join(f.destination, "codewhale")), false, "no half-installed pair is left behind");
346 assert.equal(fs.readFileSync(path.join(f.destination, "codew"), "utf8"), "another writer");
347 assert.match(result.stderr, /did not complete/);
348 assert.equal(fs.readdirSync(f.destination).some(name => name.startsWith(".codewhale-install.")), false);
349 f.untouched();
350 });
351
352 test(`${kind}: rollback never removes a command that was already installed`, t => {
353 const f = fixture(t, kind);
354 assert.equal(f.run().status, 0);
355 fs.unlinkSync(path.join(f.destination, "codew"));
356 const kept = fs.statSync(path.join(f.destination, "codewhale")).ino;
357 executable(path.join(f.bin, "ln"), `#!/bin/sh
358 case "$(basename "$1")" in codew) printf 'another writer' > "$2codew" ;; esac
359 exec /bin/ln "$@"
360 `);
361 assert.notEqual(f.run().status, 0);
362 assert.equal(fs.statSync(path.join(f.destination, "codewhale")).ino, kept);
363 f.untouched();
364 });
365
366 for (const collision of ["directory", "directory symlink"]) {
367 test(`${kind}: a raced ${collision} cannot redirect publication`, t => {
368 const f = fixture(t, kind);
369 const foreign = path.join(f.root, "foreign-directory");
370 fs.mkdirSync(foreign);
371 f.env.INSTALL_TEST_FOREIGN = foreign;
372 const create = collision === "directory"
373 ? 'mkdir "$destination"'
374 : '/bin/ln -s "$INSTALL_TEST_FOREIGN" "$destination"';
375 executable(path.join(f.bin, "ln"), `#!/bin/sh
376 destination="$2$(basename "$1")"
377 ${create}
378 exec /bin/ln "$@"
379 `);
380 const result = f.run();
381 assert.notEqual(result.status, 0, result.stdout);
382 assert.doesNotMatch(result.stdout, /Installed checksummed|Done\. Commands/);
383 const target = path.join(f.destination, "codewhale");
384 assert.equal(fs.lstatSync(target).isSymbolicLink(), collision === "directory symlink");
385 assert.deepEqual(fs.readdirSync(target), []);
386 assert.deepEqual(fs.readdirSync(foreign), []);
387 assert.equal(fs.existsSync(path.join(f.destination, "codew")), false);
388 assert.equal(fs.readdirSync(f.destination).some(name => name.startsWith(".codewhale-install.")), false);
389 f.untouched();
390 });
391 }
392 }
393
394 const blockOf = dir => `# >>> codewhale PATH >>>\nexport PATH="${dir}:$PATH"\n# <<< codewhale PATH <<<\n`;
395 const shownDir = f => (fs.realpathSync(f.destination) === fs.realpathSync(path.join(f.home, ".local", "bin")) ? "$HOME/.local/bin" : fs.realpathSync(f.destination));
396 for (const kind of ["website", "archive"]) {
397 for (const [shell, profile] of [["/bin/zsh", ".zshrc"], ["/bin/bash", ".bash_profile"], ["/bin/sh", ".profile"]]) {
398 test(`${kind}: ${shell} gets the marked PATH block in ~/${profile} by default and the output says so`, t => {
399 const f = fixture(t, kind);
400 f.env.SHELL = shell;
401 fs.writeFileSync(path.join(f.home, profile), "# mine\nalias a=b");
402 const result = f.run();
403 assert.equal(result.status, 0, result.stderr);
404 assert.equal(fs.readFileSync(path.join(f.home, profile), "utf8"), `# mine\nalias a=b\n${blockOf(shownDir(f))}`);
405 assert.ok(result.stdout.includes(`Added to ~/${profile}`), result.stdout);
406 assert.ok(result.stdout.includes("--no-modify-path"), result.stdout);
407 const lines = result.stdout.split("\n").map(line => line.trim()).filter(Boolean);
408 assert.equal(lines.at(-1), "codewhale --version", result.stdout);
409 assert.ok(lines.at(-3).startsWith("export PATH=") && lines.at(-3).endsWith("hash -r"), result.stdout);
410 f.untouched();
411 });
412 }
413
414 test(`${kind}: a fresh profile is created with only the block`, t => {
415 const f = fixture(t, kind);
416 f.env.SHELL = "/bin/zsh";
417 assert.equal(f.run().status, 0);
418 assert.equal(fs.readFileSync(path.join(f.home, ".zshrc"), "utf8"), blockOf(shownDir(f)));
419 });
420
421 test(`${kind}: the printed undo command removes exactly the block`, t => {
422 const f = fixture(t, kind);
423 f.env.SHELL = "/bin/zsh";
424 const before = "# top\nexport A=1\n";
425 const after = "export B=2\n";
426 fs.writeFileSync(path.join(f.home, ".zshrc"), before + after);
427 const result = f.run();
428 assert.equal(result.status, 0, result.stderr);
429 const undo = result.stdout.split("\n").map(line => line.trim()).find(line => line.startsWith("cw_tmp="));
430 assert.ok(undo, result.stdout);
431 const profile = path.join(f.home, ".zshrc");
432 fs.writeFileSync(profile, before + blockOf(shownDir(f)) + after);
433 const ran = spawnSync("sh", ["-c", undo], { env: { ...f.env }, encoding: "utf8" });
434 assert.equal(ran.status, 0, ran.stderr);
435 assert.equal(fs.readFileSync(profile, "utf8"), before + after);
436 });
437
438 for (const tail of ["a\n# >>> codewhale PATH >>>\nlast\n", "a\n# >>> codewhale PATH >>>\n", "a\n# >>> codewhale PATH >>>"]) {
439 test(`${kind}: the printed undo command leaves a lone start marker near end of file untouched (${JSON.stringify(tail)})`, t => {
440 const f = fixture(t, kind);
441 f.env.SHELL = "/bin/zsh";
442 const result = f.run();
443 assert.equal(result.status, 0, result.stderr);
444 const undo = result.stdout.split("\n").map(line => line.trim()).find(line => line.startsWith("cw_tmp="));
445 const profile = path.join(f.home, ".zshrc");
446 fs.writeFileSync(profile, tail);
447 const ran = spawnSync("sh", ["-c", undo], { env: { ...f.env }, encoding: "utf8" });
448 assert.equal(ran.status, 0, ran.stderr);
449 assert.equal(fs.readFileSync(profile, "utf8"), tail);
450 });
451 }
452
453 test(`${kind}: --no-modify-path and CODEWHALE_NO_MODIFY_PATH leave every profile alone and print the command`, t => {
454 for (const mode of ["flag", "env"]) {
455 const f = fixture(t, kind);
456 f.env.SHELL = "/bin/zsh";
457 if (mode === "env") f.env.CODEWHALE_NO_MODIFY_PATH = "1";
458 const result = f.run(mode === "flag" ? ["--no-modify-path"] : []);
459 assert.equal(result.status, 0, result.stderr);
460 assert.equal(fs.existsSync(path.join(f.home, ".zshrc")), false);
461 assert.ok(result.stdout.includes("Not editing your shell profile"), result.stdout);
462 assert.ok(result.stdout.includes(">> ~/.zshrc"), result.stdout);
463 assert.equal(result.stdout.trim().split("\n").at(-1).trim(), "codewhale --version");
464 }
465 });
466
467 test(`${kind}: an unknown option fails before installing`, t => {
468 const f = fixture(t, kind);
469 const result = f.run(["--no-modify-pth"]);
470 assert.equal(result.status, 2);
471 assert.equal(fs.existsSync(path.join(f.destination, "codewhale")), false);
472 });
473
474 test(`${kind}: no edit when the install directory is already on PATH`, t => {
475 const f = fixture(t, kind);
476 f.env.SHELL = "/bin/zsh";
477 const dir = fs.realpathSync(f.destination);
478 f.env.PATH = `${dir}:${f.env.PATH}`;
479 const result = f.run();
480 assert.equal(result.status, 0, result.stderr);
481 assert.equal(fs.existsSync(path.join(f.home, ".zshrc")), false);
482 assert.ok(!result.stdout.includes("Added to"), result.stdout);
483 });
484
485 test(`${kind}: reinstalling never duplicates the block`, t => {
486 const f = fixture(t, kind);
487 f.env.SHELL = "/bin/zsh";
488 assert.equal(f.run().status, 0);
489 const first = fs.readFileSync(path.join(f.home, ".zshrc"), "utf8");
490 const again = f.run();
491 assert.equal(again.status, 0, again.stderr);
492 assert.equal(fs.readFileSync(path.join(f.home, ".zshrc"), "utf8"), first);
493 assert.ok(again.stdout.includes("already has the codewhale PATH block"), again.stdout);
494 });
495
496 test(`${kind}: a symlinked profile is refused, left alone, and the command is printed`, t => {
497 const f = fixture(t, kind);
498 f.env.SHELL = "/bin/zsh";
499 const target = path.join(f.root, "dotfiles-zshrc");
500 fs.writeFileSync(target, "# managed\n");
501 fs.symlinkSync(target, path.join(f.home, ".zshrc"));
502 const result = f.run();
503 assert.equal(result.status, 0, result.stderr);
504 assert.equal(fs.readFileSync(target, "utf8"), "# managed\n");
505 assert.ok(result.stdout.includes("is a symlink"), result.stdout);
506 assert.ok(result.stdout.includes(">> ~/.zshrc"), result.stdout);
507 assert.equal(result.stdout.trim().split("\n").at(-1).trim(), "codewhale --version");
508 });
509
510 test(`${kind}: an unwritable profile is refused and left alone`, t => {
511 if (process.getuid && process.getuid() === 0) return t.skip("root can write read-only files");
512 const f = fixture(t, kind);
513 f.env.SHELL = "/bin/zsh";
514 const profile = path.join(f.home, ".zshrc");
515 fs.writeFileSync(profile, "# ro\n", { mode: 0o444 });
516 const result = f.run();
517 assert.equal(result.status, 0, result.stderr);
518 assert.equal(fs.readFileSync(profile, "utf8"), "# ro\n");
519 assert.ok(result.stdout.includes("not a writable regular file"), result.stdout);
520 });
521
522 test(`${kind}: no profile is chosen or edited when the shell cannot be determined`, t => {
523 for (const shell of ["", "/usr/bin/fish", "/bin/tcsh"]) {
524 const f = fixture(t, kind);
525 f.env.SHELL = shell;
526 const result = f.run();
527 assert.equal(result.status, 0, result.stderr);
528 assert.deepEqual(fs.readdirSync(f.home).filter(name => name !== ".local"), [], `${shell}: ${result.stdout}`);
529 assert.ok(!result.stdout.includes("Added to"), result.stdout);
530 }
531 });
532 }
533
534 const helpWithout = "Usage: codewhale [OPTIONS] [PROMPT]...\n\nCommands:\n update Update\n doctor Diagnose";
535 const helpWith = `${helpWithout}\n uninstall Remove this receipt-owned release install`;
536 for (const kind of ["website", "archive"]) {
537 for (const [label, help, supported] of [["without", helpWithout, false], ["with", helpWith, true]]) {
538 test(`${kind}: a binary ${label} an uninstall command ${supported ? "gets" : "never gets"} the uninstall line, and the update mode comes from the binary`, t => {
539 const f = fixture(t, kind);
540 f.env.INSTALL_TEST_HELP = help;
541 f.env.SHELL = "/bin/bash";
542 const result = f.run();
543 assert.equal(result.status, 0, result.stderr);
544 assert.equal(result.stdout.includes("uninstall --yes"), supported, result.stdout);
545 assert.equal(result.stdout.includes("update.mode"), false, result.stdout);
546 assert.equal(/codewhale uninstall/.test(result.stdout), supported, result.stdout);
547 assert.equal(result.stdout.includes("this release has no uninstall command"), !supported, result.stdout);
548 if (!supported) {
549 assert.ok(result.stdout.includes(`rm "${fs.realpathSync(f.destination)}/codewhale" "${fs.realpathSync(f.destination)}/codew" "${fs.realpathSync(f.destination)}/.codewhale-install.sha256"`), result.stdout);
550 }
551 f.untouched();
552 });
553 }
554 }
555
556 test("archive: install.bat forwards its arguments so -NoModifyPath reaches install.ps1", () => {
557 const bat = fs.readFileSync(path.join(repo, "scripts/release/install.bat"), "utf8");
558 const ps1 = fs.readFileSync(path.join(repo, "scripts/release/install.ps1"), "utf8");
559 assert.match(ps1, /param\(\[switch\]\$NoModifyPath\)/);
560 const call = bat.split(/\r?\n/).find(line => /powershell\.exe/i.test(line));
561 assert.match(call, /-File "%~dp0install\.ps1" %\*\s*$/);
562 });
563
564 test("website: a checksum mismatch stops before any installation", t => {
565 const f = fixture(t, "website");
566 fs.writeFileSync(path.join(f.assets, "codewhale-macos-arm64"), "tampered");
567 const result = f.run();
568 assert.notEqual(result.status, 0);
569 assert.match(result.stderr, /checksum mismatch/);
570 assert.equal(fs.existsSync(path.join(f.destination, "codewhale")), false);
571 f.untouched();
572 });
573
574 test("archive: a missing second binary stops before the first installation", t => {
575 const f = fixture(t, "archive");
576 fs.unlinkSync(path.join(f.archive, "codew"));
577 const result = f.run();
578 assert.notEqual(result.status, 0);
579 assert.match(result.stderr, /not found in archive/);
580 assert.equal(fs.existsSync(path.join(f.destination, "codewhale")), false);
581 f.untouched();
582 });
583
584 test("website: Termux never downloads a Linux binary", t => {
585 const f = fixture(t, "website");
586 f.env.TERMUX_VERSION = "fixture";
587 const result = f.run();
588 assert.notEqual(result.status, 0);
589 assert.match(result.stderr, /Android\/Termux needs the Android/);
590 assert.equal(fs.existsSync(f.env.INSTALL_TEST_DOWNLOADS), false);
591 assert.equal(fs.existsSync(path.join(f.destination, "codewhale")), false);
592 f.untouched();
593 });
594
595 function addHostPayload(f) {
596 const payloads = {
597 'codewhale-extension-host': '#!/bin/sh\nexit 0\n',
598 'codewhale-extension-host.LICENSES.txt': 'offline runtime notice fixture\n',
599 'codewhale-extension-host.relink-source.tar.gz': 'offline relink fixture\n',
600 'codewhale-extension-host.release.json': '{"fixture":"already qualified by release producer"}\n',
601 };
602 let manifest = fs.readFileSync(path.join(f.assets, 'codewhale-artifacts-sha256.txt'), 'utf8');
603 for (const [name, content] of Object.entries(payloads)) {
604 fs.writeFileSync(path.join(f.archive, name), content, { mode: name === 'codewhale-extension-host' ? 0o755 : 0o644 });
605 const asset = name === 'codewhale-extension-host.release.json' ? 'codewhale-extension-hosts.json' : name.replace('codewhale-extension-host', 'codewhale-extension-host-macos-arm64').replace('.LICENSES.txt', '-LICENSES.txt').replace('.relink-source.tar.gz', '-relink-source.tar.gz');
606 fs.writeFileSync(path.join(f.assets, asset), content);
607 manifest += `${crypto.createHash('sha256').update(content).digest('hex')} ${asset}\n`;
608 }
609 fs.writeFileSync(path.join(f.assets, 'codewhale-artifacts-sha256.txt'), manifest);
610 return payloads;
611 }
612 for (const kind of ['website', 'archive']) {
613 test(`${kind}: qualified companion presence stays inert until explicit installer choice`, t => {
614 const f = fixture(t, kind), payloads = addHostPayload(f);
615 f.env.CODEWHALE_INSTALL_COMPILED_HOST = '0';
616 assert.equal(f.run().status, 0);
617 assert.equal(fs.existsSync(path.join(f.destination, 'codewhale-extension-host')), false);
618 f.env.CODEWHALE_INSTALL_COMPILED_HOST = '1';
619 const result = f.run(); assert.equal(result.status, 0, result.stderr);
620 for (const [name, content] of Object.entries(payloads)) {
621 const file = path.join(f.destination, name);
622 assert.equal(fs.readFileSync(file, 'utf8'), content);
623 assert.equal(fs.statSync(file).mode & 0o777, name === 'codewhale-extension-host' ? 0o755 : 0o644);
624 }
625 f.untouched();
626 });
627 test(`${kind}: a conflicting companion prevents the first command publication`, t => {
628 const f = fixture(t, kind); addHostPayload(f); f.prepare(); f.env.CODEWHALE_INSTALL_COMPILED_HOST = '1';
629 const foreign = path.join(f.destination, 'codewhale-extension-host.LICENSES.txt'); fs.writeFileSync(foreign, 'foreign');
630 const result = f.run(); assert.notEqual(result.status, 0); assert.ok(result.stderr.includes(foreign), result.stderr);
631 assert.equal(fs.readFileSync(foreign, 'utf8'), 'foreign'); assert.equal(fs.existsSync(path.join(f.destination, 'codewhale')), false);
632 f.untouched();
633 });
634 test(`${kind}: late companion collision rolls back every new command and image`, t => {
635 const f = fixture(t, kind); addHostPayload(f); f.env.CODEWHALE_INSTALL_COMPILED_HOST = '1';
636 executable(path.join(f.bin, 'ln'), `#!/bin/sh\ncase "$(basename "$1")" in codewhale-extension-host.LICENSES.txt) printf 'another writer' > "$2codewhale-extension-host.LICENSES.txt" ;; esac\nexec /bin/ln "$@"\n`);
637 const result = f.run(); assert.notEqual(result.status, 0, result.stdout);
638 for (const name of ['codewhale', 'codew', 'codewhale-extension-host', 'codewhale-extension-host.release.json']) assert.equal(fs.existsSync(path.join(f.destination, name)), false, name);
639 assert.equal(fs.readFileSync(path.join(f.destination, 'codewhale-extension-host.LICENSES.txt'), 'utf8'), 'another writer');
640 f.untouched();
641 });
642 }
643
644 test('website: downloaders require HTTPS and TLS 1.2+', t => {
645 const f = fixture(t, 'website');
646 const argsFile = path.join(f.root, 'curl-args');
647 f.env.INSTALL_TEST_CURL_ARGS = argsFile;
648 executable(path.join(f.bin, 'curl'), `#!/bin/sh
649 printf '%s\n' "$*" >> "$INSTALL_TEST_CURL_ARGS"
650 url=""; output=""
651 while [ "$#" -gt 0 ]; do
652 case "$1" in
653 -o) shift; output="$1" ;;
654 http*) url="$1" ;;
655 esac
656 shift
657 done
658 printf '%s\n' "$url" >> "$INSTALL_TEST_DOWNLOADS"
659 asset="$(basename "$url")"
660 cp "$INSTALL_TEST_ASSETS/$asset" "$output"
661 `);
662 const result = f.run();
663 assert.equal(result.status, 0, result.stderr);
664 const invocations = fs.readFileSync(argsFile, 'utf8').trim().split('\n');
665 assert.ok(invocations.length >= 2);
666 for (const line of invocations) {
667 assert.ok(line.includes('--proto =https'), `expected --proto =https in: ${line}`);
668 assert.ok(line.includes('--tlsv1.2'), `expected --tlsv1.2 in: ${line}`);
669 }
670 const websiteScript = fs.readFileSync(path.join(repo, 'web/public/install.sh'), 'utf8');
671 assert.match(websiteScript, /curl --proto '=https' --tlsv1\.2 -fsSL/);
672 assert.match(websiteScript, /wget --https-only -q/);
673 });
674
674 lines JAVASCRIPT