@coderook/cli 0.46.11 → 0.47.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.
@@ -2,7 +2,7 @@
2
2
  "name": "coderook",
3
3
  "displayName": "CodeRook",
4
4
  "description": "Save, browse and restore whole-snapshot versions of a project on CodeRook, with cbx or plain git, from Claude Code.",
5
- "version": "0.46.11",
5
+ "version": "0.47.0",
6
6
  "author": {
7
7
  "name": "ACCA Gaming Productions",
8
8
  "url": "https://coderook.com"
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.FOOTER_MAGIC = exports.MANIFEST_MAGIC = exports.CHUNK_MAGIC = exports.HEADER_MAGIC = exports.cutPoints = void 0;
6
+ exports.DestinationOccupied = exports.FOOTER_MAGIC = exports.MANIFEST_MAGIC = exports.CHUNK_MAGIC = exports.HEADER_MAGIC = exports.cutPoints = void 0;
7
7
  exports.chunkFrame = chunkFrame;
8
8
  exports.openChunkFrame = openChunkFrame;
9
9
  exports.packBundle = packBundle;
@@ -340,7 +340,37 @@ async function readManifest(source) {
340
340
  * verified against the digest the manifest recorded, so a damaged archive
341
341
  * cannot leave a half-written tree looking like a finished project.
342
342
  */
343
- async function unpackBundle(source, destination, report) {
343
+ /** Thrown when a bundle would replace a folder that already has something in it. */
344
+ class DestinationOccupied extends Error {
345
+ destination;
346
+ constructor(destination) {
347
+ super(`${destination} already exists and is not empty`);
348
+ this.destination = destination;
349
+ }
350
+ }
351
+ exports.DestinationOccupied = DestinationOccupied;
352
+ /** Whether something is already at this path: a file, or a folder with anything in it. */
353
+ async function occupied(destination) {
354
+ try {
355
+ const found = await (0, promises_1.stat)(destination);
356
+ return !found.isDirectory() || (await (0, promises_1.readdir)(destination)).length > 0;
357
+ }
358
+ catch (error) {
359
+ if (error.code === "ENOENT")
360
+ return false;
361
+ throw error;
362
+ }
363
+ }
364
+ async function unpackBundle(source, destination, report,
365
+ /*
366
+ The folder is replaced whole at the end. A bundle from somebody else
367
+ names that folder, so unpacking one into a folder that already held
368
+ work deleted it (audit, 16 November 2026). Replacing is now something
369
+ the person asks for.
370
+ */
371
+ options = {}) {
372
+ if (!options.replace && (await occupied(destination)))
373
+ throw new DestinationOccupied(destination);
344
374
  const manifest = await readManifest(source);
345
375
  const handle = await (0, promises_1.open)(source, "r");
346
376
  const staging = `${destination}.incoming`;
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Downloader = exports.DownloadFailed = exports.DownloadCancelled = void 0;
7
+ exports.placementProblem = placementProblem;
7
8
  exports.underway = underway;
8
9
  exports.plainReason = plainReason;
9
10
  exports.applyMode = applyMode;
@@ -23,6 +24,40 @@ const node_stream_1 = require("node:stream");
23
24
  const node_zlib_1 = require("node:zlib");
24
25
  const node_path_1 = __importDefault(require("node:path"));
25
26
  const safe_path_js_1 = require("../shared/safe_path.js");
27
+ const promises_3 = require("node:fs/promises");
28
+ /**
29
+ * Why a file of the version cannot be put at this path without harm, or null.
30
+ *
31
+ * Walks the path one name at a time from the folder: a link or junction on
32
+ * the way would carry the write somewhere else, a file where a folder is
33
+ * needed cannot hold it, and a folder where the file goes would have to be
34
+ * deleted whole. Nothing that does not exist yet is a problem.
35
+ */
36
+ async function placementProblem(destination, relative) {
37
+ const names = relative.split("/");
38
+ let at = destination;
39
+ for (const [index, name] of names.entries()) {
40
+ at = node_path_1.default.join(at, name);
41
+ const shown = names.slice(0, index + 1).join("/");
42
+ let found;
43
+ try {
44
+ found = await (0, promises_3.lstat)(at);
45
+ }
46
+ catch (error) {
47
+ if (error.code === "ENOENT")
48
+ return null;
49
+ throw error;
50
+ }
51
+ if (found.isSymbolicLink())
52
+ return `${shown} is a link to somewhere else`;
53
+ const last = index === names.length - 1;
54
+ if (last && found.isDirectory())
55
+ return `${shown} is a folder here, and the version has a file there`;
56
+ if (!last && !found.isDirectory())
57
+ return `${shown} is a file here, and the version has a folder there`;
58
+ }
59
+ return null;
60
+ }
26
61
  const chunking_js_1 = require("../shared/chunking.js");
27
62
  const identify_js_1 = require("./identify.js");
28
63
  const faults_js_1 = require("./faults.js");
@@ -533,10 +568,29 @@ class Downloader {
533
568
  * belongs to in order to find out whether it survives the trip.
534
569
  */
535
570
  async fileTo(repositoryId, versionId, file, target) {
571
+ /*
572
+ Fetched beside the file and checked before it replaces anything. It
573
+ was streamed straight over the file and never compared, so a cut or
574
+ wrong download destroyed the copy it was meant to restore
575
+ (audit, 16 November 2026).
576
+ */
577
+ if (!/^[0-9a-f]{64}$/i.test(file.sha256 ?? "")) {
578
+ throw new Error(`${file.path} has no digest to check it against; nothing was written.`);
579
+ }
536
580
  await (0, promises_1.mkdir)(node_path_1.default.dirname(target), { recursive: true });
537
- const digest = await this.fetchInto(repositoryId, versionId, file, target);
538
- await applyMode(target, file.executable === true);
539
- return digest;
581
+ const incoming = `${target}.cbx-incoming-${process.pid}-${Date.now()}`;
582
+ try {
583
+ const digest = await this.fetchInto(repositoryId, versionId, file, incoming);
584
+ if (digest.toLowerCase() !== file.sha256.toLowerCase()) {
585
+ throw new Error(`${file.path} did not arrive intact; the file here was left as it was.`);
586
+ }
587
+ await applyMode(incoming, file.executable === true);
588
+ await (0, promises_1.rename)(incoming, target);
589
+ return digest;
590
+ }
591
+ finally {
592
+ await (0, promises_1.rm)(incoming, { force: true });
593
+ }
540
594
  }
541
595
  /**
542
596
  * Reconstruct and verify every file in a Version without materialising the
@@ -1291,6 +1345,26 @@ class Downloader {
1291
1345
  }
1292
1346
  return made;
1293
1347
  };
1348
+ /*
1349
+ Looked at before anything here changes. A file arriving where the
1350
+ folder holds a directory used to remove the directory, recursively,
1351
+ with whatever unsaved or ignored work was in it; and a path through a
1352
+ link or junction already in the folder wrote or deleted outside it
1353
+ (audit, 16 November 2026). Either way the fetch now stops untouched.
1354
+ */
1355
+ const blocked = [];
1356
+ for (const file of files) {
1357
+ if (kept.has(file.path))
1358
+ continue;
1359
+ const problem = await placementProblem(destination, file.path);
1360
+ if (problem)
1361
+ blocked.push(problem);
1362
+ if (blocked.length >= 5)
1363
+ break;
1364
+ }
1365
+ if (blocked.length) {
1366
+ throw new Error(`Nothing was changed, because placing this version would remove or write through something already here:\n ${blocked.join("\n ")}\nMove those aside and fetch again.`);
1367
+ }
1294
1368
  let nextToPlace = 0;
1295
1369
  let placingFailed = false;
1296
1370
  const placeLane = async () => {
@@ -1347,6 +1421,9 @@ class Downloader {
1347
1421
  /* A path it must not write is not one it may delete either. */
1348
1422
  if ((0, safe_path_js_1.whyUnsafe)(gone))
1349
1423
  continue;
1424
+ /* Nor one reached through a link, or one that is now a folder. */
1425
+ if (await placementProblem(destination, gone))
1426
+ continue;
1350
1427
  const target = (0, safe_path_js_1.inside)(destination, gone);
1351
1428
  /*
1352
1429
  The version dropped it — but if the bytes here are no longer the
@@ -85,6 +85,8 @@ class Tracks {
85
85
  if (!token)
86
86
  throw new Error("Sign in again");
87
87
  const response = await fetch(`${this.credentials.origin()}${route}`, {
88
+ /* Every outward request has a deadline (audit, 16 November 2026). */
89
+ signal: AbortSignal.timeout(120_000),
88
90
  method: init?.method ?? "GET",
89
91
  headers: {
90
92
  accept: "application/json",
@@ -301,6 +303,7 @@ class Tracks {
301
303
  throw new Error("Sign in again");
302
304
  const response = await fetch(`${this.credentials.origin()}/v1/repositories/${repositoryId}` +
303
305
  `/versions/${versionId}/file?path=${encodeURIComponent(path)}`, {
306
+ signal: AbortSignal.timeout(10 * 60_000),
304
307
  headers: {
305
308
  authorization: `Bearer ${token}`,
306
309
  "user-agent": "CodeRook/0.1",
@@ -344,6 +347,7 @@ class Tracks {
344
347
  const response = await fetch(`${this.credentials.origin()}/v1/repositories/${repositoryId}` +
345
348
  `/objects/${digest}?kind=chunk&role=chunk&logicalSize=${bytes.byteLength}` +
346
349
  `&mediaType=${encodeURIComponent(mediaTypeForPath(path))}`, {
350
+ signal: AbortSignal.timeout(10 * 60_000),
347
351
  method: "PUT",
348
352
  headers: {
349
353
  authorization: `Bearer ${token}`,
@@ -2666,6 +2666,8 @@ class Uploader {
2666
2666
  return null;
2667
2667
  const response = await fetch(`${this.credentials.origin()}/v1/repositories/${repositoryId}` +
2668
2668
  `/stored?sha256=${declaration.sha256}`, {
2669
+ /* A lookup; a stalled one is treated as "not stored" by the catch below (audit, 16 November 2026). */
2670
+ signal: AbortSignal.timeout(30_000),
2669
2671
  headers: {
2670
2672
  accept: "application/json",
2671
2673
  authorization: `Bearer ${token}`,
@@ -1690,8 +1690,15 @@ const SECRET_NAMES = new Set([
1690
1690
  "id_dsa",
1691
1691
  "id_ecdsa",
1692
1692
  "id_ed25519",
1693
+ /* Added after the audit of 16 November 2026: tools' own secret files. */
1694
+ ".dev.vars", // Wrangler's local secrets
1695
+ ".envrc", // direnv
1696
+ ".htpasswd",
1697
+ ".pgpass",
1698
+ "terraform.tfstate",
1699
+ "terraform.tfstate.backup",
1693
1700
  ]);
1694
- const SECRET_SUFFIXES = [".pem", ".key", ".p12", ".pfx", ".keystore", ".jks"];
1701
+ const SECRET_SUFFIXES = [".pem", ".key", ".p12", ".pfx", ".keystore", ".jks", ".ppk", ".kdbx", ".tfstate", ".tfstate.backup"];
1695
1702
  /*
1696
1703
  Directories that are one program's private state, not somebody's project.
1697
1704
 
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.isGitDirectoryName = isGitDirectoryName;
7
7
  exports.isCbxDirectoryName = isCbxDirectoryName;
8
+ exports.isLinkDirectoryName = isLinkDirectoryName;
8
9
  exports.whyUnsafe = whyUnsafe;
9
10
  exports.safeParts = safeParts;
10
11
  exports.inside = inside;
@@ -48,6 +49,14 @@ function isGitDirectoryName(part) {
48
49
  function isCbxDirectoryName(part) {
49
50
  return part.split(":")[0].replace(/[. ]+$/, "").toLowerCase() === ".cbx";
50
51
  }
52
+ /**
53
+ * `.coderook`, the folder holding a folder's link to its project. A version
54
+ * carrying one could point the next save at somebody else's project; the
55
+ * clients never upload it, so nothing real is lost (audit, 16 November 2026).
56
+ */
57
+ function isLinkDirectoryName(part) {
58
+ return part.split(":")[0].replace(/[. ]+$/, "").toLowerCase() === ".coderook";
59
+ }
51
60
  /** Why this path must not be written, or null when it may. */
52
61
  function whyUnsafe(relative) {
53
62
  if (!relative)
@@ -64,6 +73,8 @@ function whyUnsafe(relative) {
64
73
  return "it writes into git's own directory";
65
74
  if (isCbxDirectoryName(part))
66
75
  return "it writes into CBX's own history";
76
+ if (isLinkDirectoryName(part))
77
+ return "it writes into the folder's link to its project";
67
78
  /* A stream or a drive-relative name on Windows; refused by the service too. */
68
79
  if (process.platform === "win32" && part.includes(":")) {
69
80
  return "it names a Windows data stream";
@@ -769,6 +769,7 @@ async function collaborators(repositoryId) {
769
769
  collaborators: (body.collaborators ?? []).map((row) => ({
770
770
  userId: String(row.userId ?? ""),
771
771
  displayName: String(row.displayName ?? ""),
772
+ username: String(row.username ?? ""),
772
773
  email: String(row.email ?? ""),
773
774
  role: String(row.role ?? "member"),
774
775
  })),
@@ -47,6 +47,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
47
47
  * anything about it is out of the ordinary: other arguments, a Node that is
48
48
  * too old, no local history here, or the unread-messages reminder being due.
49
49
  */
50
+ /* First, so nothing reaches the terminal unfiltered (terminal_guard.ts). */
51
+ require("./terminal_guard.js");
50
52
  const reminder_gate_js_1 = require("./reminder_gate.js");
51
53
  async function quickStatus() {
52
54
  const argv = process.argv.slice(2);
@@ -694,10 +694,10 @@ async function fetchBunRuntime(target, to) {
694
694
  const pkg = `bun-${osOf(target) === "macos" ? "darwin" : osOf(target)}-${archOf(target) === "arm64" ? "aarch64" : "x64"}`;
695
695
  console.log(dim(`Fetching Bun ${version}'s runtime for ${target} (@oven/${pkg})…`));
696
696
  try {
697
- const meta = (await (await fetch(`https://registry.npmjs.org/@oven/${pkg}/${version}`)).json());
697
+ const meta = (await (await fetch(`https://registry.npmjs.org/@oven/${pkg}/${version}`, { signal: AbortSignal.timeout(60_000) })).json());
698
698
  if (!meta.dist?.tarball || !meta.dist.integrity?.startsWith("sha512-"))
699
699
  throw new Error("npm did not describe the package");
700
- const tarball = Buffer.from(await (await fetch(meta.dist.tarball)).arrayBuffer());
700
+ const tarball = Buffer.from(await (await fetch(meta.dist.tarball, { signal: AbortSignal.timeout(15 * 60_000) })).arrayBuffer());
701
701
  const digest = `sha512-${(0, node_crypto_1.createHash)("sha512").update(tarball).digest("base64")}`;
702
702
  if (digest !== meta.dist.integrity)
703
703
  throw new Error("the download does not match npm's digest");
@@ -653,7 +653,8 @@ async function commandStatus(parsed) {
653
653
  });
654
654
  console.log(bold(node_path_1.default.basename(folder)) + dim(` ${folder}`));
655
655
  console.log(link
656
- ? `Account holds ${accent(`v${link.sequence}`)} · ${Object.keys(link.manifest).length} ${Object.keys(link.manifest).length === 1 ? "file" : "files"} ${dim(`(${link.slug})`)}`
656
+ /* "Account holds" read as the project's latest; it is what this folder is on (exercise 2). */
657
+ ? `This folder is on ${accent(`v${link.sequence}`)} · ${Object.keys(link.manifest).length} ${Object.keys(link.manifest).length === 1 ? "file" : "files"} ${dim(`(${link.slug})`)}`
657
658
  : dim("This folder is not linked to a project."));
658
659
  if (!link) {
659
660
  const likes = (0, folder_match_js_1.similarProjects)(await (0, api_js_2.projects)().catch(() => []), node_path_1.default.basename(folder));
@@ -1547,7 +1548,8 @@ Pass ${accent("--allow-secrets")} if these are not real keys.`);
1547
1548
  if (plan.repositoryCreated)
1548
1549
  createdRepositoryId = plan.repositoryId;
1549
1550
  console.log(plan.estimated
1550
- ? `${accent("Upload plan")} ${bytes(plan.sourceBytes)} selected; ${bytes(plan.chargeableBytes)} of changes to send.`
1551
+ /* Before compression: the summary's "sent" is after it, and the two read as a contradiction (exercise 2). */
1552
+ ? `${accent("Upload plan")} ${bytes(plan.sourceBytes)} selected; ${bytes(plan.chargeableBytes)} of changes, compressed before sending.`
1551
1553
  : `${accent("Upload plan")} ${bytes(plan.sourceBytes)} selected → ` +
1552
1554
  `${bytes(plan.compactedBytes)} compacted; ${bytes(plan.chargeableBytes)} new storage.`);
1553
1555
  console.log(plan.estimated
@@ -1725,8 +1727,9 @@ The connection failed: ${text}`));
1725
1727
  */
1726
1728
  const repacked = Math.min(result.repackedFiles ?? 0, result.sentFiles);
1727
1729
  const changedSent = result.sentFiles - repacked;
1728
- console.log(`Saved ${accent(`v${result.sequence}`)} · sent ${bytes(result.sentBytes)} in ` +
1729
- `${changedSent} file${changedSent === 1 ? "" : "s"}` +
1730
+ console.log(`Saved ${accent(`v${result.sequence}`)} · sent ${bytes(result.sentBytes)} ` +
1731
+ /* "sent 565 B in 0 files, 11 removed" read as a failure; nothing but the list of changes went (exercise 2). */
1732
+ (changedSent ? `in ${changedSent} file${changedSent === 1 ? "" : "s"}` : "(the list of changes, no file contents)") +
1730
1733
  (repacked ? ` (and re-packed ${repacked} unchanged small file${repacked === 1 ? "" : "s"} together)` : "") +
1731
1734
  /*
1732
1735
  Three different things, kept apart. Sent is what crossed the wire.
@@ -2090,8 +2093,9 @@ trackName) {
2090
2093
  let result;
2091
2094
  try {
2092
2095
  result = await downloader.run(repositoryId, latest.id, destination, (progress) => {
2093
- line(` ${track(progress.percent)} ${String(progress.percent).padStart(3)}% ` +
2094
- `${progress.files}/${progress.totalFiles} ` +
2096
+ /* The bar and percent count bytes, the fraction files: "11% 284/298" read as a contradiction (exercise 2). */
2097
+ line(` ${track(progress.percent)} ${String(progress.percent).padStart(3)}% of the bytes ` +
2098
+ `${progress.files}/${progress.totalFiles} files ` +
2095
2099
  dim(progress.path.slice(-40)));
2096
2100
  },
2097
2101
  // What this folder received last time, so a file the project has since
@@ -2322,10 +2326,23 @@ async function commandUnbundle(parsed) {
2322
2326
  }
2323
2327
  const destination = node_path_1.default.resolve(parsed.positional[1] ?? suggested);
2324
2328
  const line = progressLine();
2325
- const result = await (0, cbx_js_1.unpackBundle)(node_path_1.default.resolve(source), destination, (progress) => {
2326
- line(` ${track(progress.percent)} ${String(progress.percent).padStart(3)}% ` +
2327
- dim(progress.path.slice(-40)));
2328
- });
2329
+ let result;
2330
+ try {
2331
+ result = await (0, cbx_js_1.unpackBundle)(node_path_1.default.resolve(source), destination, (progress) => {
2332
+ line(` ${track(progress.percent)} ${String(progress.percent).padStart(3)}% ` +
2333
+ dim(progress.path.slice(-40)));
2334
+ },
2335
+ /* The folder is replaced whole, so an existing one is kept unless asked. */
2336
+ { replace: hasFlag(parsed, "f", "force") });
2337
+ }
2338
+ catch (error) {
2339
+ if (!(error instanceof cbx_js_1.DestinationOccupied))
2340
+ throw error;
2341
+ done(line);
2342
+ console.error(red(`${destination} already has files in it, and unbundling replaces the whole folder.`));
2343
+ console.error("Name an empty or new folder: cbx unbundle <file.cbx> <folder>, or add --force to replace it.");
2344
+ return 1;
2345
+ }
2329
2346
  done(line);
2330
2347
  console.log(`${fileCount(result.files)} · ${bytes(result.bytes)} into ${destination}`);
2331
2348
  return 0;
@@ -2353,7 +2370,7 @@ async function commandDoctor() {
2353
2370
  console.log(`cbx ${version_js_1.VERSION} · Node ${node_process_1.default.versions.node} · ${node_process_1.default.platform}`);
2354
2371
  console.log(`Config: ${(0, config_js_1.configDirectory)()}`);
2355
2372
  console.log(service
2356
- ? `Service: ${service.status} · schema ${service.schemaVersion}` +
2373
+ ? `Service: ${service.status}` +
2357
2374
  (service.contentEncodings ? ` · accepts ${service.contentEncodings.join(", ")}` : "")
2358
2375
  : red("Service: unreachable"));
2359
2376
  const token = await (0, config_js_1.loadToken)();
@@ -3208,6 +3225,23 @@ const SPECS = [
3208
3225
  ],
3209
3226
  run: project_commands_js_1.commandVersions,
3210
3227
  },
3228
+ {
3229
+ name: "files",
3230
+ aliases: ["ls"],
3231
+ group: "Versions and releases",
3232
+ summary: "what a saved version holds",
3233
+ usage: "files [project] [version]",
3234
+ detail: "Every file in a saved version, with its size. The current one unless you\n" +
3235
+ "name another (12 or v12). Run it inside a linked folder to leave the\n" +
3236
+ "project out; --path narrows it to one folder.",
3237
+ options: [
3238
+ { flags: "--path <prefix>", description: "only files under this path, e.g. src/" },
3239
+ { flags: "--version <n>", description: "which version (the second argument does the same)" },
3240
+ { flags: "--json", description: "the list as JSON" },
3241
+ ],
3242
+ examples: ["cbx files", "cbx files my-project 12 --path stress/"],
3243
+ run: project_commands_js_1.commandFiles,
3244
+ },
3211
3245
  {
3212
3246
  name: "workspace",
3213
3247
  group: "Workspaces",
@@ -4407,8 +4441,8 @@ const SPECS = [
4407
4441
  name: "unbundle",
4408
4442
  group: "Mods and bundles",
4409
4443
  summary: "extract a .cbx",
4410
- usage: "unbundle <file> [dir]",
4411
- detail: "Unpacks a .cbx made by cbx bundle into a new folder, named after the folder it was made from unless you give one.",
4444
+ usage: "unbundle <file> [dir] [--force]",
4445
+ detail: "Unpacks a .cbx made by cbx bundle into a new folder, named after the folder it was made from unless you give one. A folder that already has files in it is left alone unless you add --force, which replaces it.",
4412
4446
  examples: ["cbx unbundle my-game.cbx", "cbx unbundle my-game.cbx restored-game"],
4413
4447
  run: commandUnbundle,
4414
4448
  },
@@ -33,7 +33,19 @@ const node_path_1 = __importDefault(require("node:path"));
33
33
  exports.DEFAULT_API = "https://api.coderook.com";
34
34
  function apiOrigin() {
35
35
  /* CODEROOK_API is what a run is handed (with CODEROOK_TOKEN), so cbx inside a run needs no setup. */
36
- return (process.env.CODEROOK_API_URL || process.env.CODEROOK_API || exports.DEFAULT_API).replace(/\/+$/, "");
36
+ const origin = (process.env.CODEROOK_API_URL || process.env.CODEROOK_API || exports.DEFAULT_API).replace(/\/+$/, "");
37
+ /*
38
+ The sign-in token goes with every request to it, so never over plain
39
+ http to another machine (audit, 16 November 2026). This machine's own
40
+ addresses stay allowed for a local service or test bench.
41
+ */
42
+ if (/^http:\/\//i.test(origin)) {
43
+ const host = origin.replace(/^http:\/\//i, "").split(/[/:]/)[0].toLowerCase();
44
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(host) && !host.endsWith(".localhost")) {
45
+ throw new Error(`CODEROOK_API must use https (${origin}); the sign-in token is sent with every request.`);
46
+ }
47
+ }
48
+ return origin;
37
49
  }
38
50
  /**
39
51
  * The website that goes with the service, for a link somebody can open.
@@ -96,9 +108,14 @@ const legacyLinksFile = () => node_path_1.default.join(configDirectory(), "links
96
108
  * rather than exceptional.
97
109
  */
98
110
  async function writePrivate(target, body) {
99
- await (0, promises_1.mkdir)(node_path_1.default.dirname(target), { recursive: true });
111
+ /*
112
+ Private from the moment it exists: made with the mode rather than tightened
113
+ after, which left it readable by other accounts for a moment, and the
114
+ folder kept to its owner (audit, 16 November 2026).
115
+ */
116
+ await (0, promises_1.mkdir)(node_path_1.default.dirname(target), { recursive: true, mode: 0o700 });
100
117
  const temporary = `${target}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
101
- await (0, promises_1.writeFile)(temporary, body, "utf8");
118
+ await (0, promises_1.writeFile)(temporary, body, { encoding: "utf8", mode: 0o600 });
102
119
  // Windows ignores the mode; on everything else this is what keeps the
103
120
  // token out of other accounts' reach.
104
121
  await (0, promises_1.chmod)(temporary, 0o600).catch(() => undefined);
@@ -53,6 +53,8 @@ async function call(route, method = "GET", body, raw, auth = true) {
53
53
  method,
54
54
  headers,
55
55
  body: raw ?? (body === undefined ? undefined : JSON.stringify(body)),
56
+ /* Every outward request has a deadline; an upload gets a long one (audit, 16 November 2026). */
57
+ signal: AbortSignal.timeout(raw ? 30 * 60_000 : 60_000),
56
58
  });
57
59
  const text = await response.text();
58
60
  let parsed = {};
@@ -212,6 +212,7 @@ async function pythonRuntime(cache, version, target, say) {
212
212
  return (0, promises_1.readFile)(node_path_1.default.join(folder, cached));
213
213
  const release = (await (await fetch("https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest", {
214
214
  headers: { accept: "application/vnd.github+json", "user-agent": "coderook-cli" },
215
+ signal: AbortSignal.timeout(60_000),
215
216
  })).json());
216
217
  const asset = (release.assets ?? []).find((one) => wanted.test(one.name));
217
218
  if (!asset)
@@ -219,7 +220,7 @@ async function pythonRuntime(cache, version, target, say) {
219
220
  if (!asset.digest?.startsWith("sha256:"))
220
221
  throw new Error("the release does not publish a digest for it");
221
222
  say(`Fetching ${asset.name}…`);
222
- const body = Buffer.from(await (await fetch(asset.browser_download_url)).arrayBuffer());
223
+ const body = Buffer.from(await (await fetch(asset.browser_download_url, { signal: AbortSignal.timeout(15 * 60_000) })).arrayBuffer());
223
224
  if ((0, node_crypto_1.createHash)("sha256").update(body).digest("hex") !== asset.digest.slice("sha256:".length)) {
224
225
  throw new Error("the download does not match its published digest");
225
226
  }
@@ -20,6 +20,7 @@ exports.splitVisibility = splitVisibility;
20
20
  exports.offeredPublicly = offeredPublicly;
21
21
  exports.agreed = agreed;
22
22
  exports.commandVisibility = commandVisibility;
23
+ exports.commandFiles = commandFiles;
23
24
  exports.commandVersions = commandVersions;
24
25
  const node_process_1 = __importDefault(require("node:process"));
25
26
  const promises_1 = require("node:readline/promises");
@@ -325,6 +326,47 @@ async function commandVisibility(parsed) {
325
326
  return 0;
326
327
  }
327
328
  /** Every saved version of a project, newest first. */
329
+ /*
330
+ What a saved version holds: its files, with sizes.
331
+
332
+ There was no way to ask from the terminal. An agent checking that a rename
333
+ had been saved tried "cbx files", was told "Did you mean cbx rules?", and
334
+ had to piece it together from a diff (2026-11-11 exercise 2).
335
+ */
336
+ async function commandFiles(parsed) {
337
+ const project = await resolveProject(parsed.positional[0]);
338
+ if (!project)
339
+ return 1;
340
+ const saved = await (0, api_js_1.versions)(project.id);
341
+ if (!saved.length) {
342
+ console.log((0, colour_js_1.dim)("Nothing has been saved to this project yet."));
343
+ return 0;
344
+ }
345
+ const asked = parsed.positional[1] ?? (typeof parsed.flags.get("version") === "string" ? String(parsed.flags.get("version")) : undefined);
346
+ const sequence = asked ? Number(asked.replace(/^v/i, "")) : null;
347
+ const version = sequence !== null
348
+ ? saved.find((one) => one.sequence === sequence)
349
+ : saved.find((one) => one.head) ?? saved[0];
350
+ if (!version) {
351
+ console.error((0, colour_js_1.red)(`${project.name} has no v${asked?.replace(/^v/i, "")}. cbx versions lists them.`));
352
+ return 1;
353
+ }
354
+ const prefix = typeof parsed.flags.get("path") === "string" ? String(parsed.flags.get("path")) : "";
355
+ const listed = await (0, api_js_1.callApi)(`/v1/repositories/${encodeURIComponent(project.id)}/versions/${encodeURIComponent(version.id)}/files`);
356
+ const files = (listed.files ?? [])
357
+ .map((one) => ({ path: String(one.path ?? ""), size: Number(one.sourceSize ?? 0) }))
358
+ .filter((one) => one.path.startsWith(prefix))
359
+ .sort((a, b) => a.path.localeCompare(b.path));
360
+ if (parsed.flags.get("json") === true) {
361
+ console.log(JSON.stringify({ version: version.sequence, files }, null, 2));
362
+ return 0;
363
+ }
364
+ console.log(`${(0, colour_js_1.bold)(project.name)} ${(0, colour_js_1.accent)(`v${version.sequence}`)} ` +
365
+ (0, colour_js_1.dim)(`${files.length.toLocaleString("en-US")} file${files.length === 1 ? "" : "s"}${prefix ? ` under ${prefix}` : ""}`));
366
+ for (const one of files)
367
+ console.log(` ${bytes(one.size).padStart(9)} ${one.path}`);
368
+ return 0;
369
+ }
328
370
  async function commandVersions(parsed) {
329
371
  const project = await resolveProject(parsed.positional[0]);
330
372
  if (!project)
@@ -41,7 +41,7 @@ exports.LISTING_ORDER = [
41
41
  "status", "submit", "diff", "get", "track", "ignore", "licence",
42
42
  "init", "save", "log", "restore", "switch", "push", "pull",
43
43
  "tracks", "line-rules", "merges", "merge", "propose", "proposals", "pr",
44
- "versions", "mark", "notes", "labels", "promote", "release", "releases", "attach", "held", "review", "undo",
44
+ "versions", "files", "mark", "notes", "labels", "promote", "release", "releases", "attach", "held", "review", "undo",
45
45
  "take-down", "verify", "deps",
46
46
  "about", "features", "visibility", "ai", "private", "upload-rules", "people", "watch", "hooks", "secret", "assistant",
47
47
  "security", "pages", "fork", "hand-over", "delete",
@@ -319,7 +319,7 @@ async function commandCollaborators(parsed) {
319
319
  if (changing !== undefined || removing !== undefined || cancelling !== undefined) {
320
320
  const wanted = changing ?? removing ?? cancelling;
321
321
  if (typeof wanted !== "string" || !wanted.trim()) {
322
- console.error((0, colour_js_1.red)("Who? Name them by email address or display name."));
322
+ console.error((0, colour_js_1.red)("Who? Name them by @username, display name, or their invite's email address."));
323
323
  return 1;
324
324
  }
325
325
  const who = wanted.trim().toLowerCase();
@@ -334,7 +334,8 @@ async function commandCollaborators(parsed) {
334
334
  console.log((0, colour_js_1.green)(`Withdrew the invite to ${pending.email}. Its link no longer works.`));
335
335
  return 0;
336
336
  }
337
- const person = people.collaborators.find((one) => one.email.toLowerCase() === who ||
337
+ const person = people.collaborators.find((one) => (one.email && one.email.toLowerCase() === who) ||
338
+ (one.username && one.username.toLowerCase() === who.replace(/^@/, "")) ||
338
339
  one.displayName.toLowerCase() === who ||
339
340
  one.userId === wanted.trim());
340
341
  if (!person) {
@@ -392,7 +393,7 @@ async function commandCollaborators(parsed) {
392
393
  console.log((0, colour_js_1.dim)(" Nobody else has access."));
393
394
  }
394
395
  for (const person of people.collaborators) {
395
- console.log(` ${(person.displayName || person.email).padEnd(28)} ${(0, colour_js_1.dim)(person.role)}`);
396
+ console.log(` ${(person.displayName || (person.username ? `@${person.username}` : person.email)).padEnd(28)} ${(0, colour_js_1.dim)(person.role)}`);
396
397
  }
397
398
  if (people.invites.length) {
398
399
  console.log("");
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.printable = printable;
4
+ /**
5
+ * Text from other people never drives the terminal.
6
+ *
7
+ * Issue titles, comments, names, version messages and the service's own
8
+ * error text were printed as they came. A title holding an OSC 52 sequence
9
+ * wrote the reader's clipboard, an OSC 8 one disguised a link, and others
10
+ * retitled the window or moved the cursor to overwrite what came before
11
+ * (security audit, 16 November 2026).
12
+ *
13
+ * Filtered once, here, for everything written to a terminal: the few
14
+ * sequences cbx itself prints (colours, clearing a line or the screen) pass,
15
+ * and every other escape sequence and C1 control is dropped. Output that is
16
+ * piped or redirected is left byte for byte, and so is anything written as
17
+ * bytes rather than text.
18
+ */
19
+ const ESCAPES = new RegExp([
20
+ "\\u001b\\][\\s\\S]*?(?:\\u0007|\\u001b\\\\)", // OSC ... BEL or ST
21
+ "\\u001b\\][^\\u0007\\u001b]*$", // OSC never ended in this write
22
+ "\\u001b[PX^_][\\s\\S]*?\\u001b\\\\", // DCS, SOS, PM, APC ... ST
23
+ "\\u001b\\[[0-?]*[ -/]*[@-~]", // CSI
24
+ "\\u001b[^\\[\\]PX^_]", // any other two-character escape
25
+ "[\\u0080-\\u009f]", // C1 controls
26
+ ].join("|"), "g");
27
+ /** CSI sequences cbx prints itself: colours (m), clearing a line (K) or the screen (J), cursor home (H). */
28
+ const OWN = /^\u001b\[[0-9;]*[mKJH]$/;
29
+ function printable(text) {
30
+ return text.replace(ESCAPES, (found) => (OWN.test(found) ? found : ""));
31
+ }
32
+ for (const stream of [process.stdout, process.stderr]) {
33
+ if (!stream.isTTY)
34
+ continue;
35
+ const write = stream.write.bind(stream);
36
+ stream.write = ((chunk, ...rest) => write(typeof chunk === "string" ? printable(chunk) : chunk, ...rest));
37
+ }
@@ -77,6 +77,20 @@ async function commandVerify(parsed) {
77
77
  console.error((0, colour_js_1.red)("The manifest's signature does not check out. Do not trust these files."));
78
78
  return 1;
79
79
  }
80
+ /*
81
+ One key signs every project's manifests, so a valid signature alone said
82
+ only that CodeRook signed *some* release. It must be the one asked about,
83
+ or another project's manifest could vouch for these files
84
+ (audit, 16 November 2026).
85
+ */
86
+ if (String(answer.manifest.project ?? "").toLowerCase() !== project.toLowerCase() ||
87
+ String(answer.manifest.release ?? "") !== release) {
88
+ console.error((0, colour_js_1.red)(`The signed manifest is for ${answer.manifest.project} ${answer.manifest.release}, not ${project} ${release}. Do not trust these files.`));
89
+ return 1;
90
+ }
91
+ if (key === answer.publicKey && typeof pinned !== "string" && !(exports.PINNED_RELEASE_KEY && (0, config_js_1.apiOrigin)() === config_js_1.DEFAULT_API)) {
92
+ console.log((0, colour_js_1.dim)("The signing key came from the same service as the manifest, so this checks the files, not the service. Pass --key to pin one."));
93
+ }
80
94
  console.log(`${(0, colour_js_1.green)("✓")} Signed manifest for ${(0, colour_js_1.bold)(`${answer.manifest.project} ${answer.manifest.release}`)} ${(0, colour_js_1.dim)(`(key ${key.slice(0, 12)}…)`)}`);
81
95
  let failed = false;
82
96
  for (const file of files) {