pi-better-server 0.1.1 → 0.1.3
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.
- package/README.md +17 -0
- package/package.json +1 -1
- package/scripts/private-runtime/format.ts +8 -0
- package/scripts/private-runtime/installer.ts +14 -5
- package/src/handshake.ts +1 -1
- package/src/remote-client/extension.ts +1 -0
- package/src/remote-client/packages.ts +8 -2
- package/src/remote-client/pi-1.2-bridge.ts +12 -4
- package/src/startup/activation.ts +42 -8
- package/src/startup/install.ts +79 -19
package/README.md
CHANGED
|
@@ -287,6 +287,17 @@ target downloads fail, the client downloads and uploads verified archives instea
|
|
|
287
287
|
Concurrent connectors share the same release only after integrity validation.
|
|
288
288
|
Published releases are not overwritten to repair corruption.
|
|
289
289
|
|
|
290
|
+
Repeat connections to an already installed matching release verify and reuse its
|
|
291
|
+
private Node without downloading Node or dependencies again. Before running any
|
|
292
|
+
cached executable, the client copies it into its own staging directory and checks
|
|
293
|
+
its SHA-256 against a pinned executable checksum. The freshly uploaded installer
|
|
294
|
+
then validates the complete release, manifest and source under the build lock.
|
|
295
|
+
New releases also retain the original source archive under the release inventory;
|
|
296
|
+
repeat connections copy and authenticate it locally rather than uploading it again.
|
|
297
|
+
Older releases without an archive still use a verified upload for compatibility.
|
|
298
|
+
A present but corrupted release is an error, not permission to replace it. A new
|
|
299
|
+
build still needs the normal first-install downloads and verification.
|
|
300
|
+
|
|
290
301
|
Staging can proceed while sessions run. Activation waits for all sessions to be
|
|
291
302
|
idle, including SDK preflight and settlement, queued messages, compaction, shell
|
|
292
303
|
commands, dialogs and observable background work. Native cache warming is also
|
|
@@ -316,6 +327,12 @@ an explicit migration before automatic activation can proceed. The client leaves
|
|
|
316
327
|
the old daemon running and reports the reason instead of killing it.
|
|
317
328
|
|
|
318
329
|
Activation records live in `<serverDir>/activation.json` and `activation.log`.
|
|
330
|
+
When an older build remains staged after its daemon exits, a new activation can
|
|
331
|
+
retire that build's reservations under the exclusive activation lock. Cleanup
|
|
332
|
+
requires an absent listener, verified previous-owner exit, the same agent
|
|
333
|
+
directory, and compatible SDK/protocol versions. It preserves session files and
|
|
334
|
+
compatibility evidence; live or ambiguous owners and committed upgrades remain
|
|
335
|
+
blocked.
|
|
319
336
|
`recovery-required` preserves an ambiguous or adopted candidate for inspection;
|
|
320
337
|
it does not authorize another writer or a rollback. Automatic rollback is limited
|
|
321
338
|
to a proven candidate exit before adoption and restores code only, not settings,
|
package/package.json
CHANGED
|
@@ -8,6 +8,14 @@ export const NODE_CHECKSUMS: Record<RuntimePlatform, string> = {
|
|
|
8
8
|
"darwin-x64": "2526230ad7d922be82d4fdb1e7ee1e84303e133e3b4b0ec4c2897ab31de0253d",
|
|
9
9
|
"darwin-arm64": "25495ff85bd89e2d8a24d88566d7e2f827c6b0d3d872b2cebf75371f93fcb1fe",
|
|
10
10
|
};
|
|
11
|
+
// Extracted bin/node hashes from the archives authenticated by NODE_CHECKSUMS.
|
|
12
|
+
// Source: https://nodejs.org/dist/v24.14.1/SHASUMS256.txt
|
|
13
|
+
export const NODE_EXECUTABLE_CHECKSUMS: Record<RuntimePlatform, string> = {
|
|
14
|
+
"linux-x64": "bf9112eb83a827dc9f9c8d19bb7bddcbf00f7b2fedae18fdcaee05406981f20a",
|
|
15
|
+
"linux-arm64": "7fac13c04c19207c3e904a7721f8c045e6b99493471e2df85444f764cdd21934",
|
|
16
|
+
"darwin-x64": "9ab4f6249a8de4671c3205ef58621dfb19d120a9c59fd96ed206571bafb0319c",
|
|
17
|
+
"darwin-arm64": "35d4bc736bbe4161f0c074aa140ddb74586e46969bc2ad63d32c838bec4463ff",
|
|
18
|
+
};
|
|
11
19
|
export function digest(value: string | Buffer): string { return createHash("sha256").update(value).digest("hex"); }
|
|
12
20
|
export function stable(value: any): string {
|
|
13
21
|
if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
|
|
@@ -6,14 +6,15 @@ import { gunzipSync } from "node:zlib";
|
|
|
6
6
|
import { setTimeout as delay } from "node:timers/promises";
|
|
7
7
|
import { digest, stable, validatePayload, validateStaged } from "./format.ts";
|
|
8
8
|
|
|
9
|
-
const [work, installRoot, expectedSha, mode] = process.argv.slice(2) as [string, string, string, string];
|
|
9
|
+
const [work, installRoot, expectedSha, mode, expectedBuildId] = process.argv.slice(2) as [string, string, string, string, string | undefined];
|
|
10
10
|
let lock: string | undefined;
|
|
11
11
|
let acquired = false;
|
|
12
12
|
let ownsWork = false;
|
|
13
13
|
let candidate: string | undefined;
|
|
14
14
|
function cancelled() { if (existsSync(join(work, "cancel"))) throw new Error("installation cancelled"); }
|
|
15
15
|
function plainDirectory(path: string) {
|
|
16
|
-
|
|
16
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
17
|
+
if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error(`permission: unsafe directory ${path}`);
|
|
17
18
|
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
18
19
|
}
|
|
19
20
|
function inventory(root: string): Record<string, string> {
|
|
@@ -61,9 +62,13 @@ try {
|
|
|
61
62
|
writeFileSync(join(work, "installer.pid"), String(process.pid), { flag: "wx", mode: 0o600 });
|
|
62
63
|
ownsWork = true;
|
|
63
64
|
cancelled();
|
|
64
|
-
const
|
|
65
|
+
const archivePath = join(work, "artifact.gz");
|
|
66
|
+
const archive = lstatSync(archivePath);
|
|
67
|
+
if (!archive.isFile() || archive.isSymbolicLink() || archive.size > 32 * 1024 * 1024) throw new Error("artifact integrity mismatch or size limit");
|
|
68
|
+
const bytes = readFileSync(archivePath);
|
|
65
69
|
if (bytes.length > 32 * 1024 * 1024 || digest(bytes) !== expectedSha) throw new Error("artifact integrity mismatch or size limit");
|
|
66
70
|
const payload = validatePayload(JSON.parse(gunzipSync(bytes, { maxOutputLength: 64 * 1024 * 1024 }).toString()));
|
|
71
|
+
if ((mode === "reuse-only" || expectedBuildId !== undefined) && payload.build.contentId !== expectedBuildId) throw new Error("cached artifact build identity mismatch");
|
|
67
72
|
if (`${process.platform}-${process.arch}` !== payload.build.platform || process.versions.node !== payload.build.nodeVersion) throw new Error("unsupported platform or Node version mismatch");
|
|
68
73
|
if (realpathSync(installRoot) !== resolve(installRoot)) throw new Error("permission: install root contains symlink");
|
|
69
74
|
const releases = join(installRoot, "releases");
|
|
@@ -87,8 +92,10 @@ try {
|
|
|
87
92
|
}
|
|
88
93
|
writeFileSync(join(lock, "owner.json"), JSON.stringify({ pid: process.pid, work }), { flag: "wx", mode: 0o600 });
|
|
89
94
|
const runtime = validateStaged({ format: 1, build: payload.build, root: finalRoot, node: join(finalRoot, "node/bin/node"), entrypoint: join(finalRoot, "src/cli.ts"), manifestPath: join(finalRoot, "runtime.json"), installRoot });
|
|
90
|
-
|
|
91
|
-
|
|
95
|
+
const release = lstatSync(finalRoot, { throwIfNoEntry: false });
|
|
96
|
+
if (release) {
|
|
97
|
+
if (release.isSymbolicLink()) throw new Error("corrupt cache: release symlink");
|
|
98
|
+
if (!release.isDirectory()) throw new Error("corrupt cache: expected release directory");
|
|
92
99
|
for (const path of [runtime.manifestPath, join(finalRoot, "integrity.json"), ...payload.files.map((file) => join(finalRoot, file.path))]) {
|
|
93
100
|
if (!existsSync(path) || !lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()) throw new Error(`corrupt cache: expected regular file ${path}`);
|
|
94
101
|
}
|
|
@@ -98,6 +105,7 @@ try {
|
|
|
98
105
|
cancelled();
|
|
99
106
|
process.stdout.write(JSON.stringify(runtime));
|
|
100
107
|
} else {
|
|
108
|
+
if (mode === "reuse-only") throw new Error("reuse-only: release absent");
|
|
101
109
|
candidate = join(work, "release");
|
|
102
110
|
removeOwned(candidate);
|
|
103
111
|
mkdirSync(candidate, { mode: 0o700 });
|
|
@@ -106,6 +114,7 @@ try {
|
|
|
106
114
|
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
107
115
|
writeFileSync(path, Buffer.from(file.data, "base64"), { flag: "wx", mode: 0o600 });
|
|
108
116
|
}
|
|
117
|
+
cpSync(join(work, "artifact.gz"), join(candidate, "artifact.gz"));
|
|
109
118
|
cpSync(join(work, "node"), join(candidate, "node"), { recursive: true, dereference: false, verbatimSymlinks: true });
|
|
110
119
|
const deps = join(work, "dependencies");
|
|
111
120
|
plainDirectory(deps);
|
package/src/handshake.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { ServerBuild } from "./startup/managed-types.ts";
|
|
|
4
4
|
import { PROTOCOL_VERSION, type HelloCommand, type HelloData } from "./protocol.ts";
|
|
5
5
|
|
|
6
6
|
/** Kept equal to package.json `version`; a test pins that. */
|
|
7
|
-
export const SERVER_VERSION = "0.1.
|
|
7
|
+
export const SERVER_VERSION = "0.1.3";
|
|
8
8
|
|
|
9
9
|
export const SERVER_EXTENSION_VERSIONS: Readonly<Record<string, string>> = { "pi-better-server": SERVER_VERSION };
|
|
10
10
|
|
|
@@ -22,6 +22,7 @@ import { NATIVE_RECONNECT_CAPABILITIES, openUpgradeTransport } from "./upgrade-t
|
|
|
22
22
|
const USAGE = "/remote connect <ssh-alias> [--cwd <remote-path>] [--session <id>] [--remote-dir <server-dir>]";
|
|
23
23
|
const UPGRADE_STAGES: Record<string, string> = {
|
|
24
24
|
artifact: "preparing matching server...", probe: "checking remote platform...", "node-download": "preparing private Node runtime...",
|
|
25
|
+
verifying: "verifying installed server...", "verification-upload": "sending server verification data...",
|
|
25
26
|
"node-upload": "uploading verified Node runtime...", dependencies: "checking server dependencies...", "dependencies-upload": "uploading verified dependencies...",
|
|
26
27
|
staged: "matching server staged...", activating: "activating matching server...", ready: "matching server ready...", deferred: "server update staged; current daemon continues...",
|
|
27
28
|
};
|
|
@@ -2,7 +2,7 @@ import { execFile } from "node:child_process";
|
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
|
-
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
5
|
+
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
6
6
|
import { promisify } from "node:util";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import { getAgentDir, ProjectTrustStore, SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
@@ -313,7 +313,13 @@ export async function installPackageCatalog(packages: PackageSpec[], options: {
|
|
|
313
313
|
for (const item of approved) {
|
|
314
314
|
try {
|
|
315
315
|
await run(process.execPath, [cli, "install", item.source], {
|
|
316
|
-
cwd: agentDir,
|
|
316
|
+
cwd: agentDir,
|
|
317
|
+
env: {
|
|
318
|
+
...process.env,
|
|
319
|
+
// The managed runtime's npm and its Node shebang live beside this executable.
|
|
320
|
+
PATH: [dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter),
|
|
321
|
+
PI_CODING_AGENT_DIR: agentDir,
|
|
322
|
+
},
|
|
317
323
|
encoding: "utf8", maxBuffer: 4 * 1024 * 1024,
|
|
318
324
|
});
|
|
319
325
|
} catch {
|
|
@@ -176,12 +176,14 @@ class Controller implements Pi12Bridge {
|
|
|
176
176
|
methods(ui, ["clear", "addChild", "requestRender"], "InteractiveMode.ui");
|
|
177
177
|
if (!Array.isArray(ui.children)) throw failure("InteractiveMode.ui.children is missing.");
|
|
178
178
|
methods(object(this.mode.editorContainer, "InteractiveMode.editorContainer"), ["render"], "editorContainer");
|
|
179
|
+
methods(object(this.mode.footerContainer, "InteractiveMode.footerContainer"), ["render"], "footerContainer");
|
|
179
180
|
const header = object(this.mode.headerContainer, "InteractiveMode.headerContainer");
|
|
180
181
|
methods(header, ["render"], "headerContainer");
|
|
181
182
|
writable(header, "render");
|
|
182
183
|
if (ui.mode === "fullscreen") {
|
|
183
184
|
methods(ui, ["setLayoutRoot"], "InteractiveMode.ui");
|
|
184
|
-
object(this.mode.fullscreenLayoutRoot, "InteractiveMode.fullscreenLayoutRoot");
|
|
185
|
+
const root = object(this.mode.fullscreenLayoutRoot, "InteractiveMode.fullscreenLayoutRoot");
|
|
186
|
+
if (typeof root.constructor !== "function" || root.constructor === Object) throw failure("fullscreen layout cannot compose the browse footer.");
|
|
185
187
|
}
|
|
186
188
|
}
|
|
187
189
|
|
|
@@ -194,6 +196,12 @@ class Controller implements Pi12Bridge {
|
|
|
194
196
|
const ui = this.mode.ui as Native;
|
|
195
197
|
const roots = [...ui.children];
|
|
196
198
|
const layoutRoot = this.mode.fullscreenLayoutRoot;
|
|
199
|
+
// Reuse Pi 1.2's native stack type without importing a newer TUI API on SDK 0.82.
|
|
200
|
+
const browseRoot = ui.mode === "fullscreen" ? new layoutRoot.constructor([
|
|
201
|
+
{ component: this.mode.editorContainer, basis: 0, grow: 1, shrink: 1, minSize: 0 },
|
|
202
|
+
{ component: this.mode.footerContainer, basis: "auto", grow: 0, shrink: 0 },
|
|
203
|
+
]) : undefined;
|
|
204
|
+
if (browseRoot) methods(browseRoot, ["render"], "browse layout");
|
|
197
205
|
let active = true;
|
|
198
206
|
const cleanup = () => {
|
|
199
207
|
if (!active) return;
|
|
@@ -206,11 +214,11 @@ class Controller implements Pi12Bridge {
|
|
|
206
214
|
};
|
|
207
215
|
this.endBrowse = cleanup;
|
|
208
216
|
try {
|
|
209
|
-
//
|
|
210
|
-
// surrounding local view, not its children or its still-live runtime.
|
|
217
|
+
// Keep the live footer/status map, but hide the local transcript and widgets.
|
|
211
218
|
ui.clear();
|
|
212
219
|
ui.addChild(this.mode.editorContainer);
|
|
213
|
-
|
|
220
|
+
ui.addChild(this.mode.footerContainer);
|
|
221
|
+
if (ui.mode === "fullscreen") ui.setLayoutRoot(browseRoot);
|
|
214
222
|
ui.requestRender(true);
|
|
215
223
|
} catch (error) {
|
|
216
224
|
cleanup();
|
|
@@ -213,9 +213,10 @@ export async function activateStagedRuntime(options: ActivateOptions): Promise<A
|
|
|
213
213
|
const journal = readActivationJournal(serverDir);
|
|
214
214
|
if (journal && !freshRollbackRequest(journal, request)) {
|
|
215
215
|
if (journal.desiredBuild.contentId !== options.runtime.build.contentId) {
|
|
216
|
-
// The detached worker
|
|
217
|
-
// Keep
|
|
218
|
-
|
|
216
|
+
// The detached worker may still be replacing a ready journal or retiring
|
|
217
|
+
// a stale staged activation. Keep its caller reservation until it decides.
|
|
218
|
+
const awaitingWorker = journal.phase === "staged" && worker.exitCode === null && worker.signalCode === null;
|
|
219
|
+
if ((journal.phase !== "ready" && !awaitingWorker) || !reservedAgainst(request, journal.operationId)) { unreserve(); return conflict(journal); }
|
|
219
220
|
} else if (journal.phase === "ready") {
|
|
220
221
|
const probe = await defaultActivationPorts.probe(serverDir);
|
|
221
222
|
if (matches(probe, journal)) { unreserve(); return result(journal); }
|
|
@@ -297,11 +298,21 @@ export const defaultActivationPorts: ActivationPorts = {
|
|
|
297
298
|
export async function runActivationWorker(request: UpgradeRequest, ports: ActivationPorts = defaultActivationPorts): Promise<ActivationResult> {
|
|
298
299
|
const serverDir = canonicalStateDir(request.serverDir);
|
|
299
300
|
let release: () => void;
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
301
|
+
for (let attempt = 0; ; attempt++) {
|
|
302
|
+
try { release = claimDaemonOwner(serverDir, LOCK); break; }
|
|
303
|
+
catch (error) {
|
|
304
|
+
const journal = readActivationJournal(serverDir);
|
|
305
|
+
// A staged journal can still name the abandoned build while the coordinator
|
|
306
|
+
// awaits stale-owner proof. Keep this worker alive so its caller keeps waiting.
|
|
307
|
+
if (journal?.phase === "staged" && journal.desiredBuild.contentId !== request.runtime.build.contentId
|
|
308
|
+
&& journal.rollbackPermit === undefined && reservedAgainst(request, journal.operationId)
|
|
309
|
+
&& inspectDaemonOwner(serverDir, LOCK).status === "live" && attempt < 300) {
|
|
310
|
+
await ports.pause();
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
if (journal) return journal.desiredBuild.contentId === request.runtime.build.contentId ? result(journal) : conflict(journal);
|
|
314
|
+
return { status: "deferred", operationId: request.operationId, reason: `Activation coordinator already owns this directory: ${message(error)}` };
|
|
315
|
+
}
|
|
305
316
|
}
|
|
306
317
|
let journal: ActivationJournal | undefined;
|
|
307
318
|
try {
|
|
@@ -323,6 +334,29 @@ export async function runActivationWorker(request: UpgradeRequest, ports: Activa
|
|
|
323
334
|
const probe = await ports.probe(serverDir);
|
|
324
335
|
if (probe.kind === "ready" && matches(probe, journal)) { clearReservations(journal); return result(journal); }
|
|
325
336
|
}
|
|
337
|
+
// A legacy daemon may have exited after deferring a staged build. Its durable
|
|
338
|
+
// reservation must not block every later build. Only the exclusive coordinator
|
|
339
|
+
// can retire it, after proving no writer remains and preserving compatibility.
|
|
340
|
+
if (journal?.phase === "staged" && journal.desiredBuild.contentId !== request.runtime.build.contentId
|
|
341
|
+
&& journal.rollbackPermit === undefined && !journal.candidateOwner
|
|
342
|
+
&& realpathSync(journal.agentDir) === realpathSync(request.agentDir)
|
|
343
|
+
&& reservedAgainst(request, journal.operationId)) {
|
|
344
|
+
const probe = await ports.probe(serverDir);
|
|
345
|
+
const owner = inspectDaemonOwner(serverDir);
|
|
346
|
+
const previous = journal.previousBuild ?? journal.previousCompatibility;
|
|
347
|
+
if (probe.kind === "absent" && (owner.status === "missing" || owner.status === "dead")
|
|
348
|
+
&& journal.previousOwner && !ownerIsAlive(journal.previousOwner)
|
|
349
|
+
&& previous && compatibleUpgrade(previous, request.runtime.build)
|
|
350
|
+
&& reservedAgainst(request, journal.operationId)) {
|
|
351
|
+
const retired = journal;
|
|
352
|
+
journal = { ...request, serverDir, version: 1, phase: "staged", desiredBuild: request.runtime.build,
|
|
353
|
+
previousBuild: retired.previousBuild, previousRuntime: retired.previousRuntime,
|
|
354
|
+
previousCompatibility: retired.previousCompatibility, previousOwner: retired.previousOwner,
|
|
355
|
+
emptyNamespace: retired.emptyNamespace };
|
|
356
|
+
save(journal);
|
|
357
|
+
clearReservations(retired);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
326
360
|
if (journal && journal.desiredBuild.contentId !== request.runtime.build.contentId && journal.phase !== "ready"
|
|
327
361
|
&& (committed(journal.phase) || hasActivationReservations(journal))) return conflict(journal);
|
|
328
362
|
if (journal?.phase === "recovery-required") {
|
package/src/startup/install.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { posix } from "node:path";
|
|
|
3
3
|
import { decodeServerArtifact } from "./artifact.ts";
|
|
4
4
|
import { absolutePath, probeRemoteRuntime, shellQuote } from "./runtime.ts";
|
|
5
5
|
import type { RunRemote, ServerArtifact, StagedRuntime } from "./managed-types.ts";
|
|
6
|
-
import { NODE_CHECKSUMS, validateStaged } from "../../scripts/private-runtime/format.ts";
|
|
6
|
+
import { NODE_CHECKSUMS, NODE_EXECUTABLE_CHECKSUMS, validateStaged } from "../../scripts/private-runtime/format.ts";
|
|
7
7
|
|
|
8
8
|
export interface StageRuntimeOptions {
|
|
9
9
|
run: RunRemote;
|
|
@@ -61,30 +61,90 @@ export async function stageRuntime(options: StageRuntimeOptions): Promise<Staged
|
|
|
61
61
|
|
|
62
62
|
signal?.throwIfAborted();
|
|
63
63
|
signal?.addEventListener("abort", cancel, { once: true });
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
64
|
+
const finalRoot = `${root}/releases/${artifact.build.contentId}`;
|
|
65
|
+
const cachedArtifact = `${finalRoot}/artifact.gz`;
|
|
66
|
+
const artifactPath = `${work}/artifact.gz`;
|
|
67
|
+
// Older releases may lack the archive. Its contents are authenticated by the fresh installer against the requested build.
|
|
68
|
+
const archiveCache = await checked(`set -eu
|
|
69
|
+
p=${q(finalRoot)}
|
|
70
|
+
while [ "$p" != / ]; do
|
|
71
|
+
[ ! -L "$p" ] || { echo 'corrupt cache: symlink release path' >&2; exit 1; }
|
|
72
|
+
[ ! -e "$p" ] || { [ -d "$p" ] && [ -x "$p" ]; } || { echo 'corrupt cache: unsafe release directory' >&2; exit 1; }
|
|
73
|
+
p=$(dirname "$p")
|
|
74
|
+
done
|
|
75
|
+
if [ -L ${q(cachedArtifact)} ]; then echo 'corrupt cache: artifact symlink' >&2; exit 1; fi
|
|
76
|
+
if [ ! -e ${q(cachedArtifact)} ]; then
|
|
77
|
+
if [ -e ${q(finalRoot)} ]; then printf 'legacy\\n'; else printf 'absent\\n'; fi
|
|
78
|
+
exit 0
|
|
79
|
+
fi
|
|
80
|
+
[ -f ${q(cachedArtifact)} ] || { echo 'corrupt cache: expected regular artifact' >&2; exit 1; }
|
|
81
|
+
[ "$(wc -c < ${q(cachedArtifact)})" -le 33554432 ] || { echo 'corrupt cache: artifact size limit' >&2; exit 1; }
|
|
82
|
+
cp ${q(cachedArtifact)} ${q(artifactPath)}
|
|
83
|
+
[ "$(wc -c < ${q(artifactPath)})" -le 33554432 ] || { echo 'corrupt cache: artifact size limit' >&2; exit 1; }
|
|
84
|
+
if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(artifactPath)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(artifactPath)} | cut -d ' ' -f 1); fi
|
|
85
|
+
printf 'reuse:%s\\n' "$actual"`, undefined, 120_000);
|
|
86
|
+
const archiveResponse = archiveCache.stdout.trim();
|
|
87
|
+
const archiveDigest = /^reuse:([a-f0-9]{64})$/.exec(archiveResponse)?.[1];
|
|
88
|
+
const archiveState = archiveDigest ? "reuse" : archiveResponse;
|
|
89
|
+
if (archiveState !== "reuse" && archiveState !== "absent" && archiveState !== "legacy") throw new Error("Runtime staging: unexpected artifact cache probe result");
|
|
90
|
+
if (archiveState !== "reuse") {
|
|
91
|
+
onProgress?.("verification-upload");
|
|
92
|
+
await checked(`cat > ${q(artifactPath)}`, artifact.bytes, 120_000);
|
|
75
93
|
}
|
|
76
|
-
await checked(`set -eu; if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(tar)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(tar)} | cut -d ' ' -f 1); fi; [ "$actual" = ${q(sha)} ] || { echo 'Node archive integrity mismatch' >&2; exit 1; }; tar -xzf ${q(tar)} -C ${q(work)}; mv ${q(`${work}/${archive}`)} ${q(`${work}/node`)}; rm ${q(tar)}`, undefined, 120_000);
|
|
77
|
-
await checked(`cat > ${q(`${work}/artifact.gz`)}`, artifact.bytes);
|
|
78
94
|
for (const name of ["installer.ts", "format.ts"]) {
|
|
79
95
|
const file = payload.files.find((entry) => entry.path === `scripts/private-runtime/${name}`)!;
|
|
80
96
|
await checked(`cat > ${q(`${work}/${name}`)}`, Buffer.from(file.data, "base64"));
|
|
81
97
|
}
|
|
82
|
-
const
|
|
83
|
-
|
|
98
|
+
const cachedNode = `${finalRoot}/node/bin/node`;
|
|
99
|
+
const node = `${work}/node/bin/node`;
|
|
100
|
+
onProgress?.("verifying");
|
|
101
|
+
// Authenticate the scratch copy before executing any bytes from the cached release.
|
|
102
|
+
const cached = await checked(`set -eu
|
|
103
|
+
p=${q(`${root}/releases`)}
|
|
104
|
+
while [ "$p" != / ]; do
|
|
105
|
+
[ ! -L "$p" ] || { echo 'corrupt cache: symlink release path' >&2; exit 1; }
|
|
106
|
+
[ ! -e "$p" ] || { [ -d "$p" ] && [ -x "$p" ]; } || { echo 'corrupt cache: unsafe release directory' >&2; exit 1; }
|
|
107
|
+
p=$(dirname "$p")
|
|
108
|
+
done
|
|
109
|
+
[ ! -L ${q(finalRoot)} ] || { echo 'corrupt cache: release symlink' >&2; exit 1; }
|
|
110
|
+
if [ ! -e ${q(finalRoot)} ]; then printf 'absent\\n'; exit 0; fi
|
|
111
|
+
[ -d ${q(finalRoot)} ] && [ -x ${q(finalRoot)} ] || { echo 'corrupt cache: expected accessible release directory' >&2; exit 1; }
|
|
112
|
+
p=${q(cachedNode)}
|
|
113
|
+
while [ "$p" != ${q(finalRoot)} ]; do
|
|
114
|
+
[ ! -L "$p" ] || { echo 'corrupt cache: symlink Node path' >&2; exit 1; }
|
|
115
|
+
p=$(dirname "$p")
|
|
116
|
+
done
|
|
117
|
+
[ -f ${q(cachedNode)} ] && [ -x ${q(cachedNode)} ] || { echo 'corrupt cache: expected regular Node executable' >&2; exit 1; }
|
|
118
|
+
mkdir -p ${q(`${work}/node/bin`)}
|
|
119
|
+
cp ${q(cachedNode)} ${q(node)}
|
|
120
|
+
if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(node)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(node)} | cut -d ' ' -f 1); fi
|
|
121
|
+
[ "$actual" = ${q(NODE_EXECUTABLE_CHECKSUMS[probe.platform])} ] || { echo 'Node executable integrity mismatch' >&2; exit 1; }
|
|
122
|
+
printf 'reuse\\n'`, undefined, 120_000);
|
|
123
|
+
const cachedState = cached.stdout.trim();
|
|
124
|
+
if (cachedState !== "reuse" && cachedState !== "absent") throw new Error("Runtime staging: unexpected cache probe result");
|
|
125
|
+
if (cachedState === "absent" && archiveState !== "absent") throw new Error("Runtime staging: cached release disappeared during verification");
|
|
126
|
+
const reuse = cachedState === "reuse";
|
|
127
|
+
if (!reuse) {
|
|
128
|
+
onProgress?.("node-download");
|
|
129
|
+
signal?.throwIfAborted();
|
|
130
|
+
const archive = `node-v${artifact.build.nodeVersion}-${probe.platform}`;
|
|
131
|
+
const url = `https://nodejs.org/dist/v${artifact.build.nodeVersion}/${archive}.tar.gz`;
|
|
132
|
+
const sha = NODE_CHECKSUMS[probe.platform];
|
|
133
|
+
const tar = `${work}/node.tar.gz`;
|
|
134
|
+
const remote = await run(`curl -q --fail --silent --show-error --location --proto '=https' --connect-timeout 10 --max-time 120 ${q(url)} -o ${q(tar)}`, undefined, 125_000);
|
|
135
|
+
signal?.throwIfAborted();
|
|
136
|
+
if (remote.exitCode !== 0 || remote.timedOut) {
|
|
137
|
+
onProgress?.("node-upload");
|
|
138
|
+
await checked(`cat > ${q(tar)}`, await download(url, `sha256-${sha}`, signal), 120_000);
|
|
139
|
+
}
|
|
140
|
+
await checked(`set -eu; if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum ${q(tar)} | cut -d ' ' -f 1); else actual=$(shasum -a 256 ${q(tar)} | cut -d ' ' -f 1); fi; [ "$actual" = ${q(sha)} ] || { echo 'Node archive integrity mismatch' >&2; exit 1; }; tar -xzf ${q(tar)} -C ${q(work)}; mv ${q(`${work}/${archive}`)} ${q(`${work}/node`)}; rm ${q(tar)}`, undefined, 120_000);
|
|
141
|
+
}
|
|
142
|
+
const invoke = (mode: "online" | "offline" | "reuse-only") => `env -i HOME=${q(`${work}/home`)} PATH=${q(`${work}/node/bin:/usr/bin:/bin`)} ${q(node)} ${q(`${work}/installer.ts`)} ${q(work)} ${q(root)} ${q(archiveDigest ?? artifact.sha256)} ${mode} ${q(artifact.build.contentId)}`;
|
|
143
|
+
if (!reuse) onProgress?.("dependencies");
|
|
84
144
|
signal?.throwIfAborted();
|
|
85
|
-
let installed = await run(invoke(
|
|
145
|
+
let installed = await run(invoke(reuse ? "reuse-only" : "online"), undefined, 600_000);
|
|
86
146
|
signal?.throwIfAborted();
|
|
87
|
-
if (installed.exitCode === 75) {
|
|
147
|
+
if (!reuse && installed.exitCode === 75) {
|
|
88
148
|
onProgress?.("dependencies-upload");
|
|
89
149
|
const lock = JSON.parse(Buffer.from(payload.files.find((f) => f.path === "scripts/private-runtime/package-lock.json")!.data, "base64").toString());
|
|
90
150
|
await checked(`mkdir -p ${q(`${work}/archives`)}`);
|
|
@@ -98,7 +158,7 @@ export async function stageRuntime(options: StageRuntimeOptions): Promise<Staged
|
|
|
98
158
|
const failed = batch.find((result) => result.status === "rejected");
|
|
99
159
|
if (failed?.status === "rejected") throw failed.reason;
|
|
100
160
|
}
|
|
101
|
-
installed = await run(invoke(
|
|
161
|
+
installed = await run(invoke("offline"), undefined, 600_000);
|
|
102
162
|
signal?.throwIfAborted();
|
|
103
163
|
}
|
|
104
164
|
if (installed.exitCode !== 0 || installed.timedOut) throw new Error(`Runtime staging: ${installed.stderr || "installer failed"}`);
|