nano-brain 2026.11.2113 → 2026.11.2115

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.
@@ -60,19 +60,63 @@ function safeUnlink(p) {
60
60
  }
61
61
  }
62
62
 
63
+ // Release downloads start at github.com and are redirected to GitHub's asset
64
+ // CDN. Only follow a redirect that stays on https and on a GitHub-owned host,
65
+ // so a tampered or hijacked response cannot point the installer at another
66
+ // origin; anything else is a non-retryable "SECURITY:" failure (#659).
67
+ const MAX_REDIRECTS = 5;
68
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
69
+
70
+ function isAllowedDownloadHost(hostname) {
71
+ const host = String(hostname).toLowerCase();
72
+ return host === "github.com" || host.endsWith(".githubusercontent.com");
73
+ }
74
+
75
+ // Returns the absolute URL to follow for a redirect response, resolving a
76
+ // relative Location against the URL that produced it. Throws when the hop
77
+ // budget is spent or the target is not an allowed https GitHub host.
78
+ function nextRedirectURL(currentUrl, location, redirectsLeft) {
79
+ if (redirectsLeft <= 0) {
80
+ throw new Error(`Download failed: too many redirects (more than ${MAX_REDIRECTS})`);
81
+ }
82
+ if (!location) {
83
+ throw new Error("Download failed: redirect without a Location header");
84
+ }
85
+ let target;
86
+ try {
87
+ target = new URL(location, currentUrl);
88
+ } catch (_) {
89
+ throw new Error(`SECURITY: refusing redirect to unparseable location ${JSON.stringify(location)}`);
90
+ }
91
+ if (target.protocol !== "https:" || !isAllowedDownloadHost(target.hostname)) {
92
+ throw new Error(
93
+ `SECURITY: refusing redirect from ${currentUrl} to ${target.protocol}//${target.host} ` +
94
+ `(only https://github.com and https://*.githubusercontent.com are allowed)`
95
+ );
96
+ }
97
+ return target.href;
98
+ }
99
+
63
100
  // file.close() is asynchronous; the fd is only released when its callback
64
101
  // fires. Every unlink / recursive-redirect / reject is therefore deferred into
65
102
  // file.close(() => …) so the partial file is gone (and not re-opened by a
66
103
  // racing redirect) before we act — otherwise Windows unlink fails with EPERM
67
104
  // while the fd is open, and a raw request error would leak the write stream.
