Repository navigation
Expand file tree
/
Copy pathnative.test.mjs
More file actions
944 lines (919 loc) · 30.6 KB
/
Copy pathnative.test.mjs
File metadata and controls
944 lines (919 loc) · 30.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
import assert from "node:assert/strict";
import { execFile, spawn } from "node:child_process";
import { createHash } from "node:crypto";
import http from "node:http";
import {
copyFile,
mkdir,
mkdtemp,
readFile,
readdir,
rm,
stat,
symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { promisify } from "node:util";
import {
binaryHeader,
packageManifest,
npmRun,
platforms,
verifyNative,
} from "./native.mjs";
import { proveNative } from "./native-proof.mjs";
import { fixtureBinary, prepareHostFixture } from "./native-fixture.mjs";
import { verifyGlibcBaseline, verifyMuslStatic } from "./native-abi.mjs";
import {
publishVerifiedArchive,
releaseGuard,
verifyInstalledMatrix,
} from "./native-publish.mjs";
import { selectPlatform } from "../../packages/grida-cli/native/bin.mjs";
import {
checkForUpdate,
enabled,
newer,
notice,
refresh,
stateFile,
} from "../../packages/grida-cli/native/update.mjs";
const root = fileURLToPath(new URL("../../", import.meta.url));
const exec = promisify(execFile);
test("installed proof reports a safe failure stage without private paths", async (t) => {
const scratch = await mkdtemp(
path.join(tmpdir(), "grida-native-private-path-")
);
t.after(() => rm(scratch, { recursive: true, force: true }));
await assert.rejects(
exec(process.execPath, [
path.join(root, "scripts/cli-release/native-proof.mjs"),
"--out",
scratch,
]),
(error) => {
assert.equal(error.code, 1);
assert.equal(error.stdout, "");
assert.equal(
error.stderr,
"Installed native candidate proof failed at candidate_verification (ENOENT).\n"
);
assert(!error.stderr.includes(scratch));
return true;
}
);
});
test("npm runs with a disposable home even before loading its explicit config", async (t) => {
const scratch = await mkdtemp(path.join(tmpdir(), "grida-native-npm-home-"));
t.after(() => rm(scratch, { recursive: true, force: true }));
await writeFile(
path.join(scratch, "package.json"),
JSON.stringify({ scripts: { proof: "node home.cjs" } })
);
await writeFile(
path.join(scratch, "home.cjs"),
"if (require('node:fs').realpathSync(require('node:os').homedir()) !== process.cwd()) process.exit(19); process.stdout.write('isolated home\\n');\n"
);
const { stdout } = await npmRun(
["run", "--silent", "--ignore-scripts", "proof"],
scratch
);
assert.equal(stdout, "isolated home\n");
});
test("Windows checkout filters preserve byte-verified native release sources", async (t) => {
const scratch = await mkdtemp(path.join(tmpdir(), "grida-native-checkout-"));
t.after(() => rm(scratch, { recursive: true, force: true }));
await exec("git", ["init", "--quiet", scratch]);
try {
await copyFile(
path.join(root, ".gitattributes"),
path.join(scratch, ".gitattributes")
);
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
const git = (...args) =>
exec("git", ["-c", "core.autocrlf=true", "-c", "core.eol=crlf", ...args], {
cwd: scratch,
maxBuffer: 16 * 1024 * 1024,
});
for (const filename of [
"Cargo.lock",
"LICENSE",
"packages/grida-cli/README.md",
"packages/grida-cli/THIRD-PARTY-NOTICES.txt",
"packages/grida-cli/native/bin.mjs",
"packages/grida-cli/native/update.mjs",
"packages/grida-cli/native/platforms.json",
"packages/grida-cli/native/licenses.json",
]) {
const bytes = await readFile(path.join(root, filename));
const input = path.join(scratch, "source");
await writeFile(input, bytes);
const { stdout: object } = await git(
"hash-object",
"--no-filters",
"-w",
input
);
const { stdout } = await git(
"cat-file",
"--filters",
`--path=${filename}`,
object.trim()
);
assert.equal(
createHash("sha256").update(stdout).digest("hex"),
createHash("sha256").update(bytes).digest("hex"),
filename
);
}
});
async function rootOnlyInstall(out, report, runtime) {
const metadata = new Map();
const archives = new Map();
const records = [
["archives", report.package],
...report.dependencies.map((record) => ["dependencies", record]),
];
for (const [folder, record] of records) {
const filename = path.join(out, folder, record.archive);
const bytes = await readFile(filename);
const manifest = JSON.parse(
(
await exec("tar", ["-xOzf", record.archive, "package/package.json"], {
cwd: path.dirname(filename),
timeout: 10_000,
maxBuffer: 1024 * 1024,
})
).stdout
);
metadata.set(record.name, {
manifest,
archive: record.archive,
integrity:
"sha512-" + createHash("sha512").update(bytes).digest("base64"),
});
archives.set(`/-/${record.archive}`, bytes);
}
const requestedArchives = [];
const unexpected = [];
let origin;
const registry = http.createServer((request, response) => {
const pathname = decodeURIComponent(new URL(request.url, origin).pathname);
const archive = archives.get(pathname);
if (request.method === "GET" && archive) {
requestedArchives.push(pathname.slice(3));
response.writeHead(200, { "content-type": "application/octet-stream" });
response.end(archive);
return;
}
const entry = metadata.get(pathname.slice(1));
if (request.method === "GET" && entry) {
const { manifest, archive, integrity } = entry;
response.writeHead(200, { "content-type": "application/json" });
response.end(
JSON.stringify({
name: manifest.name,
"dist-tags": { latest: manifest.version },
versions: {
[manifest.version]: {
...manifest,
dist: { tarball: `${origin}/-/${archive}`, integrity },
},
},
})
);
return;
}
unexpected.push(`${request.method} ${pathname}`);
response.writeHead(404, { "content-type": "application/json" });
response.end('{"error":"Unknown fixture package"}');
});
await new Promise((resolve, reject) => {
registry.once("error", reject);
registry.listen(0, "127.0.0.1", resolve);
});
origin = `http://127.0.0.1:${registry.address().port}`;
try {
await mkdir(runtime);
// The public registry contract is grida and the @grida/fx it pins: one archive each, and
// an engine archive only where Grida FX has one for this host.
// npmRun supplies an empty per-test cache/configuration, with audit off.
await npmRun(
[
"install",
`grida@${report.version}`,
"--registry",
origin,
"--ignore-scripts",
"--no-audit",
"--no-fund",
"--package-lock=false",
"--omit=dev",
"--fetch-retries=0",
],
runtime
);
assert.deepEqual(unexpected, []);
const host = selectPlatform();
const selected = report.binaries.find((p) => p.platform === host.id);
assert.deepEqual(
(await readdir(path.join(runtime, "node_modules")))
.filter((name) => name !== ".package-lock.json")
.sort(),
[".bin", "@grida", "grida"]
);
assert.deepEqual(
requestedArchives.sort(),
[report.package.archive, report.dependencies[0].archive].sort()
);
assert.deepEqual(
(await readdir(path.join(runtime, "node_modules/grida/binaries"))).sort(),
platforms.map((p) => p.id).sort()
);
const executable = path.join(runtime, "node_modules/grida", selected.path);
assert.equal(
createHash("sha256")
.update(await readFile(executable))
.digest("hex"),
selected.binary_sha256
);
const version = await exec(
process.execPath,
[path.join(runtime, "node_modules/grida/native/bin.mjs"), "--version"],
{ cwd: runtime, timeout: 10_000, maxBuffer: 1024 * 1024 }
);
assert.equal(version.stdout, `grida ${report.version}\n`);
assert.equal(version.stderr, "");
const fx = await exec(
process.execPath,
[
path.join(runtime, "node_modules/grida/native/bin.mjs"),
"fx",
"--version",
],
{ cwd: runtime, timeout: 10_000, maxBuffer: 1024 * 1024 }
);
assert.equal(fx.stdout, `grida-fx ${report.dependencies[0].version}\n`);
} finally {
registry.closeAllConnections();
await new Promise((resolve) => registry.close(resolve));
}
}
async function publicationFixture(t) {
const out = await mkdtemp(
path.join(tmpdir(), "grida-native-publication-test-")
);
t.after(() => rm(out, { recursive: true, force: true }));
await mkdir(path.join(out, "archives"));
const record = {
name: "grida",
version: "0.3.0-rc.2",
archive: "grida-0.3.0-rc.2.tgz",
};
const registry = new Map();
const calls = [];
const integrity = (record) =>
"sha512-" + createHash("sha512").update(record.name).digest("base64");
await writeFile(path.join(out, "archives", record.archive), record.name);
async function invoke(args) {
calls.push(args);
if (args[0] === "publish") return { stdout: "" };
assert.equal(args[0], "view");
const entry = registry.get(args[1]);
if (!entry)
throw Object.assign(new Error("Registry version is absent"), {
stdout: JSON.stringify({ error: { code: "E404" } }),
});
return { stdout: JSON.stringify(entry[args[2]]) };
}
function published(record, overrides = {}) {
registry.set(`${record.name}@${record.version}`, {
"dist.integrity": integrity(record),
...overrides,
});
registry.set(record.name, { "dist-tags.next": record.version });
}
return {
record,
out,
tag: "next",
invoke,
log: () => {},
registry,
calls,
published,
};
}
test("an immutable package version collision fails before publication", async (t) => {
const fixture = await publicationFixture(t);
fixture.published(fixture.record, {
"dist.integrity": "sha512-different",
});
await assert.rejects(
publishVerifiedArchive(fixture.record, fixture),
/Existing immutable grida/
);
assert.equal(
fixture.calls.filter(([operation]) => operation === "publish").length,
0
);
});
test("an identical archive with a changed tag fails without registry writes", async (t) => {
const fixture = await publicationFixture(t);
const last = fixture.record;
fixture.published(last);
fixture.registry.set(last.name, { "dist-tags.next": "0.2.0" });
await assert.rejects(
publishVerifiedArchive(fixture.record, fixture),
/different next tag/
);
assert.equal(
fixture.calls.filter(([operation]) => operation === "publish").length,
0
);
});
test("publication sends only the reviewed grida archive with provenance", async (t) => {
const fixture = await publicationFixture(t);
await publishVerifiedArchive(fixture.record, fixture);
assert.equal(fixture.calls[0][0], "view");
assert.deepEqual(
fixture.calls.filter(([operation]) => operation === "publish"),
[
[
"publish",
path.join(fixture.out, "archives", fixture.record.archive),
"--access",
"public",
"--provenance",
"--tag",
"next",
"--ignore-scripts",
"--registry",
"https://registry.npmjs.org",
],
]
);
});
test("an identical single-package release retry performs no registry writes", async (t) => {
const fixture = await publicationFixture(t);
fixture.published(fixture.record);
await publishVerifiedArchive(fixture.record, fixture);
assert.equal(
fixture.calls.filter(([operation]) => operation === "publish").length,
0
);
});
test("registry read failures and malformed metadata never become permission to publish", async (t) => {
for (const failure of [
Object.assign(new Error("network"), {
stdout: JSON.stringify({ error: { code: "E503" } }),
stderr: "Registry proxy mentioned E404 while failing",
}),
{ stdout: "{}" },
{ stdout: "null" },
{ stdout: '""' },
]) {
const fixture = await publicationFixture(t);
const invoke = async (args) => {
if (args[1] === `grida@${fixture.record.version}`) {
if (failure instanceof Error) throw failure;
return failure;
}
return fixture.invoke(args);
};
await assert.rejects(
publishVerifiedArchive(fixture.record, { ...fixture, invoke })
);
assert.equal(
fixture.calls.filter(([operation]) => operation === "publish").length,
0
);
}
});
test("a failed immutable publication is not retried or repaired by moving tags", async (t) => {
const fixture = await publicationFixture(t);
let publishes = 0;
const invoke = async (args) => {
if (args[0] === "publish") {
publishes++;
throw new Error("Concurrent immutable version collision");
}
return fixture.invoke(args);
};
await assert.rejects(
publishVerifiedArchive(fixture.record, { ...fixture, invoke }),
/immutable version collision/
);
assert.equal(publishes, 1);
assert(fixture.calls.every(([operation]) => operation === "view"));
});
test("musl artifacts reject interpreters and shared dependencies while allowing static PIE", () => {
const headers = "Program Headers:\n Type Offset VirtAddr\n LOAD 0x0 0x0\n";
const pie =
"Dynamic section at offset 0x100 contains 2 entries:\n (FLAGS_1) Flags: PIE\n (NULL) 0x0\n";
const fixed = "There is no dynamic section in this file.\n";
assert.deepEqual(verifyMuslStatic(headers, pie), {
linkage: "static",
needed: [],
});
assert.deepEqual(verifyMuslStatic(headers, fixed), {
linkage: "static",
needed: [],
});
// musl-gcc's static-PIE wrapper regression links successfully but adds this
// loader and crashes before main. ABI inspection must reject it before packing.
assert.throws(
() => verifyMuslStatic(`${headers} INTERP 0x270 0x270\n`, pie),
/dynamic interpreter/
);
assert.throws(
() =>
verifyMuslStatic(headers, `${pie} (NEEDED) Shared library: [libc.so]\n`),
/shared libraries/
);
assert.throws(() => verifyMuslStatic("", pie), /program headers/);
assert.throws(
() => verifyMuslStatic(headers, ""),
/dynamic-section inspection/
);
});
test("GNU packages reject newer glibc symbols and unbundled libraries", () => {
const dynamic =
"0x1 (NEEDED) Shared library: [libc.so.6]\n0x1 (NEEDED) Shared library: [libgcc_s.so.1]";
assert.equal(
verifyGlibcBaseline("GLIBC_2.17 GLIBC_2.28", dynamic).glibc_maximum,
"2.28"
);
assert.throws(
() => verifyGlibcBaseline("GLIBC_2.29", dynamic),
/maximum is 2.28/
);
assert.throws(
() => verifyGlibcBaseline("GLIBC_PRIVATE", dynamic),
/Unsupported/
);
assert.throws(
() =>
verifyGlibcBaseline("GLIBC_2.17", dynamic + "\n(NEEDED) [libssl.so.3]"),
/Unbundled/
);
});
test("release requires the native manifest, stable tag policy and real installed proofs", async (t) => {
const manifest = packageManifest({
name: "grida",
version: "0.2.0",
private: false,
dependencies: { "@grida/fx": "0.2.0" },
});
releaseGuard(manifest, "0.2.0", "latest");
releaseGuard({ ...manifest, version: "0.3.0-rc.2" }, "0.3.0-rc.2", "next");
assert.throws(() =>
releaseGuard({ ...manifest, grida_native: undefined }, "0.2.0", "latest")
);
assert.throws(() => releaseGuard(manifest, "0.2.1", "latest"));
assert.throws(() =>
releaseGuard({ ...manifest, version: "0.2.0-01" }, "0.2.0-01", "next")
);
assert.throws(() =>
releaseGuard({ ...manifest, version: "0.2.0-rc.1" }, "0.2.0-rc.1", "latest")
);
const out = await mkdtemp(path.join(tmpdir(), "grida-native-release-test-"));
t.after(() => rm(out, { recursive: true, force: true }));
const report = {
version: "0.2.0",
format: 2,
package: { sha256: "package" },
binaries: platforms.map((p) => ({
platform: p.id,
binary_sha256: `${p.id}-binary`,
})),
dependencies: [{ name: "@grida/fx", version: "0.2.0", sha256: "fx" }],
};
const checks = [
"offline_npm_install",
"exact_fx_dependency",
"fx_dispatch",
"exact_package_version",
"bundled_platform_matrix",
"installed_binary_hash",
"version",
"help",
"docs",
"usage_exit_2",
"npm_bin_shim",
];
for (const p of report.binaries)
await writeFile(
path.join(out, `installed-${p.platform}.json`),
JSON.stringify({
format: 2,
version: report.version,
platform: p.platform,
archive_sha256: "package",
binary_sha256: p.binary_sha256,
fx: { version: "0.2.0", sha256: "fx", engine: null },
checks,
})
);
await verifyInstalledMatrix(out, report);
await assert.rejects(
verifyInstalledMatrix(out, { ...report, fixture_targets: ["win32-arm64"] }),
/cannot be released/
);
await assert.rejects(
verifyInstalledMatrix(out, { ...report, fixture_dependencies: true }),
/fixture Grida FX cannot be released/
);
await assert.rejects(
verifyInstalledMatrix(out, {
...report,
dependencies: [{ name: "@grida/fx", version: "0.2.0", sha256: "other" }],
})
);
await writeFile(
path.join(out, `installed-${report.binaries[0].platform}.json`),
JSON.stringify({ version: "0.1.0" })
);
await assert.rejects(verifyInstalledMatrix(out, report));
});
test("platform metadata is exact, libc-specific and never guesses another architecture", () => {
assert.equal(platforms.length, 8);
assert.equal(new Set(platforms.map((p) => p.target)).size, 8);
const source = {
name: "grida",
version: "0.2.0",
dependencies: { "@grida/fx": "0.2.0" },
};
const manifest = packageManifest(source);
assert.equal(manifest.optionalDependencies, undefined);
assert.deepEqual(manifest.dependencies, { "@grida/fx": "0.2.0" });
assert.equal(manifest.scripts, undefined);
// Grida FX is the one dependency, pinned to one exact version.
for (const changed of [
{ dependencies: undefined },
{ dependencies: { "@grida/fx": "^0.2.0" } },
{ dependencies: { "@grida/fx": "0.2.0", other: "1.0.0" } },
{ optionalDependencies: { "@grida/fx-darwin-arm64": "0.2.0" } },
])
assert.throws(() => packageManifest({ ...source, ...changed }));
assert(manifest.files.includes("binaries"));
assert.equal(
selectPlatform("linux", "x64", { header: { glibcVersionRuntime: "2.35" } })
.id,
"linux-x64-gnu"
);
assert.equal(
selectPlatform("linux", "arm64", { header: {} }).id,
"linux-arm64-musl"
);
assert.equal(selectPlatform("win32", "arm64").id, "win32-arm64");
assert.equal(selectPlatform("linux", "riscv64", { header: {} }), undefined);
for (const p of platforms) {
binaryHeader(fixtureBinary(p), p);
assert.throws(() =>
binaryHeader(fixtureBinary(p), {
...p,
cpu: p.cpu === "arm64" ? "x64" : "arm64",
})
);
}
});
test(
"one bundled archive packs all eight binaries and installs from a fresh npm registry",
{ timeout: 120_000 },
async (t) => {
const scratch = await mkdtemp(
path.join(tmpdir(), "grida-native-proof-test-")
);
t.after(() => rm(scratch, { recursive: true, force: true }));
const host = selectPlatform();
assert(host);
const binary =
process.env.GRIDA_NATIVE_TEST_BINARY ??
path.join(
root,
"target/debug",
process.platform === "win32" ? "grida.exe" : "grida"
);
const out = path.join(scratch, "candidate");
const report = await prepareHostFixture(binary, out);
await assert.rejects(
verifyInstalledMatrix(out, report),
/cannot be released/
);
assert.equal((await verifyNative(out)).version, report.version);
const proof = await proveNative(out);
assert.equal(proof.platform, host.id);
assert(proof.checks.includes("installed_binary_hash"));
await rootOnlyInstall(out, report, path.join(scratch, "root-only-install"));
assert.equal(report.format, 2);
assert.equal(report.binaries.length, 8);
assert.equal((await readdir(path.join(out, "archives"))).length, 1);
assert.equal(report.fixture_dependencies, true);
assert.deepEqual(
(await readdir(path.join(out, "dependencies"))).sort(),
report.dependencies.map((record) => record.archive).sort()
);
assert(proof.checks.includes("fx_dispatch"));
const reportFile = path.join(out, "native-candidate.json");
for (const changed of [
{ ...report, binaries: report.binaries.slice(1) },
{
...report,
binaries: report.binaries.map((binary, index) =>
index ? binary : { ...binary, path: "../outside" }
),
},
{
...report,
binaries: report.binaries.map((binary, index) =>
index ? binary : { ...binary, binary_sha256: "bad" }
),
},
]) {
await writeFile(reportFile, JSON.stringify(changed));
await assert.rejects(verifyNative(out));
}
await writeFile(reportFile, JSON.stringify(report));
const fxArchive = path.join(
out,
"dependencies",
report.dependencies[0].archive
);
const fxBytes = await readFile(fxArchive);
await writeFile(fxArchive, Buffer.concat([fxBytes, Buffer.from("tamper")]));
await assert.rejects(verifyNative(out));
await writeFile(fxArchive, fxBytes);
const archive = path.join(out, "archives", report.package.archive);
await writeFile(
archive,
Buffer.concat([await readFile(archive), Buffer.from("tamper")])
);
await assert.rejects(verifyNative(out));
}
);
async function launcherFixture(scratch) {
const platform = selectPlatform();
const version = "0.2.0";
const directory = path.join(scratch, "grida");
await mkdir(path.join(directory, "native"), { recursive: true });
await writeFile(
path.join(directory, "package.json"),
JSON.stringify({ name: "grida", version, type: "module" })
);
for (const file of ["bin.mjs", "update.mjs", "platforms.json"])
await copyFile(
path.join(root, "packages/grida-cli/native", file),
path.join(directory, "native", file)
);
const installed = path.join(directory, "binaries", platform.id);
await mkdir(installed, { recursive: true });
// A real native executable (Node) exposes argv/stdin/signal behavior without
// invoking credentials, providers, or network from the Grida application.
const executable = path.join(
installed,
process.platform === "win32" ? "grida.exe" : "grida"
);
if (process.platform === "win32")
await copyFile(process.execPath, executable);
else await symlink(process.execPath, executable);
return { launcher: path.join(directory, "native/bin.mjs"), installed };
}
function childResult(child) {
let stdout = "",
stderr = "";
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
stdout += chunk;
});
child.stderr.on("data", (chunk) => {
stderr += chunk;
});
return new Promise((resolve, reject) => {
child.once("error", reject);
child.once("close", (code, signal) =>
resolve({ code, signal, stdout, stderr })
);
});
}
test("launcher preserves arguments, stdin, stdout, stderr and exit status", async (t) => {
const scratch = await mkdtemp(path.join(tmpdir(), "grida-launcher-"));
t.after(() => rm(scratch, { recursive: true, force: true }));
const { launcher, installed } = await launcherFixture(scratch);
const args = ["a b", "--no-input", "雪", "%PATH%"];
const script =
"process.stdout.write(JSON.stringify({args:process.argv.slice(1),stdin:require('node:fs').readFileSync(0,'utf8')}));process.stderr.write('diagnostic');process.exitCode=7";
const child = spawn(
process.execPath,
[launcher, "-e", script, "--", ...args],
{ stdio: "pipe" }
);
const result = childResult(child);
child.stdin.end("stdin bytes\n");
const value = await result;
assert.equal(value.code, 7, JSON.stringify(value));
assert.equal(value.stderr, "diagnostic");
assert.deepEqual(JSON.parse(value.stdout), { args, stdin: "stdin bytes\n" });
await rm(installed, { recursive: true });
const missing = spawn(process.execPath, [launcher, "--version"], {
stdio: "pipe",
});
missing.stdin.end();
const absent = await childResult(missing);
assert.equal(absent.code, 1);
assert.equal(absent.stdout, "");
assert.match(absent.stderr, /bundled executable is missing/);
});
test(
"launcher forwards process termination to its child",
{ skip: process.platform === "win32", timeout: 10_000 },
async (t) => {
const scratch = await mkdtemp(
path.join(tmpdir(), "grida-launcher-signal-")
);
t.after(() => rm(scratch, { recursive: true, force: true }));
const { launcher } = await launcherFixture(scratch);
const child = spawn(
process.execPath,
[
launcher,
"-e",
"process.on('SIGTERM',()=>process.exit(19));process.stdout.write('ready');setInterval(()=>{},1000)",
],
{ stdio: "pipe" }
);
const result = childResult(child);
child.stdin.end();
t.after(() => child.kill("SIGKILL"));
await new Promise((resolve, reject) => {
child.stdout.once("data", resolve);
child.once("exit", () =>
reject(new Error("Fixture exited before signal readiness"))
);
});
child.kill("SIGTERM");
assert.equal((await result).code, 19);
}
);
async function fxFixture(directory, contract = 1) {
const fx = path.join(directory, "node_modules/@grida/fx");
await mkdir(fx, { recursive: true });
await writeFile(
path.join(fx, "package.json"),
JSON.stringify({
name: "@grida/fx",
version: "0.2.0",
type: "module",
exports: { "./cli": "./cli.js" },
})
);
await writeFile(
path.join(fx, "cli.js"),
`export const HOST_CONTRACT = ${contract};\n` +
"export function launch(argv, options) { process.stdout.write(JSON.stringify({ argv, options })); process.exitCode = 5; }\n"
);
}
test("grida fx hands its arguments to the pinned Grida FX as the grida invoker", async (t) => {
const scratch = await mkdtemp(path.join(tmpdir(), "grida-launcher-fx-"));
t.after(() => rm(scratch, { recursive: true, force: true }));
const { launcher } = await launcherFixture(scratch);
const run = (args) => {
const child = spawn(process.execPath, [launcher, ...args], {
stdio: "pipe",
});
child.stdin.end();
return childResult(child);
};
const missing = await run(["fx", "--version"]);
assert.equal(missing.code, 1);
assert.equal(missing.stdout, "");
assert.equal(
missing.stderr,
"grida fx: Grida FX is not installed with this grida. Reinstall grida.\n"
);
await fxFixture(path.join(scratch, "grida"), 2);
const foreign = await run(["fx", "--version"]);
assert.equal(foreign.code, 1);
assert.match(foreign.stderr, /host contract 2, not 1/);
await fxFixture(path.join(scratch, "grida"));
const args = ["run", "a b", "--live", "--json", "雪"];
const handed = await run(["fx", ...args]);
assert.equal(handed.code, 5, JSON.stringify(handed));
assert.deepEqual(JSON.parse(handed.stdout), {
argv: args,
options: { invoker: "grida" },
});
// Only the first word selects FX.
const other = await run(["-e", "process.stdout.write('native')", "--", "fx"]);
assert.equal(other.stdout, "native");
});
test("the update notice compares SemVer and stays out of scripts, CI and --json", () => {
for (const [a, b] of [
["0.6.0", "0.5.0"],
["1.0.0", "0.9.9"],
["0.5.1", "0.5.0"],
["0.5.0", "0.5.0-rc.1"],
["0.5.0-rc.2", "0.5.0-rc.1"],
["0.5.0-rc.10", "0.5.0-rc.9"],
["0.5.0-rc", "0.5.0-1"],
]) {
assert(newer(a, b), `${a} > ${b}`);
assert(!newer(b, a), `${b} < ${a}`);
}
assert(!newer("0.5.0", "0.5.0"));
assert(!newer("garbage", "0.5.0"));
assert.equal(stateFile({ GRIDA_HOME: "relative" }), null);
assert.equal(stateFile({ GRIDA_HOME: "" }), null);
assert.equal(
stateFile({ GRIDA_HOME: "/home/a/.grida" }),
path.join("/home/a/.grida", "cli", "update.json")
);
const tty = { isTTY: true };
assert(enabled([], {}, tty));
assert(!enabled([], {}, {}));
assert(!enabled([], { CI: "true" }, tty));
assert(!enabled([], { GRIDA_NO_UPDATE_CHECK: "1" }, tty));
assert(!enabled(["ai", "models", "list", "--json"], {}, tty));
assert.equal(
notice("0.5.0", { latest: "0.6.0" }),
"grida 0.6.0 is available (this is 0.5.0). Update: npm install -g grida@latest\n"
);
assert.equal(notice("0.5.0", { latest: "0.5.0" }), null);
assert.equal(notice("0.6.0", { latest: "0.5.0" }), null);
assert.equal(notice("0.5.0", {}), null);
});
test("the update notice reads a local record and refreshes it at most daily", async (t) => {
const home = await mkdtemp(path.join(tmpdir(), "grida-update-"));
t.after(() => rm(home, { recursive: true, force: true }));
const env = { GRIDA_HOME: home };
const file = stateFile(env);
const written = [];
const refreshed = [];
const stderr = { isTTY: true, write: (text) => written.push(text) };
const options = (now) => ({
version: "0.5.0",
env,
stderr,
now,
refresh: (target) => refreshed.push(target),
});
// No record: no notice, and a check starts.
checkForUpdate([], options(1_000));
assert.deepEqual([written, refreshed], [[], [file]]);
// A failed check records the attempt and keeps no version.
await refresh(file, {
fetch: async () => {
throw new Error("offline");
},
now: () => 1_000,
});
assert.deepEqual(JSON.parse(await readFile(file, "utf8")), {
checked_at: 1_000,
latest: null,
});
if (process.platform !== "win32")
assert.equal((await stat(file)).mode & 0o777, 0o600);
refreshed.length = 0;
checkForUpdate([], options(2_000));
assert.deepEqual([written, refreshed], [[], []]);
// A day later the next check runs; it finds a newer grida.
checkForUpdate([], options(1_000 + 24 * 60 * 60 * 1000));
assert.deepEqual(refreshed, [file]);
await refresh(file, {
fetch: async (url) => {
assert.equal(url, "https://registry.npmjs.org/-/package/grida/dist-tags");
return {
ok: true,
json: async () => ({ latest: "0.6.0", next: "0.7.0-rc.1" }),
};
},
now: () => 5_000,
});
refreshed.length = 0;
checkForUpdate(["fx", "run", "case"], options(6_000));
assert.deepEqual(written, [
"grida 0.6.0 is available (this is 0.5.0). Update: npm install -g grida@latest\n",
]);
assert.deepEqual(refreshed, []);
// A failed later check keeps the version it knew.
await refresh(file, { fetch: async () => ({ ok: false }), now: () => 7_000 });
assert.deepEqual(JSON.parse(await readFile(file, "utf8")), {
checked_at: 7_000,
latest: "0.6.0",
});
// Disabled: neither notice nor check.
written.length = 0;
checkForUpdate(["--json"], options(99 * 24 * 60 * 60 * 1000));
checkForUpdate([], {
...options(99 * 24 * 60 * 60 * 1000),
stderr: { write: stderr.write },
});
assert.deepEqual([written, refreshed], [[], []]);
});