Repository navigation
Expand file tree
/
Copy pathnative-proof.mjs
More file actions
283 lines (276 loc) · 8.78 KB
/
Copy pathnative-proof.mjs
File metadata and controls
283 lines (276 loc) · 8.78 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
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { parseArgs, promisify } from "node:util";
import { FX, npmRun, verifyNative } from "./native.mjs";
import { selectPlatform } from "../../packages/grida-cli/native/bin.mjs";
const exec = promisify(execFile);
class NativeProofError extends Error {
constructor(stage, cause) {
const code = cause?.code;
const detail = Number.isInteger(code)
? ` (exit ${code})`
: ["ENOENT", "EACCES", "EPERM", "ENOTDIR", "ENOSPC"].includes(code)
? ` (${code})`
: "";
super(`Installed native candidate proof failed at ${stage}${detail}.`, {
cause,
});
}
}
async function proofStep(stage, operation) {
try {
return await operation();
} catch (error) {
throw new NativeProofError(stage, error);
}
}
/** The engine package npm would install with @grida/fx on this host, if Grida FX has one. */
export function fxEngine(dependencies, host = process) {
const libc = host.report?.getReport().header.glibcVersionRuntime
? "glibc"
: "musl";
return (
dependencies
.slice(1)
.find(
(record) =>
record.os?.includes(host.platform) &&
record.cpu?.includes(host.arch) &&
(host.platform !== "linux" ||
!record.libc ||
record.libc.includes(libc))
) ?? null
);
}
/** Install the verified bundled package into a caller-owned directory; caller cleans up.
* @grida/fx and this host's engine package (if any) come from the candidate's own archives. */
export async function installNative(out, runtime) {
assert(path.isAbsolute(runtime));
const report = await proofStep("candidate_verification", () =>
verifyNative(out)
);
const platform = selectPlatform();
assert(platform, "Unsupported proof host");
const selected = report.binaries.find(
(item) => item.platform === platform.id
);
await mkdir(runtime, { recursive: true });
const engine = fxEngine(report.dependencies);
const fxArchives = [report.dependencies[0], ...(engine ? [engine] : [])].map(
(record) => path.join(out, "dependencies", record.archive)
);
await proofStep("offline_npm_install", () =>
npmRun(
[
"install",
path.join(out, "archives", report.package.archive),
...fxArchives,
"--offline",
"--ignore-scripts",
"--no-audit",
"--no-fund",
"--package-lock=false",
"--omit=dev",
],
runtime
)
);
const launcher = path.join(runtime, "node_modules/grida/native/bin.mjs");
const executable = path.join(runtime, "node_modules/grida", selected.path);
const hash = createHash("sha256")
.update(await readFile(executable))
.digest("hex");
assert.equal(hash, selected.binary_sha256);
const installed = JSON.parse(
await readFile(
path.join(runtime, "node_modules/grida/package.json"),
"utf8"
)
);
assert.equal(installed.version, report.version);
assert.equal(installed.name, "grida");
assert.equal(installed.optionalDependencies, undefined);
assert.deepEqual(installed.dependencies, {
[FX]: report.dependencies[0].version,
});
assert.equal(installed.scripts, undefined);
const fx = JSON.parse(
await readFile(
path.join(runtime, "node_modules", FX, "package.json"),
"utf8"
)
);
assert.equal(fx.version, report.dependencies[0].version);
// Installation contains the complete reviewed matrix, even on a single host.
for (const binary of report.binaries) {
const bytes = await readFile(
path.join(runtime, "node_modules/grida", binary.path)
);
assert.equal(
createHash("sha256").update(bytes).digest("hex"),
binary.binary_sha256
);
}
return {
report,
platform,
selected,
launcher,
executable,
binary_sha256: hash,
fx_engine: engine,
};
}
export async function proveNative(out) {
// Exercise the npm shim with a space-containing path on every proof host.
const scratch = await mkdtemp(path.join(tmpdir(), "grida native install-"));
let stage = "installed_metadata";
try {
const {
report,
platform,
launcher,
binary_sha256: hash,
fx_engine: engine,
} = await installNative(out, scratch);
const options = {
cwd: scratch,
timeout: 10_000,
maxBuffer: 1024 * 1024,
env: {
PATH: [path.dirname(process.execPath), "/usr/bin", "/bin"].join(
path.delimiter
),
...(process.env.SystemRoot
? { SystemRoot: process.env.SystemRoot }
: {}),
GRIDA_HOME: path.join(scratch, "profile"),
},
};
stage = "version";
const version = await exec(
process.execPath,
[launcher, "--version"],
options
);
assert.equal(version.stdout.trim(), `grida ${report.version}`);
assert.equal(version.stderr, "");
stage = "help";
const help = await exec(process.execPath, [launcher, "--help"], options);
assert(help.stdout.includes("grida"));
assert.equal(help.stderr, "");
stage = "docs";
const docs = await exec(
process.execPath,
[launcher, "docs", "ai", "providers"],
options
);
assert(docs.stdout.startsWith("https://grida.co/docs/cli"));
stage = "usage_exit_2";
await assert.rejects(
exec(process.execPath, [launcher, "--definitely-invalid"], options),
(error) =>
error.code === 2 && error.stdout === "" && error.stderr.length > 0
);
// `grida fx` reaches Grida FX: its engine where FX has one for this host, else FX's own
// explanation (spec/distribution.md in gridaco/fx). A fixture FX answers everywhere.
stage = "fx_dispatch";
const fxVersion = report.dependencies[0].version;
if (engine || report.fixture_dependencies) {
const fx = await exec(
process.execPath,
[launcher, "fx", "--version"],
options
);
assert.equal(fx.stdout, `grida-fx ${fxVersion}\n`);
} else {
await assert.rejects(
exec(process.execPath, [launcher, "fx", "--version"], options),
(error) =>
error.code === 1 &&
error.stdout === "" &&
error.stderr.startsWith("grida fx: ")
);
}
stage = "npm_bin_shim";
if (process.platform !== "win32") {
const shim = await exec(
path.join(scratch, "node_modules/.bin/grida"),
["--version"],
options
);
assert.equal(shim.stdout.trim(), `grida ${report.version}`);
} else {
const shim = path.join(scratch, "node_modules/.bin/grida.cmd");
assert(!shim.includes('"'));
const command = path.join(process.env.SystemRoot, "System32/cmd.exe");
const invoked = await exec(
command,
["/d", "/s", "/c", `""${shim}" --version"`],
// The /c command is already quoted for cmd.exe. Node's default
// Windows argv escaping would add a second, incompatible quote layer.
{ ...options, windowsVerbatimArguments: true }
);
assert.equal(invoked.stdout.trim(), `grida ${report.version}`);
}
const result = {
format: 2,
version: report.version,
platform: platform.id,
archive_sha256: report.package.sha256,
binary_sha256: hash,
fx: {
version: report.dependencies[0].version,
sha256: report.dependencies[0].sha256,
engine: engine && { name: engine.name, sha256: engine.sha256 },
},
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",
],
};
stage = "write_report";
await writeFile(
path.join(out, `installed-${platform.id}.json`),
JSON.stringify(result, null, 2) + "\n",
{ mode: 0o600 }
);
return result;
} catch (error) {
if (error instanceof NativeProofError) throw error;
throw new NativeProofError(stage, error);
} finally {
await rm(scratch, { recursive: true, force: true });
}
}
if (
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
const { values } = parseArgs({ options: { out: { type: "string" } } });
assert(values.out && path.isAbsolute(values.out));
proveNative(values.out)
.then((result) =>
process.stdout.write(JSON.stringify(result, null, 2) + "\n")
)
.catch((error) => {
process.stderr.write(
`${error instanceof NativeProofError ? error.message : "Installed native candidate proof failed."}\n`
);
process.exitCode = 1;
});
}