@nathanstephenson/flow 0.1.1 → 0.1.2
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 +5 -2
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +187 -36
- package/dist/cli/host-control.js +2 -2
- package/dist/cli/install-guard.js +5 -2
- package/dist/cli/systemd-update.js +129 -0
- package/dist/cli/update.js +36 -6
- package/dist/cli/web-update.js +22 -3
- package/dist/daemon/host-control-routes.js +18 -2
- package/dist/daemon/server.js +17 -1
- package/package.json +1 -1
- package/web/dist/assets/{index-CaJfF2tQ.js → index-BlZBshi8.js} +3 -3
- package/web/dist/assets/{settings-mcp-COi1p_1o.js → settings-mcp-ZMIfuuZU.js} +1 -1
- package/web/dist/assets/{settings-secrets-C599riFl.js → settings-secrets-CgTrBpi2.js} +1 -1
- package/web/dist/assets/{settings-workflows-BPjeFoaT.js → settings-workflows-1DMYfZtn.js} +1 -1
- package/web/dist/assets/{workflows-Bmsrl5kE.js → workflows-CBuB_bva.js} +1 -1
- package/web/dist/assets/{workflows-pane-DJ3UwHjd.js → workflows-pane-DPXGg0na.js} +1 -1
- package/web/dist/index.html +1 -1
package/README.md
CHANGED
|
@@ -60,7 +60,7 @@ do not tag a version until its license and release contents are approved.
|
|
|
60
60
|
## Updating Flow
|
|
61
61
|
|
|
62
62
|
Run `flow update` to install `@nathanstephenson/flow@latest` with the npm selected by PATH.
|
|
63
|
-
An authorised browser connected to a background Session Host can perform the same guarded operation
|
|
63
|
+
An authorised browser connected to a background or configured systemd-owned Session Host can perform the same guarded operation
|
|
64
64
|
from **Settings → General → Flow update** after explicit confirmation. The browser checks only npm's
|
|
65
65
|
stable `latest` tag, cannot select a package/version/path or force active work to stop, and reconnects
|
|
66
66
|
on the same address and port to verify the running version. Updates are never automatic.
|
|
@@ -73,7 +73,10 @@ installations manually with npm after stopping all Flow processes.
|
|
|
73
73
|
Close all CLI/TUI clients and stop other Session Hosts that use this installation, including those
|
|
74
74
|
under other `FLOW_STATE_DIR` roots. The selected root's background Session Host can stay running:
|
|
75
75
|
Flow stops it, updates, and restores its saved address, port, working directory and OIDC settings
|
|
76
|
-
with a new process. Use `--force` to interrupt active work.
|
|
76
|
+
with a new process. Use `--force` to interrupt active work. Unmanaged foreground and embedded hosts are refused.
|
|
77
|
+
For foreground systemd services (including system units with `User=agent`), see
|
|
78
|
+
[systemd update setup](docs/systemd-updates.md): a separate non-root updater unit retains service ownership
|
|
79
|
+
and needs only narrowly scoped start/stop authority configured once by an administrator.
|
|
77
80
|
The same OIDC configuration must be present when you update. No version argument is accepted.
|
|
78
81
|
|
|
79
82
|
Before first adopting this release, stop **all** older Flow processes. Old processes have no
|
package/dist/build-id
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
a05670ad-d8b7-4859-afde-7cc8ad2f6548
|
package/dist/cli/bootstrap.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
// src/cli/bootstrap.ts
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
|
-
import { resolve as resolve3, join as
|
|
5
|
+
import { resolve as resolve3, join as join7 } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
|
|
8
8
|
// src/cli/install-guard.ts
|
|
@@ -55,11 +55,11 @@ async function getHostStatus(host) {
|
|
|
55
55
|
if (status.instanceId !== host.instanceId || status.pid !== host.pid) throw new Error("Session Host identity changed");
|
|
56
56
|
return status;
|
|
57
57
|
}
|
|
58
|
-
async function requestHostStop(host, force) {
|
|
58
|
+
async function requestHostStop(host, force, quiesce = false) {
|
|
59
59
|
const response = await fetch(`${host.url}/api/host/stop`, {
|
|
60
60
|
method: "POST",
|
|
61
61
|
headers: { authorization: `Bearer ${host.token}`, "content-type": "application/json" },
|
|
62
|
-
body: JSON.stringify({ instanceId: host.instanceId, force }),
|
|
62
|
+
body: JSON.stringify({ instanceId: host.instanceId, force, quiesce }),
|
|
63
63
|
signal: AbortSignal.timeout(5e3)
|
|
64
64
|
});
|
|
65
65
|
if (!response.ok) throw new HostRefusal(`Session Host refused: ${await response.text()}`);
|
|
@@ -334,13 +334,15 @@ function installation(slot) {
|
|
|
334
334
|
} };
|
|
335
335
|
});
|
|
336
336
|
}
|
|
337
|
-
async function beginUpdate(lease, previous, host) {
|
|
337
|
+
async function beginUpdate(lease, previous, host, systemdArgs) {
|
|
338
338
|
const barrier = { pid: process.pid, id: randomUUID2(), phase: "preparing", previous };
|
|
339
339
|
await locked(() => {
|
|
340
340
|
if (readBarrier(barrierPath)) throw new Error(`Update already blocked: ${barrierPath}`);
|
|
341
341
|
const active = leases();
|
|
342
342
|
if (!active.some((other) => other.id === lease.id && other.pid === process.pid && other.root === lease.root)) throw new Error("Update process has no installation lease");
|
|
343
|
-
|
|
343
|
+
const selected = host && active.find((other) => other.pid === host.pid && other.root === lease.root);
|
|
344
|
+
if (systemdArgs && selected && JSON.stringify(selected.args) !== JSON.stringify(systemdArgs)) throw new Error("Configured systemd hostArgs do not match the running Session Host; correct systemd-update.json before updating");
|
|
345
|
+
if (active.some((other) => other.id !== lease.id && !(host && other.pid === host.pid && other.root === lease.root && (systemdArgs ? JSON.stringify(other.args) === JSON.stringify(systemdArgs) : other.args.includes("--background-host"))))) throw new Error("Stop all other Flow hosts and CLI/TUI clients using this installation first");
|
|
344
346
|
if (host && !active.some((other) => other.pid === host.pid && other.root === lease.root)) throw new Error("Stop all pre-guard Flow processes before updating");
|
|
345
347
|
save(barrier);
|
|
346
348
|
});
|
|
@@ -389,8 +391,8 @@ function installation(slot) {
|
|
|
389
391
|
|
|
390
392
|
// src/cli/update.ts
|
|
391
393
|
import { execFileSync } from "node:child_process";
|
|
392
|
-
import { accessSync, constants as constants2, readFileSync as
|
|
393
|
-
import { delimiter, join as
|
|
394
|
+
import { accessSync, constants as constants2, readFileSync as readFileSync4, realpathSync as realpathSync4 } from "node:fs";
|
|
395
|
+
import { delimiter, join as join5, resolve as resolve2 } from "node:path";
|
|
394
396
|
|
|
395
397
|
// src/cli/install-process.ts
|
|
396
398
|
import { spawn as spawn2 } from "node:child_process";
|
|
@@ -435,6 +437,113 @@ async function replacePackage(npm, prefix, packageSpec) {
|
|
|
435
437
|
if (result.code !== 0) throw new Error(`npm installation failed (${result.signal ?? result.code})`);
|
|
436
438
|
}
|
|
437
439
|
|
|
440
|
+
// src/cli/systemd-update.ts
|
|
441
|
+
import { execFile } from "node:child_process";
|
|
442
|
+
import { promisify } from "node:util";
|
|
443
|
+
import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, unlinkSync as unlinkSync3 } from "node:fs";
|
|
444
|
+
import { join as join4 } from "node:path";
|
|
445
|
+
var exec = promisify(execFile);
|
|
446
|
+
function parseSystemdUpdate(value) {
|
|
447
|
+
const c = value;
|
|
448
|
+
const unit = (v) => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]*\.service$/.test(v);
|
|
449
|
+
if (!c || !["system", "user"].includes(c.scope) || !unit(c.service) || !unit(c.updater) || c.service === c.updater || !Array.isArray(c.hostArgs) || c.hostArgs[0] !== "serve" || c.hostArgs.some((a) => typeof a !== "string") || c.hostArgs.includes("--background-host") || c.hostArgs.includes("start")) {
|
|
450
|
+
throw new Error("Invalid systemd-update.json: use distinct fixed service units and foreground serve arguments");
|
|
451
|
+
}
|
|
452
|
+
return c;
|
|
453
|
+
}
|
|
454
|
+
function systemdUpdate(root) {
|
|
455
|
+
try {
|
|
456
|
+
return parseSystemdUpdate(JSON.parse(readFileSync3(join4(root, "systemd-update.json"), "utf8")));
|
|
457
|
+
} catch (error) {
|
|
458
|
+
if (error.code === "ENOENT") return void 0;
|
|
459
|
+
throw error;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
var SystemdCommandFailed = class extends Error {
|
|
463
|
+
completed;
|
|
464
|
+
constructor(error) {
|
|
465
|
+
super(String(error), { cause: error });
|
|
466
|
+
const command = error;
|
|
467
|
+
this.completed = typeof command.code === "number" && !command.killed && !command.signal;
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
async function systemctl(c, action, unit, extra = []) {
|
|
471
|
+
try {
|
|
472
|
+
const { stdout } = await exec("/usr/bin/systemctl", [`--${c.scope}`, "--no-ask-password", action, unit, ...extra], { timeout: 6e4 });
|
|
473
|
+
return stdout.trim();
|
|
474
|
+
} catch (error) {
|
|
475
|
+
throw new SystemdCommandFailed(error);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
async function resumeSystemdAdmission(c, host) {
|
|
479
|
+
await assertSystemdOwner(c, c.service, host.pid);
|
|
480
|
+
if (await systemctl(c, "show", c.service, ["--property=ActiveState", "--value"]) !== "active" || await systemctl(c, "show", c.service, ["--property=Job", "--value"]) !== "") {
|
|
481
|
+
throw new Error("The original systemd service is not active and job-free; admission cannot safely resume");
|
|
482
|
+
}
|
|
483
|
+
const response = await fetch(`${host.url}/api/host/stop`, {
|
|
484
|
+
method: "POST",
|
|
485
|
+
headers: { authorization: `Bearer ${host.token}`, "content-type": "application/json" },
|
|
486
|
+
body: JSON.stringify({ instanceId: host.instanceId, resume: true }),
|
|
487
|
+
signal: AbortSignal.timeout(5e3)
|
|
488
|
+
});
|
|
489
|
+
if (!response.ok) throw new Error(`Cannot resume Session Host admission: ${await response.text()}`);
|
|
490
|
+
}
|
|
491
|
+
async function assertSystemdOwner(c, unit, pid) {
|
|
492
|
+
if (await systemctl(c, "show", unit, ["--property=MainPID", "--value"]) !== String(pid)) throw new Error(`systemd ${unit} does not own the expected process`);
|
|
493
|
+
}
|
|
494
|
+
var SystemdLaunchUncertain = class extends Error {
|
|
495
|
+
};
|
|
496
|
+
var requestPath = (root) => join4(root, "systemd-update-request.json");
|
|
497
|
+
async function launchSystemdUpdate(root, c, request) {
|
|
498
|
+
const state = await systemctl(c, "show", c.updater, ["--property=ActiveState", "--value"]);
|
|
499
|
+
if (!["inactive", "failed"].includes(state)) throw new Error(`Systemd updater ${c.updater} is ${state || "unknown"}; wait for it to stop before updating`);
|
|
500
|
+
writeFileSync3(requestPath(root), JSON.stringify(request), { flag: "wx", mode: 384 });
|
|
501
|
+
try {
|
|
502
|
+
await systemctl(c, "start", c.updater, ["--no-block"]);
|
|
503
|
+
} catch (error) {
|
|
504
|
+
throw new SystemdLaunchUncertain(`Could not confirm systemd update submission: ${String(error)}. Inspect ${c.updater} and ${requestPath(root)} before retrying; the request has been retained.`);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
function readSystemdRequest(root) {
|
|
508
|
+
const r = JSON.parse(readFileSync3(requestPath(root), "utf8"));
|
|
509
|
+
if (!r || typeof r.force !== "boolean" || r.id !== void 0 && !/^[a-f0-9-]{36}$/.test(r.id) || r.version !== void 0 && (typeof r.version !== "string" || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(r.version)) || r.id === void 0 !== (r.version === void 0)) throw new Error("Invalid systemd update request");
|
|
510
|
+
return r;
|
|
511
|
+
}
|
|
512
|
+
function clearSystemdRequest(root) {
|
|
513
|
+
unlinkSync3(requestPath(root));
|
|
514
|
+
}
|
|
515
|
+
function systemdCapability(root) {
|
|
516
|
+
if (process.env.FLOW_SYSTEMD_HOST !== "1") return void 0;
|
|
517
|
+
try {
|
|
518
|
+
return readFileSync3(join4(root, "systemd-update-capability"), "utf8");
|
|
519
|
+
} catch (error) {
|
|
520
|
+
if (error.code === "ENOENT") return void 0;
|
|
521
|
+
throw error;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
async function restoreSystemd(root, c, transaction, old, version) {
|
|
525
|
+
const env = await transaction.authorizeRestoration(c.hostArgs);
|
|
526
|
+
const path = join4(root, "systemd-update-capability");
|
|
527
|
+
writeFileSync3(path, env.FLOW_UPDATE_CAPABILITY, { flag: "wx", mode: 384 });
|
|
528
|
+
try {
|
|
529
|
+
await systemctl(c, "start", c.service);
|
|
530
|
+
await waitUntil(async () => {
|
|
531
|
+
const host = readHost(root);
|
|
532
|
+
if (!host || host.instanceId === old.instanceId) return false;
|
|
533
|
+
await assertSystemdOwner(c, c.service, host.pid);
|
|
534
|
+
const status = await getHostStatus(host);
|
|
535
|
+
if (status.version !== version || status.mode !== "foreground" || ["port", "address", "cwd", "oidc"].some((k) => status.settings[k] !== old.settings[k])) throw new Error("Restored systemd Session Host settings or version differ");
|
|
536
|
+
return true;
|
|
537
|
+
}, "systemd Session Host startup timed out");
|
|
538
|
+
await transaction.assertAuthorizationConsumed();
|
|
539
|
+
} catch (error) {
|
|
540
|
+
await systemctl(c, "stop", c.service);
|
|
541
|
+
throw error;
|
|
542
|
+
} finally {
|
|
543
|
+
unlinkSync3(path);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
438
547
|
// src/daemon/release-checker.ts
|
|
439
548
|
var STABLE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
440
549
|
var SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
@@ -494,16 +603,16 @@ function npmPath(npm, command) {
|
|
|
494
603
|
}
|
|
495
604
|
function packageVersion(slot) {
|
|
496
605
|
privatePath(slot);
|
|
497
|
-
const metadata = JSON.parse(
|
|
606
|
+
const metadata = JSON.parse(readFileSync4(join5(slot, "package.json"), "utf8"));
|
|
498
607
|
if (metadata?.name !== packageName || typeof metadata.version !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(metadata.version)) throw new Error("Installed package identity is invalid");
|
|
499
608
|
return metadata.version;
|
|
500
609
|
}
|
|
501
610
|
async function verify(install, transaction, expected) {
|
|
502
611
|
const version = packageVersion(install.slot);
|
|
503
612
|
if (expected && version !== expected) throw new Error("Installed package verification failed");
|
|
504
|
-
if (!
|
|
613
|
+
if (!readFileSync4(join5(install.slot, "dist/build-id"), "utf8").trim()) throw new Error("Installed build identity is missing");
|
|
505
614
|
const env = await transaction.authorizeVerification();
|
|
506
|
-
const reported = execFileSync(process.execPath, [
|
|
615
|
+
const reported = execFileSync(process.execPath, [join5(install.slot, "dist/cli/bootstrap.js"), "--version"], { env, encoding: "utf8", timeout: 15e3 }).trim();
|
|
507
616
|
if (reported !== version) throw new Error("Fresh Flow process reports the wrong version");
|
|
508
617
|
await transaction.assertAuthorizationConsumed();
|
|
509
618
|
return version;
|
|
@@ -514,7 +623,7 @@ async function restore(install, transaction, root, host, version, preserveConcre
|
|
|
514
623
|
await launchBackground({
|
|
515
624
|
root,
|
|
516
625
|
settings,
|
|
517
|
-
entry: [
|
|
626
|
+
entry: [join5(install.slot, "dist/cli/bootstrap.js")],
|
|
518
627
|
env,
|
|
519
628
|
validate(status) {
|
|
520
629
|
if (status.instanceId === host.instanceId || status.version !== version || status.mode !== "background" || ["port", "address", "cwd", "oidc"].some((key) => status.settings[key] !== settings[key])) {
|
|
@@ -527,7 +636,7 @@ async function restore(install, transaction, root, host, version, preserveConcre
|
|
|
527
636
|
function inspectUpdateInstallation(install) {
|
|
528
637
|
const npm = npmExecutable();
|
|
529
638
|
const prefix = npmPath(npm, "prefix"), root = npmPath(npm, "root");
|
|
530
|
-
if (prefix !== install.prefix || root !==
|
|
639
|
+
if (prefix !== install.prefix || root !== join5(prefix, "lib/node_modules") || realpathSync4(join5(root, packageName)) !== install.slot) throw new Error("npm selects a different installation. Put the matching npm in PATH and select its prefix.");
|
|
531
640
|
return { npm, version: packageVersion(install.slot) };
|
|
532
641
|
}
|
|
533
642
|
async function update(install, lease, args, options = {}) {
|
|
@@ -541,13 +650,21 @@ async function update(install, lease, args, options = {}) {
|
|
|
541
650
|
}
|
|
542
651
|
const target = options.expectedVersion ?? "latest";
|
|
543
652
|
const preserveConcretePort = options.preserveConcreteHostPort === true;
|
|
653
|
+
const managed = options.systemd;
|
|
654
|
+
if (managed) await assertSystemdOwner(managed, managed.updater, process.pid);
|
|
544
655
|
let host = readHost(lease.root);
|
|
545
656
|
if (host && processAlive(host.pid)) {
|
|
546
657
|
const status = await getHostStatus(host);
|
|
547
|
-
|
|
658
|
+
if (managed) {
|
|
659
|
+
if (status.mode !== "foreground") throw new Error("systemd updates require a foreground Session Host");
|
|
660
|
+
if (preserveConcretePort && status.settings.port === 0) throw new Error("Systemd web updates require a fixed service port for browser reconnection");
|
|
661
|
+
await assertSystemdOwner(managed, managed.service, host.pid);
|
|
662
|
+
} else requireRestartable(status);
|
|
548
663
|
host = { ...host, ...status };
|
|
549
664
|
} else host = void 0;
|
|
550
|
-
|
|
665
|
+
if (managed && !host) throw new Error("Start the configured systemd Session Host before updating");
|
|
666
|
+
const transaction = await install.beginUpdate(lease, previous, host, managed?.hostArgs);
|
|
667
|
+
const restoreHost = (host2, version) => managed ? restoreSystemd(lease.root, managed, transaction, host2, version) : restore(install, transaction, lease.root, host2, version, preserveConcretePort);
|
|
551
668
|
let needsRestoration = false, replacing = false;
|
|
552
669
|
const repair = () => `Flow startup remains blocked by ${install.barrierPath}. Stop all Flow and npm processes for this prefix. Reinstall ${packageName}@${previous} with the matching npm and prefix ${JSON.stringify(prefix)}. Verify the package files manually, then remove ${install.barrierPath} and start the Session Host again.`;
|
|
553
670
|
async function replace(version, expected) {
|
|
@@ -556,7 +673,7 @@ async function update(install, lease, args, options = {}) {
|
|
|
556
673
|
await replacePackage(npm, prefix, `${packageName}@${version}`);
|
|
557
674
|
const installed = await verify(install, transaction, expected);
|
|
558
675
|
if (host && needsRestoration) {
|
|
559
|
-
await
|
|
676
|
+
await restoreHost(host, installed);
|
|
560
677
|
needsRestoration = false;
|
|
561
678
|
}
|
|
562
679
|
await transaction.complete();
|
|
@@ -566,7 +683,8 @@ async function update(install, lease, args, options = {}) {
|
|
|
566
683
|
if (host) {
|
|
567
684
|
needsRestoration = true;
|
|
568
685
|
try {
|
|
569
|
-
await requestHostStop(host, args.includes("--force"));
|
|
686
|
+
await requestHostStop(host, args.includes("--force"), !!managed);
|
|
687
|
+
if (managed) await systemctl(managed, "stop", managed.service);
|
|
570
688
|
} catch (error) {
|
|
571
689
|
if (error instanceof HostRefusal) needsRestoration = false;
|
|
572
690
|
throw error;
|
|
@@ -580,10 +698,21 @@ async function update(install, lease, args, options = {}) {
|
|
|
580
698
|
} catch (error) {
|
|
581
699
|
if (error instanceof InstallationProcessUncertain) throw new Error(`${String(error)}. ${repair()}`);
|
|
582
700
|
if (!replacing) {
|
|
583
|
-
if (needsRestoration && host && processAlive(host.pid))
|
|
701
|
+
if (needsRestoration && host && processAlive(host.pid)) {
|
|
702
|
+
if (managed && error instanceof SystemdCommandFailed && error.completed) {
|
|
703
|
+
try {
|
|
704
|
+
await resumeSystemdAdmission(managed, host);
|
|
705
|
+
} catch (failure) {
|
|
706
|
+
throw new Error(`${String(error)}; could not resume admission: ${String(failure)}. No package files were changed. ${repair()}`);
|
|
707
|
+
}
|
|
708
|
+
await transaction.complete();
|
|
709
|
+
throw new Error(`${String(error)}. No package files were changed; the original Session Host is accepting requests again.`);
|
|
710
|
+
}
|
|
711
|
+
throw new Error(`${String(error)}. No package files were changed; wait for the stopping host to exit. ${repair()}`);
|
|
712
|
+
}
|
|
584
713
|
if (needsRestoration && host) {
|
|
585
714
|
try {
|
|
586
|
-
await
|
|
715
|
+
await restoreHost(host, previous);
|
|
587
716
|
} catch (failure) {
|
|
588
717
|
throw new Error(`${String(error)}; restoration failed: ${String(failure)}. ${repair()}`);
|
|
589
718
|
}
|
|
@@ -608,24 +737,24 @@ import {
|
|
|
608
737
|
fchmodSync as fchmodSync2,
|
|
609
738
|
mkdirSync as mkdirSync4,
|
|
610
739
|
openSync as openSync2,
|
|
611
|
-
readFileSync as
|
|
740
|
+
readFileSync as readFileSync5,
|
|
612
741
|
readdirSync as readdirSync3,
|
|
613
742
|
renameSync as renameSync3,
|
|
614
743
|
rmdirSync as rmdirSync3,
|
|
615
|
-
unlinkSync as
|
|
616
|
-
writeFileSync as
|
|
744
|
+
unlinkSync as unlinkSync4,
|
|
745
|
+
writeFileSync as writeFileSync4
|
|
617
746
|
} from "node:fs";
|
|
618
|
-
import { join as
|
|
747
|
+
import { join as join6 } from "node:path";
|
|
619
748
|
var STATUS_FILE = "web-update.json";
|
|
620
749
|
var STATUS_LOCK = "web-update-lock";
|
|
621
750
|
var STATUS_LOCK_ATTEMPTS = 100;
|
|
622
751
|
var STATUS_LOCK_WAIT_MS = 25;
|
|
623
752
|
function statusPath(root) {
|
|
624
|
-
return
|
|
753
|
+
return join6(root, STATUS_FILE);
|
|
625
754
|
}
|
|
626
755
|
function readOperation(root) {
|
|
627
756
|
try {
|
|
628
|
-
const value = JSON.parse(
|
|
757
|
+
const value = JSON.parse(readFileSync5(statusPath(root), "utf8"));
|
|
629
758
|
if (!value || typeof value.id !== "string" || !["updating", "succeeded", "failed", "unverified"].includes(value.state)) return void 0;
|
|
630
759
|
return value;
|
|
631
760
|
} catch {
|
|
@@ -633,13 +762,13 @@ function readOperation(root) {
|
|
|
633
762
|
}
|
|
634
763
|
}
|
|
635
764
|
function writeOperation(root, operation) {
|
|
636
|
-
const temporary =
|
|
637
|
-
|
|
765
|
+
const temporary = join6(root, `${STATUS_FILE}-${process.pid}-${randomUUID3()}`);
|
|
766
|
+
writeFileSync4(temporary, JSON.stringify(operation), { mode: 384 });
|
|
638
767
|
renameSync3(temporary, statusPath(root));
|
|
639
768
|
}
|
|
640
769
|
function removeLockOwner(path, filename) {
|
|
641
770
|
try {
|
|
642
|
-
|
|
771
|
+
unlinkSync4(join6(path, filename));
|
|
643
772
|
} catch (error) {
|
|
644
773
|
if (error.code !== "ENOENT") throw error;
|
|
645
774
|
}
|
|
@@ -655,10 +784,10 @@ function sleep(milliseconds) {
|
|
|
655
784
|
function transitionOperation(root, transition) {
|
|
656
785
|
const ownerId = randomUUID3();
|
|
657
786
|
const filename = `${ownerId}.json`;
|
|
658
|
-
const candidate =
|
|
659
|
-
const lock =
|
|
787
|
+
const candidate = join6(root, `${STATUS_LOCK}-${ownerId}`);
|
|
788
|
+
const lock = join6(root, STATUS_LOCK);
|
|
660
789
|
mkdirSync4(candidate, { mode: 448 });
|
|
661
|
-
|
|
790
|
+
writeFileSync4(join6(candidate, filename), JSON.stringify({ pid: process.pid, id: ownerId }), { mode: 384 });
|
|
662
791
|
let acquired = false;
|
|
663
792
|
try {
|
|
664
793
|
for (let attempt = 0; !acquired; attempt++) {
|
|
@@ -682,7 +811,7 @@ function transitionOperation(root, transition) {
|
|
|
682
811
|
if (entries.length !== 1 || !/^[a-f0-9-]+\.json$/.test(entries[0])) throw new Error("Invalid web update status owner");
|
|
683
812
|
let owner2;
|
|
684
813
|
try {
|
|
685
|
-
owner2 = JSON.parse(
|
|
814
|
+
owner2 = JSON.parse(readFileSync5(join6(lock, entries[0]), "utf8"));
|
|
686
815
|
} catch (readError) {
|
|
687
816
|
if (readError.code === "ENOENT") continue;
|
|
688
817
|
throw readError;
|
|
@@ -706,6 +835,9 @@ function publicError(error) {
|
|
|
706
835
|
const message = error instanceof Error ? error.message : String(error);
|
|
707
836
|
return message.replace(/Bearer\s+\S+/gi, "Bearer [redacted]").replace(/((?:token|secret|password)[=:]\s*)[^\s;,]+/gi, "$1[redacted]").slice(0, 2e3);
|
|
708
837
|
}
|
|
838
|
+
function claimWebUpdate(root, id) {
|
|
839
|
+
transitionOperation(root, (current) => current?.id === id && ["updating", "unverified"].includes(current.state) ? { ...current, state: "updating", pid: process.pid } : current);
|
|
840
|
+
}
|
|
709
841
|
function finishWebUpdate(root, id, result, error) {
|
|
710
842
|
transitionOperation(root, (current) => {
|
|
711
843
|
if (!current || current.id !== id || !["updating", "unverified"].includes(current.state)) return current;
|
|
@@ -734,27 +866,46 @@ function finishWebUpdate(root, id, result, error) {
|
|
|
734
866
|
async function bootstrap() {
|
|
735
867
|
const slot = resolve3(fileURLToPath(new URL("../..", import.meta.url)));
|
|
736
868
|
const args = process.argv.slice(2);
|
|
737
|
-
const root = canonicalRoot(process.env.FLOW_STATE_DIR ??
|
|
869
|
+
const root = canonicalRoot(process.env.FLOW_STATE_DIR ?? join7(homedir(), ".flow"));
|
|
738
870
|
const globalSlot = slot.endsWith("/lib/node_modules/@nathanstephenson/flow");
|
|
739
871
|
let updateSupport;
|
|
740
872
|
if (globalSlot && (args[0] === "update" || updateEligible(slot) || registryExists(slot))) {
|
|
741
873
|
const install = installation(slot);
|
|
742
|
-
const
|
|
874
|
+
const managed = systemdUpdate(root);
|
|
875
|
+
const worker = args[0] === "update" && process.env.FLOW_SYSTEMD_WORKER === "1";
|
|
876
|
+
if (args[0] === "update" && managed && !worker) {
|
|
877
|
+
if (args.length > 2 || args[1] !== void 0 && args[1] !== "--force") throw new Error("usage: flow update [--force]");
|
|
878
|
+
await launchSystemdUpdate(root, managed, { force: args.includes("--force") });
|
|
879
|
+
console.log("Systemd update queued. See the updater unit journal for the result.");
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
if (worker) {
|
|
883
|
+
if (!managed) throw new Error("Missing systemd update configuration");
|
|
884
|
+
await assertSystemdOwner(managed, managed.updater, process.pid);
|
|
885
|
+
}
|
|
886
|
+
const lease = await install.register("a05670ad-d8b7-4859-afde-7cc8ad2f6548", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
|
|
743
887
|
delete process.env.FLOW_UPDATE_CAPABILITY;
|
|
744
888
|
process.on("exit", lease.release);
|
|
745
889
|
if (args[0] === "update") {
|
|
746
|
-
const
|
|
747
|
-
const
|
|
890
|
+
const request = worker ? readSystemdRequest(root) : void 0;
|
|
891
|
+
const webId = request?.id ?? process.env.FLOW_WEB_UPDATE_ID;
|
|
892
|
+
const webVersion = request?.version ?? process.env.FLOW_WEB_UPDATE_VERSION;
|
|
893
|
+
if (webId) claimWebUpdate(root, webId);
|
|
748
894
|
delete process.env.FLOW_WEB_UPDATE_ID;
|
|
749
895
|
delete process.env.FLOW_WEB_UPDATE_VERSION;
|
|
750
896
|
try {
|
|
751
897
|
if (webId === void 0 !== (webVersion === void 0)) throw new Error("Web update authorization is incomplete");
|
|
752
|
-
const result = await update(install, lease,
|
|
898
|
+
const result = await update(install, lease, request ? ["update", ...request.force ? ["--force"] : []] : args, {
|
|
899
|
+
...webId ? { expectedVersion: webVersion, preserveConcreteHostPort: true } : {},
|
|
900
|
+
...worker ? { systemd: managed } : {}
|
|
901
|
+
});
|
|
753
902
|
if (webId) finishWebUpdate(root, webId, result);
|
|
754
903
|
return;
|
|
755
904
|
} catch (error) {
|
|
756
905
|
if (webId) finishWebUpdate(root, webId, void 0, error);
|
|
757
906
|
throw error;
|
|
907
|
+
} finally {
|
|
908
|
+
if (worker) clearSystemdRequest(root);
|
|
758
909
|
}
|
|
759
910
|
}
|
|
760
911
|
updateSupport = { installation: install, bootstrapEntry: fileURLToPath(import.meta.url) };
|
package/dist/cli/host-control.js
CHANGED
|
@@ -29,10 +29,10 @@ export async function getHostStatus(host) {
|
|
|
29
29
|
throw new Error('Session Host identity changed');
|
|
30
30
|
return status;
|
|
31
31
|
}
|
|
32
|
-
export async function requestHostStop(host, force) {
|
|
32
|
+
export async function requestHostStop(host, force, quiesce = false) {
|
|
33
33
|
const response = await fetch(`${host.url}/api/host/stop`, {
|
|
34
34
|
method: 'POST', headers: { authorization: `Bearer ${host.token}`, 'content-type': 'application/json' },
|
|
35
|
-
body: JSON.stringify({ instanceId: host.instanceId, force }), signal: AbortSignal.timeout(5000),
|
|
35
|
+
body: JSON.stringify({ instanceId: host.instanceId, force, quiesce }), signal: AbortSignal.timeout(5000),
|
|
36
36
|
});
|
|
37
37
|
if (!response.ok)
|
|
38
38
|
throw new HostRefusal(`Session Host refused: ${await response.text()}`);
|
|
@@ -260,7 +260,7 @@ export function installation(slot) {
|
|
|
260
260
|
} } };
|
|
261
261
|
});
|
|
262
262
|
}
|
|
263
|
-
async function beginUpdate(lease, previous, host) {
|
|
263
|
+
async function beginUpdate(lease, previous, host, systemdArgs) {
|
|
264
264
|
const barrier = { pid: process.pid, id: randomUUID(), phase: 'preparing', previous };
|
|
265
265
|
await locked(() => {
|
|
266
266
|
if (readBarrier(barrierPath))
|
|
@@ -268,7 +268,10 @@ export function installation(slot) {
|
|
|
268
268
|
const active = leases();
|
|
269
269
|
if (!active.some(other => other.id === lease.id && other.pid === process.pid && other.root === lease.root))
|
|
270
270
|
throw new Error('Update process has no installation lease');
|
|
271
|
-
|
|
271
|
+
const selected = host && active.find(other => other.pid === host.pid && other.root === lease.root);
|
|
272
|
+
if (systemdArgs && selected && JSON.stringify(selected.args) !== JSON.stringify(systemdArgs))
|
|
273
|
+
throw new Error('Configured systemd hostArgs do not match the running Session Host; correct systemd-update.json before updating');
|
|
274
|
+
if (active.some(other => other.id !== lease.id && !(host && other.pid === host.pid && other.root === lease.root && (systemdArgs ? JSON.stringify(other.args) === JSON.stringify(systemdArgs) : other.args.includes('--background-host')))))
|
|
272
275
|
throw new Error('Stop all other Flow hosts and CLI/TUI clients using this installation first');
|
|
273
276
|
if (host && !active.some(other => other.pid === host.pid && other.root === lease.root))
|
|
274
277
|
throw new Error('Stop all pre-guard Flow processes before updating');
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
import { readFileSync, writeFileSync, unlinkSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { getHostStatus, waitUntil } from "./host-control.js";
|
|
6
|
+
import { readHost } from "../daemon/ownership.js";
|
|
7
|
+
const exec = promisify(execFile);
|
|
8
|
+
export function parseSystemdUpdate(value) {
|
|
9
|
+
const c = value;
|
|
10
|
+
const unit = (v) => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.-]*\.service$/.test(v);
|
|
11
|
+
if (!c || !['system', 'user'].includes(c.scope) || !unit(c.service) || !unit(c.updater) || c.service === c.updater ||
|
|
12
|
+
!Array.isArray(c.hostArgs) || c.hostArgs[0] !== 'serve' || c.hostArgs.some(a => typeof a !== 'string') || c.hostArgs.includes('--background-host') || c.hostArgs.includes('start')) {
|
|
13
|
+
throw new Error('Invalid systemd-update.json: use distinct fixed service units and foreground serve arguments');
|
|
14
|
+
}
|
|
15
|
+
return c;
|
|
16
|
+
}
|
|
17
|
+
export function systemdUpdate(root) {
|
|
18
|
+
try {
|
|
19
|
+
return parseSystemdUpdate(JSON.parse(readFileSync(join(root, 'systemd-update.json'), 'utf8')));
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
if (error.code === 'ENOENT')
|
|
23
|
+
return undefined;
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export class SystemdCommandFailed extends Error {
|
|
28
|
+
completed;
|
|
29
|
+
constructor(error) {
|
|
30
|
+
super(String(error), { cause: error });
|
|
31
|
+
const command = error;
|
|
32
|
+
this.completed = typeof command.code === 'number' && !command.killed && !command.signal;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export async function systemctl(c, action, unit, extra = []) {
|
|
36
|
+
try {
|
|
37
|
+
const { stdout } = await exec('/usr/bin/systemctl', [`--${c.scope}`, '--no-ask-password', action, unit, ...extra], { timeout: 60000 });
|
|
38
|
+
return stdout.trim();
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
throw new SystemdCommandFailed(error);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Undo admission-only quiescence after a definite manager refusal, never an uncertain stop. */
|
|
45
|
+
export async function resumeSystemdAdmission(c, host) {
|
|
46
|
+
await assertSystemdOwner(c, c.service, host.pid);
|
|
47
|
+
if (await systemctl(c, 'show', c.service, ['--property=ActiveState', '--value']) !== 'active' ||
|
|
48
|
+
await systemctl(c, 'show', c.service, ['--property=Job', '--value']) !== '') {
|
|
49
|
+
throw new Error('The original systemd service is not active and job-free; admission cannot safely resume');
|
|
50
|
+
}
|
|
51
|
+
const response = await fetch(`${host.url}/api/host/stop`, {
|
|
52
|
+
method: 'POST', headers: { authorization: `Bearer ${host.token}`, 'content-type': 'application/json' },
|
|
53
|
+
body: JSON.stringify({ instanceId: host.instanceId, resume: true }), signal: AbortSignal.timeout(5000),
|
|
54
|
+
});
|
|
55
|
+
if (!response.ok)
|
|
56
|
+
throw new Error(`Cannot resume Session Host admission: ${await response.text()}`);
|
|
57
|
+
}
|
|
58
|
+
export async function assertSystemdOwner(c, unit, pid) {
|
|
59
|
+
if (await systemctl(c, 'show', unit, ['--property=MainPID', '--value']) !== String(pid))
|
|
60
|
+
throw new Error(`systemd ${unit} does not own the expected process`);
|
|
61
|
+
}
|
|
62
|
+
export class SystemdLaunchUncertain extends Error {
|
|
63
|
+
}
|
|
64
|
+
const requestPath = (root) => join(root, 'systemd-update-request.json');
|
|
65
|
+
export async function launchSystemdUpdate(root, c, request) {
|
|
66
|
+
// A worker removes its request just before exiting. Starting an already-active oneshot is a
|
|
67
|
+
// no-op, so do not enqueue another request in that window (or while a unit is deactivating).
|
|
68
|
+
const state = await systemctl(c, 'show', c.updater, ['--property=ActiveState', '--value']);
|
|
69
|
+
if (!['inactive', 'failed'].includes(state))
|
|
70
|
+
throw new Error(`Systemd updater ${c.updater} is ${state || 'unknown'}; wait for it to stop before updating`);
|
|
71
|
+
// Exclusive durable request also serializes CLI and web launchers. Never overwrite an uncertain job.
|
|
72
|
+
writeFileSync(requestPath(root), JSON.stringify(request), { flag: 'wx', mode: 0o600 });
|
|
73
|
+
// --no-block: Type=oneshot must not wait for the update to finish (and kill this launcher).
|
|
74
|
+
// On an ambiguous systemctl failure retain the request for inspection, not automatic retry.
|
|
75
|
+
try {
|
|
76
|
+
await systemctl(c, 'start', c.updater, ['--no-block']);
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
throw new SystemdLaunchUncertain(`Could not confirm systemd update submission: ${String(error)}. Inspect ${c.updater} and ${requestPath(root)} before retrying; the request has been retained.`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export function readSystemdRequest(root) {
|
|
83
|
+
const r = JSON.parse(readFileSync(requestPath(root), 'utf8'));
|
|
84
|
+
if (!r || typeof r.force !== 'boolean' || (r.id !== undefined && !/^[a-f0-9-]{36}$/.test(r.id)) ||
|
|
85
|
+
(r.version !== undefined && (typeof r.version !== 'string' || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(r.version))) || ((r.id === undefined) !== (r.version === undefined)))
|
|
86
|
+
throw new Error('Invalid systemd update request');
|
|
87
|
+
return r;
|
|
88
|
+
}
|
|
89
|
+
export function clearSystemdRequest(root) { unlinkSync(requestPath(root)); }
|
|
90
|
+
export function systemdCapability(root) {
|
|
91
|
+
if (process.env.FLOW_SYSTEMD_HOST !== '1')
|
|
92
|
+
return undefined;
|
|
93
|
+
try {
|
|
94
|
+
return readFileSync(join(root, 'systemd-update-capability'), 'utf8');
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
if (error.code === 'ENOENT')
|
|
98
|
+
return undefined;
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
export async function restoreSystemd(root, c, transaction, old, version) {
|
|
103
|
+
const env = await transaction.authorizeRestoration(c.hostArgs);
|
|
104
|
+
const path = join(root, 'systemd-update-capability');
|
|
105
|
+
writeFileSync(path, env.FLOW_UPDATE_CAPABILITY, { flag: 'wx', mode: 0o600 });
|
|
106
|
+
try {
|
|
107
|
+
await systemctl(c, 'start', c.service);
|
|
108
|
+
await waitUntil(async () => {
|
|
109
|
+
const host = readHost(root);
|
|
110
|
+
if (!host || host.instanceId === old.instanceId)
|
|
111
|
+
return false;
|
|
112
|
+
await assertSystemdOwner(c, c.service, host.pid);
|
|
113
|
+
const status = await getHostStatus(host);
|
|
114
|
+
if (status.version !== version || status.mode !== 'foreground' ||
|
|
115
|
+
['port', 'address', 'cwd', 'oidc'].some(k => status.settings[k] !== old.settings[k]))
|
|
116
|
+
throw new Error('Restored systemd Session Host settings or version differ');
|
|
117
|
+
return true;
|
|
118
|
+
}, 'systemd Session Host startup timed out');
|
|
119
|
+
await transaction.assertAuthorizationConsumed();
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
// Stop a failed restoration before rollback touches package files.
|
|
123
|
+
await systemctl(c, 'stop', c.service);
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
unlinkSync(path);
|
|
128
|
+
}
|
|
129
|
+
}
|