@firstpick/pi-package-webui 0.10.7 → 0.10.9
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/DEVELOPMENT.md +95 -15
- package/README.md +1 -1
- package/TECHNICAL.md +6 -4
- package/bin/pi-webui-launcher.mjs +6 -3
- package/bin/pi-webui-native-update-guardian.mjs +37 -0
- package/bin/pi-webui-native-update-runner.mjs +148 -0
- package/bin/pi-webui-rpc-supervisor.mjs +85 -10
- package/bin/pi-webui-update-context.mjs +83 -0
- package/bin/pi-webui.mjs +537 -339
- package/lib/component-update-state.mjs +4 -4
- package/lib/rpc-supervisor-client.mjs +4 -0
- package/lib/rpc-supervisor-protocol.mjs +17 -4
- package/lib/update/coordination.mjs +207 -0
- package/lib/update/discovery.mjs +58 -0
- package/lib/update/migration.mjs +115 -0
- package/lib/update/native-jobs.mjs +215 -0
- package/lib/update/native-targets.mjs +81 -0
- package/lib/update/path-pi.mjs +76 -0
- package/lib/update/supervisor.mjs +50 -29
- package/lib/update/verification.mjs +18 -0
- package/lib/update-commands.mjs +17 -27
- package/package.json +2 -2
- package/public/app.js +170 -201
- package/public/index.html +5 -3
- package/public/styles.css +29 -1
- package/tests/browser/control-deck-component-updates.spec.mjs +90 -141
- package/tests/browser/update-reconnect.spec.mjs +37 -1
- package/tests/component-update-api-static.test.mjs +13 -11
- package/tests/control-deck-component-updates-static.test.mjs +25 -25
- package/tests/cwd-footer-reliability-static.test.mjs +4 -1
- package/tests/http-endpoints-harness.test.mjs +32 -9
- package/tests/mobile-static.test.mjs +9 -6
- package/tests/native-update-discovery.test.mjs +69 -0
- package/tests/native-update-lifecycle.test.mjs +92 -0
- package/tests/native-update-shell-survival.test.mjs +68 -0
- package/tests/native-update-verification.test.mjs +17 -0
- package/tests/rpc-supervisor-host.test.mjs +63 -1
- package/tests/rpc-supervisor-protocol.test.mjs +8 -0
- package/tests/run-all.mjs +6 -2
- package/tests/update-api-harness.test.mjs +57 -50
- package/tests/update-commands.test.mjs +29 -15
- package/tests/update-executor-process-tree-harness.test.mjs +84 -1
- package/tests/update-journal-harness.test.mjs +9 -1
- package/tests/update-lock-multiprocess-harness.test.mjs +60 -1
- package/tests/update-owners.test.mjs +32 -0
- package/tests/update-plan.test.mjs +110 -0
- package/tests/update-resolver.test.mjs +36 -0
- package/tests/update-supervisor-harness.test.mjs +74 -1
- package/tests/update-tab-restore-harness.test.mjs +9 -2
- package/bin/pi-webui-update-supervisor.mjs +0 -86
|
@@ -40,11 +40,11 @@ export function validateComponentUpdateRequest(body) {
|
|
|
40
40
|
export function validateUpdatePlanRequest(body) {
|
|
41
41
|
if (!body || typeof body !== "object" || Array.isArray(body)) return { ok: false, error: "Request body must be an object." };
|
|
42
42
|
const keys = Object.keys(body).sort();
|
|
43
|
-
if (keys.some((key) =>
|
|
44
|
-
return { ok: false, error: "targets must contain one
|
|
43
|
+
if (keys.some((key) => key !== "targets") || !Array.isArray(body.targets) || body.targets.length !== 1) {
|
|
44
|
+
return { ok: false, error: "targets must contain exactly one value: pi or webui." };
|
|
45
45
|
}
|
|
46
|
-
const targets =
|
|
47
|
-
if (
|
|
46
|
+
const targets = body.targets;
|
|
47
|
+
if (!TARGET_SET.has(targets[0])) return { ok: false, error: "targets contains an unsupported target." };
|
|
48
48
|
return { ok: true, targets };
|
|
49
49
|
}
|
|
50
50
|
|
|
@@ -218,6 +218,10 @@ export class RpcSupervisorClient {
|
|
|
218
218
|
if (!this.isCurrentVersion()) return Promise.reject(supervisorRestartRequiredError(this.state, "replace a Pi tab"));
|
|
219
219
|
return this.request("replace", { tabId, metadata, child }, options);
|
|
220
220
|
}
|
|
221
|
+
replaceTabUnderUpdate({ tabId, metadata, child, restart }, options) {
|
|
222
|
+
if (!this.isCurrentVersion()) return Promise.reject(supervisorRestartRequiredError(this.state, "restart a Pi tab after an update"));
|
|
223
|
+
return this.request("replace_update", { tabId, metadata, child, restart }, options);
|
|
224
|
+
}
|
|
221
225
|
closeTab(tabId, options) { return this.request("close", { tabId }, options); }
|
|
222
226
|
command(tabId, command, { requestId = newRequestId(), timeoutMs } = {}) {
|
|
223
227
|
return this.request("command", { tabId, command, ...(timeoutMs ? { timeoutMs } : {}) }, { requestId });
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import { StringDecoder } from "node:string_decoder";
|
|
3
3
|
|
|
4
|
-
export const RPC_SUPERVISOR_PROTOCOL = Object.freeze({ major: 1, minor:
|
|
4
|
+
export const RPC_SUPERVISOR_PROTOCOL = Object.freeze({ major: 1, minor: 3 });
|
|
5
5
|
// Pi permits one bounded JSONL record this large. IPC envelopes need a small
|
|
6
6
|
// additional allowance so a single valid Pi record can always be forwarded.
|
|
7
7
|
export const PI_RPC_JSONL_LINE_MAX_BYTES = 32 * 1024 * 1024;
|
|
@@ -27,7 +27,7 @@ const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
|
27
27
|
const TAB_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
28
28
|
const SCOPE_ID = /^[a-f0-9]{64}$/;
|
|
29
29
|
const SEQ = /^(?:0|[1-9][0-9]{0,19})$/;
|
|
30
|
-
const OPERATION_TYPES = new Set(["create", "update", "replace", "close", "command", "write", "ack", "prepare_handoff", "detach", "shutdown"]);
|
|
30
|
+
const OPERATION_TYPES = new Set(["create", "update", "replace", "replace_update", "close", "command", "write", "ack", "prepare_handoff", "detach", "shutdown"]);
|
|
31
31
|
|
|
32
32
|
export class RpcSupervisorProtocolError extends Error {
|
|
33
33
|
constructor(message, code = "RPC_SUPERVISOR_PROTOCOL") {
|
|
@@ -191,14 +191,27 @@ export function validateClientFrame(frame) {
|
|
|
191
191
|
};
|
|
192
192
|
}
|
|
193
193
|
if (!OPERATION_TYPES.has(type)) fail(`unsupported operation: ${type}`);
|
|
194
|
-
const common = new Set(["type", "requestId", "tabId", "metadata", "child", "command", "timeoutMs", "cursor"]);
|
|
194
|
+
const common = new Set(["type", "requestId", "tabId", "metadata", "child", "command", "timeoutMs", "cursor", "restart"]);
|
|
195
195
|
onlyKeys(value, common, type);
|
|
196
|
+
if (type !== "replace_update" && value.restart !== undefined) fail("restart authorization is only valid for replace_update");
|
|
196
197
|
const requestId = string(value.requestId, "requestId", { pattern: REQUEST_ID });
|
|
197
198
|
if (type === "create") {
|
|
198
199
|
return { type, requestId, tabId: validateTabId(value.tabId), metadata: validateMetadata(value.metadata), child: validateChild(value.child) };
|
|
199
200
|
}
|
|
200
201
|
if (type === "update") return { type, requestId, tabId: validateTabId(value.tabId), metadata: validateMetadata(value.metadata) };
|
|
201
|
-
if (type === "replace"
|
|
202
|
+
if (type === "replace" || type === "replace_update") {
|
|
203
|
+
const commonReplace = { type, requestId, tabId: validateTabId(value.tabId),
|
|
204
|
+
metadata: value.metadata === undefined ? undefined : validateMetadata(value.metadata), child: validateChild(value.child) };
|
|
205
|
+
if (type === "replace") return commonReplace;
|
|
206
|
+
const restart = object(value.restart, "restart");
|
|
207
|
+
onlyKeys(restart, new Set(["transactionId", "lockToken", "effectRoot", "nonce"]), "restart");
|
|
208
|
+
return { ...commonReplace, restart: {
|
|
209
|
+
transactionId: string(restart.transactionId, "restart.transactionId", { pattern: REQUEST_ID }),
|
|
210
|
+
lockToken: string(restart.lockToken, "restart.lockToken", { pattern: REQUEST_ID }),
|
|
211
|
+
effectRoot: string(restart.effectRoot, "restart.effectRoot", { max: 4096 }),
|
|
212
|
+
nonce: string(restart.nonce, "restart.nonce", { pattern: REQUEST_ID }),
|
|
213
|
+
} };
|
|
214
|
+
}
|
|
202
215
|
if (type === "close") return { type, requestId, tabId: validateTabId(value.tabId) };
|
|
203
216
|
if (type === "command" || type === "write") {
|
|
204
217
|
const command = object(value.command, "command");
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { chmod, lstat, mkdir, open, readFile, realpath, readdir, rename, rm } from "node:fs/promises";
|
|
3
|
+
import { tmpdir, userInfo } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
const IDENTIFIER = /^[A-Za-z0-9._-]{1,128}$/;
|
|
7
|
+
const tokenFor = (root) => createHash("sha256").update(root).digest("hex");
|
|
8
|
+
|
|
9
|
+
async function privateDirectory(root) {
|
|
10
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
11
|
+
// A symlinked coordination root could move locks into a target being replaced.
|
|
12
|
+
if (!(await lstat(root)).isDirectory() || await realpath(root) !== root) throw new Error("Update coordination root is not a physical directory.");
|
|
13
|
+
if (process.platform !== "win32") {
|
|
14
|
+
await chmod(root, 0o700);
|
|
15
|
+
const info = await lstat(root);
|
|
16
|
+
if (info.uid !== process.getuid()) throw new Error("Update coordination directory is not owned by this OS user.");
|
|
17
|
+
}
|
|
18
|
+
return root;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function sharedUpdateRoot({ home, platform = process.platform } = {}) {
|
|
22
|
+
// An explicit fixture home must agree with its child processes, even when
|
|
23
|
+
// the outer test runner supplies a different default isolation directory.
|
|
24
|
+
const testHome = (process.env.NODE_ENV === "test" || process.env.PI_WEBUI_STARTUP_PROBE === "1") &&
|
|
25
|
+
process.env.PI_WEBUI_UPDATE_TEST_HOME;
|
|
26
|
+
if (home === undefined) {
|
|
27
|
+
home = testHome && path.resolve(testHome).startsWith(`${path.resolve(tmpdir())}${path.sep}`)
|
|
28
|
+
? testHome : userInfo().homedir;
|
|
29
|
+
}
|
|
30
|
+
const root = platform === "win32"
|
|
31
|
+
? path.join(home, "AppData", "Local", "PiWebUI", "updates")
|
|
32
|
+
: path.join(home, ".local", "state", "pi-webui-updates");
|
|
33
|
+
return privateDirectory(path.resolve(root));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function canonicalEffects(roots, stateRoot) {
|
|
37
|
+
const canonical = [...new Set(await Promise.all(roots.map((root) => realpath(root))))].sort();
|
|
38
|
+
if (!canonical.length) throw new Error("An update must have at least one proven physical effect root.");
|
|
39
|
+
for (const root of canonical) {
|
|
40
|
+
const relative = path.relative(root, stateRoot);
|
|
41
|
+
if (relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative))) {
|
|
42
|
+
throw new Error("Update coordination must remain outside every affected installation.");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return canonical;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function exclusiveJson(file, value) {
|
|
49
|
+
const handle = await open(file, "wx", 0o600);
|
|
50
|
+
try { await handle.writeFile(`${JSON.stringify(value)}\n`); await handle.sync(); } finally { await handle.close(); }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function atomicJson(file, value) {
|
|
54
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
55
|
+
try {
|
|
56
|
+
await exclusiveJson(temporary, value);
|
|
57
|
+
await rename(temporary, file);
|
|
58
|
+
} finally { await rm(temporary, { force: true }); }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function effectLockPath(stateRoot, canonicalRoot) {
|
|
62
|
+
return path.join(stateRoot, "effects", `${tokenFor(canonicalRoot)}.lock`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function inside(root, candidate) {
|
|
66
|
+
const relative = path.relative(root, candidate);
|
|
67
|
+
return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function overlaps(left, right) { return inside(left, right) || inside(right, left); }
|
|
71
|
+
|
|
72
|
+
async function activeEffectLocks(stateRoot) {
|
|
73
|
+
let entries = [];
|
|
74
|
+
try { entries = await readdir(path.join(stateRoot, "effects")); }
|
|
75
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
76
|
+
const locks = [];
|
|
77
|
+
for (const name of entries.filter((entry) => entry.endsWith(".lock"))) {
|
|
78
|
+
const lock = JSON.parse(await readFile(path.join(stateRoot, "effects", name), "utf8"));
|
|
79
|
+
if (!path.isAbsolute(lock.canonicalRoot) || !IDENTIFIER.test(lock.transactionId)) throw new Error("Effect fence is unreadable; manual recovery is required.");
|
|
80
|
+
locks.push(lock);
|
|
81
|
+
}
|
|
82
|
+
return locks;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function assertEffectAdmission(stateRoot, roots) {
|
|
86
|
+
const effects = await canonicalEffects(roots, stateRoot);
|
|
87
|
+
let acquisitionHeld = false;
|
|
88
|
+
try { await lstat(path.join(stateRoot, "effects", "acquire.guard")); acquisitionHeld = true; }
|
|
89
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
90
|
+
if (acquisitionHeld || (await activeEffectLocks(stateRoot)).some((lock) => effects.some((effect) => overlaps(effect, lock.canonicalRoot)))) {
|
|
91
|
+
throw Object.assign(new Error("An affected installation is fenced for an update or recovery."), { code: "UPDATE_FENCED" });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** A crashed owner cannot release locks: only observed command receipts permit release. */
|
|
96
|
+
export async function acquireEffectLocks(stateRoot, roots, transactionId) {
|
|
97
|
+
if (!IDENTIFIER.test(transactionId)) throw new TypeError("invalid transaction id");
|
|
98
|
+
const effects = await canonicalEffects(roots, stateRoot);
|
|
99
|
+
await mkdir(path.join(stateRoot, "effects"), { recursive: true, mode: 0o700 });
|
|
100
|
+
// Serializing acquisition also prevents parent/child effect roots from
|
|
101
|
+
// entering concurrently before either lock file becomes visible.
|
|
102
|
+
const guard = path.join(stateRoot, "effects", "acquire.guard");
|
|
103
|
+
let guardHandle;
|
|
104
|
+
try { guardHandle = await open(guard, "wx", 0o600); }
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (error.code === "EEXIST") throw Object.assign(new Error("Update admission is held or recovery is required."), { code: "UPDATE_FENCED" });
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
const token = randomUUID();
|
|
110
|
+
const acquired = [];
|
|
111
|
+
try {
|
|
112
|
+
if ((await activeEffectLocks(stateRoot)).some((lock) => effects.some((effect) => overlaps(effect, lock.canonicalRoot)))) {
|
|
113
|
+
throw Object.assign(new Error("An affected installation is already fenced."), { code: "UPDATE_FENCED" });
|
|
114
|
+
}
|
|
115
|
+
for (const root of effects) {
|
|
116
|
+
const file = effectLockPath(stateRoot, root);
|
|
117
|
+
await exclusiveJson(file, { token, transactionId, canonicalRoot: root, at: new Date().toISOString() });
|
|
118
|
+
acquired.push(file);
|
|
119
|
+
}
|
|
120
|
+
return Object.freeze({ token, transactionId, effects, files: acquired });
|
|
121
|
+
} catch (error) {
|
|
122
|
+
for (const file of acquired) await rm(file, { force: true });
|
|
123
|
+
if (error?.code === "EEXIST") throw Object.assign(new Error("An affected installation is already fenced."), { code: "UPDATE_FENCED" });
|
|
124
|
+
throw error;
|
|
125
|
+
} finally {
|
|
126
|
+
await guardHandle.close();
|
|
127
|
+
await rm(guard);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function releaseEffectLocks(lock, { completionVerified = false } = {}) {
|
|
132
|
+
if (!completionVerified) throw new Error("Cannot release effects before command completion is verified.");
|
|
133
|
+
for (const file of lock.files) {
|
|
134
|
+
const saved = JSON.parse(await readFile(file, "utf8"));
|
|
135
|
+
if (saved.token !== lock.token || saved.transactionId !== lock.transactionId) throw new Error("Update effect lock changed owner.");
|
|
136
|
+
}
|
|
137
|
+
for (const file of lock.files) await rm(file);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function persistSharedJob(stateRoot, job) {
|
|
141
|
+
if (!IDENTIFIER.test(job?.transactionId)) throw new TypeError("invalid transaction id");
|
|
142
|
+
await mkdir(path.join(stateRoot, "jobs"), { recursive: true, mode: 0o700 });
|
|
143
|
+
await atomicJson(path.join(stateRoot, "jobs", `${job.transactionId}.json`), job);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function registerUpdateParticipant(stateRoot, { kind, roots, pid = process.pid } = {}) {
|
|
147
|
+
if (!["server", "rpc-supervisor"].includes(kind)) throw new TypeError("unknown update participant");
|
|
148
|
+
const canonicalRoots = await canonicalEffects(roots, stateRoot);
|
|
149
|
+
const token = randomUUID();
|
|
150
|
+
const file = path.join(stateRoot, "participants", `${token}.json`);
|
|
151
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
152
|
+
await exclusiveJson(file, { token, kind, pid, canonicalRoots, registeredAt: new Date().toISOString(), ack: null });
|
|
153
|
+
return Object.freeze({ token, kind, pid, file, canonicalRoots });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export async function acknowledgeUpdateFence(participant, lock, idle) {
|
|
157
|
+
if (!participant || !lock) return;
|
|
158
|
+
if (!participant.canonicalRoots.some((root) => lock.effects.some((effect) => overlaps(effect, root)))) return;
|
|
159
|
+
await atomicJson(participant.file, { token: participant.token, kind: participant.kind, pid: participant.pid,
|
|
160
|
+
canonicalRoots: participant.canonicalRoots, ack: { lockToken: lock.token, idle: idle === true, at: new Date().toISOString() } });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export async function effectLockForRoot(stateRoot, root) {
|
|
164
|
+
const canonical = await realpath(root);
|
|
165
|
+
const matching = (await activeEffectLocks(stateRoot)).filter((lock) => overlaps(canonical, lock.canonicalRoot));
|
|
166
|
+
if (matching.length > 1) throw new Error("Multiple overlapping update fences require manual recovery.");
|
|
167
|
+
return matching[0] || null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export async function unregisterUpdateParticipant(participant) {
|
|
171
|
+
if (!participant) return;
|
|
172
|
+
const current = JSON.parse(await readFile(participant.file, "utf8"));
|
|
173
|
+
if (current.token !== participant.token || current.pid !== participant.pid) throw new Error("Update participant changed identity.");
|
|
174
|
+
await rm(participant.file);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function affectedParticipants(stateRoot, lock) {
|
|
178
|
+
let entries = [];
|
|
179
|
+
try { entries = await readdir(path.join(stateRoot, "participants")); }
|
|
180
|
+
catch (error) { if (error?.code === "ENOENT") return []; throw error; }
|
|
181
|
+
const participants = [];
|
|
182
|
+
for (const entry of entries.filter((name) => /^[a-f0-9-]{36}\.json$/.test(name))) {
|
|
183
|
+
let participant;
|
|
184
|
+
try { participant = JSON.parse(await readFile(path.join(stateRoot, "participants", entry), "utf8")); }
|
|
185
|
+
catch { throw new Error("Update participant state is unreadable; recovery is required."); }
|
|
186
|
+
if (participant.canonicalRoots?.some((root) => lock.effects.some((effect) => overlaps(effect, root)))) participants.push(participant);
|
|
187
|
+
}
|
|
188
|
+
return participants;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function createUpdateAdmissionCounter() {
|
|
192
|
+
let pending = 0;
|
|
193
|
+
return {
|
|
194
|
+
begin() {
|
|
195
|
+
pending++;
|
|
196
|
+
let closed = false;
|
|
197
|
+
return () => { if (!closed) { pending--; closed = true; } };
|
|
198
|
+
},
|
|
199
|
+
get idle() { return pending === 0; },
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export async function readSharedJob(stateRoot, transactionId) {
|
|
204
|
+
if (!IDENTIFIER.test(transactionId)) throw new TypeError("invalid transaction id");
|
|
205
|
+
try { return JSON.parse(await readFile(path.join(stateRoot, "jobs", `${transactionId}.json`), "utf8")); }
|
|
206
|
+
catch (error) { if (error?.code === "ENOENT") return null; throw error; }
|
|
207
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { lstat, readdir } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { readSharedJob } from "./coordination.mjs";
|
|
4
|
+
import { inspectNativeJob } from "./native-jobs.mjs";
|
|
5
|
+
|
|
6
|
+
const TERMINAL_PHASES = new Set(["success", "partial", "failed", "unchanged"]);
|
|
7
|
+
const JOB_FILE = /^[a-f0-9-]{36}\.json$/i;
|
|
8
|
+
|
|
9
|
+
export function nativeJobBlocksUpdates(job) {
|
|
10
|
+
return Boolean(job && !TERMINAL_PHASES.has(job.phase));
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Keep fence tokens, private capsule paths and process credentials off HTTP responses. */
|
|
14
|
+
export function publicNativeJob(job) {
|
|
15
|
+
if (!job) return null;
|
|
16
|
+
const { transactionId, plan, phase, receipts = [], verifiedTargets = [], outcome = "", error = "" } = job;
|
|
17
|
+
return { transactionId, plan, phase, receipts, verifiedTargets, outcome, error };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Discover launched jobs without trusting browser storage or taking over another owner. */
|
|
21
|
+
export async function discoverNativeJobs(stateRoot, { agentDir, ownerPackageRoot, ownerBootIdentity, maxRecords = 1024 }) {
|
|
22
|
+
const result = { pi: null, webui: null };
|
|
23
|
+
const directory = path.join(stateRoot, "jobs");
|
|
24
|
+
let entries;
|
|
25
|
+
try { entries = await readdir(directory, { withFileTypes: true }); }
|
|
26
|
+
catch (error) { if (error.code === "ENOENT") return result; throw error; }
|
|
27
|
+
const records = entries.filter((entry) => JOB_FILE.test(entry.name));
|
|
28
|
+
let launchedRecords = 0;
|
|
29
|
+
const selectedTimes = { pi: 0, webui: 0 };
|
|
30
|
+
for (const entry of records) {
|
|
31
|
+
const info = await lstat(path.join(directory, entry.name));
|
|
32
|
+
if (!info.isFile() || info.size > 256 * 1024) throw new Error("An update record is linked or exceeds its size limit.");
|
|
33
|
+
const transactionId = entry.name.slice(0, -5);
|
|
34
|
+
const record = await readSharedJob(stateRoot, transactionId);
|
|
35
|
+
if (record?.transactionId !== transactionId || record.plan?.schemaVersion !== 2 || !record.plan.context ||
|
|
36
|
+
!["pi", "webui"].includes(record.plan.requested)) throw new Error("An update record cannot be verified; inspect the host.");
|
|
37
|
+
if (record.phase === "planned" || record.plan.context.agentDir !== agentDir ||
|
|
38
|
+
record.plan.context.ownerPackageRoot !== ownerPackageRoot) continue;
|
|
39
|
+
if (++launchedRecords > maxRecords) throw new Error("Launched update history exceeds the discovery limit; inspect the host before starting another update.");
|
|
40
|
+
const createdAt = Date.parse(record.plan.createdAt);
|
|
41
|
+
if (!Number.isFinite(createdAt)) throw new Error("An update record has no valid creation time.");
|
|
42
|
+
const job = await inspectNativeJob(stateRoot, transactionId);
|
|
43
|
+
if (!job) throw new Error("An update record disappeared during discovery.");
|
|
44
|
+
if (ownerBootIdentity && record.plan.context.ownerBootIdentity !== ownerBootIdentity &&
|
|
45
|
+
nativeJobBlocksUpdates(job) && !["launching", "running"].includes(job.phase)) {
|
|
46
|
+
job.phase = "unknown";
|
|
47
|
+
job.error = "The original update owner exited; command receipts remain available, but recovery needs manual verification.";
|
|
48
|
+
}
|
|
49
|
+
const target = record.plan.requested;
|
|
50
|
+
const previous = result[target];
|
|
51
|
+
const priority = Number(nativeJobBlocksUpdates(job)) - Number(nativeJobBlocksUpdates(previous));
|
|
52
|
+
if (!previous || priority > 0 || priority === 0 && createdAt >= selectedTimes[target]) {
|
|
53
|
+
result[target] = publicNativeJob(job);
|
|
54
|
+
selectedTimes[target] = createdAt;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { chmod, lstat, mkdir, open, readFile, realpath, rename, rm, stat } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { managedRuntimePaths, probeStartupRestore, readRuntimePointer } from "./supervisor.mjs";
|
|
5
|
+
|
|
6
|
+
const WEBUI = "@firstpick/pi-package-webui";
|
|
7
|
+
const VERSION = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
8
|
+
const digest = (text) => createHash("sha256").update(text).digest("hex");
|
|
9
|
+
|
|
10
|
+
export function compareWebuiVersions(left, right) {
|
|
11
|
+
const a = VERSION.exec(String(left || ""));
|
|
12
|
+
const b = VERSION.exec(String(right || ""));
|
|
13
|
+
if (!a || !b) return null;
|
|
14
|
+
for (let i = 1; i <= 3; i++) {
|
|
15
|
+
const diff = Number(a[i]) - Number(b[i]);
|
|
16
|
+
if (diff) return Math.sign(diff);
|
|
17
|
+
}
|
|
18
|
+
if (!a[4] && !b[4]) return 0;
|
|
19
|
+
if (!a[4]) return 1;
|
|
20
|
+
if (!b[4]) return -1;
|
|
21
|
+
const ac = a[4].split(".");
|
|
22
|
+
const bc = b[4].split(".");
|
|
23
|
+
for (let i = 0; i < Math.max(ac.length, bc.length); i++) {
|
|
24
|
+
if (ac[i] === undefined) return -1;
|
|
25
|
+
if (bc[i] === undefined) return 1;
|
|
26
|
+
const x = ac[i], y = bc[i];
|
|
27
|
+
if (x === y) continue;
|
|
28
|
+
const xn = /^\d+$/.test(x), yn = /^\d+$/.test(y);
|
|
29
|
+
if (xn && yn) return BigInt(x) > BigInt(y) ? 1 : -1;
|
|
30
|
+
if (xn !== yn) return xn ? -1 : 1;
|
|
31
|
+
return x > y ? 1 : -1;
|
|
32
|
+
}
|
|
33
|
+
return 0;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function privateJson(file, value) {
|
|
37
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
38
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
39
|
+
try {
|
|
40
|
+
const handle = await open(temporary, "wx", 0o600);
|
|
41
|
+
try { await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`); await handle.sync(); }
|
|
42
|
+
finally { await handle.close(); }
|
|
43
|
+
await rename(temporary, file);
|
|
44
|
+
await chmod(file, 0o600).catch(() => {});
|
|
45
|
+
} finally { await rm(temporary, { force: true }); }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function candidateBootstrap(bootstrapRoot) {
|
|
49
|
+
const root = path.resolve(bootstrapRoot);
|
|
50
|
+
if (!(await lstat(root)).isDirectory()) throw new Error("Installed Web UI is linked or not a package directory.");
|
|
51
|
+
const resolved = await realpath(root);
|
|
52
|
+
if (resolved !== root || !root.split(path.sep).includes("node_modules")) throw new Error("Bootstrap is not a proven npm package root.");
|
|
53
|
+
const manifest = JSON.parse(await readFile(path.join(root, "package.json"), "utf8"));
|
|
54
|
+
const entry = path.join(root, "bin", "pi-webui.mjs");
|
|
55
|
+
if (manifest.name !== WEBUI || !VERSION.test(manifest.version) || !(await stat(entry)).isFile() || await realpath(entry) !== entry) {
|
|
56
|
+
throw new Error("Installed Web UI package name, version or server entry is unproven.");
|
|
57
|
+
}
|
|
58
|
+
return { root, entry, version: manifest.version };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function pointerSnapshot(paths) {
|
|
62
|
+
const current = await readFile(paths.currentPointer, "utf8");
|
|
63
|
+
const previous = await readFile(paths.previousPointer, "utf8").catch((error) => {
|
|
64
|
+
if (error.code === "ENOENT") return null;
|
|
65
|
+
throw error;
|
|
66
|
+
});
|
|
67
|
+
return { current, previous, currentHash: digest(current), previousHash: digest(previous || "") };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Never discard pointers or runtime trees; the marker only changes bootstrap selection. */
|
|
71
|
+
export async function migrateLegacyBootstrap(agentDir, bootstrapRoot, { probe = probeStartupRestore } = {}) {
|
|
72
|
+
const pointer = await readRuntimePointer(agentDir, "current");
|
|
73
|
+
if (!pointer) return { migrated: false, serverEntry: path.join(bootstrapRoot, "bin", "pi-webui.mjs"), reason: "no-legacy-pointer" };
|
|
74
|
+
const paths = managedRuntimePaths(agentDir);
|
|
75
|
+
const legacy = { migrated: false, serverEntry: pointer.serverEntry, reason: "legacy-fallback" };
|
|
76
|
+
try {
|
|
77
|
+
const bootstrap = await candidateBootstrap(bootstrapRoot);
|
|
78
|
+
const legacyManifest = JSON.parse(await readFile(path.join(path.dirname(path.dirname(pointer.serverEntry)), "package.json"), "utf8"));
|
|
79
|
+
if (legacyManifest.name !== WEBUI || legacyManifest.version !== pointer.version) return { ...legacy, reason: "legacy-pointer-version-unproven" };
|
|
80
|
+
const comparison = compareWebuiVersions(bootstrap.version, pointer.version);
|
|
81
|
+
if (comparison === null || comparison < 0) return { ...legacy, reason: "downgrade-or-unproven-version" };
|
|
82
|
+
const snapshot = await pointerSnapshot(paths);
|
|
83
|
+
const markerFile = path.join(paths.root, "native-migration.json");
|
|
84
|
+
let marker;
|
|
85
|
+
try { marker = JSON.parse(await readFile(markerFile, "utf8")); }
|
|
86
|
+
catch (error) { if (error.code !== "ENOENT") return { ...legacy, reason: "migration-marker-invalid" }; }
|
|
87
|
+
if (marker && (marker.schemaVersion !== 1 || marker.currentHash !== snapshot.currentHash ||
|
|
88
|
+
marker.previousHash !== snapshot.previousHash || marker.bootstrapRoot !== bootstrap.root ||
|
|
89
|
+
!path.isAbsolute(marker.backups || "") || compareWebuiVersions(bootstrap.version, marker.version) === null)) {
|
|
90
|
+
return { ...legacy, reason: "migration-marker-mismatch" };
|
|
91
|
+
}
|
|
92
|
+
if (marker && compareWebuiVersions(bootstrap.version, marker.version) < 0) {
|
|
93
|
+
return { ...legacy, reason: "downgrade-below-accepted-version" };
|
|
94
|
+
}
|
|
95
|
+
const health = await probe(bootstrap.entry, { expectedVersion: bootstrap.version });
|
|
96
|
+
if (!health?.ok) return { ...legacy, reason: "startup-or-restore-validation-failed" };
|
|
97
|
+
if ((await candidateBootstrap(bootstrapRoot)).version !== bootstrap.version ||
|
|
98
|
+
(await pointerSnapshot(paths)).currentHash !== snapshot.currentHash ||
|
|
99
|
+
(await pointerSnapshot(paths)).previousHash !== snapshot.previousHash) {
|
|
100
|
+
return { ...legacy, reason: "candidate-or-pointer-changed-during-probe" };
|
|
101
|
+
}
|
|
102
|
+
if (!marker) {
|
|
103
|
+
const backups = path.join(paths.root, "pointer-backups", randomUUID());
|
|
104
|
+
await mkdir(backups, { recursive: true, mode: 0o700 });
|
|
105
|
+
await privateJson(path.join(backups, "current.json"), JSON.parse(snapshot.current));
|
|
106
|
+
await privateJson(path.join(backups, "previous.json"), snapshot.previous ? JSON.parse(snapshot.previous) : { absent: true });
|
|
107
|
+
marker = { schemaVersion: 1, bootstrapRoot: bootstrap.root, version: bootstrap.version,
|
|
108
|
+
currentHash: snapshot.currentHash, previousHash: snapshot.previousHash, backups };
|
|
109
|
+
await privateJson(markerFile, marker);
|
|
110
|
+
} else if (marker.version !== bootstrap.version) {
|
|
111
|
+
await privateJson(markerFile, { ...marker, version: bootstrap.version });
|
|
112
|
+
}
|
|
113
|
+
return { migrated: true, serverEntry: bootstrap.entry, reason: "validated-equal-or-newer", legacyEntry: pointer.serverEntry };
|
|
114
|
+
} catch (error) { return { ...legacy, reason: `validation-failed: ${String(error?.message || error).slice(0, 160)}` }; }
|
|
115
|
+
}
|