68
- function download(url, dest) {
105
+ function download(url, dest, redirectsLeft = MAX_REDIRECTS) {
69
106
  return new Promise((resolve, reject) => {
70
107
  const file = fs.createWriteStream(dest);
71
108
  https.get(url, (res) => {
72
- if (res.statusCode === 301 || res.statusCode === 302) {
109
+ if (REDIRECT_STATUSES.has(res.statusCode)) {
110
+ let next, redirectErr;
111
+ try {
112
+ next = nextRedirectURL(url, res.headers.location, redirectsLeft);
113
+ } catch (err) {
114
+ redirectErr = err;
115
+ }
73
116
  file.close(() => {
74
117
  safeUnlink(dest);
75
- download(res.headers.location, dest).then(resolve).catch(reject);
118
+ if (redirectErr) return reject(redirectErr);
119
+ download(next, dest, redirectsLeft - 1).then(resolve).catch(reject);
76
120
  });
77
121
  return;
78
122
  }
@@ -105,15 +149,22 @@ function download(url, dest) {
105
149
  });
106
150
  }
107
151
 
108
- function downloadWithHash(url, dest) {
152
+ function downloadWithHash(url, dest, redirectsLeft = MAX_REDIRECTS) {
109
153
  return new Promise((resolve, reject) => {
110
154
  const file = fs.createWriteStream(dest);
111
155
  const hash = crypto.createHash("sha256");
112
156
  https.get(url, (res) => {
113
- if (res.statusCode === 301 || res.statusCode === 302) {
157
+ if (REDIRECT_STATUSES.has(res.statusCode)) {
158
+ let next, redirectErr;
159
+ try {
160
+ next = nextRedirectURL(url, res.headers.location, redirectsLeft);
161
+ } catch (err) {
162
+ redirectErr = err;
163
+ }
114
164
  file.close(() => {
115
165
  safeUnlink(dest);
116
- downloadWithHash(res.headers.location, dest).then(resolve).catch(reject);
166
+ if (redirectErr) return reject(redirectErr);
167
+ downloadWithHash(next, dest, redirectsLeft - 1).then(resolve).catch(reject);
117
168
  });
118
169
  return;
119
170
  }
@@ -155,6 +206,21 @@ function parseSHA256Line(content, targetFilename) {
155
206
  return null;
156
207
  }
157
208
 
209
+ // A release without a usable checksum is treated like a checksum mismatch:
210
+ // delete the downloaded binary and fail with a non-retryable "SECURITY:" error
211
+ // rather than install something unverified (#659). install.sh does the same.
212
+ function unverifiableError(tag, assetName, binPath, reason) {
213
+ safeUnlink(binPath);
214
+ return new Error(
215
+ `SECURITY: cannot verify ${assetName} from release ${tag}: ${reason}\n` +
216
+ `The downloaded binary has been deleted. The release may be incomplete ` +
217
+ `(see https://github.com/${REPO}/releases/tag/${tag}) or the checksum download was blocked.\n` +
218
+ ` - Retry later, or install a different version.\n` +
219
+ ` - To install without verification (not recommended), set NANO_BRAIN_SKIP_SHA_VERIFY=1.\n` +
220
+ ` - Build from source: CGO_ENABLED=0 go build -o nano-brain ./cmd/nano-brain`
221
+ );
222
+ }
223
+
158
224
  async function verifySHA256(tag, assetName, binPath, computedHex) {
159
225
  const sumsUrl = `https://github.com/${REPO}/releases/download/${tag}/SHA256SUMS`;
160
226
  const sumsPath = `${binPath}.SHA256SUMS.tmp`;
@@ -163,16 +229,15 @@ async function verifySHA256(tag, assetName, binPath, computedHex) {
163
229
  await download(sumsUrl, sumsPath);
164
230
  sumsContent = fs.readFileSync(sumsPath, "utf8");
165
231
  } catch (err) {
166
- console.warn(`⚠ SHA256SUMS not available for ${tag} (${err.message}); skipping integrity verification.`);
167
- return;
232
+ const detail = String(err && err.message ? err.message : err).replace(/^SECURITY:\s*/, "");
233
+ throw unverifiableError(tag, assetName, binPath, `SHA256SUMS could not be downloaded (${detail})`);
168
234
  } finally {
169
235
  safeUnlink(sumsPath);
170
236
  }
171
237
 
172
238
  const expectedHex = parseSHA256Line(sumsContent, assetName);
173
239
  if (!expectedHex) {
174
- console.warn(`⚠ ${assetName} not listed in SHA256SUMS for ${tag}; skipping integrity verification.`);
175
- return;
240
+ throw unverifiableError(tag, assetName, binPath, `SHA256SUMS has no entry for ${assetName}`);
176
241
  }
177
242
 
178
243
  if (expectedHex.toLowerCase() !== computedHex.toLowerCase()) {
@@ -397,4 +462,4 @@ if (require.main === module) {
397
462
  main();
398
463
  }
399
464
 
400
- module.exports = { parseSHA256Line, download, downloadWithHash, verifySHA256, tryAutoLink, safeUnlink, ensureBinary, binaryPath, getPlatformKey, platformExtension, binaryMatchesVersion };
465
+ module.exports = { parseSHA256Line, isAllowedDownloadHost, download, downloadWithHash, verifySHA256, tryAutoLink, safeUnlink, ensureBinary, binaryPath, getPlatformKey, platformExtension, binaryMatchesVersion };
@@ -7,7 +7,10 @@ const path = require("node:path");
7
7
  const os = require("node:os");
8
8
  const crypto = require("node:crypto");
9
9
  const { spawnSync } = require("node:child_process");
10
- const { parseSHA256Line, tryAutoLink, safeUnlink, download, downloadWithHash, ensureBinary, binaryPath, getPlatformKey, platformExtension, binaryMatchesVersion } = require("./postinstall");
10
+ const https = require("node:https");
11
+ const { EventEmitter } = require("node:events");
12
+ const { Readable } = require("node:stream");
13
+ const { parseSHA256Line, isAllowedDownloadHost, tryAutoLink, safeUnlink, download, downloadWithHash, ensureBinary, binaryPath, getPlatformKey, platformExtension, binaryMatchesVersion } = require("./postinstall");
11
14
  const VERSION = require("../package.json").version;
12
15
  const isWin = os.platform() === "win32";
13
16
 
@@ -496,3 +499,255 @@ test("TestAutoLink_MacOS_TargetPath", (t) => {
496
499
  assert.ok(calls.some((c) => c.fn === "copyFileSync" && c.dst === targetPath), "should copy to ~/Library/nano-brain/bin/nano-brain");
497
500
  assert.ok(calls.some((c) => c.fn === "mkdirSync" && c.dir === targetDir), "should mkdir ~/Library/nano-brain/bin");
498
501
  });
502
+
503
+ // --- #659: checksum verification fails closed; redirects stay on GitHub ---
504
+
505
+ // Replace https.get with an in-memory responder so these tests never touch the
506
+ // network. `respond(url)` returns { status, headers, body } or { error }.
507
+ // Returns the list of requested URLs.
508
+ const REAL_HTTPS_GET = https.get;
509
+ function stubHttps(t, respond) {
510
+ const requested = [];
511
+ https.get = (url, opts, cb) => {
512
+ if (typeof opts === "function") cb = opts;
513
+ requested.push(String(url));
514
+ const req = new EventEmitter();
515
+ const r = respond(String(url));
516
+ setImmediate(() => {
517
+ if (r.error) return req.emit("error", r.error);
518
+ const res = Readable.from(r.body === undefined ? [] : [Buffer.from(r.body)]);
519
+ res.statusCode = r.status;
520
+ res.headers = r.headers || {};
521
+ cb(res);
522
+ });
523
+ return req;
524
+ };
525
+ t.after(() => { https.get = REAL_HTTPS_GET; });
526
+ return requested;
527
+ }
528
+
529
+ // Force ensureBinary() down the download path: move any real binary aside and
530
+ // restore it afterwards, removing whatever the test installed.
531
+ function withoutInstalledBinary(t) {
532
+ const bin = binaryPath();
533
+ const backup = `${bin}.itest659.bak`;
534
+ const hadReal = fs.existsSync(bin);
535
+ if (hadReal) fs.renameSync(bin, backup);
536
+ t.after(() => {
537
+ safeUnlink(bin);
538
+ if (hadReal) fs.renameSync(backup, bin);
539
+ });
540
+ return bin;
541
+ }
542
+
543
+ function captureStderr(t) {
544
+ const lines = [];
545
+ const realError = console.error;
546
+ console.error = (...args) => lines.push(args.join(" "));
547
+ t.after(() => { console.error = realError; });
548
+ return lines;
549
+ }
550
+
551
+ // main() and ensureBinary() key off err.message starting with "SECURITY:", so
552
+ // assert on the message itself (assert.rejects' regex form matches String(err)).
553
+ function securityError(re) {
554
+ return (err) => {
555
+ assert.ok(err.message.startsWith("SECURITY:"), err.message);
556
+ assert.match(err.message, re);
557
+ return true;
558
+ };
559
+ }
560
+
561
+ // Redirect the first request only; anything requested after that is served,
562
+ // so code that wrongly follows the redirect fails an assertion instead of
563
+ // looping forever.
564
+ function redirectOnce(location) {
565
+ let first = true;
566
+ return () => {
567
+ if (!first) return { status: 200, body: "followed" };
568
+ first = false;
569
+ return { status: 302, headers: { location } };
570
+ };
571
+ }
572
+
573
+ const FAKE_BINARY = "fake nano-brain binary for #659 tests\n";
574
+ const FAKE_BINARY_SHA = crypto.createHash("sha256").update(FAKE_BINARY).digest("hex");
575
+ const ASSET_NAME = `nano-brain-${getPlatformKey()}${platformExtension()}`;
576
+ const isAssetURL = (url) => url.endsWith(`/${ASSET_NAME}`);
577
+ const isSumsURL = (url) => url.endsWith("/SHA256SUMS");
578
+
579
+ test("ensureBinary: missing SHA256SUMS is a SECURITY failure and leaves no binary (#659)", async (t) => {
580
+ const bin = withoutInstalledBinary(t);
581
+ captureStderr(t);
582
+ stubHttps(t, (url) => (isAssetURL(url) ? { status: 200, body: FAKE_BINARY } : { status: 404 }));
583
+
584
+ await assert.rejects(() => ensureBinary(), (err) => {
585
+ assert.match(err.message, /^SECURITY: cannot verify /);
586
+ assert.match(err.message, /SHA256SUMS could not be downloaded \(Download failed: HTTP 404\)/);
587
+ assert.match(err.message, /NANO_BRAIN_SKIP_SHA_VERIFY=1/);
588
+ assert.match(err.message, /go build/);
589
+ return true;
590
+ });
591
+ assert.strictEqual(fs.existsSync(bin), false, "unverified binary must not stay installed");
592
+ assert.strictEqual(fs.existsSync(`${bin}.SHA256SUMS.tmp`), false);
593
+ });
594
+
595
+ test("ensureBinary: SHA256SUMS network error is a SECURITY failure and leaves no binary (#659)", async (t) => {
596
+ const bin = withoutInstalledBinary(t);
597
+ captureStderr(t);
598
+ stubHttps(t, (url) => (isAssetURL(url) ? { status: 200, body: FAKE_BINARY } : { error: new Error("ECONNRESET") }));
599
+
600
+ await assert.rejects(() => ensureBinary(), securityError(/cannot verify .*ECONNRESET/));
601
+ assert.strictEqual(fs.existsSync(bin), false);
602
+ });
603
+
604
+ test("ensureBinary: asset not listed in SHA256SUMS is a SECURITY failure and leaves no binary (#659)", async (t) => {
605
+ const bin = withoutInstalledBinary(t);
606
+ captureStderr(t);
607
+ stubHttps(t, (url) => {
608
+ if (isAssetURL(url)) return { status: 200, body: FAKE_BINARY };
609
+ if (isSumsURL(url)) return { status: 200, body: `${FAKE_BINARY_SHA} nano-brain-some-other-platform\n` };
610
+ return { status: 404 };
611
+ });
612
+
613
+ await assert.rejects(() => ensureBinary(), (err) => {
614
+ assert.match(err.message, /^SECURITY: cannot verify /);
615
+ assert.ok(err.message.includes(`SHA256SUMS has no entry for ${ASSET_NAME}`), err.message);
616
+ return true;
617
+ });
618
+ assert.strictEqual(fs.existsSync(bin), false, "unverified binary must not stay installed");
619
+ });
620
+
621
+ test("ensureBinary: NANO_BRAIN_SKIP_SHA_VERIFY installs without SHA256SUMS and warns (#659)", async (t) => {
622
+ const bin = withoutInstalledBinary(t);
623
+ const stderr = captureStderr(t);
624
+ const prev = process.env.NANO_BRAIN_SKIP_SHA_VERIFY;
625
+ process.env.NANO_BRAIN_SKIP_SHA_VERIFY = "1";
626
+ t.after(() => {
627
+ if (prev === undefined) delete process.env.NANO_BRAIN_SKIP_SHA_VERIFY;
628
+ else process.env.NANO_BRAIN_SKIP_SHA_VERIFY = prev;
629
+ });
630
+ const requested = stubHttps(t, (url) => (isAssetURL(url) ? { status: 200, body: FAKE_BINARY } : { status: 404 }));
631
+
632
+ assert.strictEqual(await ensureBinary(), bin);
633
+ assert.strictEqual(fs.readFileSync(bin, "utf8"), FAKE_BINARY);
634
+ assert.ok(stderr.some((l) => l.includes("NANO_BRAIN_SKIP_SHA_VERIFY is set")), "must warn that verification is skipped");
635
+ assert.ok(!requested.some(isSumsURL), "opt-out must not fetch SHA256SUMS");
636
+ });
637
+
638
+ test("ensureBinary: verified install through a GitHub-only redirect chain (#659)", async (t) => {
639
+ const bin = withoutInstalledBinary(t);
640
+ captureStderr(t);
641
+ const cdn = "https://release-assets.githubusercontent.com/github-production-release-asset/1/";
642
+ const requested = stubHttps(t, (url) => {
643
+ if (url.startsWith("https://github.com/") && isAssetURL(url)) {
644
+ return { status: 302, headers: { location: "https://objects.githubusercontent.com/hop/bin" } };
645
+ }
646
+ if (url === "https://objects.githubusercontent.com/hop/bin") return { status: 307, headers: { location: `${cdn}bin` } };
647
+ if (url === `${cdn}bin`) return { status: 200, body: FAKE_BINARY };
648
+ if (url.startsWith("https://github.com/") && isSumsURL(url)) return { status: 301, headers: { location: `${cdn}sums` } };
649
+ if (url === `${cdn}sums`) return { status: 200, body: `${FAKE_BINARY_SHA} ${ASSET_NAME}\n` };
650
+ return { status: 404 };
651
+ });
652
+
653
+ assert.strictEqual(await ensureBinary(), bin);
654
+ assert.strictEqual(fs.readFileSync(bin, "utf8"), FAKE_BINARY);
655
+ assert.ok(requested.includes(`${cdn}bin`) && requested.includes(`${cdn}sums`));
656
+ });
657
+
658
+ test("ensureBinary: binary redirected off GitHub is a SECURITY failure, target never requested (#659)", async (t) => {
659
+ const bin = withoutInstalledBinary(t);
660
+ captureStderr(t);
661
+ const requested = stubHttps(t, (url) => {
662
+ if (isAssetURL(url)) return { status: 302, headers: { location: "https://evil.example.com/nano-brain" } };
663
+ return { status: 200, body: FAKE_BINARY };
664
+ });
665
+
666
+ await assert.rejects(() => ensureBinary(), securityError(/refusing redirect .* to https:\/\/evil\.example\.com/));
667
+ assert.strictEqual(fs.existsSync(bin), false);
668
+ assert.ok(!requested.some((u) => u.includes("evil.example.com")), "must not contact the redirect target");
669
+ });
670
+
671
+ for (const fn of [download, downloadWithHash]) {
672
+ test(`${fn.name}: redirect to a non-GitHub host is a SECURITY failure (#659)`, async (t) => {
673
+ const dest = path.join(os.tmpdir(), `nb-redir-host-${fn.name}-${process.pid}-${Date.now()}`);
674
+ for (const location of [
675
+ "https://evil.example.com/x",
676
+ "https://githubusercontent.com.evil.example.com/x",
677
+ "https://evilgithubusercontent.com/x",
678
+ "https://github.com.evil.example.com/x",
679
+ "//evil.example.com/x",
680
+ ]) {
681
+ const requested = stubHttps(t, redirectOnce(location));
682
+ await assert.rejects(() => fn("https://github.com/o/r/releases/download/v1/x", dest), securityError(/refusing redirect/), location);
683
+ assert.strictEqual(requested.length, 1, `must not follow ${location}`);
684
+ assert.strictEqual(fs.existsSync(dest), false);
685
+ }
686
+ });
687
+
688
+ test(`${fn.name}: http:// redirect is a SECURITY failure even on a GitHub host (#659)`, async (t) => {
689
+ const dest = path.join(os.tmpdir(), `nb-redir-http-${fn.name}-${process.pid}-${Date.now()}`);
690
+ const requested = stubHttps(t, redirectOnce("http://objects.githubusercontent.com/x"));
691
+ await assert.rejects(() => fn("https://github.com/o/r/releases/download/v1/x", dest), securityError(/refusing redirect .* to http:\/\//));
692
+ assert.strictEqual(requested.length, 1);
693
+ assert.strictEqual(fs.existsSync(dest), false);
694
+ });
695
+
696
+ test(`${fn.name}: follows at most 5 redirects (#659)`, async (t) => {
697
+ const dest = path.join(os.tmpdir(), `nb-redir-cap-${fn.name}-${process.pid}-${Date.now()}`);
698
+ t.after(() => safeUnlink(dest));
699
+ const chain = (hops) => (url) => {
700
+ const n = Number(new URL(url).searchParams.get("n") || 0);
701
+ if (n < hops) return { status: 302, headers: { location: `https://objects.githubusercontent.com/x?n=${n + 1}` } };
702
+ return { status: 200, body: "ok" };
703
+ };
704
+
705
+ const tooMany = stubHttps(t, chain(6));
706
+ await assert.rejects(() => fn("https://github.com/x", dest), (err) => {
707
+ assert.match(err.message, /too many redirects/);
708
+ return true;
709
+ });
710
+ assert.strictEqual(tooMany.length, 6, "initial request + 5 followed redirects, the 6th is refused");
711
+ assert.strictEqual(fs.existsSync(dest), false);
712
+
713
+ stubHttps(t, chain(5));
714
+ await fn("https://github.com/x", dest);
715
+ assert.strictEqual(fs.readFileSync(dest, "utf8"), "ok");
716
+ });
717
+
718
+ test(`${fn.name}: follows 303/307/308 and resolves a relative Location (#659)`, async (t) => {
719
+ const dest = path.join(os.tmpdir(), `nb-redir-rel-${fn.name}-${process.pid}-${Date.now()}`);
720
+ t.after(() => safeUnlink(dest));
721
+ const requested = stubHttps(t, (url) => {
722
+ if (url === "https://github.com/a/b") return { status: 303, headers: { location: "/c/d" } };
723
+ if (url === "https://github.com/c/d") return { status: 308, headers: { location: "https://Objects.GitHubUserContent.com/e" } };
724
+ if (url === "https://objects.githubusercontent.com/e") return { status: 307, headers: { location: "f" } };
725
+ if (url === "https://objects.githubusercontent.com/f") return { status: 200, body: "ok" };
726
+ return { status: 404 };
727
+ });
728
+ await fn("https://github.com/a/b", dest);
729
+ assert.deepStrictEqual(requested, [
730
+ "https://github.com/a/b",
731
+ "https://github.com/c/d",
732
+ "https://objects.githubusercontent.com/e",
733
+ "https://objects.githubusercontent.com/f",
734
+ ]);
735
+ assert.strictEqual(fs.readFileSync(dest, "utf8"), "ok");
736
+ });
737
+
738
+ test(`${fn.name}: redirect without Location rejects (#659)`, async (t) => {
739
+ const dest = path.join(os.tmpdir(), `nb-redir-noloc-${fn.name}-${process.pid}-${Date.now()}`);
740
+ stubHttps(t, redirectOnce(undefined));
741
+ await assert.rejects(() => fn("https://github.com/x", dest), /redirect without a Location/);
742
+ assert.strictEqual(fs.existsSync(dest), false);
743
+ });
744
+ }
745
+
746
+ test("isAllowedDownloadHost: github.com and *.githubusercontent.com only (#659)", () => {
747
+ for (const h of ["github.com", "GitHub.com", "objects.githubusercontent.com", "release-assets.githubusercontent.com", "raw.githubusercontent.com"]) {
748
+ assert.strictEqual(isAllowedDownloadHost(h), true, h);
749
+ }
750
+ for (const h of ["githubusercontent.com", "api.github.com", "evilgithub.com", "github.com.evil.example.com", "evilgithubusercontent.com", "example.com", ""]) {
751
+ assert.strictEqual(isAllowedDownloadHost(h), false, h);
752
+ }
753
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nano-brain",
3
- "version": "2026.11.2113",
3
+ "version": "2026.11.2115",
4
4
  "description": "Persistent memory and code intelligence for AI coding agents",
5
5
  "bin": {
6
6
  "nano-brain": "npm/run.js"