@xmoon76/dsh-pi-tui 0.5.6 → 0.5.8
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/LICENSE +33 -0
- package/README.en.md +103 -814
- package/README.md +102 -711
- package/cordis.patch.yml +186 -0
- package/dist/acp-preferences.d.mts +29 -0
- package/dist/acp-preferences.mjs +15 -0
- package/dist/{bootstrap-DQ4YPL-7.mjs → bootstrap-CMIjGyuk.mjs} +33515 -7587
- package/dist/builtins.mjs +3 -3
- package/dist/{client-bootstrap-Cr1JCaF5.mjs → client-bootstrap-BjGPc-DM.mjs} +4637 -492
- package/dist/client-extension-loader-probe-BUw7q8bJ.mjs +119 -0
- package/dist/command-trust-DChWUamk.mjs +406 -0
- package/dist/daemon-launcher-Dult7Jxv.mjs +1932 -0
- package/dist/daemon-launcher.d.mts +159 -0
- package/dist/daemon-launcher.mjs +2 -0
- package/dist/diagnostics-D5jwc-q1.d.mts +11 -0
- package/dist/{dist-CIsR7cz4.mjs → dist-BFgC-5tL.mjs} +938 -487
- package/dist/entry-control-DjNsE3I0.mjs +190 -0
- package/dist/extension/advanced.d.mts +1 -1
- package/dist/extension/unstable.d.mts +1 -1
- package/dist/extension-config-probe-BDdvutkG.mjs +95 -0
- package/dist/extension-config.d.mts +29 -0
- package/dist/extension-config.mjs +22 -0
- package/dist/{extensions-Bp0L37lP.mjs → extensions-B4uLpSTv.mjs} +1109 -100
- package/dist/{extensions-Bte3XOt5.d.mts → extensions-C8eAM0gX.d.mts} +1 -1
- package/dist/extensions.d.mts +2 -2
- package/dist/extensions.mjs +1 -1
- package/dist/{host-bootstrap-DilsvA6f.mjs → host-bootstrap-MVxks641.mjs} +129 -24
- package/dist/{host-foundation-probe--5jtvHVe.mjs → host-foundation-probe-DMNTmNrH.mjs} +2 -2
- package/dist/host-runtime.d.mts +11 -5
- package/dist/host-runtime.mjs +4171 -920
- package/dist/index.d.mts +86 -174
- package/dist/index.mjs +38087 -9967
- package/dist/local-acp-listener-B65J0Bx4.mjs +3115 -0
- package/dist/local-client.mjs +1158 -59
- package/dist/local-daemon-control-C14q9KnD.mjs +1588 -0
- package/dist/local-daemon-control-TCnERL7n.mjs +1424 -0
- package/dist/local-discovery-DOSsCh9q.mjs +2883 -0
- package/dist/local-discovery-egN4_gsQ.mjs +2 -0
- package/dist/local-discovery-uOBfFq5j.mjs +2764 -0
- package/dist/local-host.mjs +812 -89
- package/dist/local-profile-daemon-admin-BmQSdzT0.mjs +210 -0
- package/dist/local-scope-DamiMqPd.mjs +1340 -0
- package/dist/{local-transport-BVwFYq_Y.mjs → local-transport-Iwo0mtu3.mjs} +313 -38
- package/dist/local-web-control-DMrjwCkl.mjs +454 -0
- package/dist/local-workspace-object-D06GL0UO.mjs +248 -0
- package/dist/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
- package/dist/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
- package/dist/open-CmOBxSjN.mjs +63 -0
- package/dist/persisted-setting-probe-DWZLtWoB.mjs +145 -0
- package/dist/pi-tui-acp-access-contract-BdLwduU6.mjs +75 -0
- package/dist/pi-tui-remote-contribution-Do8ECrUy.mjs +1492 -0
- package/dist/pi-tui-terminal-progress-contract-B3RoEzjK.mjs +146 -0
- package/dist/preferences.d.mts +17 -0
- package/dist/preferences.mjs +20 -0
- package/dist/preset-BcWqOtY7.mjs +46 -0
- package/dist/profile-preferences-migration-BfUGdPZx.mjs +500 -0
- package/dist/profile-preferences-migration-CThz4rHH.mjs +2 -0
- package/dist/prompt-sections-DUKmWb8g.mjs +2232 -0
- package/dist/prompt-sections-DXmjB58H.mjs +634 -0
- package/dist/{public-types-Dgf1bDke.d.mts → public-types-C1YgFtwC.d.mts} +56 -3
- package/dist/row-id-DPbyt9Nn.mjs +24 -0
- package/dist/{runtime-status-Cj1nFOdS.mjs → runtime-status-v-FTnWcD.mjs} +49 -3
- package/dist/schema-BTGYn8_X.d.mts +54 -0
- package/dist/schema-qE_P09zJ.mjs +124 -0
- package/dist/{session-BKGXyh80.mjs → session-C6tSs86s.mjs} +9672 -7270
- package/dist/{session-CPt_U8_f.mjs → session-CstInGIA.mjs} +9674 -7273
- package/dist/startup-CarQxWwi.d.mts +213 -0
- package/dist/{startup-7BYWuvBU.mjs → startup-EG5UqIcd.mjs} +341 -26
- package/dist/startup.d.mts +2 -99
- package/dist/startup.mjs +2 -2
- package/dist/{terminal-progress-source-DrqQhtT8.mjs → terminal-progress-source-CpfpQO_h.mjs} +2038 -67
- package/dist/{pasted-path-range-CMnxuGPx.mjs → transcript-view-C1YtJ49Y.mjs} +11590 -6718
- package/dist/{pasted-path-range-r6qzV_tC.mjs → transcript-view-CuJYWkhp.mjs} +12296 -6923
- package/dist/version-B9yC7bBk.mjs +83 -0
- package/dist/visual-tools.d.mts +1 -1
- package/dist/visual-tools.mjs +1 -1
- package/dist/web-preferences.d.mts +1 -1
- package/dist/{web-roster-CjqnUXNk.mjs → web-roster-Dis7BhrA.mjs} +63 -3
- package/generated/dsh-presets/cordis.patch.yml +4 -2
- package/generated/dsh-presets/ptc.patch.yml +4 -0
- package/generated/dsh-presets/standard.patch.yml +7 -0
- package/generated/web-access/cordis.patch.yml +239 -0
- package/package.json +217 -170
- package/dist/entry-control-DnduyDiw.mjs +0 -92
- package/dist/local-discovery-C9VMjc0K.mjs +0 -759
- package/dist/local-discovery-CDaQHA_R.mjs +0 -2
- package/dist/pi-tui-remote-contribution-B0EQsP0N.mjs +0 -85
- package/dist/pi-tui-terminal-progress-contract-CdBH9j78.mjs +0 -70
- package/dist/pi-tui-terminal-progress-contract-MLXZ-i3t.mjs +0 -905
- package/dist/version-a-eF-QER.mjs +0 -80
|
@@ -0,0 +1,2883 @@
|
|
|
1
|
+
import { _ as parseProcessStat, b as readProcessStarttime, d as readInstalledDshVersion, f as readLinuxStarttime, n as LocalScopeError, s as computeBuildId, u as installedPackageRootFromEntry, x as sameKernelProcess, y as readKernelProcess } from "./local-scope-DamiMqPd.mjs";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { accessSync, closeSync, constants, existsSync, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
4
|
+
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { userInfo } from "node:os";
|
|
7
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
8
|
+
//#region src/app/remote-process/local-host-launchd.ts
|
|
9
|
+
/**
|
|
10
|
+
* macOS user-level launchd LaunchAgent adapter (M6-D4).
|
|
11
|
+
*
|
|
12
|
+
* This module owns exactly ONE Darwin OS supervision route: a user-level
|
|
13
|
+
* LaunchAgent in the account's `~/Library/LaunchAgents` directory, inside the
|
|
14
|
+
* `gui/<uid>` domain. It never defines a Host/Session/Agent/Writer owner and
|
|
15
|
+
* never starts a second Host launcher: the installed plist runs the existing
|
|
16
|
+
* foreground `dist/local-host.mjs` entry directly.
|
|
17
|
+
*
|
|
18
|
+
* The installed plist file is the ONLY manager-installed identity. A live
|
|
19
|
+
* `launchctl` job is attributed to this profile only when its printed source
|
|
20
|
+
* file and fixed launch facts match the verified profile plist AND a real
|
|
21
|
+
* process PID is present; an active job is never readiness. `bootstrap`,
|
|
22
|
+
* `kickstart` and `bootout` are the only mutating commands and are always
|
|
23
|
+
* invoked with a fixed argument array through `/bin/launchctl` (no shell).
|
|
24
|
+
*
|
|
25
|
+
* The default job does NOT start at login and is NOT restarted automatically:
|
|
26
|
+
* `RunAtLoad=false` and `KeepAlive=false` are deliberate. The product does not
|
|
27
|
+
* rewrite user runtime directives in an existing same-owner plist.
|
|
28
|
+
*
|
|
29
|
+
* @module app/remote-process/local-host-launchd
|
|
30
|
+
*/
|
|
31
|
+
/** The fixed manager label prefix; the scope id suffix names one profile. */
|
|
32
|
+
const LAUNCHD_LABEL_PREFIX = "com.xmoon.dsh-pi-tui";
|
|
33
|
+
/** The plist owner metadata marker shared by the product's launchd adapter. */
|
|
34
|
+
const LAUNCHD_OWNER_MARKER = "local-host-launchd-v1";
|
|
35
|
+
/** The launchd executable: a system binary, never resolved through a shell. */
|
|
36
|
+
const LAUNCHCTL = "/bin/launchctl";
|
|
37
|
+
/** Hard bound on one `launchctl` invocation. */
|
|
38
|
+
const LAUNCHCTL_TIMEOUT_MS = 5e3;
|
|
39
|
+
/** Hard cap on captured stdout/stderr bytes per invocation. */
|
|
40
|
+
const LAUNCHCTL_MAX_OUTPUT_BYTES = 65536;
|
|
41
|
+
/** The fixed private log file names below the profile scope directory. */
|
|
42
|
+
const LAUNCHD_STDOUT_NAME = "launchd.stdout.log";
|
|
43
|
+
const LAUNCHD_STDERR_NAME = "launchd.stderr.log";
|
|
44
|
+
/** Bound on the post-`bootout` job-removal re-query window. */
|
|
45
|
+
const LAUNCHD_STOP_TIMEOUT_MS = 5e3;
|
|
46
|
+
/** Poll interval for the post-`bootout` removal observation. */
|
|
47
|
+
const LAUNCHD_STOP_POLL_MS = 100;
|
|
48
|
+
/** The fixed launchd job umask (0077 octal). */
|
|
49
|
+
const LAUNCHD_UMASK = 63;
|
|
50
|
+
/** The deterministic job label for one profile scope. */
|
|
51
|
+
function buildLaunchdLabel(scopeId) {
|
|
52
|
+
return `${LAUNCHD_LABEL_PREFIX}.${scopeId.slice(0, 40)}`;
|
|
53
|
+
}
|
|
54
|
+
/** The fixed private launchd stdout/stderr paths below the profile scope. */
|
|
55
|
+
function launchdLogPaths(scopeDir) {
|
|
56
|
+
return {
|
|
57
|
+
stdout: join(scopeDir, LAUNCHD_STDOUT_NAME),
|
|
58
|
+
stderr: join(scopeDir, LAUNCHD_STDERR_NAME)
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** The fixed file name of one LaunchAgent. */
|
|
62
|
+
function launchdPlistName(scopeId) {
|
|
63
|
+
return `${buildLaunchdLabel(scopeId)}.plist`;
|
|
64
|
+
}
|
|
65
|
+
/** Reject any value that could corrupt the XML document or add a new key. */
|
|
66
|
+
function assertPlistSafe(value, label) {
|
|
67
|
+
if (value === "" || value.includes("\0") || /[\u0000-\u001f\u007f]/u.test(value)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the ${label} is empty or contains a control character`);
|
|
68
|
+
}
|
|
69
|
+
/** Encode one value for an XML text node. */
|
|
70
|
+
function encodePlistValue(value, label) {
|
|
71
|
+
assertPlistSafe(value, label);
|
|
72
|
+
return value.replace(/&/gu, "&").replace(/</gu, "<").replace(/>/gu, ">").replace(/"/gu, """).replace(/'/gu, "'");
|
|
73
|
+
}
|
|
74
|
+
/** Render the complete, fixed LaunchAgent plist for one installed Host. */
|
|
75
|
+
function renderLaunchdPlist(facts) {
|
|
76
|
+
const label = buildLaunchdLabel(facts.scopeId);
|
|
77
|
+
const logs = launchdLogPaths(facts.scopeDir);
|
|
78
|
+
return [
|
|
79
|
+
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
|
|
80
|
+
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
|
|
81
|
+
"<plist version=\"1.0\">",
|
|
82
|
+
"<dict>",
|
|
83
|
+
" <key>Label</key>",
|
|
84
|
+
` <string>${encodePlistValue(label, "Label")}</string>`,
|
|
85
|
+
" <key>ProgramArguments</key>",
|
|
86
|
+
" <array>",
|
|
87
|
+
` <string>${encodePlistValue(facts.nodePath, "node path")}</string>`,
|
|
88
|
+
` <string>${encodePlistValue(facts.hostEntryPath, "Host entry path")}</string>`,
|
|
89
|
+
" </array>",
|
|
90
|
+
" <key>WorkingDirectory</key>",
|
|
91
|
+
` <string>${encodePlistValue(facts.profileRealpath, "WorkingDirectory")}</string>`,
|
|
92
|
+
" <key>RunAtLoad</key>",
|
|
93
|
+
" <false/>",
|
|
94
|
+
" <key>KeepAlive</key>",
|
|
95
|
+
" <false/>",
|
|
96
|
+
" <key>StandardOutPath</key>",
|
|
97
|
+
` <string>${encodePlistValue(logs.stdout, "StandardOutPath")}</string>`,
|
|
98
|
+
" <key>StandardErrorPath</key>",
|
|
99
|
+
` <string>${encodePlistValue(logs.stderr, "StandardErrorPath")}</string>`,
|
|
100
|
+
" <key>Umask</key>",
|
|
101
|
+
` <integer>${String(LAUNCHD_UMASK)}</integer>`,
|
|
102
|
+
" <key>EnvironmentVariables</key>",
|
|
103
|
+
" <dict>",
|
|
104
|
+
" <key>DSH_HOME</key>",
|
|
105
|
+
` <string>${encodePlistValue(facts.dshHome, "DSH_HOME")}</string>`,
|
|
106
|
+
" <key>SPLIT_PROCESS_DSH_ANCHOR</key>",
|
|
107
|
+
` <string>${encodePlistValue(facts.dshAnchor, "SPLIT_PROCESS_DSH_ANCHOR")}</string>`,
|
|
108
|
+
" <key>SPLIT_PROCESS_PROFILE</key>",
|
|
109
|
+
` <string>${encodePlistValue(facts.profile, "SPLIT_PROCESS_PROFILE")}</string>`,
|
|
110
|
+
" </dict>",
|
|
111
|
+
" <key>X-DshPiTuiOwner</key>",
|
|
112
|
+
` <string>${encodePlistValue(LAUNCHD_OWNER_MARKER, "owner marker")}</string>`,
|
|
113
|
+
" <key>X-DshPiTuiScopeId</key>",
|
|
114
|
+
` <string>${encodePlistValue(facts.scopeId, "scope id")}</string>`,
|
|
115
|
+
" <key>X-DshPiTuiProfileIdentity</key>",
|
|
116
|
+
` <string>${encodePlistValue(facts.profileIdentity, "profile identity")}</string>`,
|
|
117
|
+
" <key>X-DshPiTuiInstallBuild</key>",
|
|
118
|
+
` <string>${encodePlistValue(facts.buildId, "install build")}</string>`,
|
|
119
|
+
"</dict>",
|
|
120
|
+
"</plist>",
|
|
121
|
+
""
|
|
122
|
+
].join("\n");
|
|
123
|
+
}
|
|
124
|
+
/** Decode one plist with the native parser; structural/unsupported input fails closed. */
|
|
125
|
+
function decodeLaunchdPlist(content) {
|
|
126
|
+
const decoded = spawnSync("/usr/bin/plutil", [
|
|
127
|
+
"-convert",
|
|
128
|
+
"json",
|
|
129
|
+
"-o",
|
|
130
|
+
"-",
|
|
131
|
+
"--",
|
|
132
|
+
"-"
|
|
133
|
+
], {
|
|
134
|
+
input: content,
|
|
135
|
+
encoding: "utf8",
|
|
136
|
+
timeout: 5e3,
|
|
137
|
+
maxBuffer: 65536
|
|
138
|
+
});
|
|
139
|
+
if (decoded.error !== void 0 || decoded.status !== 0 || typeof decoded.stdout !== "string" || decoded.stdout.trim() === "") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the native plist decoder rejected the plist");
|
|
140
|
+
let parsed;
|
|
141
|
+
try {
|
|
142
|
+
parsed = JSON.parse(decoded.stdout);
|
|
143
|
+
} catch {
|
|
144
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the native plist decoder did not produce JSON");
|
|
145
|
+
}
|
|
146
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist root is not a dictionary");
|
|
147
|
+
return parsed;
|
|
148
|
+
}
|
|
149
|
+
function requirePlistString(root, key) {
|
|
150
|
+
const value = root[key];
|
|
151
|
+
if (typeof value !== "string") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the plist has no single top-level ${key} value`);
|
|
152
|
+
return value;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Resolve the STABLE named entry below the official profile directory:
|
|
156
|
+
* `<profileRealpath>/node_modules/@xmoon76/dsh-pi-tui/dist/local-host.mjs`.
|
|
157
|
+
*
|
|
158
|
+
* The named path survives an official profile package upgrade (pnpm keeps the
|
|
159
|
+
* lexical path while the physical payload changes), unlike a versioned store
|
|
160
|
+
* path. The caller uses it ONLY when creating a FRESH plist or migrating a
|
|
161
|
+
* proven old generated entry; every other command keeps validating the real
|
|
162
|
+
* installed entry through `collectUnitFacts()`. The path must resolve to the
|
|
163
|
+
* very same physical file the official facts named, and the nearest manifest
|
|
164
|
+
* above the named entry must be this installed product package — otherwise the
|
|
165
|
+
* profile layout does not provide a stable entry and the operation fails closed.
|
|
166
|
+
*/
|
|
167
|
+
function resolveNamedLaunchdEntry(facts) {
|
|
168
|
+
const namedEntry = join(facts.profileRealpath, "node_modules", "@xmoon76", "dsh-pi-tui", "dist", "local-host.mjs");
|
|
169
|
+
let namedReal;
|
|
170
|
+
let entryReal;
|
|
171
|
+
try {
|
|
172
|
+
namedReal = realpathSync(namedEntry);
|
|
173
|
+
entryReal = realpathSync(facts.hostEntryPath);
|
|
174
|
+
} catch (error) {
|
|
175
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile stable named entry is not readable", error);
|
|
176
|
+
}
|
|
177
|
+
if (namedReal !== entryReal) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile stable named entry does not resolve to the installed Host entry");
|
|
178
|
+
let manifest;
|
|
179
|
+
try {
|
|
180
|
+
manifest = JSON.parse(readFileSync(join(dirname(dirname(namedReal)), "package.json"), "utf8"));
|
|
181
|
+
} catch (error) {
|
|
182
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile stable named entry has no readable package identity", error);
|
|
183
|
+
}
|
|
184
|
+
if (manifest === null || typeof manifest !== "object" || manifest.name !== "@xmoon76/dsh-pi-tui") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile stable named entry is not @xmoon76/dsh-pi-tui");
|
|
185
|
+
return namedEntry;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Prove the installed plist's PROFILE LAUNCH ANCHORS before `bootstrap`.
|
|
189
|
+
*
|
|
190
|
+
* The native plist decoder is the authority for the top-level semantics: XML
|
|
191
|
+
* comments, character references, CDATA and tag whitespace all normalize to the
|
|
192
|
+
* same keys/values. Only the facts that bind the job to THIS profile are
|
|
193
|
+
* checked: the exact `Label` and the three official environment anchors
|
|
194
|
+
* (`DSH_HOME`, `SPLIT_PROCESS_DSH_ANCHOR`, `SPLIT_PROCESS_PROFILE`). Every
|
|
195
|
+
* other runtime directive — `ProgramArguments`, `WorkingDirectory`, log
|
|
196
|
+
* sinks, `RunAtLoad`, `KeepAlive`, triggers, extra environment keys and
|
|
197
|
+
* comments — belongs to the user and launchd, and is executed as written; the
|
|
198
|
+
* caller proves the resulting Host through the official authentication.
|
|
199
|
+
*/
|
|
200
|
+
function assertLaunchdProfileAnchors(facts, content) {
|
|
201
|
+
const reject = (reason) => {
|
|
202
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the profile plist has a changed profile launch anchor (${reason}); refusing to bootstrap it`);
|
|
203
|
+
};
|
|
204
|
+
const root = decodeLaunchdPlist(content);
|
|
205
|
+
const text = (key) => {
|
|
206
|
+
const value = root[key];
|
|
207
|
+
if (typeof value !== "string") return reject(key);
|
|
208
|
+
return value;
|
|
209
|
+
};
|
|
210
|
+
if (text("Label") !== buildLaunchdLabel(facts.scopeId)) reject("Label");
|
|
211
|
+
const environment = root.EnvironmentVariables;
|
|
212
|
+
if (environment === null || typeof environment !== "object" || Array.isArray(environment)) reject("EnvironmentVariables");
|
|
213
|
+
const env = environment;
|
|
214
|
+
const expectedEnvironment = {
|
|
215
|
+
DSH_HOME: facts.dshHome,
|
|
216
|
+
SPLIT_PROCESS_DSH_ANCHOR: facts.dshAnchor,
|
|
217
|
+
SPLIT_PROCESS_PROFILE: facts.profile
|
|
218
|
+
};
|
|
219
|
+
for (const [key, value] of Object.entries(expectedEnvironment)) if (env[key] !== value) reject(`EnvironmentVariables.${key}`);
|
|
220
|
+
}
|
|
221
|
+
/** The installed plist metadata of one owned unit (native top-level values). */
|
|
222
|
+
function inspectLaunchdIdentity(content, facts, label) {
|
|
223
|
+
const root = decodeLaunchdPlist(content);
|
|
224
|
+
if (requirePlistString(root, "Label") !== label) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist Label is not this profile scope");
|
|
225
|
+
if (requirePlistString(root, "X-DshPiTuiOwner") !== LAUNCHD_OWNER_MARKER) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist is not owned by this product");
|
|
226
|
+
if (requirePlistString(root, "X-DshPiTuiScopeId") !== facts.scopeId) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist belongs to another profile scope");
|
|
227
|
+
if (requirePlistString(root, "X-DshPiTuiProfileIdentity") !== facts.profileIdentity) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist belongs to another canonical profile");
|
|
228
|
+
const installBuild = requirePlistString(root, "X-DshPiTuiInstallBuild");
|
|
229
|
+
if (!/^[0-9a-f]{64}$/u.test(installBuild)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the plist has no valid install build identity");
|
|
230
|
+
return installBuild;
|
|
231
|
+
}
|
|
232
|
+
/** Resolve and prove the OS account home without trusting `$HOME`/`DSH_HOME`. */
|
|
233
|
+
function resolveAccountHome(deps) {
|
|
234
|
+
const uid = effectiveUid(deps);
|
|
235
|
+
let home;
|
|
236
|
+
if (deps.accountHome !== void 0) try {
|
|
237
|
+
home = realpathSync(deps.accountHome);
|
|
238
|
+
} catch (error) {
|
|
239
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "launchd: the account home is not readable", error);
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
let info;
|
|
243
|
+
try {
|
|
244
|
+
info = userInfo();
|
|
245
|
+
} catch (error) {
|
|
246
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "launchd: the OS account home is unavailable", error);
|
|
247
|
+
}
|
|
248
|
+
if (info.uid !== uid) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "launchd: the OS account uid does not match this process uid");
|
|
249
|
+
try {
|
|
250
|
+
home = realpathSync(info.homedir);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "launchd: the OS account home is not readable", error);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
let info;
|
|
256
|
+
try {
|
|
257
|
+
info = lstatSync(home);
|
|
258
|
+
} catch (error) {
|
|
259
|
+
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "launchd: the account home is not accessible", error);
|
|
260
|
+
}
|
|
261
|
+
if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== uid) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "launchd: the account home must be a real uid-owned directory");
|
|
262
|
+
return home;
|
|
263
|
+
}
|
|
264
|
+
function effectiveUid(deps) {
|
|
265
|
+
const uid = deps.uid ?? (typeof process.getuid === "function" ? process.getuid() : void 0);
|
|
266
|
+
if (uid === void 0) throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", "launchd: this operation requires a local user identity");
|
|
267
|
+
return uid;
|
|
268
|
+
}
|
|
269
|
+
/** The `<account-home>/Library/LaunchAgents` path WITHOUT creating it. */
|
|
270
|
+
function launchAgentsDir(accountHome) {
|
|
271
|
+
return join(accountHome, "Library", "LaunchAgents");
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Walk the LaunchAgents directory chain, creating only missing components 0700.
|
|
275
|
+
* An existing real directory or resolvable directory symlink is accepted as the
|
|
276
|
+
* user's own layout and is never chmodded; only an inaccessible path or a
|
|
277
|
+
* non-directory is refused.
|
|
278
|
+
*/
|
|
279
|
+
function ensureLaunchAgentsDir(accountHome) {
|
|
280
|
+
let current = accountHome;
|
|
281
|
+
for (const component of ["Library", "LaunchAgents"]) {
|
|
282
|
+
const next = join(current, component);
|
|
283
|
+
let real;
|
|
284
|
+
try {
|
|
285
|
+
real = realpathSync(next);
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (error.code !== "ENOENT") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the ${component} directory is not accessible`, error);
|
|
288
|
+
try {
|
|
289
|
+
mkdirSync(next, { mode: 448 });
|
|
290
|
+
} catch (mkdirError) {
|
|
291
|
+
if (mkdirError.code !== "EEXIST") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the ${component} directory could not be created`, mkdirError);
|
|
292
|
+
}
|
|
293
|
+
try {
|
|
294
|
+
real = realpathSync(next);
|
|
295
|
+
} catch (realpathError) {
|
|
296
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the ${component} directory is not accessible`, realpathError);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (!statSync(real).isDirectory()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the ${component} directory is not a directory`);
|
|
300
|
+
current = next;
|
|
301
|
+
}
|
|
302
|
+
return current;
|
|
303
|
+
}
|
|
304
|
+
/** The exact named plist path without touching the filesystem. */
|
|
305
|
+
function plistPathOf(accountHome, scopeId) {
|
|
306
|
+
return join(launchAgentsDir(accountHome), launchdPlistName(scopeId));
|
|
307
|
+
}
|
|
308
|
+
/** Read the named plist and its regular canonical target without mutation. */
|
|
309
|
+
function readLaunchdFileIdentity(filePath) {
|
|
310
|
+
let pathInfo;
|
|
311
|
+
try {
|
|
312
|
+
pathInfo = lstatSync(filePath);
|
|
313
|
+
} catch (error) {
|
|
314
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist is not accessible", error);
|
|
315
|
+
}
|
|
316
|
+
if (pathInfo.isSymbolicLink()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist must not be a symlink");
|
|
317
|
+
if (!pathInfo.isFile()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist must be a regular file");
|
|
318
|
+
let resolvedPath;
|
|
319
|
+
let target;
|
|
320
|
+
try {
|
|
321
|
+
resolvedPath = realpathSync(filePath);
|
|
322
|
+
target = lstatSync(resolvedPath);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist target is not readable", error);
|
|
325
|
+
}
|
|
326
|
+
if (!target.isFile()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist target must be a regular file");
|
|
327
|
+
let content;
|
|
328
|
+
try {
|
|
329
|
+
content = readFileSync(resolvedPath, "utf8");
|
|
330
|
+
} catch (error) {
|
|
331
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist is not readable", error);
|
|
332
|
+
}
|
|
333
|
+
return {
|
|
334
|
+
content,
|
|
335
|
+
resolvedPath,
|
|
336
|
+
pathDevice: pathInfo.dev,
|
|
337
|
+
pathInode: pathInfo.ino,
|
|
338
|
+
device: target.dev,
|
|
339
|
+
inode: target.ino
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Inspect the exact profile plist path. A missing `LaunchAgents` directory or
|
|
344
|
+
* plist is `none`; an existing file that is not this product/profile scope is a
|
|
345
|
+
* hard ownership refusal. No directory is created and `launchctl` is not invoked.
|
|
346
|
+
*/
|
|
347
|
+
function inspectOwnedLaunchdUnit(facts, deps = {}) {
|
|
348
|
+
const accountHome = resolveAccountHome(deps);
|
|
349
|
+
const label = buildLaunchdLabel(facts.scopeId);
|
|
350
|
+
const filePath = plistPathOf(accountHome, facts.scopeId);
|
|
351
|
+
let exists = true;
|
|
352
|
+
try {
|
|
353
|
+
lstatSync(filePath);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
if (error.code === "ENOENT") exists = false;
|
|
356
|
+
else throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist path is not accessible", error);
|
|
357
|
+
}
|
|
358
|
+
if (!exists) return { kind: "none" };
|
|
359
|
+
const file = readLaunchdFileIdentity(filePath);
|
|
360
|
+
return {
|
|
361
|
+
kind: "owned",
|
|
362
|
+
unit: {
|
|
363
|
+
label,
|
|
364
|
+
filePath,
|
|
365
|
+
installBuild: inspectLaunchdIdentity(file.content, facts, label),
|
|
366
|
+
...file
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
/** Re-prove one owned plist's captured file identity before a mutation. */
|
|
371
|
+
function assertLaunchdFileIdentity(unit, facts, deps) {
|
|
372
|
+
const inspected = inspectOwnedLaunchdUnit(facts, deps);
|
|
373
|
+
if (inspected.kind !== "owned" || inspected.unit.filePath !== unit.filePath || inspected.unit.resolvedPath !== unit.resolvedPath || inspected.unit.pathDevice !== unit.pathDevice || inspected.unit.pathInode !== unit.pathInode || inspected.unit.device !== unit.device || inspected.unit.inode !== unit.inode || inspected.unit.content !== unit.content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist changed during the transition");
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Run exactly one fixed `launchctl` invocation: `shell: false`, an absolute
|
|
377
|
+
* binary path, a hard timeout, bounded output and a fully reaped child.
|
|
378
|
+
*/
|
|
379
|
+
function runLaunchctl(args, options = {}) {
|
|
380
|
+
return new Promise((resolve) => {
|
|
381
|
+
let settled = false;
|
|
382
|
+
let stdout = "";
|
|
383
|
+
let stderr = "";
|
|
384
|
+
let overflow = false;
|
|
385
|
+
const settle = (result) => {
|
|
386
|
+
if (settled) return;
|
|
387
|
+
settled = true;
|
|
388
|
+
clearTimeout(timer);
|
|
389
|
+
resolve(result);
|
|
390
|
+
};
|
|
391
|
+
let child;
|
|
392
|
+
try {
|
|
393
|
+
child = spawn(LAUNCHCTL, [...args], {
|
|
394
|
+
shell: false,
|
|
395
|
+
stdio: options.discardStdout === true ? [
|
|
396
|
+
"ignore",
|
|
397
|
+
"ignore",
|
|
398
|
+
"pipe"
|
|
399
|
+
] : [
|
|
400
|
+
"ignore",
|
|
401
|
+
"pipe",
|
|
402
|
+
"pipe"
|
|
403
|
+
],
|
|
404
|
+
env: process.env
|
|
405
|
+
});
|
|
406
|
+
} catch (error) {
|
|
407
|
+
settle({
|
|
408
|
+
kind: "spawn-error",
|
|
409
|
+
error
|
|
410
|
+
});
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
const timer = setTimeout(() => {
|
|
414
|
+
child.kill("SIGKILL");
|
|
415
|
+
settle({ kind: "timeout" });
|
|
416
|
+
}, LAUNCHCTL_TIMEOUT_MS);
|
|
417
|
+
const collect = (current, chunk) => {
|
|
418
|
+
if (overflow) return current;
|
|
419
|
+
const next = current + chunk.toString("utf8");
|
|
420
|
+
if (Buffer.byteLength(next, "utf8") > LAUNCHCTL_MAX_OUTPUT_BYTES) {
|
|
421
|
+
overflow = true;
|
|
422
|
+
child.kill("SIGKILL");
|
|
423
|
+
return current;
|
|
424
|
+
}
|
|
425
|
+
return next;
|
|
426
|
+
};
|
|
427
|
+
child.stdout?.on("data", (chunk) => {
|
|
428
|
+
stdout = collect(stdout, chunk);
|
|
429
|
+
});
|
|
430
|
+
child.stderr?.on("data", (chunk) => {
|
|
431
|
+
stderr = collect(stderr, chunk);
|
|
432
|
+
});
|
|
433
|
+
child.once("error", (error) => {
|
|
434
|
+
settle({
|
|
435
|
+
kind: "spawn-error",
|
|
436
|
+
error
|
|
437
|
+
});
|
|
438
|
+
});
|
|
439
|
+
child.once("close", (code) => {
|
|
440
|
+
if (overflow) {
|
|
441
|
+
settle({ kind: "output-overflow" });
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
settle({
|
|
445
|
+
kind: "exited",
|
|
446
|
+
code: code ?? 1,
|
|
447
|
+
stdout,
|
|
448
|
+
stderr
|
|
449
|
+
});
|
|
450
|
+
});
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
/** One scalar `key = value` line of `launchctl print` (first occurrence wins). */
|
|
454
|
+
function readLaunchctlScalar(lines, key) {
|
|
455
|
+
const prefix = `${key} = `;
|
|
456
|
+
for (const line of lines) if (line.startsWith(prefix)) return line.slice(prefix.length);
|
|
457
|
+
}
|
|
458
|
+
/** One `name = { ... }` block of `launchctl print`, preserving raw entry lines. */
|
|
459
|
+
function readLaunchctlBlock(lines, key) {
|
|
460
|
+
const head = `${key} = {`;
|
|
461
|
+
const start = lines.indexOf(head);
|
|
462
|
+
if (start < 0) return void 0;
|
|
463
|
+
const entries = [];
|
|
464
|
+
for (const line of lines.slice(start + 1)) {
|
|
465
|
+
if (line === "}") return entries;
|
|
466
|
+
if (!line.startsWith(" ")) return void 0;
|
|
467
|
+
entries.push(line.slice(1));
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Parse the ONE narrow set of real facts this product consumes from
|
|
472
|
+
* `launchctl print gui/<uid>/<label>`. The manager's whole output is never
|
|
473
|
+
* cached or treated as a second state machine; an incomplete or ambiguous
|
|
474
|
+
* answer is `undefined` (the caller must fail closed).
|
|
475
|
+
*/
|
|
476
|
+
function parseLaunchctlPrint(stdout) {
|
|
477
|
+
const lines = stdout.replace(/\r\n/gu, "\n").split("\n").map((line) => line.startsWith(" ") ? line.slice(1) : line);
|
|
478
|
+
const type = readLaunchctlScalar(lines, "type");
|
|
479
|
+
const path = readLaunchctlScalar(lines, "path");
|
|
480
|
+
const state = readLaunchctlScalar(lines, "state");
|
|
481
|
+
const program = readLaunchctlScalar(lines, "program");
|
|
482
|
+
const workingDirectory = readLaunchctlScalar(lines, "working directory");
|
|
483
|
+
const stdoutPath = readLaunchctlScalar(lines, "stdout path");
|
|
484
|
+
const stderrPath = readLaunchctlScalar(lines, "stderr path");
|
|
485
|
+
const argumentLines = readLaunchctlBlock(lines, "arguments");
|
|
486
|
+
const environmentLines = readLaunchctlBlock(lines, "environment");
|
|
487
|
+
if (type === void 0 || path === void 0 || state === void 0 || program === void 0 || argumentLines === void 0 || environmentLines === void 0) return void 0;
|
|
488
|
+
if (type !== "LaunchAgent" || !path.startsWith("/") || !program.startsWith("/")) return void 0;
|
|
489
|
+
for (const optional of [
|
|
490
|
+
workingDirectory,
|
|
491
|
+
stdoutPath,
|
|
492
|
+
stderrPath
|
|
493
|
+
]) if (optional !== void 0 && !optional.startsWith("/")) return void 0;
|
|
494
|
+
const argumentsList = [];
|
|
495
|
+
for (const line of argumentLines) {
|
|
496
|
+
if (line === "") return void 0;
|
|
497
|
+
argumentsList.push(line);
|
|
498
|
+
}
|
|
499
|
+
if (argumentsList.length === 0) return void 0;
|
|
500
|
+
const environment = {};
|
|
501
|
+
for (const line of environmentLines) {
|
|
502
|
+
const separator = line.indexOf(" => ");
|
|
503
|
+
if (separator <= 0) return void 0;
|
|
504
|
+
const key = line.slice(0, separator);
|
|
505
|
+
if (Object.hasOwn(environment, key)) return void 0;
|
|
506
|
+
environment[key] = line.slice(separator + 4);
|
|
507
|
+
}
|
|
508
|
+
const pidText = readLaunchctlScalar(lines, "pid");
|
|
509
|
+
let pid;
|
|
510
|
+
if (pidText !== void 0) {
|
|
511
|
+
if (!/^[0-9]+$/u.test(pidText)) return void 0;
|
|
512
|
+
const parsed = Number(pidText);
|
|
513
|
+
if (!Number.isSafeInteger(parsed) || parsed <= 0) return void 0;
|
|
514
|
+
pid = parsed;
|
|
515
|
+
}
|
|
516
|
+
return {
|
|
517
|
+
type,
|
|
518
|
+
path,
|
|
519
|
+
state,
|
|
520
|
+
program,
|
|
521
|
+
arguments: argumentsList,
|
|
522
|
+
...workingDirectory === void 0 ? {} : { workingDirectory },
|
|
523
|
+
...stdoutPath === void 0 ? {} : { stdoutPath },
|
|
524
|
+
...stderrPath === void 0 ? {} : { stderrPath },
|
|
525
|
+
environment,
|
|
526
|
+
...pid === void 0 ? {} : { pid }
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
/** Map one launchctl answer into the narrow read-only service observation. */
|
|
530
|
+
function launchctlFailure(result, action) {
|
|
531
|
+
switch (result.kind) {
|
|
532
|
+
case "timeout": return new LocalScopeError("HOST_MANAGER_ERROR", `launchd: launchctl ${action} timed out`);
|
|
533
|
+
case "spawn-error": return new LocalScopeError("HOST_MANAGER_ERROR", `launchd: launchctl ${action} could not be spawned`, result.error);
|
|
534
|
+
case "output-overflow": return new LocalScopeError("HOST_MANAGER_ERROR", `launchd: launchctl ${action} produced too much output`);
|
|
535
|
+
case "exited": return new LocalScopeError("HOST_MANAGER_ERROR", `launchd: launchctl ${action} failed (exit ${String(result.code)})`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
/** Query the current service of one fixed job label. */
|
|
539
|
+
async function inspectLaunchdServiceByLabel(label, deps) {
|
|
540
|
+
const uid = effectiveUid(deps);
|
|
541
|
+
const result = await (deps.launchctl ?? runLaunchctl)(["print", `gui/${String(uid)}/${label}`]);
|
|
542
|
+
if (result.kind !== "exited") throw launchctlFailure(result, "print");
|
|
543
|
+
if (result.code === 113) return { kind: "not-loaded" };
|
|
544
|
+
if (result.code === 112) throw new LocalScopeError("HOST_MANAGER_ERROR", "launchd: the user GUI domain is not available");
|
|
545
|
+
if (result.code !== 0) throw launchctlFailure(result, "print");
|
|
546
|
+
const service = parseLaunchctlPrint(result.stdout);
|
|
547
|
+
if (service === void 0) return { kind: "unknown" };
|
|
548
|
+
return {
|
|
549
|
+
kind: "loaded",
|
|
550
|
+
service
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
/** Read-only inspection of one owned plist's live launchd service. */
|
|
554
|
+
async function inspectLaunchdService(unit, deps = {}) {
|
|
555
|
+
return await inspectLaunchdServiceByLabel(unit.label, deps);
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Answer ONE question: is the currently loaded `gui/<uid>/<label>` job
|
|
559
|
+
* bootstrapped from THIS profile's verified LaunchAgent plist and carrying the
|
|
560
|
+
* same target profile's runtime anchors?
|
|
561
|
+
*
|
|
562
|
+
* YES requires `service.type === 'LaunchAgent'`, the printed `path` to be the
|
|
563
|
+
* canonical target of the verified plist (a lexical alias is admitted only
|
|
564
|
+
* while it resolves to the same real file), and the three official profile
|
|
565
|
+
* environment anchors to match the current installed facts. Everything else —
|
|
566
|
+
* program, arguments, working directory, log sinks, `RunAtLoad`/`KeepAlive`,
|
|
567
|
+
* extra environment keys — is the user's own launchd configuration and is NOT
|
|
568
|
+
* identity. This is NEVER Host readiness and NEVER a PID authorization: the
|
|
569
|
+
* caller separately proves the real PID against the authenticated Host.
|
|
570
|
+
*/
|
|
571
|
+
function launchdServiceMatches(facts, unit, service) {
|
|
572
|
+
if (service.type !== "LaunchAgent") return false;
|
|
573
|
+
if (service.path === unit.resolvedPath) return sameLaunchdProfileAnchors(facts, service);
|
|
574
|
+
try {
|
|
575
|
+
return realpathSync(service.path) === unit.resolvedPath && sameLaunchdProfileAnchors(facts, service);
|
|
576
|
+
} catch {
|
|
577
|
+
return false;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
/** The three official profile anchors of one loaded job environment. */
|
|
581
|
+
function sameLaunchdProfileAnchors(facts, service) {
|
|
582
|
+
return service.environment.DSH_HOME === facts.dshHome && service.environment.SPLIT_PROCESS_DSH_ANCHOR === facts.dshAnchor && service.environment.SPLIT_PROCESS_PROFILE === facts.profile;
|
|
583
|
+
}
|
|
584
|
+
/** Prove the user GUI domain is queryable before an install writes anything. */
|
|
585
|
+
async function assertLaunchdDomain(deps) {
|
|
586
|
+
const uid = effectiveUid(deps);
|
|
587
|
+
const result = await (deps.launchctl ?? runLaunchctl)(["print", `gui/${String(uid)}`], { discardStdout: true });
|
|
588
|
+
if (result.kind !== "exited" || result.code !== 0) {
|
|
589
|
+
if (result.kind === "exited" && result.code === 112) throw new LocalScopeError("HOST_MANAGER_ERROR", "launchd: the user GUI domain is not available");
|
|
590
|
+
throw launchctlFailure(result, "domain check");
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
/** Create a NEW private log file without truncating an existing one. The
|
|
594
|
+
* creation mode is 0600; an existing user file is opened append-only and its
|
|
595
|
+
* mode is never changed. A non-regular entry (FIFO, socket, device,
|
|
596
|
+
* directory) is refused before a blocking write-only FIFO open; O_NONBLOCK
|
|
597
|
+
* and the post-open fstat close the preflight/open race. */
|
|
598
|
+
function ensureLaunchdLogFile(path) {
|
|
599
|
+
let before;
|
|
600
|
+
try {
|
|
601
|
+
before = lstatSync(path);
|
|
602
|
+
} catch (error) {
|
|
603
|
+
if (error.code !== "ENOENT") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the private log path is not accessible", error);
|
|
604
|
+
}
|
|
605
|
+
if (before !== void 0 && !before.isFile()) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the private log path is not a regular file");
|
|
606
|
+
let fd;
|
|
607
|
+
try {
|
|
608
|
+
fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK, 384);
|
|
609
|
+
if (!fstatSync(fd).isFile()) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the private log path is not a regular file");
|
|
610
|
+
closeSync(fd);
|
|
611
|
+
fd = void 0;
|
|
612
|
+
} catch (error) {
|
|
613
|
+
if (fd !== void 0) closeSync(fd);
|
|
614
|
+
if (error instanceof LocalScopeError) throw error;
|
|
615
|
+
throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the private log file could not be prepared", error);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Prepare the two independent private launchd log sinks 0600 before a job
|
|
620
|
+
* starts. An existing file is opened append-only and never chmodded/truncated;
|
|
621
|
+
* a final symlink is refused (O_NOFOLLOW) and never followed.
|
|
622
|
+
*/
|
|
623
|
+
function ensureLaunchdLogFiles(facts) {
|
|
624
|
+
const logs = launchdLogPaths(facts.scopeDir);
|
|
625
|
+
ensureLaunchdLogFile(logs.stdout);
|
|
626
|
+
ensureLaunchdLogFile(logs.stderr);
|
|
627
|
+
}
|
|
628
|
+
/** Write one NEW plist atomically; an existing file is preserved untouched. */
|
|
629
|
+
function installLaunchdFile(options) {
|
|
630
|
+
const finalPath = join(options.dir, `${options.label}.plist`);
|
|
631
|
+
const tempPath = join(options.dir, `.${options.label}.${String(process.pid)}.${randomUUID()}.tmp`);
|
|
632
|
+
let fd;
|
|
633
|
+
try {
|
|
634
|
+
fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
|
|
635
|
+
fchmodSync(fd, 384);
|
|
636
|
+
const buffer = Buffer.from(options.content, "utf8");
|
|
637
|
+
let offset = 0;
|
|
638
|
+
while (offset < buffer.length) offset += writeSync(fd, buffer, offset, buffer.length - offset);
|
|
639
|
+
fsyncSync(fd);
|
|
640
|
+
closeSync(fd);
|
|
641
|
+
fd = void 0;
|
|
642
|
+
} catch (error) {
|
|
643
|
+
if (fd !== void 0) closeSync(fd);
|
|
644
|
+
try {
|
|
645
|
+
unlinkSync(tempPath);
|
|
646
|
+
} catch {}
|
|
647
|
+
if (error instanceof LocalScopeError) throw error;
|
|
648
|
+
throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the plist temp file could not be written", error);
|
|
649
|
+
}
|
|
650
|
+
let created = false;
|
|
651
|
+
try {
|
|
652
|
+
linkSync(tempPath, finalPath);
|
|
653
|
+
created = true;
|
|
654
|
+
} catch (linkError) {
|
|
655
|
+
if (linkError.code !== "EEXIST") {
|
|
656
|
+
try {
|
|
657
|
+
unlinkSync(tempPath);
|
|
658
|
+
} catch {}
|
|
659
|
+
throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the plist could not be installed atomically", linkError);
|
|
660
|
+
}
|
|
661
|
+
} finally {
|
|
662
|
+
try {
|
|
663
|
+
unlinkSync(tempPath);
|
|
664
|
+
} catch {}
|
|
665
|
+
}
|
|
666
|
+
if (!created) return {
|
|
667
|
+
created: false,
|
|
668
|
+
filePath: finalPath
|
|
669
|
+
};
|
|
670
|
+
const stat = statSync(finalPath);
|
|
671
|
+
const published = readFileSync(finalPath, "utf8");
|
|
672
|
+
if (!stat.isFile() || published !== options.content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the newly created plist changed before verification; preserving it");
|
|
673
|
+
return {
|
|
674
|
+
created: true,
|
|
675
|
+
filePath: finalPath,
|
|
676
|
+
identity: {
|
|
677
|
+
dev: stat.dev,
|
|
678
|
+
ino: stat.ino,
|
|
679
|
+
content: published
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
/** Remove ONLY this call's newly published plist after a failed post-link
|
|
684
|
+
* verification. A changed/foreign replacement is preserved; an unreadable or
|
|
685
|
+
* unremovable file reports the combined failure instead of hiding it. */
|
|
686
|
+
function rollbackNewLaunchdFile(installed, error) {
|
|
687
|
+
if (!installed.created || installed.identity === void 0) throw error;
|
|
688
|
+
let stat;
|
|
689
|
+
try {
|
|
690
|
+
stat = lstatSync(installed.filePath);
|
|
691
|
+
} catch (inspectError) {
|
|
692
|
+
if (inspectError.code === "ENOENT") throw error;
|
|
693
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: post-install verification failed and the new plist could not be re-inspected; preserving it", inspectError);
|
|
694
|
+
}
|
|
695
|
+
if (!stat.isFile() || stat.dev !== installed.identity.dev || stat.ino !== installed.identity.ino) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: post-install verification failed but the new plist was replaced; preserving the replacement", error);
|
|
696
|
+
let current;
|
|
697
|
+
try {
|
|
698
|
+
current = readFileSync(installed.filePath, "utf8");
|
|
699
|
+
} catch (readError) {
|
|
700
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: post-install verification failed and the new plist could not be read; preserving it", readError);
|
|
701
|
+
}
|
|
702
|
+
if (current !== installed.identity.content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: post-install verification failed but the new plist content changed; preserving it", error);
|
|
703
|
+
try {
|
|
704
|
+
unlinkSync(installed.filePath);
|
|
705
|
+
} catch (unlinkError) {
|
|
706
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: post-install verification failed and the new plist could not be removed; preserving it", unlinkError);
|
|
707
|
+
}
|
|
708
|
+
throw error;
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Install the ONE explicit user-level LaunchAgent for this profile. This path
|
|
712
|
+
* verifies the GUI domain, the current owned file (if any) and the same-label
|
|
713
|
+
* job source, then writes the plist atomically. A job loaded from our target
|
|
714
|
+
* path with no owned file is an unprovable source and is refused rather than
|
|
715
|
+
* conflated with a new file. It never bootstraps, kickstarts, enables, stops or
|
|
716
|
+
* restarts a job and never creates the profile runtime scope.
|
|
717
|
+
*/
|
|
718
|
+
async function installLaunchdUnit(facts, deps = {}) {
|
|
719
|
+
const accountHome = resolveAccountHome(deps);
|
|
720
|
+
const label = buildLaunchdLabel(facts.scopeId);
|
|
721
|
+
await assertLaunchdDomain(deps);
|
|
722
|
+
const dir = ensureLaunchAgentsDir(accountHome);
|
|
723
|
+
const filePath = join(dir, `${label}.plist`);
|
|
724
|
+
const canonicalTarget = join(realpathSync(dir), `${label}.plist`);
|
|
725
|
+
const existing = inspectOwnedLaunchdUnit(facts, deps);
|
|
726
|
+
const observed = await inspectLaunchdServiceByLabel(label, deps);
|
|
727
|
+
if (observed.kind === "unknown") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job state of this label is unknown; refusing to install");
|
|
728
|
+
if (observed.kind === "loaded") {
|
|
729
|
+
if (!(() => {
|
|
730
|
+
if (observed.service.path === filePath || observed.service.path === canonicalTarget) return true;
|
|
731
|
+
try {
|
|
732
|
+
return realpathSync(observed.service.path) === canonicalTarget;
|
|
733
|
+
} catch {
|
|
734
|
+
return false;
|
|
735
|
+
}
|
|
736
|
+
})()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: this label is already loaded from another source; refusing to install");
|
|
737
|
+
if (existing.kind === "none") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: this label is loaded from the profile plist path but no owned plist exists; the loaded source cannot be proven, refusing to install");
|
|
738
|
+
}
|
|
739
|
+
if (existing.kind === "owned") return {
|
|
740
|
+
label,
|
|
741
|
+
filePath: existing.unit.filePath,
|
|
742
|
+
created: false
|
|
743
|
+
};
|
|
744
|
+
const installed = installLaunchdFile({
|
|
745
|
+
dir,
|
|
746
|
+
label,
|
|
747
|
+
content: renderLaunchdPlist({
|
|
748
|
+
...facts,
|
|
749
|
+
hostEntryPath: resolveNamedLaunchdEntry(facts)
|
|
750
|
+
})
|
|
751
|
+
});
|
|
752
|
+
try {
|
|
753
|
+
const verified = (deps.verifyInstalledUnit ?? ((current) => inspectOwnedLaunchdUnit(current, deps)))(facts);
|
|
754
|
+
if (verified.kind !== "owned") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the installed profile plist could not be confirmed");
|
|
755
|
+
return {
|
|
756
|
+
label,
|
|
757
|
+
filePath: verified.unit.filePath,
|
|
758
|
+
created: installed.created
|
|
759
|
+
};
|
|
760
|
+
} catch (error) {
|
|
761
|
+
if (installed.created) rollbackNewLaunchdFile(installed, error);
|
|
762
|
+
throw error;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
/** Issue one kickstart for a verified job. */
|
|
766
|
+
async function kickstartLaunchdJob(unit, deps) {
|
|
767
|
+
const uid = effectiveUid(deps);
|
|
768
|
+
const result = await (deps.launchctl ?? runLaunchctl)(["kickstart", `gui/${String(uid)}/${unit.label}`]);
|
|
769
|
+
if (result.kind !== "exited" || result.code !== 0) throw launchctlFailure(result, "kickstart");
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Start the installed job through launchd only: prove the captured file
|
|
773
|
+
* identity and the profile launch anchors, inspect the current service,
|
|
774
|
+
* refuse a foreign loaded definition, reload a verified IDLE loaded job from
|
|
775
|
+
* the current on-disk user plist (launchd's `kickstart` reuses the cached
|
|
776
|
+
* bootstrap definition, which may predate a user edit), `bootstrap` exactly
|
|
777
|
+
* once when the job is not loaded, then `kickstart` exactly once when no
|
|
778
|
+
* process is running. The USER-OWNED definition is executed as written:
|
|
779
|
+
* `RunAtLoad`, `KeepAlive`, custom arguments, working directory, triggers and
|
|
780
|
+
* extra environment keys are legal launchd configuration and are not judged
|
|
781
|
+
* here; the caller proves the resulting Host through the official
|
|
782
|
+
* authentication (a custom command that never becomes a real Host fails there,
|
|
783
|
+
* with no detached fallback). The manager request is never readiness.
|
|
784
|
+
*/
|
|
785
|
+
async function startLaunchdService(facts, unit, deps = {}) {
|
|
786
|
+
const uid = effectiveUid(deps);
|
|
787
|
+
assertLaunchdFileIdentity(unit, facts, deps);
|
|
788
|
+
assertLaunchdProfileAnchors(facts, unit.content);
|
|
789
|
+
let observed = await inspectLaunchdService(unit, deps);
|
|
790
|
+
if (observed.kind === "unknown") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job state is not recognizable; refusing to start");
|
|
791
|
+
if (observed.kind === "loaded") {
|
|
792
|
+
if (!launchdServiceMatches(facts, unit, observed.service)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job does not match this profile plist; run daemon uninstall before reinstalling");
|
|
793
|
+
if (observed.service.pid !== void 0) return;
|
|
794
|
+
if (observed.service.state !== "not running") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job is in an unconfirmed state; refusing to start");
|
|
795
|
+
await stopLaunchdService(facts, unit, deps);
|
|
796
|
+
if ((await inspectLaunchdService(unit, deps)).kind !== "not-loaded") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the idle job could not be confirmed unloaded before the reload");
|
|
797
|
+
}
|
|
798
|
+
ensureLaunchdLogFiles(facts);
|
|
799
|
+
assertLaunchdFileIdentity(unit, facts, deps);
|
|
800
|
+
const bootstrap = await (deps.launchctl ?? runLaunchctl)([
|
|
801
|
+
"bootstrap",
|
|
802
|
+
`gui/${String(uid)}`,
|
|
803
|
+
unit.filePath
|
|
804
|
+
]);
|
|
805
|
+
if (bootstrap.kind !== "exited" || bootstrap.code !== 0) {
|
|
806
|
+
const raced = await inspectLaunchdService(unit, deps);
|
|
807
|
+
if (raced.kind !== "loaded" || !launchdServiceMatches(facts, unit, raced.service)) throw launchctlFailure(bootstrap, "bootstrap");
|
|
808
|
+
if (raced.service.pid !== void 0) return;
|
|
809
|
+
assertLaunchdFileIdentity(unit, facts, deps);
|
|
810
|
+
await kickstartLaunchdJob(unit, deps);
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
observed = await inspectLaunchdService(unit, deps);
|
|
814
|
+
if (observed.kind !== "loaded" || !launchdServiceMatches(facts, unit, observed.service)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the bootstrapped job is not this profile plist");
|
|
815
|
+
if (observed.service.pid !== void 0) return;
|
|
816
|
+
assertLaunchdFileIdentity(unit, facts, deps);
|
|
817
|
+
await kickstartLaunchdJob(unit, deps);
|
|
818
|
+
}
|
|
819
|
+
/** Bounded wait until a verified label is genuinely no longer loaded. */
|
|
820
|
+
async function waitForLaunchdJobRemoved(unit, deps) {
|
|
821
|
+
const now = deps.now ?? Date.now;
|
|
822
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
823
|
+
const deadline = now() + (deps.stopTimeoutMs ?? LAUNCHD_STOP_TIMEOUT_MS);
|
|
824
|
+
for (;;) {
|
|
825
|
+
if ((await inspectLaunchdService(unit, deps)).kind === "not-loaded") return;
|
|
826
|
+
if (now() >= deadline) throw new LocalScopeError("HOST_STOP_TIMEOUT", "launchd: the profile job did not leave the manager within the bounded window");
|
|
827
|
+
await sleep(LAUNCHD_STOP_POLL_MS);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Stop the verified profile job through `bootout` only. `bootout` is a shutdown
|
|
832
|
+
* REQUEST, not proof of process exit: the caller still waits for the recorded
|
|
833
|
+
* Darwin kernel identity to become gone/different. A loaded job that does not
|
|
834
|
+
* match the current profile plist is never booted out.
|
|
835
|
+
*/
|
|
836
|
+
async function stopLaunchdService(facts, unit, deps = {}, expectedPid) {
|
|
837
|
+
assertLaunchdFileIdentity(unit, facts, deps);
|
|
838
|
+
const observed = await inspectLaunchdService(unit, deps);
|
|
839
|
+
if (observed.kind === "not-loaded") return { stopped: false };
|
|
840
|
+
if (observed.kind === "unknown") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job state is not recognizable; refusing to stop");
|
|
841
|
+
if (!launchdServiceMatches(facts, unit, observed.service)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job does not match this profile plist; refusing to stop an unknown process");
|
|
842
|
+
if (observed.service.pid !== void 0) {
|
|
843
|
+
if (observed.service.state !== "running") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job has a process in an unconfirmed state; refusing to stop");
|
|
844
|
+
if (expectedPid === void 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job has a process but no authenticated Host record proves its identity; refusing to stop");
|
|
845
|
+
if (observed.service.pid !== expectedPid) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job PID changed before the stop; refusing to bootout an unverified process");
|
|
846
|
+
} else {
|
|
847
|
+
if (observed.service.state === "running" || observed.service.state === "spawn scheduled") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job is starting without a verifiable PID; refusing to stop");
|
|
848
|
+
if (observed.service.state !== "not running") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `launchd: the loaded job is in an unconfirmed state (${observed.service.state === "" ? "unknown" : observed.service.state}); refusing to stop`);
|
|
849
|
+
}
|
|
850
|
+
const stopped = observed.service.pid !== void 0;
|
|
851
|
+
assertLaunchdFileIdentity(unit, facts, deps);
|
|
852
|
+
const uid = effectiveUid(deps);
|
|
853
|
+
const result = await (deps.launchctl ?? runLaunchctl)(["bootout", `gui/${String(uid)}/${unit.label}`]);
|
|
854
|
+
if (result.kind !== "exited" || result.code !== 0 && result.code !== 3) throw launchctlFailure(result, "bootout");
|
|
855
|
+
await waitForLaunchdJobRemoved(unit, deps);
|
|
856
|
+
return { stopped };
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Remove ONE verified profile plist and, only when it is loaded from THIS exact
|
|
860
|
+
* file, the verified job. An independent Host, Sessions, Workspace,
|
|
861
|
+
* credentials, `host.log` and the launchd private logs are never removed.
|
|
862
|
+
*/
|
|
863
|
+
async function uninstallLaunchdUnit(facts, unit, deps = {}, expectedPid) {
|
|
864
|
+
assertLaunchdFileIdentity(unit, facts, deps);
|
|
865
|
+
const observed = await inspectLaunchdService(unit, deps);
|
|
866
|
+
if (observed.kind === "unknown") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the loaded job state is not recognizable; refusing to uninstall");
|
|
867
|
+
if (observed.kind === "loaded") {
|
|
868
|
+
if (!launchdServiceMatches(facts, unit, observed.service)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the loaded job does not match this profile plist; refusing to remove the job");
|
|
869
|
+
await stopLaunchdService(facts, unit, deps, expectedPid);
|
|
870
|
+
}
|
|
871
|
+
assertLaunchdFileIdentity(unit, facts, deps);
|
|
872
|
+
try {
|
|
873
|
+
unlinkSync(unit.filePath);
|
|
874
|
+
} catch (error) {
|
|
875
|
+
if (error.code === "ENOENT") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist vanished during uninstall");
|
|
876
|
+
throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the profile plist could not be removed", error);
|
|
877
|
+
}
|
|
878
|
+
if (inspectOwnedLaunchdUnit(facts, deps).kind !== "none") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist could not be confirmed removed");
|
|
879
|
+
}
|
|
880
|
+
/** The exact `ProgramArguments` block this product's renderer has always written. */
|
|
881
|
+
const GENERATED_PROGRAM_ARGUMENTS_SPAN = {
|
|
882
|
+
head: " <key>ProgramArguments</key>\n <array>\n <string>",
|
|
883
|
+
tail: "</string>\n </array>\n"
|
|
884
|
+
};
|
|
885
|
+
/** The exact `X-DshPiTuiInstallBuild` block this product's renderer writes. */
|
|
886
|
+
const GENERATED_INSTALL_BUILD_SPAN = {
|
|
887
|
+
head: " <key>X-DshPiTuiInstallBuild</key>\n <string>",
|
|
888
|
+
tail: "</string>\n"
|
|
889
|
+
};
|
|
890
|
+
/** The stable product entry suffix shared by every legal package layout. */
|
|
891
|
+
const PRODUCT_ENTRY_SUFFIX = "/node_modules/@xmoon76/dsh-pi-tui/dist/local-host.mjs";
|
|
892
|
+
/**
|
|
893
|
+
* Prove one old `ProgramArguments[1]` was generated by THIS Profile's install.
|
|
894
|
+
*
|
|
895
|
+
* A matching package name or a pnpm directory spelling only proves a layout,
|
|
896
|
+
* not generation provenance. Provenance requires the old package to live under
|
|
897
|
+
* THIS Profile's own `node_modules` layout (the real DSH install layout), to be
|
|
898
|
+
* readable, to be this product, and to have a computed build identity equal to
|
|
899
|
+
* the plist's recorded `X-DshPiTuiInstallBuild`. A pruned old package or any
|
|
900
|
+
* user pin outside this Profile (external store, another Profile, global
|
|
901
|
+
* install) cannot prove provenance and is preserved as user-managed.
|
|
902
|
+
*/
|
|
903
|
+
function proveGeneratedEntryForProfile(entryValue, facts, recordedBuild) {
|
|
904
|
+
if (!entryValue.startsWith(`${facts.profileRealpath}/node_modules/`)) return false;
|
|
905
|
+
let packageRoot;
|
|
906
|
+
let manifest;
|
|
907
|
+
try {
|
|
908
|
+
packageRoot = realpathSync(dirname(dirname(entryValue)));
|
|
909
|
+
manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
|
|
910
|
+
} catch {
|
|
911
|
+
return false;
|
|
912
|
+
}
|
|
913
|
+
if (manifest === null || typeof manifest !== "object" || manifest.name !== "@xmoon76/dsh-pi-tui") return false;
|
|
914
|
+
try {
|
|
915
|
+
return computeBuildId(packageRoot, readInstalledDshVersion(facts.dshAnchor)) === recordedBuild;
|
|
916
|
+
} catch {
|
|
917
|
+
return false;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Locate the product's EXACT generated `ProgramArguments` block: precisely two
|
|
922
|
+
* `<string>` children whose first value is the renderer's node executable form
|
|
923
|
+
* and whose second value is an accepted product Host entry path. The lexical
|
|
924
|
+
* span must equal the renderer's exact bytes; any reordering, binary plist,
|
|
925
|
+
* wrapper, extra argument or another program is not our generated block and
|
|
926
|
+
* returns `undefined`.
|
|
927
|
+
*/
|
|
928
|
+
function locateGeneratedProgramArguments(content, facts) {
|
|
929
|
+
const decoded = decodeLaunchdPlist(content);
|
|
930
|
+
const argv = decoded.ProgramArguments;
|
|
931
|
+
if (!Array.isArray(argv) || argv.length !== 2 || argv.some((value) => typeof value !== "string")) return void 0;
|
|
932
|
+
const [nodeValue, entryValue] = argv;
|
|
933
|
+
if (nodeValue !== facts.nodePath) return void 0;
|
|
934
|
+
if (!entryValue.endsWith(PRODUCT_ENTRY_SUFFIX)) return void 0;
|
|
935
|
+
const recordedBuild = decoded["X-DshPiTuiInstallBuild"];
|
|
936
|
+
if (typeof recordedBuild !== "string" || !/^[0-9a-f]{64}$/u.test(recordedBuild)) return void 0;
|
|
937
|
+
const entryStart = content.indexOf(GENERATED_PROGRAM_ARGUMENTS_SPAN.head);
|
|
938
|
+
if (entryStart < 0) return void 0;
|
|
939
|
+
const valueStart = entryStart + GENERATED_PROGRAM_ARGUMENTS_SPAN.head.length;
|
|
940
|
+
const firstTail = content.indexOf("</string>\n <string>", valueStart);
|
|
941
|
+
if (firstTail < 0) return void 0;
|
|
942
|
+
const secondStart = firstTail + 22;
|
|
943
|
+
const tailStart = content.indexOf(GENERATED_PROGRAM_ARGUMENTS_SPAN.tail, secondStart);
|
|
944
|
+
if (tailStart < 0) return void 0;
|
|
945
|
+
const end = tailStart + GENERATED_PROGRAM_ARGUMENTS_SPAN.tail.length;
|
|
946
|
+
if (content.slice(entryStart, end) !== ` <key>ProgramArguments</key>\n <array>\n <string>${nodeValue}</string>\n <string>${entryValue}</string>\n </array>\n`) return void 0;
|
|
947
|
+
if (content.indexOf(" <key>ProgramArguments</key>", entryStart + 1) >= 0) return void 0;
|
|
948
|
+
return {
|
|
949
|
+
oldEntry: entryValue,
|
|
950
|
+
recordedBuild,
|
|
951
|
+
start: entryStart,
|
|
952
|
+
end
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
/** Locate the product's exact generated `X-DshPiTuiInstallBuild` block. */
|
|
956
|
+
function locateGeneratedInstallBuild(content) {
|
|
957
|
+
const start = content.indexOf(GENERATED_INSTALL_BUILD_SPAN.head);
|
|
958
|
+
if (start < 0) return void 0;
|
|
959
|
+
const valueStart = start + GENERATED_INSTALL_BUILD_SPAN.head.length;
|
|
960
|
+
const tailStart = content.indexOf(GENERATED_INSTALL_BUILD_SPAN.tail, valueStart);
|
|
961
|
+
if (tailStart < 0) return void 0;
|
|
962
|
+
const end = tailStart + GENERATED_INSTALL_BUILD_SPAN.tail.length;
|
|
963
|
+
const block = content.slice(start, end);
|
|
964
|
+
const value = block.slice(GENERATED_INSTALL_BUILD_SPAN.head.length, block.length - GENERATED_INSTALL_BUILD_SPAN.tail.length);
|
|
965
|
+
if (!/^[0-9a-f]{64}$/u.test(value)) return void 0;
|
|
966
|
+
if (content.indexOf(GENERATED_INSTALL_BUILD_SPAN.head, start + 1) >= 0) return void 0;
|
|
967
|
+
return {
|
|
968
|
+
start,
|
|
969
|
+
end
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* The ONE bounded migration of an old PRODUCT-GENERATED plist fragment to the
|
|
974
|
+
* current install. `inspect` is read-only and may run before a stop; `apply`
|
|
975
|
+
* performs the atomic in-place replacement and is legal ONLY after the old
|
|
976
|
+
* Host kernel identity is proven gone and the loaded job is proven booted out.
|
|
977
|
+
*
|
|
978
|
+
* The ONLY bytes ever modified are a PROVEN generated `ProgramArguments[1]`
|
|
979
|
+
* (old installed entry -> the current stable named entry) and, when the
|
|
980
|
+
* arguments actually migrate, the adjacent generated `X-DshPiTuiInstallBuild`
|
|
981
|
+
* value. Provenance requires the old package to live under THIS Profile's own
|
|
982
|
+
* `node_modules` layout and the recorded install-build identity to equal its
|
|
983
|
+
* computed build identity. A user-customized argv, an external pin to another
|
|
984
|
+
* Profile/store/build, a pruned old package,
|
|
985
|
+
* a restructured XML, a binary plist or any other unrecognized shape is
|
|
986
|
+
* preserved byte-for-byte and reported `user-managed`: the plist is then
|
|
987
|
+
* executed exactly as the user wrote it and the resulting Host is authenticated
|
|
988
|
+
* (or truthfully reported `other-build`).
|
|
989
|
+
*/
|
|
990
|
+
function prepareOwnedLaunchdForCurrentInstall(facts, unit, deps, mode) {
|
|
991
|
+
assertLaunchdFileIdentity(unit, facts, deps);
|
|
992
|
+
assertLaunchdProfileAnchors(facts, unit.content);
|
|
993
|
+
const generated = locateGeneratedProgramArguments(unit.content, facts);
|
|
994
|
+
if (generated === void 0) return { plan: {
|
|
995
|
+
kind: "no-op",
|
|
996
|
+
reason: "user-managed"
|
|
997
|
+
} };
|
|
998
|
+
const namedEntry = resolveNamedLaunchdEntry(facts);
|
|
999
|
+
if (generated.oldEntry === namedEntry) return { plan: {
|
|
1000
|
+
kind: "no-op",
|
|
1001
|
+
reason: "current"
|
|
1002
|
+
} };
|
|
1003
|
+
if (!proveGeneratedEntryForProfile(generated.oldEntry, facts, generated.recordedBuild)) return { plan: {
|
|
1004
|
+
kind: "no-op",
|
|
1005
|
+
reason: "user-managed"
|
|
1006
|
+
} };
|
|
1007
|
+
const plan = {
|
|
1008
|
+
kind: "migrate",
|
|
1009
|
+
namedEntry
|
|
1010
|
+
};
|
|
1011
|
+
if (mode === "inspect") return { plan };
|
|
1012
|
+
const current = inspectOwnedLaunchdUnit(facts, deps);
|
|
1013
|
+
if (current.kind !== "owned" || current.unit.filePath !== unit.filePath || current.unit.content !== unit.content || current.unit.device !== unit.device || current.unit.inode !== unit.inode) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist changed before the migration was applied");
|
|
1014
|
+
const reGenerated = locateGeneratedProgramArguments(current.unit.content, facts);
|
|
1015
|
+
if (reGenerated === void 0 || reGenerated.oldEntry !== generated.oldEntry) return { plan: {
|
|
1016
|
+
kind: "no-op",
|
|
1017
|
+
reason: "user-managed"
|
|
1018
|
+
} };
|
|
1019
|
+
let next = spliceString(current.unit.content, generated.start, generated.end, [
|
|
1020
|
+
" <key>ProgramArguments</key>\n <array>\n <string>",
|
|
1021
|
+
encodePlistValue(facts.nodePath, "node path"),
|
|
1022
|
+
"</string>\n <string>",
|
|
1023
|
+
encodePlistValue(namedEntry, "Host entry path"),
|
|
1024
|
+
"</string>\n </array>\n"
|
|
1025
|
+
].join(""));
|
|
1026
|
+
const buildSpan = locateGeneratedInstallBuild(next);
|
|
1027
|
+
if (buildSpan !== void 0) next = spliceString(next, buildSpan.start, buildSpan.end, [
|
|
1028
|
+
" <key>X-DshPiTuiInstallBuild</key>\n <string>",
|
|
1029
|
+
encodePlistValue(facts.buildId, "install build"),
|
|
1030
|
+
"</string>\n"
|
|
1031
|
+
].join(""));
|
|
1032
|
+
decodeLaunchdPlist(next);
|
|
1033
|
+
const written = replacePlistAtomic(current.unit.filePath, next);
|
|
1034
|
+
const verified = inspectOwnedLaunchdUnit(facts, deps);
|
|
1035
|
+
if (verified.kind !== "owned" || verified.unit.content !== written) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the migrated plist could not be confirmed after the replacement");
|
|
1036
|
+
const argv = decodeLaunchdPlist(verified.unit.content).ProgramArguments;
|
|
1037
|
+
if (!Array.isArray(argv) || argv.length !== 2 || argv[1] !== namedEntry) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the migrated plist does not decode to the stable named entry");
|
|
1038
|
+
return {
|
|
1039
|
+
plan,
|
|
1040
|
+
unit: verified.unit
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
/** Replace an exact byte span of one string. */
|
|
1044
|
+
function spliceString(content, start, end, replacement) {
|
|
1045
|
+
return content.slice(0, start) + replacement + content.slice(end);
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Atomically replace one owned plist file in its own directory with the
|
|
1049
|
+
* original file mode, through a same-directory temp file, native `plutil`
|
|
1050
|
+
* validation, `fsync` and `rename`. The target must still be a regular
|
|
1051
|
+
* non-symlink file; a replaced or vanished target is a hard refusal (never a
|
|
1052
|
+
* blind overwrite).
|
|
1053
|
+
*/
|
|
1054
|
+
function replacePlistAtomic(filePath, content) {
|
|
1055
|
+
let originalMode;
|
|
1056
|
+
try {
|
|
1057
|
+
const info = lstatSync(filePath);
|
|
1058
|
+
if (!info.isFile() || info.isSymbolicLink()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist is not a regular file for an in-place migration");
|
|
1059
|
+
originalMode = info.mode & 511;
|
|
1060
|
+
} catch (error) {
|
|
1061
|
+
if (error instanceof LocalScopeError) throw error;
|
|
1062
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the profile plist could not be re-read before the migration", error);
|
|
1063
|
+
}
|
|
1064
|
+
const tempPath = join(dirname(filePath), `.${basename(filePath)}.${String(process.pid)}.${randomUUID()}.tmp`);
|
|
1065
|
+
let fd;
|
|
1066
|
+
try {
|
|
1067
|
+
fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, originalMode);
|
|
1068
|
+
fchmodSync(fd, originalMode);
|
|
1069
|
+
const buffer = Buffer.from(content, "utf8");
|
|
1070
|
+
let offset = 0;
|
|
1071
|
+
while (offset < buffer.length) offset += writeSync(fd, buffer, offset, buffer.length - offset);
|
|
1072
|
+
fsyncSync(fd);
|
|
1073
|
+
closeSync(fd);
|
|
1074
|
+
fd = void 0;
|
|
1075
|
+
const lint = spawnSync("/usr/bin/plutil", [
|
|
1076
|
+
"-lint",
|
|
1077
|
+
"-s",
|
|
1078
|
+
"--",
|
|
1079
|
+
tempPath
|
|
1080
|
+
], { timeout: 5e3 });
|
|
1081
|
+
if (lint.error !== void 0 || lint.status !== 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "launchd: the migrated plist failed the native lint before publication");
|
|
1082
|
+
renameSync(tempPath, filePath);
|
|
1083
|
+
} catch (error) {
|
|
1084
|
+
if (fd !== void 0) closeSync(fd);
|
|
1085
|
+
try {
|
|
1086
|
+
unlinkSync(tempPath);
|
|
1087
|
+
} catch {}
|
|
1088
|
+
if (error instanceof LocalScopeError) throw error;
|
|
1089
|
+
throw new LocalScopeError("HOST_MANAGER_START_FAILED", "launchd: the migrated plist could not be installed atomically", error);
|
|
1090
|
+
}
|
|
1091
|
+
return content;
|
|
1092
|
+
}
|
|
1093
|
+
//#endregion
|
|
1094
|
+
//#region src/app/remote-process/local-host-manager.ts
|
|
1095
|
+
/**
|
|
1096
|
+
* Profile-aware Host lifecycle: the basic detached process and the explicit
|
|
1097
|
+
* Linux systemd user service / macOS user LaunchAgent install.
|
|
1098
|
+
*
|
|
1099
|
+
* The basic daemon is an independent Host process. A public cold start inspects
|
|
1100
|
+
* whether THIS profile has an installed service definition first: on Linux no
|
|
1101
|
+
* unit means `spawnHostCandidate()` immediately, with no user-manager probe at
|
|
1102
|
+
* all; an installed, manager-loaded unit means one fixed `systemctl --user
|
|
1103
|
+
* start`. On macOS no plist keeps the same detached path; an owned plist means
|
|
1104
|
+
* one verified launchd bootstrap/kickstart through the Darwin adapter. The
|
|
1105
|
+
* Linux `installProfileHostUnit()` and macOS `installLaunchdUnit()` are the ONLY
|
|
1106
|
+
* paths that create a service definition; the ONE bounded exception is
|
|
1107
|
+
* `prepareOwnedProfileUnitForCurrentInstall()`, which an EXPLICIT CLI
|
|
1108
|
+
* `start`/`restart` uses to migrate a recognized pre-existing generated unit
|
|
1109
|
+
* field pair to the stable Profile entry. None of them starts, stops, enables,
|
|
1110
|
+
* auto-restarts or migrates a Host.
|
|
1111
|
+
*
|
|
1112
|
+
* `systemctl`/`journalctl` and `/bin/launchctl` are invoked through fixed
|
|
1113
|
+
* argument arrays. A missing command can only affect the explicit service-
|
|
1114
|
+
* managed branch; the detached Host never depends on it.
|
|
1115
|
+
*
|
|
1116
|
+
* This module never imports `app/bootstrap.ts`, Cordis, the Web or a Session
|
|
1117
|
+
* service, and it creates no manager store, daemon or public API: the Host's
|
|
1118
|
+
* official 0700 scope directory, abstract kernel seat, authenticated identity
|
|
1119
|
+
* and `runProfile` shutdown owner are all unchanged. A `systemctl start` or
|
|
1120
|
+
* `launchctl bootstrap` here only means the manager accepted a request;
|
|
1121
|
+
* readiness is still proven later by the existing authenticated Host handshake
|
|
1122
|
+
* in `local-discovery.ts`.
|
|
1123
|
+
*
|
|
1124
|
+
* @module app/remote-process/local-host-manager
|
|
1125
|
+
*/
|
|
1126
|
+
/** The system manager executable resolved through PATH (distribution-agnostic). */
|
|
1127
|
+
const SYSTEMCTL = "systemctl";
|
|
1128
|
+
/** Hard bound on one `systemctl` invocation. */
|
|
1129
|
+
const SYSTEMCTL_TIMEOUT_MS = 5e3;
|
|
1130
|
+
/** Hard cap on captured stdout/stderr bytes per invocation. */
|
|
1131
|
+
const SYSTEMCTL_MAX_OUTPUT_BYTES = 65536;
|
|
1132
|
+
/** The user unit subdirectory below the account home. */
|
|
1133
|
+
const USER_UNIT_SUBDIR = [
|
|
1134
|
+
".config",
|
|
1135
|
+
"systemd",
|
|
1136
|
+
"user"
|
|
1137
|
+
];
|
|
1138
|
+
/** The unit owner metadata marker. */
|
|
1139
|
+
const UNIT_OWNER_MARKER = "local-host-manager-v1";
|
|
1140
|
+
/** Bound on the post-`daemon-reload` LoadState re-query window. */
|
|
1141
|
+
const UNIT_LOAD_WAIT_MS = 3e3;
|
|
1142
|
+
/** Bound on the per-attempt LoadState poll interval. */
|
|
1143
|
+
const UNIT_LOAD_POLL_MS = 100;
|
|
1144
|
+
/** The one installed package a Profile Host unit launches. */
|
|
1145
|
+
const PROFILE_PACKAGE_NAME = "@xmoon76/dsh-pi-tui";
|
|
1146
|
+
/** The one stable lexical Host entry below an official Profile. */
|
|
1147
|
+
const PROFILE_HOST_ENTRY = ["dist", "local-host.mjs"];
|
|
1148
|
+
/** The user runtime directory to hand to a child `systemctl`. */
|
|
1149
|
+
function selectRuntimeDir(uid) {
|
|
1150
|
+
const standard = `/run/user/${String(uid)}`;
|
|
1151
|
+
try {
|
|
1152
|
+
const info = lstatSync(standard);
|
|
1153
|
+
if (info.isDirectory() && !info.isSymbolicLink() && info.uid === uid) return standard;
|
|
1154
|
+
} catch {}
|
|
1155
|
+
const ambient = process.env.XDG_RUNTIME_DIR;
|
|
1156
|
+
if (ambient !== void 0 && ambient !== "") return ambient;
|
|
1157
|
+
}
|
|
1158
|
+
function systemctlEnv(runtimeDir) {
|
|
1159
|
+
if (runtimeDir === void 0) return { ...process.env };
|
|
1160
|
+
return {
|
|
1161
|
+
...process.env,
|
|
1162
|
+
XDG_RUNTIME_DIR: runtimeDir
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
/**
|
|
1166
|
+
* Run exactly one fixed `systemctl` invocation: `shell: false`, an absolute
|
|
1167
|
+
* binary path, a hard timeout, bounded output and a fully reaped child.
|
|
1168
|
+
*/
|
|
1169
|
+
function runSystemctl(args, runtimeDir) {
|
|
1170
|
+
return new Promise((resolve) => {
|
|
1171
|
+
let settled = false;
|
|
1172
|
+
let stdout = "";
|
|
1173
|
+
let stderr = "";
|
|
1174
|
+
let overflow = false;
|
|
1175
|
+
const settle = (result) => {
|
|
1176
|
+
if (settled) return;
|
|
1177
|
+
settled = true;
|
|
1178
|
+
clearTimeout(timer);
|
|
1179
|
+
resolve(result);
|
|
1180
|
+
};
|
|
1181
|
+
let child;
|
|
1182
|
+
try {
|
|
1183
|
+
child = spawn(SYSTEMCTL, [...args], {
|
|
1184
|
+
shell: false,
|
|
1185
|
+
stdio: [
|
|
1186
|
+
"ignore",
|
|
1187
|
+
"pipe",
|
|
1188
|
+
"pipe"
|
|
1189
|
+
],
|
|
1190
|
+
env: systemctlEnv(runtimeDir)
|
|
1191
|
+
});
|
|
1192
|
+
} catch (error) {
|
|
1193
|
+
settle({
|
|
1194
|
+
kind: "spawn-error",
|
|
1195
|
+
error
|
|
1196
|
+
});
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
const timer = setTimeout(() => {
|
|
1200
|
+
overflow = false;
|
|
1201
|
+
child.kill("SIGKILL");
|
|
1202
|
+
settle({ kind: "timeout" });
|
|
1203
|
+
}, SYSTEMCTL_TIMEOUT_MS);
|
|
1204
|
+
const collect = (current, chunk) => {
|
|
1205
|
+
if (overflow) return current;
|
|
1206
|
+
const next = current + chunk.toString("utf8");
|
|
1207
|
+
if (Buffer.byteLength(next, "utf8") > SYSTEMCTL_MAX_OUTPUT_BYTES) {
|
|
1208
|
+
overflow = true;
|
|
1209
|
+
child.kill("SIGKILL");
|
|
1210
|
+
return current;
|
|
1211
|
+
}
|
|
1212
|
+
return next;
|
|
1213
|
+
};
|
|
1214
|
+
child.stdout?.on("data", (chunk) => {
|
|
1215
|
+
stdout = collect(stdout, chunk);
|
|
1216
|
+
});
|
|
1217
|
+
child.stderr?.on("data", (chunk) => {
|
|
1218
|
+
stderr = collect(stderr, chunk);
|
|
1219
|
+
});
|
|
1220
|
+
child.once("error", (error) => {
|
|
1221
|
+
settle({
|
|
1222
|
+
kind: "spawn-error",
|
|
1223
|
+
error
|
|
1224
|
+
});
|
|
1225
|
+
});
|
|
1226
|
+
child.once("close", (code) => {
|
|
1227
|
+
if (overflow) {
|
|
1228
|
+
settle({ kind: "output-overflow" });
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
settle({
|
|
1232
|
+
kind: "exited",
|
|
1233
|
+
code: code ?? 1,
|
|
1234
|
+
stdout,
|
|
1235
|
+
stderr
|
|
1236
|
+
});
|
|
1237
|
+
});
|
|
1238
|
+
});
|
|
1239
|
+
}
|
|
1240
|
+
/** Reject any control character that could inject a second unit directive. */
|
|
1241
|
+
function assertUnitSafe(value, label) {
|
|
1242
|
+
if (value.includes("\0") || /[\u0000-\u001f\u007f]/u.test(value)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the ${label} contains a control character`);
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* Encode one value for a systemd unit directive. Specifier expansion (`%`) is
|
|
1246
|
+
* universal, so `%` becomes `%%` everywhere; `$` variable substitution only
|
|
1247
|
+
* applies to command lines (`ExecStart`), so it becomes `$$` only there. Values
|
|
1248
|
+
* are wrapped in double quotes with the C-style backslash/quote escapes systemd
|
|
1249
|
+
* honours inside double quotes.
|
|
1250
|
+
*/
|
|
1251
|
+
function encodeUnitValue(value, label, commandLine) {
|
|
1252
|
+
assertUnitSafe(value, label);
|
|
1253
|
+
let out = "";
|
|
1254
|
+
for (const character of value) switch (character) {
|
|
1255
|
+
case "\\":
|
|
1256
|
+
out += "\\\\";
|
|
1257
|
+
break;
|
|
1258
|
+
case "\"":
|
|
1259
|
+
out += "\\\"";
|
|
1260
|
+
break;
|
|
1261
|
+
case "%":
|
|
1262
|
+
out += "%%";
|
|
1263
|
+
break;
|
|
1264
|
+
case "$":
|
|
1265
|
+
out += commandLine ? "$$" : "$";
|
|
1266
|
+
break;
|
|
1267
|
+
default: out += character;
|
|
1268
|
+
}
|
|
1269
|
+
return `"${out}"`;
|
|
1270
|
+
}
|
|
1271
|
+
/**
|
|
1272
|
+
* Encode a single systemd PATH directive (`WorkingDirectory`). Unlike command
|
|
1273
|
+
* lines and `Environment=`, a path setting is parsed as ONE raw value: double
|
|
1274
|
+
* quotes are NOT stripped, so a quoted path is a different (wrong) path. `%`
|
|
1275
|
+
* specifiers still expand (`%%` for a literal `%`) and a literal backslash must
|
|
1276
|
+
* be doubled; a `"` cannot appear unquoted without changing the parse, so it is
|
|
1277
|
+
* refused rather than silently corrupting the unit.
|
|
1278
|
+
*/
|
|
1279
|
+
function encodeUnitPath(value, label) {
|
|
1280
|
+
assertUnitSafe(value, label);
|
|
1281
|
+
if (value.includes("\"")) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the ${label} must not contain a double quote`);
|
|
1282
|
+
let out = "";
|
|
1283
|
+
for (const character of value) switch (character) {
|
|
1284
|
+
case "\\":
|
|
1285
|
+
out += "\\\\";
|
|
1286
|
+
break;
|
|
1287
|
+
case "%":
|
|
1288
|
+
out += "%%";
|
|
1289
|
+
break;
|
|
1290
|
+
default: out += character;
|
|
1291
|
+
}
|
|
1292
|
+
return out;
|
|
1293
|
+
}
|
|
1294
|
+
/**
|
|
1295
|
+
* Encode a systemd `Environment=` assignment (`KEY=VALUE`): the value uses the
|
|
1296
|
+
* no-variable-substitution rules (a literal `$` stays `$`), specifiers escape.
|
|
1297
|
+
*/
|
|
1298
|
+
function encodeEnvironment(key, value) {
|
|
1299
|
+
return `Environment=${encodeUnitValue(`${key}=${value}`, `environment ${key}`, false)}`;
|
|
1300
|
+
}
|
|
1301
|
+
/** The deterministic profile-identity digest stored in the unit owner metadata. */
|
|
1302
|
+
function profileIdentityDigest(profileRealpath) {
|
|
1303
|
+
return createHash("sha256").update(`dsh-pi-tui/profile-identity/1\0${profileRealpath}`).digest("hex");
|
|
1304
|
+
}
|
|
1305
|
+
/**
|
|
1306
|
+
* Build the readable, ASCII-safe profile slug used ONLY in the unit file name.
|
|
1307
|
+
* Full scopeId ownership is always validated separately; the slug never grants
|
|
1308
|
+
* ownership. Non-ASCII or unsafe characters become `_`; the first character is
|
|
1309
|
+
* prefixed with `p` when it is not alphanumeric; the result is bounded to 32.
|
|
1310
|
+
*/
|
|
1311
|
+
function profileUnitSlug(profile) {
|
|
1312
|
+
let slug = "";
|
|
1313
|
+
for (const character of profile) slug += /[A-Za-z0-9_.-]/u.test(character) ? character : "_";
|
|
1314
|
+
if (slug === "") slug = "profile";
|
|
1315
|
+
if (!/[A-Za-z0-9]/u.test(slug[0])) slug = `p${slug}`;
|
|
1316
|
+
if (slug.length > 32) slug = slug.slice(0, 32);
|
|
1317
|
+
return slug;
|
|
1318
|
+
}
|
|
1319
|
+
/** The stable unit name for one (profile, scopeId) pair. */
|
|
1320
|
+
function buildUnitName(profile, scopeId) {
|
|
1321
|
+
return `dsh-pi-tui@${profileUnitSlug(profile)}-${scopeId.slice(0, 16)}.service`;
|
|
1322
|
+
}
|
|
1323
|
+
/** Render the complete, fixed unit file for one installed Host. */
|
|
1324
|
+
function renderUnitContent(facts) {
|
|
1325
|
+
return [
|
|
1326
|
+
"[Unit]",
|
|
1327
|
+
"Description=dsh-pi-tui local Host (profile-scoped)",
|
|
1328
|
+
`X-DshPiTuiOwner=${UNIT_OWNER_MARKER}`,
|
|
1329
|
+
`X-DshPiTuiScopeId=${facts.scopeId}`,
|
|
1330
|
+
`X-DshPiTuiProfileIdentity=${profileIdentityDigest(facts.profileRealpath)}`,
|
|
1331
|
+
`X-DshPiTuiInstallBuild=${facts.buildId}`,
|
|
1332
|
+
"StartLimitIntervalSec=60s",
|
|
1333
|
+
"StartLimitBurst=3",
|
|
1334
|
+
"",
|
|
1335
|
+
"[Service]",
|
|
1336
|
+
"Type=exec",
|
|
1337
|
+
`ExecStart=${encodeUnitValue(facts.nodePath, "node path", true)} ${encodeUnitValue(facts.hostEntryPath, "Host entry path", true)}`,
|
|
1338
|
+
`WorkingDirectory=${encodeUnitPath(facts.profileRealpath, "WorkingDirectory")}`,
|
|
1339
|
+
encodeEnvironment("DSH_HOME", facts.dshHome),
|
|
1340
|
+
encodeEnvironment("SPLIT_PROCESS_DSH_ANCHOR", facts.dshAnchor),
|
|
1341
|
+
encodeEnvironment("SPLIT_PROCESS_PROFILE", facts.profile),
|
|
1342
|
+
"Restart=on-failure",
|
|
1343
|
+
"RestartSec=2s",
|
|
1344
|
+
"TimeoutStopSec=15s",
|
|
1345
|
+
"KillMode=control-group",
|
|
1346
|
+
"StandardOutput=journal",
|
|
1347
|
+
"StandardError=journal",
|
|
1348
|
+
""
|
|
1349
|
+
].join("\n");
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* Prove one built entry can locate its own installed product package root from
|
|
1353
|
+
* its REAL module URL. The preflight accepts a shared-store/dist symlink only
|
|
1354
|
+
* when the spawned process will be able to do the same.
|
|
1355
|
+
*/
|
|
1356
|
+
function assertEntrySelfLocation(entryPath, code, label) {
|
|
1357
|
+
try {
|
|
1358
|
+
installedPackageRootFromEntry(pathToFileURL(entryPath).href);
|
|
1359
|
+
} catch (error) {
|
|
1360
|
+
throw new LocalScopeError(code, `managed Host: the ${label} cannot locate its installed package root`, error);
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
/**
|
|
1364
|
+
* A validated installed fact: a canonical regular file. The user's install
|
|
1365
|
+
* layout (shared npm store, root-owned system package, legal entry symlink) is
|
|
1366
|
+
* not judged; only the real target file type is.
|
|
1367
|
+
*/
|
|
1368
|
+
function inspectOwnedRegular(path, label) {
|
|
1369
|
+
let real;
|
|
1370
|
+
try {
|
|
1371
|
+
real = realpathSync(path);
|
|
1372
|
+
} catch (error) {
|
|
1373
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the ${label} is not readable`, error);
|
|
1374
|
+
}
|
|
1375
|
+
if (!lstatSync(real).isFile()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the ${label} must be a regular file`);
|
|
1376
|
+
return real;
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* Validate a trusted EXECUTABLE the unit will run (the Node interpreter). Its
|
|
1380
|
+
* trust is "an absolute, canonical, executable regular file", NOT "owned by this
|
|
1381
|
+
* uid": a system Node such as `/usr/bin/node` is normally root-owned yet a
|
|
1382
|
+
* normal user may run it.
|
|
1383
|
+
*/
|
|
1384
|
+
function inspectTrustedExecutable(path, label) {
|
|
1385
|
+
let real;
|
|
1386
|
+
try {
|
|
1387
|
+
real = realpathSync(path);
|
|
1388
|
+
} catch (error) {
|
|
1389
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the ${label} is not readable`, error);
|
|
1390
|
+
}
|
|
1391
|
+
const info = lstatSync(real);
|
|
1392
|
+
if (info.isSymbolicLink() || !info.isFile() || (info.mode & 73) === 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the ${label} must be an executable regular file`);
|
|
1393
|
+
return real;
|
|
1394
|
+
}
|
|
1395
|
+
/**
|
|
1396
|
+
* Validate the official DSH install anchor (`@deepseek-ai/dsh/package.json`).
|
|
1397
|
+
* Its trust is "a readable, canonical regular file declaring the exact
|
|
1398
|
+
* `@deepseek-ai/dsh` package and the pinned runtime version" — NOT uid,
|
|
1399
|
+
* mode or install layout: a normal user may run against a root-owned,
|
|
1400
|
+
* system-wide DSH install or a symlinked package store. The caller checks the
|
|
1401
|
+
* package identity and exact version pin.
|
|
1402
|
+
*/
|
|
1403
|
+
function inspectTrustedDshAnchor(path) {
|
|
1404
|
+
let real;
|
|
1405
|
+
try {
|
|
1406
|
+
real = realpathSync(path);
|
|
1407
|
+
} catch (error) {
|
|
1408
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor is not readable", error);
|
|
1409
|
+
}
|
|
1410
|
+
if (!lstatSync(real).isFile()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor must be a regular file");
|
|
1411
|
+
return real;
|
|
1412
|
+
}
|
|
1413
|
+
/** Collect and validate the exact installed facts one service definition is rendered from. */
|
|
1414
|
+
function collectUnitFacts(options) {
|
|
1415
|
+
const nodePath = inspectTrustedExecutable(process.execPath, "node executable");
|
|
1416
|
+
if (!isAbsolute(options.hostEntryPath)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the Host entry path must be absolute");
|
|
1417
|
+
inspectOwnedRegular(options.hostEntryPath, "Host entry");
|
|
1418
|
+
assertEntrySelfLocation(options.hostEntryPath, "HOST_MANAGER_UNIT_CONFLICT", "Host entry");
|
|
1419
|
+
const dshAnchor = inspectTrustedDshAnchor(options.dshAnchor);
|
|
1420
|
+
let manifest;
|
|
1421
|
+
try {
|
|
1422
|
+
manifest = JSON.parse(readFileSync(dshAnchor, "utf8"));
|
|
1423
|
+
} catch (error) {
|
|
1424
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor manifest is unreadable", error);
|
|
1425
|
+
}
|
|
1426
|
+
if (manifest === null || typeof manifest !== "object" || manifest.name !== "@deepseek-ai/dsh") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor is not @deepseek-ai/dsh");
|
|
1427
|
+
if (manifest.version !== options.scope.dshVersion) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the DSH anchor version does not match the installed runtime pin");
|
|
1428
|
+
return {
|
|
1429
|
+
dshHome: options.scope.dshHome,
|
|
1430
|
+
profileRealpath: options.scope.profileRealpath,
|
|
1431
|
+
profile: options.profile,
|
|
1432
|
+
scopeId: options.scope.scopeId,
|
|
1433
|
+
buildId: options.scope.buildId,
|
|
1434
|
+
nodePath,
|
|
1435
|
+
hostEntryPath: options.hostEntryPath,
|
|
1436
|
+
dshAnchor
|
|
1437
|
+
};
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* The stable LEXICAL Host entry inside this Profile's own package. The official
|
|
1441
|
+
* DSH/pnpm resolution keeps pointing `node_modules/@xmoon76/dsh-pi-tui` at the
|
|
1442
|
+
* CURRENT install, so this path survives a package update where a frozen pnpm
|
|
1443
|
+
* store path does not.
|
|
1444
|
+
*/
|
|
1445
|
+
function stableProfileHostEntry(scope) {
|
|
1446
|
+
return join(scope.profileRealpath, "node_modules", PROFILE_PACKAGE_NAME, ...PROFILE_HOST_ENTRY);
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* Prove the stable Profile entry resolves to the CURRENT official install and
|
|
1450
|
+
* return the lexical path a user unit may launch. The installed root is the
|
|
1451
|
+
* launcher's real `createRequire` resolution result; a different real target
|
|
1452
|
+
* means this profile layout is not the official one and must not be written.
|
|
1453
|
+
*/
|
|
1454
|
+
function resolveStableProfileHostEntry(scope, installedHostEntryPath) {
|
|
1455
|
+
const namedEntry = stableProfileHostEntry(scope);
|
|
1456
|
+
let installedReal;
|
|
1457
|
+
let namedReal;
|
|
1458
|
+
try {
|
|
1459
|
+
installedReal = realpathSync(installedHostEntryPath);
|
|
1460
|
+
namedReal = realpathSync(namedEntry);
|
|
1461
|
+
} catch (error) {
|
|
1462
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the stable profile Host entry or the current installed Host entry is not readable", error);
|
|
1463
|
+
}
|
|
1464
|
+
if (namedReal !== installedReal) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the stable profile Host entry does not resolve to the current installed package");
|
|
1465
|
+
return namedEntry;
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Walk the user unit directory chain below the account home, creating missing
|
|
1469
|
+
* components 0700. Existing user components are used as-is: an existing real
|
|
1470
|
+
* directory or a resolvable directory symlink is accepted regardless of owner or
|
|
1471
|
+
* mode, and nothing is chmodded. Only "not accessible", "not a directory" and a
|
|
1472
|
+
* real filesystem failure are refused.
|
|
1473
|
+
*/
|
|
1474
|
+
function ensureOwnedUnitDir(home) {
|
|
1475
|
+
let current = home;
|
|
1476
|
+
for (const component of USER_UNIT_SUBDIR) {
|
|
1477
|
+
const next = join(current, component);
|
|
1478
|
+
let real;
|
|
1479
|
+
try {
|
|
1480
|
+
real = realpathSync(next);
|
|
1481
|
+
} catch (error) {
|
|
1482
|
+
if (error.code !== "ENOENT") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the unit directory ${component} is not accessible`, error);
|
|
1483
|
+
try {
|
|
1484
|
+
mkdirSync(next, { mode: 448 });
|
|
1485
|
+
} catch (mkdirError) {
|
|
1486
|
+
if (mkdirError.code !== "EEXIST") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the unit directory ${component} could not be created`, mkdirError);
|
|
1487
|
+
}
|
|
1488
|
+
try {
|
|
1489
|
+
real = realpathSync(next);
|
|
1490
|
+
} catch (realpathError) {
|
|
1491
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the unit directory ${component} is not accessible`, realpathError);
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
if (!statSync(real).isDirectory()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the unit directory ${component} is not a directory`);
|
|
1495
|
+
current = next;
|
|
1496
|
+
}
|
|
1497
|
+
return current;
|
|
1498
|
+
}
|
|
1499
|
+
/** The canonical account home (never a Client HOME). */
|
|
1500
|
+
function accountHome() {
|
|
1501
|
+
let home;
|
|
1502
|
+
try {
|
|
1503
|
+
home = realpathSync(userInfo().homedir);
|
|
1504
|
+
} catch (error) {
|
|
1505
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the account home is not readable", error);
|
|
1506
|
+
}
|
|
1507
|
+
if (!statSync(home).isDirectory()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the account home is not a directory");
|
|
1508
|
+
return home;
|
|
1509
|
+
}
|
|
1510
|
+
/**
|
|
1511
|
+
* The fixed `<account-home>/.config/systemd/user` target WITHOUT creating it.
|
|
1512
|
+
* The manager UnitPath gate must run before ANY user-directory write; the
|
|
1513
|
+
* account-home spelling is kept (not realpathed) so the manager's own default
|
|
1514
|
+
* search path compares exactly even when the tail does not exist yet.
|
|
1515
|
+
*/
|
|
1516
|
+
function userUnitDirPath() {
|
|
1517
|
+
return join(userInfo().homedir, ...USER_UNIT_SUBDIR);
|
|
1518
|
+
}
|
|
1519
|
+
/**
|
|
1520
|
+
* Prove the RUNNING user manager is genuinely reachable BEFORE any unit write.
|
|
1521
|
+
* The manager's `UnitPath` is deliberately not used as a pre-write admission
|
|
1522
|
+
* gate: systemd omits still-empty directories from that property, so a clean
|
|
1523
|
+
* account's first install could never reach the mkdir. Manager reachability is
|
|
1524
|
+
* proven by a real bounded request; the POST-write `daemon-reload` plus the
|
|
1525
|
+
* real `LoadState`/`FragmentPath` verification decide whether the manager
|
|
1526
|
+
* loaded this exact file. A manager failure is a hard error and never falls
|
|
1527
|
+
* back to a detached process.
|
|
1528
|
+
*/
|
|
1529
|
+
async function assertUserManagerAvailable(runtimeDir, systemctl) {
|
|
1530
|
+
const result = await systemctl([
|
|
1531
|
+
"--user",
|
|
1532
|
+
"--no-pager",
|
|
1533
|
+
"--no-ask-password",
|
|
1534
|
+
"show",
|
|
1535
|
+
"-p",
|
|
1536
|
+
"UnitPath",
|
|
1537
|
+
"--value"
|
|
1538
|
+
], runtimeDir);
|
|
1539
|
+
if (result.kind !== "exited" || result.code !== 0) throw new LocalScopeError("HOST_MANAGER_ERROR", "managed Host: the user manager is not reachable");
|
|
1540
|
+
}
|
|
1541
|
+
/**
|
|
1542
|
+
* Atomically install ONE default unit file. A pre-existing target is a user
|
|
1543
|
+
* configuration fact, not a template conflict: leave it byte-for-byte untouched
|
|
1544
|
+
* and let the later identity/FragmentPath checks decide whether this Profile may
|
|
1545
|
+
* manage it. Two concurrent creators still converge on exactly one winner.
|
|
1546
|
+
*/
|
|
1547
|
+
function installProfileUnit(options) {
|
|
1548
|
+
const finalPath = join(options.unitDir, options.unitName);
|
|
1549
|
+
const tempPath = join(options.unitDir, `.${options.unitName}.${String(process.pid)}.${randomUUID()}.tmp`);
|
|
1550
|
+
let fd;
|
|
1551
|
+
try {
|
|
1552
|
+
fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
|
|
1553
|
+
fchmodSync(fd, 384);
|
|
1554
|
+
const buffer = Buffer.from(options.content, "utf8");
|
|
1555
|
+
let offset = 0;
|
|
1556
|
+
while (offset < buffer.length) offset += writeSync(fd, buffer, offset, buffer.length - offset);
|
|
1557
|
+
fsyncSync(fd);
|
|
1558
|
+
closeSync(fd);
|
|
1559
|
+
fd = void 0;
|
|
1560
|
+
} catch (error) {
|
|
1561
|
+
if (fd !== void 0) closeSync(fd);
|
|
1562
|
+
try {
|
|
1563
|
+
unlinkSync(tempPath);
|
|
1564
|
+
} catch {}
|
|
1565
|
+
if (error instanceof LocalScopeError) throw error;
|
|
1566
|
+
throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the unit temp file could not be written", error);
|
|
1567
|
+
}
|
|
1568
|
+
let created = false;
|
|
1569
|
+
try {
|
|
1570
|
+
linkSync(tempPath, finalPath);
|
|
1571
|
+
created = true;
|
|
1572
|
+
} catch (linkError) {
|
|
1573
|
+
if (linkError.code !== "EEXIST") {
|
|
1574
|
+
try {
|
|
1575
|
+
unlinkSync(tempPath);
|
|
1576
|
+
} catch {}
|
|
1577
|
+
throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the unit could not be installed atomically", linkError);
|
|
1578
|
+
}
|
|
1579
|
+
} finally {
|
|
1580
|
+
try {
|
|
1581
|
+
unlinkSync(tempPath);
|
|
1582
|
+
} catch {}
|
|
1583
|
+
}
|
|
1584
|
+
return { created };
|
|
1585
|
+
}
|
|
1586
|
+
/** Run `systemctl --user show -p ... <unit>` and parse the properties. */
|
|
1587
|
+
async function showUnit(unitName, runtimeDir, systemctl) {
|
|
1588
|
+
const result = await systemctl([
|
|
1589
|
+
"--user",
|
|
1590
|
+
"--no-pager",
|
|
1591
|
+
"--no-ask-password",
|
|
1592
|
+
"show",
|
|
1593
|
+
"-p",
|
|
1594
|
+
"LoadState",
|
|
1595
|
+
"-p",
|
|
1596
|
+
"ActiveState",
|
|
1597
|
+
"-p",
|
|
1598
|
+
"FragmentPath",
|
|
1599
|
+
"-p",
|
|
1600
|
+
"MainPID",
|
|
1601
|
+
"-p",
|
|
1602
|
+
"UnitFileState",
|
|
1603
|
+
unitName
|
|
1604
|
+
], runtimeDir);
|
|
1605
|
+
if (result.kind !== "exited" || result.code !== 0) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the unit state could not be queried");
|
|
1606
|
+
const read = (key) => {
|
|
1607
|
+
const match = new RegExp(`^${key}=(.*)$`, "mu").exec(result.stdout);
|
|
1608
|
+
return match === null ? "" : match[1].trim();
|
|
1609
|
+
};
|
|
1610
|
+
return {
|
|
1611
|
+
loadState: read("LoadState"),
|
|
1612
|
+
activeState: read("ActiveState"),
|
|
1613
|
+
fragmentPath: read("FragmentPath"),
|
|
1614
|
+
mainPid: read("MainPID"),
|
|
1615
|
+
unitFileState: read("UnitFileState")
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
/** Verify the manager loaded this Profile's canonical unit target. */
|
|
1619
|
+
function assertUnitOwned(state, finalPath) {
|
|
1620
|
+
if (state.loadState === "" || state.loadState === "not-found") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the installed unit is not loaded by the manager");
|
|
1621
|
+
if (state.fragmentPath === "") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the manager reported no FragmentPath for the unit");
|
|
1622
|
+
let realFragment;
|
|
1623
|
+
try {
|
|
1624
|
+
realFragment = realpathSync(state.fragmentPath);
|
|
1625
|
+
} catch (error) {
|
|
1626
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the manager FragmentPath is not a readable file", error);
|
|
1627
|
+
}
|
|
1628
|
+
if (realFragment !== realpathSync(finalPath)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the manager loaded a different unit file than the installed target");
|
|
1629
|
+
}
|
|
1630
|
+
async function waitForUnitLoaded(unitName, runtimeDir, systemctl) {
|
|
1631
|
+
const deadline = Date.now() + UNIT_LOAD_WAIT_MS;
|
|
1632
|
+
for (;;) {
|
|
1633
|
+
const state = await showUnit(unitName, runtimeDir, systemctl);
|
|
1634
|
+
if (state.loadState !== "not-found") return state;
|
|
1635
|
+
if (Date.now() >= deadline) return state;
|
|
1636
|
+
await new Promise((resolve) => setTimeout(resolve, UNIT_LOAD_POLL_MS));
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
/** The stable stop-settlement window (systemd TimeoutStopSec is 15s). */
|
|
1640
|
+
const UNIT_STOP_TIMEOUT_MS = 2e4;
|
|
1641
|
+
/** Poll interval for the post-stop MainPID/ActiveState observation. */
|
|
1642
|
+
const UNIT_STOP_POLL_MS = 100;
|
|
1643
|
+
/**
|
|
1644
|
+
* Resolve the fixed user unit directory WITHOUT creating it. The management
|
|
1645
|
+
* queries must be side-effect free, so this returns `undefined` when any
|
|
1646
|
+
* component of `<home>/.config/systemd/user` is missing. Existing user
|
|
1647
|
+
* components are not judged by owner/mode, and a resolvable directory symlink
|
|
1648
|
+
* is followed exactly like the account's own layout.
|
|
1649
|
+
*/
|
|
1650
|
+
function inspectExistingUserUnitDir() {
|
|
1651
|
+
let home;
|
|
1652
|
+
try {
|
|
1653
|
+
home = realpathSync(userInfo().homedir);
|
|
1654
|
+
} catch (error) {
|
|
1655
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the account home is not readable", error);
|
|
1656
|
+
}
|
|
1657
|
+
if (!statSync(home).isDirectory()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the account home is not a directory");
|
|
1658
|
+
let current = home;
|
|
1659
|
+
for (const component of USER_UNIT_SUBDIR) {
|
|
1660
|
+
const next = join(current, component);
|
|
1661
|
+
let real;
|
|
1662
|
+
try {
|
|
1663
|
+
real = realpathSync(next);
|
|
1664
|
+
} catch (error) {
|
|
1665
|
+
if (error.code === "ENOENT") return void 0;
|
|
1666
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the unit directory ${component} is not accessible`, error);
|
|
1667
|
+
}
|
|
1668
|
+
if (!statSync(real).isDirectory()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the unit directory ${component} is not a directory`);
|
|
1669
|
+
current = next;
|
|
1670
|
+
}
|
|
1671
|
+
return current;
|
|
1672
|
+
}
|
|
1673
|
+
/** Read one exact `X-DshPiTui...` unit metadata value, rejecting duplicates. */
|
|
1674
|
+
function readUnitMetadata(lines, key) {
|
|
1675
|
+
const matches = lines.filter((line) => line.startsWith(`${key}=`));
|
|
1676
|
+
if (matches.length !== 1) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the unit has no single ${key} owner metadata line`);
|
|
1677
|
+
return matches[0].slice(key.length + 1);
|
|
1678
|
+
}
|
|
1679
|
+
/** Read the named user unit and its regular canonical target without mutation. */
|
|
1680
|
+
function readUnitFileIdentity(filePath) {
|
|
1681
|
+
try {
|
|
1682
|
+
const pathInfo = lstatSync(filePath);
|
|
1683
|
+
const resolvedPath = realpathSync(filePath);
|
|
1684
|
+
const target = lstatSync(resolvedPath);
|
|
1685
|
+
if (!target.isFile()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit target is not a regular configuration file");
|
|
1686
|
+
return {
|
|
1687
|
+
content: readFileSync(resolvedPath, "utf8"),
|
|
1688
|
+
resolvedPath,
|
|
1689
|
+
pathDevice: pathInfo.dev,
|
|
1690
|
+
pathInode: pathInfo.ino,
|
|
1691
|
+
device: target.dev,
|
|
1692
|
+
inode: target.ino
|
|
1693
|
+
};
|
|
1694
|
+
} catch (error) {
|
|
1695
|
+
if (error instanceof LocalScopeError) throw error;
|
|
1696
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit configuration could not be read", error);
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
/** Runtime directives belong to the user and systemd; only metadata proves scope. */
|
|
1700
|
+
function inspectUnitIdentity(content, scope) {
|
|
1701
|
+
const lines = content.split("\n");
|
|
1702
|
+
if (readUnitMetadata(lines, "X-DshPiTuiOwner") !== UNIT_OWNER_MARKER) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit is not owned by this product");
|
|
1703
|
+
if (readUnitMetadata(lines, "X-DshPiTuiScopeId") !== scope.scopeId) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit belongs to another profile scope");
|
|
1704
|
+
if (readUnitMetadata(lines, "X-DshPiTuiProfileIdentity") !== profileIdentityDigest(scope.profileRealpath)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit belongs to another canonical profile");
|
|
1705
|
+
const installBuild = readUnitMetadata(lines, "X-DshPiTuiInstallBuild");
|
|
1706
|
+
if (!/^[0-9a-f]{64}$/u.test(installBuild)) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit has no valid install build identity");
|
|
1707
|
+
return installBuild;
|
|
1708
|
+
}
|
|
1709
|
+
/** Compare this operation's observation, never the generated default template. */
|
|
1710
|
+
function assertUnitFileIdentity(unit) {
|
|
1711
|
+
const current = readUnitFileIdentity(unit.filePath);
|
|
1712
|
+
if (current.pathDevice !== unit.pathDevice || current.pathInode !== unit.pathInode || current.resolvedPath !== unit.resolvedPath || current.device !== unit.device || current.inode !== unit.inode || current.content !== unit.content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit file changed during the transition");
|
|
1713
|
+
}
|
|
1714
|
+
/** Inspect the exact Profile unit path, following a user-created configuration link. */
|
|
1715
|
+
function inspectOwnedProfileUnit(scope, profile, unitDir) {
|
|
1716
|
+
const dir = unitDir ?? inspectExistingUserUnitDir();
|
|
1717
|
+
if (dir === void 0) return { kind: "none" };
|
|
1718
|
+
const unitName = buildUnitName(profile, scope.scopeId);
|
|
1719
|
+
const filePath = join(dir, unitName);
|
|
1720
|
+
try {
|
|
1721
|
+
lstatSync(filePath);
|
|
1722
|
+
} catch (error) {
|
|
1723
|
+
if (error.code === "ENOENT") return { kind: "none" };
|
|
1724
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit path is not accessible", error);
|
|
1725
|
+
}
|
|
1726
|
+
const file = readUnitFileIdentity(filePath);
|
|
1727
|
+
return {
|
|
1728
|
+
kind: "owned",
|
|
1729
|
+
unitName,
|
|
1730
|
+
unitDir: dir,
|
|
1731
|
+
filePath,
|
|
1732
|
+
installBuild: inspectUnitIdentity(file.content, scope),
|
|
1733
|
+
...file
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
/**
|
|
1737
|
+
* Query the manager facts of ONE owned profile unit and cross-check that the
|
|
1738
|
+
* manager really loads THIS file, including a canonical symlink target. A `not-found`
|
|
1739
|
+
* LoadState is returned as such (the file exists but is not loaded); every
|
|
1740
|
+
* contradicting fact is an ownership refusal.
|
|
1741
|
+
*/
|
|
1742
|
+
async function queryOwnedProfileUnit(unit, runtimeDir, systemctl) {
|
|
1743
|
+
const state = await showUnit(unit.unitName, runtimeDir, systemctl);
|
|
1744
|
+
if (state.loadState === "not-found") return {
|
|
1745
|
+
loadState: state.loadState,
|
|
1746
|
+
activeState: state.activeState,
|
|
1747
|
+
mainPid: 0,
|
|
1748
|
+
unitFileState: state.unitFileState
|
|
1749
|
+
};
|
|
1750
|
+
assertUnitOwned(state, unit.resolvedPath);
|
|
1751
|
+
return {
|
|
1752
|
+
loadState: state.loadState,
|
|
1753
|
+
activeState: state.activeState,
|
|
1754
|
+
mainPid: Number(state.mainPid) === 0 ? 0 : Number(state.mainPid),
|
|
1755
|
+
unitFileState: state.unitFileState
|
|
1756
|
+
};
|
|
1757
|
+
}
|
|
1758
|
+
/**
|
|
1759
|
+
* Stop ONE verified owned profile unit through the user manager and wait for
|
|
1760
|
+
* its original MainPID to actually disappear. This never falls back to a PID
|
|
1761
|
+
* signal: the manager is the only supervision authority. A timeout is the
|
|
1762
|
+
* stable `HOST_STOP_TIMEOUT`, never a claimed stop.
|
|
1763
|
+
*/
|
|
1764
|
+
async function stopOwnedProfileUnit(unit, runtimeDir, systemctl, timeoutMs = UNIT_STOP_TIMEOUT_MS) {
|
|
1765
|
+
const before = await queryOwnedProfileUnit(unit, runtimeDir, systemctl);
|
|
1766
|
+
if (before.activeState === "inactive" || before.activeState === "failed") return {
|
|
1767
|
+
stopped: false,
|
|
1768
|
+
alreadyInactive: true,
|
|
1769
|
+
mainPid: before.mainPid
|
|
1770
|
+
};
|
|
1771
|
+
if (before.activeState !== "active" && before.activeState !== "activating" && before.activeState !== "deactivating" && before.activeState !== "reloading") throw new LocalScopeError("HOST_MANAGER_START_FAILED", `managed Host: the unit is in an unrecognized state (${before.activeState})`);
|
|
1772
|
+
assertUnitFileIdentity(unit);
|
|
1773
|
+
const stop = await systemctl([
|
|
1774
|
+
"--user",
|
|
1775
|
+
"--no-pager",
|
|
1776
|
+
"--no-ask-password",
|
|
1777
|
+
"stop",
|
|
1778
|
+
unit.unitName
|
|
1779
|
+
], runtimeDir);
|
|
1780
|
+
if (stop.kind !== "exited" || stop.code !== 0) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: systemctl could not stop the unit");
|
|
1781
|
+
const deadline = Date.now() + timeoutMs;
|
|
1782
|
+
for (;;) {
|
|
1783
|
+
let after;
|
|
1784
|
+
try {
|
|
1785
|
+
after = await queryOwnedProfileUnit(unit, runtimeDir, systemctl);
|
|
1786
|
+
} catch (error) {
|
|
1787
|
+
if (!(error instanceof LocalScopeError)) throw error;
|
|
1788
|
+
throw new LocalScopeError(error.code, `managed Host stop may already be committed; final verification failed. Run daemon status before retrying. ${error.message}`, error);
|
|
1789
|
+
}
|
|
1790
|
+
if ((after.loadState === "not-found" || after.activeState === "inactive" || after.activeState === "failed") && (after.mainPid === 0 || after.mainPid !== before.mainPid)) return {
|
|
1791
|
+
stopped: true,
|
|
1792
|
+
alreadyInactive: false,
|
|
1793
|
+
mainPid: before.mainPid
|
|
1794
|
+
};
|
|
1795
|
+
if (Date.now() >= deadline) throw new LocalScopeError("HOST_STOP_TIMEOUT", "managed Host stop may already be committed; final verification failed. Run daemon status before retrying. The unit did not stop within the bounded window");
|
|
1796
|
+
await new Promise((resolve) => setTimeout(resolve, UNIT_STOP_POLL_MS));
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
/** Remove ONE verified owned profile unit file. There is no Host kill here: an
|
|
1800
|
+
* independent Host is not unit-supervised and is never stopped by uninstall. The
|
|
1801
|
+
* caller owns the `daemon-reload` that follows.
|
|
1802
|
+
*/
|
|
1803
|
+
function uninstallOwnedProfileUnit(unit, scope, profile) {
|
|
1804
|
+
const current = inspectOwnedProfileUnit(scope, profile, unit.unitDir);
|
|
1805
|
+
if (current.kind !== "owned" || current.filePath !== unit.filePath || current.device !== unit.device || current.inode !== unit.inode) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit file changed during the transition");
|
|
1806
|
+
assertUnitFileIdentity(unit);
|
|
1807
|
+
try {
|
|
1808
|
+
unlinkSync(unit.filePath);
|
|
1809
|
+
} catch (error) {
|
|
1810
|
+
if (error.code === "ENOENT") return;
|
|
1811
|
+
throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the profile unit file could not be removed", error);
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
/**
|
|
1815
|
+
* Prove the manager does not already run THIS unit name from another source
|
|
1816
|
+
* before a fresh high-priority unit file may shadow it. A loaded definition
|
|
1817
|
+
* with a different FragmentPath is either a foreign service (must be refused,
|
|
1818
|
+
* never redefined) or an obsolete cache of a removed file. Only the latter is
|
|
1819
|
+
* recoverable: the manager must report the previous file as gone for the
|
|
1820
|
+
* refusal to lift. The unit name embeds the profile slug and scope prefix, so
|
|
1821
|
+
* an unrelated same-named service is an ownership conflict by construction.
|
|
1822
|
+
*/
|
|
1823
|
+
async function assertFreshUnitNameIsNotShadowed(unitName, unitDir, runtimeDir, systemctl) {
|
|
1824
|
+
join(unitDir, unitName);
|
|
1825
|
+
const state = await showUnit(unitName, runtimeDir, systemctl);
|
|
1826
|
+
const mainPid = Number(state.mainPid);
|
|
1827
|
+
const definitelyInactive = state.activeState === "inactive" && Number.isFinite(mainPid) && mainPid === 0;
|
|
1828
|
+
if (state.loadState === "") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the manager did not report a load state for this unit name; refusing to shadow a possibly live unit");
|
|
1829
|
+
if (state.loadState === "not-found") {
|
|
1830
|
+
if (definitelyInactive) return;
|
|
1831
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the manager reports this unit name as ${state.activeState === "" ? "unknown" : state.activeState} while it is not loaded; refusing to shadow a possibly live unit`);
|
|
1832
|
+
}
|
|
1833
|
+
let fragmentReal;
|
|
1834
|
+
try {
|
|
1835
|
+
fragmentReal = realpathSync(state.fragmentPath);
|
|
1836
|
+
} catch (error) {
|
|
1837
|
+
if (error.code !== "ENOENT") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the loaded source of this unit name cannot be verified; refusing to shadow a possibly live unit", error);
|
|
1838
|
+
fragmentReal = void 0;
|
|
1839
|
+
}
|
|
1840
|
+
if (fragmentReal === void 0) {
|
|
1841
|
+
if (definitelyInactive) return;
|
|
1842
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", `managed Host: the loaded source is gone but the unit is ${state.activeState === "" ? "in unknown state" : state.activeState}; refusing to shadow a possibly running foreign service`);
|
|
1843
|
+
}
|
|
1844
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the user manager already runs this unit name from another unit file; refusing to shadow a foreign service");
|
|
1845
|
+
}
|
|
1846
|
+
/** The Linux uid this Host-supervision operation needs. */
|
|
1847
|
+
function requireLinuxUid() {
|
|
1848
|
+
if (process.platform !== "linux" || typeof process.getuid !== "function") throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", "managed Host: this operation requires Linux");
|
|
1849
|
+
return process.getuid();
|
|
1850
|
+
}
|
|
1851
|
+
/**
|
|
1852
|
+
* Install the ONE explicit systemd user unit for this profile. This is the only
|
|
1853
|
+
* path that writes a unit: it proves the user manager is reachable before any
|
|
1854
|
+
* write (an empty target directory is legitimately absent from `UnitPath`),
|
|
1855
|
+
* installs the rendered file atomically (never overwriting user content),
|
|
1856
|
+
* re-verifies the same-profile metadata/build identity and reloads/verifies the
|
|
1857
|
+
* manager's real `LoadState`/`FragmentPath`. It never starts, stops,
|
|
1858
|
+
* enables or restarts a unit and never creates a Client/Host.
|
|
1859
|
+
*/
|
|
1860
|
+
async function installProfileHostUnit(options, deps = {}) {
|
|
1861
|
+
const uid = requireLinuxUid();
|
|
1862
|
+
const systemctl = deps.systemctl ?? runSystemctl;
|
|
1863
|
+
const runtimeDir = selectRuntimeDir(uid);
|
|
1864
|
+
const unitDir = deps.unitDir !== void 0 ? deps.unitDir(uid) : userUnitDirPath();
|
|
1865
|
+
await assertUserManagerAvailable(runtimeDir, systemctl);
|
|
1866
|
+
if (deps.unitDir === void 0) ensureOwnedUnitDir(accountHome());
|
|
1867
|
+
else try {
|
|
1868
|
+
mkdirSync(unitDir, {
|
|
1869
|
+
recursive: true,
|
|
1870
|
+
mode: 448
|
|
1871
|
+
});
|
|
1872
|
+
} catch (error) {
|
|
1873
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the unit directory is not accessible", error);
|
|
1874
|
+
}
|
|
1875
|
+
const unitName = buildUnitName(options.profile, options.scope.scopeId);
|
|
1876
|
+
let unit = inspectOwnedProfileUnit(options.scope, options.profile, unitDir);
|
|
1877
|
+
let created = false;
|
|
1878
|
+
if (unit.kind === "none") {
|
|
1879
|
+
const content = renderUnitContent(collectUnitFacts({
|
|
1880
|
+
...options,
|
|
1881
|
+
hostEntryPath: resolveStableProfileHostEntry(options.scope, options.hostEntryPath)
|
|
1882
|
+
}));
|
|
1883
|
+
await assertFreshUnitNameIsNotShadowed(unitName, unitDir, runtimeDir, systemctl);
|
|
1884
|
+
created = installProfileUnit({
|
|
1885
|
+
unitDir,
|
|
1886
|
+
unitName,
|
|
1887
|
+
content
|
|
1888
|
+
}).created;
|
|
1889
|
+
unit = inspectOwnedProfileUnit(options.scope, options.profile, unitDir);
|
|
1890
|
+
}
|
|
1891
|
+
if (unit.kind !== "owned") throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the installed unit could not be confirmed");
|
|
1892
|
+
let reloaded = false;
|
|
1893
|
+
if (created) {
|
|
1894
|
+
const reload = await systemctl([
|
|
1895
|
+
"--user",
|
|
1896
|
+
"--no-pager",
|
|
1897
|
+
"--no-ask-password",
|
|
1898
|
+
"daemon-reload"
|
|
1899
|
+
], runtimeDir);
|
|
1900
|
+
if (reload.kind !== "exited" || reload.code !== 0) {
|
|
1901
|
+
const reloadFailure = new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: systemctl daemon-reload failed after the unit install");
|
|
1902
|
+
const rollbackFailure = rollbackFreshUnit(unit);
|
|
1903
|
+
if (rollbackFailure !== void 0) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: daemon-reload failed after the unit install and the freshly created unit could not be rolled back", new AggregateError([reloadFailure, rollbackFailure]));
|
|
1904
|
+
throw reloadFailure;
|
|
1905
|
+
}
|
|
1906
|
+
reloaded = true;
|
|
1907
|
+
let state;
|
|
1908
|
+
try {
|
|
1909
|
+
state = await waitForUnitLoaded(unitName, runtimeDir, systemctl);
|
|
1910
|
+
} catch (error) {
|
|
1911
|
+
const rollbackFailure = rollbackFreshUnit(unit);
|
|
1912
|
+
if (rollbackFailure !== void 0) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the freshly installed unit could not be verified and could not be rolled back", new AggregateError([error instanceof Error ? error : new Error(String(error)), rollbackFailure]));
|
|
1913
|
+
throw error instanceof LocalScopeError ? error : new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the freshly installed unit could not be verified after the reload", error);
|
|
1914
|
+
}
|
|
1915
|
+
if (state.loadState === "not-found") {
|
|
1916
|
+
const rollbackFailure = rollbackFreshUnit(unit);
|
|
1917
|
+
if (rollbackFailure !== void 0) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the freshly installed unit is not loaded by the manager and could not be rolled back", rollbackFailure);
|
|
1918
|
+
throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the freshly installed unit is not loadable by this user manager (its unit search path does not include the target directory)");
|
|
1919
|
+
}
|
|
1920
|
+
try {
|
|
1921
|
+
assertUnitOwned(state, unit.resolvedPath);
|
|
1922
|
+
} catch (error) {
|
|
1923
|
+
const rollbackFailure = rollbackFreshUnit(unit);
|
|
1924
|
+
if (rollbackFailure !== void 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the freshly installed unit was not adopted by the manager and could not be rolled back", new AggregateError([error instanceof Error ? error : new Error(String(error)), rollbackFailure]));
|
|
1925
|
+
throw error instanceof LocalScopeError ? error : new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the freshly installed unit was not adopted by the manager", error);
|
|
1926
|
+
}
|
|
1927
|
+
} else if ((await queryOwnedProfileUnit(unit, runtimeDir, systemctl)).loadState === "not-found") {
|
|
1928
|
+
const reload = await systemctl([
|
|
1929
|
+
"--user",
|
|
1930
|
+
"--no-pager",
|
|
1931
|
+
"--no-ask-password",
|
|
1932
|
+
"daemon-reload"
|
|
1933
|
+
], runtimeDir);
|
|
1934
|
+
if (reload.kind !== "exited" || reload.code !== 0) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: systemctl daemon-reload failed after the unit install");
|
|
1935
|
+
reloaded = true;
|
|
1936
|
+
const state = await waitForUnitLoaded(unitName, runtimeDir, systemctl);
|
|
1937
|
+
if (state.loadState === "not-found") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the installed unit is not loaded by the manager");
|
|
1938
|
+
assertUnitOwned(state, unit.resolvedPath);
|
|
1939
|
+
}
|
|
1940
|
+
assertUnitFileIdentity(unit);
|
|
1941
|
+
return {
|
|
1942
|
+
unitName,
|
|
1943
|
+
unitPath: unit.filePath,
|
|
1944
|
+
created,
|
|
1945
|
+
reloaded
|
|
1946
|
+
};
|
|
1947
|
+
}
|
|
1948
|
+
/**
|
|
1949
|
+
* Remove only the unit file THIS install just created, after a failed load
|
|
1950
|
+
* request. A changed identity is left alone (the user won the race).
|
|
1951
|
+
*/
|
|
1952
|
+
function rollbackFreshUnit(unit) {
|
|
1953
|
+
try {
|
|
1954
|
+
assertUnitFileIdentity(unit);
|
|
1955
|
+
unlinkSync(unit.filePath);
|
|
1956
|
+
return;
|
|
1957
|
+
} catch (error) {
|
|
1958
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
/** Decode ONE canonical `encodeUnitValue(..., commandLine: true)` double-quoted token. */
|
|
1962
|
+
function decodeCommandToken(text, start) {
|
|
1963
|
+
if (text[start] !== "\"") return void 0;
|
|
1964
|
+
let value = "";
|
|
1965
|
+
let index = start + 1;
|
|
1966
|
+
for (; index < text.length; index += 1) {
|
|
1967
|
+
const character = text[index];
|
|
1968
|
+
if (character === "\"") return {
|
|
1969
|
+
raw: text.slice(start, index + 1),
|
|
1970
|
+
value,
|
|
1971
|
+
end: index + 1
|
|
1972
|
+
};
|
|
1973
|
+
if (character === "\\") {
|
|
1974
|
+
const escaped = text[index + 1];
|
|
1975
|
+
if (escaped !== "\\" && escaped !== "\"") return void 0;
|
|
1976
|
+
value += escaped;
|
|
1977
|
+
index += 1;
|
|
1978
|
+
continue;
|
|
1979
|
+
}
|
|
1980
|
+
if (character === "%" || character === "$") {
|
|
1981
|
+
if (text[index + 1] !== character) return void 0;
|
|
1982
|
+
value += character;
|
|
1983
|
+
index += 1;
|
|
1984
|
+
continue;
|
|
1985
|
+
}
|
|
1986
|
+
value += character;
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
/**
|
|
1990
|
+
* Recognize the ONE generated command line: exactly two canonical encoded
|
|
1991
|
+
* tokens (absolute Node executable and a physical PiTui `local-host.mjs`). The
|
|
1992
|
+
* historical root may already be gone; then only the recognizable published
|
|
1993
|
+
* layout is required. A root that is still accessible must declare this exact
|
|
1994
|
+
* package. Anything else is user configuration and returns `undefined`.
|
|
1995
|
+
*/
|
|
1996
|
+
function parseGeneratedExecStart(value) {
|
|
1997
|
+
const node = decodeCommandToken(value, 0);
|
|
1998
|
+
if (node === void 0 || value[node.end] !== " ") return void 0;
|
|
1999
|
+
const host = decodeCommandToken(value, node.end + 1);
|
|
2000
|
+
if (host === void 0 || host.end !== value.length) return void 0;
|
|
2001
|
+
if (!isAbsolute(node.value) || !isAbsolute(host.value)) return void 0;
|
|
2002
|
+
if (!host.value.endsWith("/node_modules/@xmoon76/dsh-pi-tui/dist/local-host.mjs")) return void 0;
|
|
2003
|
+
if (existsSync(host.value)) try {
|
|
2004
|
+
installedPackageRootFromEntry(pathToFileURL(host.value).href);
|
|
2005
|
+
} catch {
|
|
2006
|
+
return;
|
|
2007
|
+
}
|
|
2008
|
+
return {
|
|
2009
|
+
line: `ExecStart=${value}`,
|
|
2010
|
+
nodeToken: node.raw,
|
|
2011
|
+
hostEntryPath: host.value
|
|
2012
|
+
};
|
|
2013
|
+
}
|
|
2014
|
+
/** Find the single PiTui-generated `ExecStart=` of one unit, if it is recognized. */
|
|
2015
|
+
function inspectGeneratedExecStart(content) {
|
|
2016
|
+
let section = "";
|
|
2017
|
+
let found;
|
|
2018
|
+
let count = 0;
|
|
2019
|
+
for (const line of content.split("\n")) {
|
|
2020
|
+
const sectionMatch = /^\[([^\]]+)\]$/u.exec(line);
|
|
2021
|
+
if (sectionMatch !== null) {
|
|
2022
|
+
section = sectionMatch[1];
|
|
2023
|
+
continue;
|
|
2024
|
+
}
|
|
2025
|
+
if (!/^\s*ExecStart\s*=/u.test(line)) continue;
|
|
2026
|
+
count += 1;
|
|
2027
|
+
if (count > 1 || section !== "Service" || !line.startsWith("ExecStart=")) return void 0;
|
|
2028
|
+
found = {
|
|
2029
|
+
line,
|
|
2030
|
+
value: line.slice(10)
|
|
2031
|
+
};
|
|
2032
|
+
}
|
|
2033
|
+
if (found === void 0) return void 0;
|
|
2034
|
+
return parseGeneratedExecStart(found.value);
|
|
2035
|
+
}
|
|
2036
|
+
/** The current user may replace this regular main unit file in place. */
|
|
2037
|
+
function inspectMigrationWriteAdmission(unit, uid) {
|
|
2038
|
+
let info;
|
|
2039
|
+
try {
|
|
2040
|
+
info = lstatSync(unit.filePath);
|
|
2041
|
+
} catch (error) {
|
|
2042
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit changed during the migration plan", error);
|
|
2043
|
+
}
|
|
2044
|
+
if (info.isSymbolicLink()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is a user-managed symlink; its configuration source is never rewritten");
|
|
2045
|
+
if (!info.isFile()) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is not a regular file");
|
|
2046
|
+
if (info.uid !== uid) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is not owned by the current user");
|
|
2047
|
+
if ((info.mode & 128) === 0) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the profile unit is not writable by the current user");
|
|
2048
|
+
try {
|
|
2049
|
+
accessSync(unit.unitDir, constants.W_OK);
|
|
2050
|
+
} catch (error) {
|
|
2051
|
+
throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the user unit directory is not writable", error);
|
|
2052
|
+
}
|
|
2053
|
+
return info.mode & 511;
|
|
2054
|
+
}
|
|
2055
|
+
/** Rewrite exactly the two generated fields; every other byte is preserved. */
|
|
2056
|
+
function migrateGeneratedUnitContent(content, generated, namedEntry, buildId) {
|
|
2057
|
+
const execStart = `ExecStart=${generated.nodeToken} ${encodeUnitValue(namedEntry, "Host entry path", true)}`;
|
|
2058
|
+
let execStartReplaced = false;
|
|
2059
|
+
let buildReplaced = false;
|
|
2060
|
+
const migrated = content.split("\n").map((line) => {
|
|
2061
|
+
if (line === generated.line) {
|
|
2062
|
+
execStartReplaced = true;
|
|
2063
|
+
return execStart;
|
|
2064
|
+
}
|
|
2065
|
+
if (line.startsWith("X-DshPiTuiInstallBuild=")) {
|
|
2066
|
+
buildReplaced = true;
|
|
2067
|
+
return `X-DshPiTuiInstallBuild=${buildId}`;
|
|
2068
|
+
}
|
|
2069
|
+
return line;
|
|
2070
|
+
});
|
|
2071
|
+
if (!execStartReplaced || !buildReplaced) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the generated unit fields are not the planned shape");
|
|
2072
|
+
return migrated.join("\n");
|
|
2073
|
+
}
|
|
2074
|
+
/** Atomically replace the OWNED main unit file, preserving its original mode. */
|
|
2075
|
+
function replaceOwnedUnitFile(unit, content, mode) {
|
|
2076
|
+
const tempPath = join(unit.unitDir, `.${unit.unitName}.${String(process.pid)}.${randomUUID()}.tmp`);
|
|
2077
|
+
let fd;
|
|
2078
|
+
try {
|
|
2079
|
+
fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, mode);
|
|
2080
|
+
fchmodSync(fd, mode);
|
|
2081
|
+
const buffer = Buffer.from(content, "utf8");
|
|
2082
|
+
let offset = 0;
|
|
2083
|
+
while (offset < buffer.length) offset += writeSync(fd, buffer, offset, buffer.length - offset);
|
|
2084
|
+
fsyncSync(fd);
|
|
2085
|
+
closeSync(fd);
|
|
2086
|
+
fd = void 0;
|
|
2087
|
+
assertUnitFileIdentity(unit);
|
|
2088
|
+
renameSync(tempPath, unit.filePath);
|
|
2089
|
+
} catch (error) {
|
|
2090
|
+
if (fd !== void 0) closeSync(fd);
|
|
2091
|
+
try {
|
|
2092
|
+
unlinkSync(tempPath);
|
|
2093
|
+
} catch {}
|
|
2094
|
+
if (error instanceof LocalScopeError) throw error;
|
|
2095
|
+
throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the migrated unit could not be written", error);
|
|
2096
|
+
} finally {
|
|
2097
|
+
try {
|
|
2098
|
+
unlinkSync(tempPath);
|
|
2099
|
+
} catch {}
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
/**
|
|
2103
|
+
* Prepare the Profile unit for the CURRENT installed package, for the explicit
|
|
2104
|
+
* CLI `start`/`restart` paths only. `inspect` never writes and proves whether the
|
|
2105
|
+
* `apply` rewrite is possible before a Host is stopped; `apply` performs the one
|
|
2106
|
+
* bounded atomic rewrite plus manager reload and re-verifies the manager source.
|
|
2107
|
+
* A user-custom `ExecStart` and a unit already pointing at the stable entry are
|
|
2108
|
+
* byte-preserved no-ops. There is no upgrade state, parser or manager here.
|
|
2109
|
+
*/
|
|
2110
|
+
async function prepareOwnedProfileUnitForCurrentInstall(options, deps = {}) {
|
|
2111
|
+
const uid = requireLinuxUid();
|
|
2112
|
+
const unitDir = deps.unitDir !== void 0 ? deps.unitDir(uid) : inspectExistingUserUnitDir();
|
|
2113
|
+
if (unitDir === void 0) return { kind: "none" };
|
|
2114
|
+
const inspected = inspectOwnedProfileUnit(options.scope, options.profile, unitDir);
|
|
2115
|
+
if (inspected.kind === "none") return { kind: "none" };
|
|
2116
|
+
const systemctl = deps.systemctl ?? runSystemctl;
|
|
2117
|
+
const runtimeDir = selectRuntimeDir(uid);
|
|
2118
|
+
if ((await queryOwnedProfileUnit(inspected, runtimeDir, systemctl)).loadState === "not-found") return { kind: "not-loaded" };
|
|
2119
|
+
const generated = inspectGeneratedExecStart(inspected.content);
|
|
2120
|
+
if (generated === void 0) return { kind: "unchanged" };
|
|
2121
|
+
if (generated.hostEntryPath === stableProfileHostEntry(options.scope)) return { kind: "unchanged" };
|
|
2122
|
+
const namedEntry = resolveStableProfileHostEntry(options.scope, options.hostEntryPath);
|
|
2123
|
+
const mode = inspectMigrationWriteAdmission(inspected, uid);
|
|
2124
|
+
if (options.mode === "inspect") return { kind: "migration-required" };
|
|
2125
|
+
const content = migrateGeneratedUnitContent(inspected.content, generated, namedEntry, options.scope.buildId);
|
|
2126
|
+
assertUnitFileIdentity(inspected);
|
|
2127
|
+
const beforeWrite = await queryOwnedProfileUnit(inspected, runtimeDir, systemctl);
|
|
2128
|
+
if (beforeWrite.loadState === "not-found") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the installed unit is not loaded by the manager");
|
|
2129
|
+
if (beforeWrite.activeState !== "inactive" && beforeWrite.activeState !== "failed") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the profile unit is not stopped; refusing to rewrite its command while it may start a Host");
|
|
2130
|
+
replaceOwnedUnitFile(inspected, content, mode);
|
|
2131
|
+
const reload = await systemctl([
|
|
2132
|
+
"--user",
|
|
2133
|
+
"--no-pager",
|
|
2134
|
+
"--no-ask-password",
|
|
2135
|
+
"daemon-reload"
|
|
2136
|
+
], runtimeDir);
|
|
2137
|
+
if (reload.kind !== "exited" || reload.code !== 0) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the migrated unit was written but systemctl daemon-reload failed; the manager load state is unconfirmed");
|
|
2138
|
+
const refreshed = inspectOwnedProfileUnit(options.scope, options.profile, unitDir);
|
|
2139
|
+
if (refreshed.kind !== "owned" || refreshed.filePath !== inspected.filePath || refreshed.content !== content) throw new LocalScopeError("HOST_MANAGER_UNIT_CONFLICT", "managed Host: the migrated unit could not be confirmed");
|
|
2140
|
+
if ((await queryOwnedProfileUnit(refreshed, runtimeDir, systemctl)).loadState === "not-found") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the migrated unit is not loaded by the manager");
|
|
2141
|
+
return { kind: "migrated" };
|
|
2142
|
+
}
|
|
2143
|
+
/**
|
|
2144
|
+
* Start the public daemon Host candidate. The ONE decision input is the
|
|
2145
|
+
* installed unit fact: no unit means the basic detached Host immediately, with
|
|
2146
|
+
* no user-manager probe and no systemctl call; an installed unit must be loaded
|
|
2147
|
+
* by the real manager with a matching FragmentPath, and is then started through
|
|
2148
|
+
* exactly one `systemctl --user start`. A different installed build is a
|
|
2149
|
+
* diagnostic fact, never an ownership verdict. A manager failure or unit
|
|
2150
|
+
* conflict is thrown and NEVER degrades to a detached process; this function
|
|
2151
|
+
* never writes a unit.
|
|
2152
|
+
*/
|
|
2153
|
+
async function startPublicHostCandidate(options, deps = {}) {
|
|
2154
|
+
const uid = requireLinuxUid();
|
|
2155
|
+
const unitDir = deps.unitDir !== void 0 ? deps.unitDir(uid) : inspectExistingUserUnitDir();
|
|
2156
|
+
if (unitDir === void 0) return spawnHostCandidate(options);
|
|
2157
|
+
const unit = inspectOwnedProfileUnit(options.scope, options.profile, unitDir);
|
|
2158
|
+
if (unit.kind === "none") return spawnHostCandidate(options);
|
|
2159
|
+
const systemctl = deps.systemctl ?? runSystemctl;
|
|
2160
|
+
const runtimeDir = selectRuntimeDir(uid);
|
|
2161
|
+
if ((await queryOwnedProfileUnit(unit, runtimeDir, systemctl)).loadState === "not-found") throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: the installed unit is not loaded by the manager");
|
|
2162
|
+
assertUnitFileIdentity(unit);
|
|
2163
|
+
const start = await systemctl([
|
|
2164
|
+
"--user",
|
|
2165
|
+
"--no-pager",
|
|
2166
|
+
"--no-ask-password",
|
|
2167
|
+
"start",
|
|
2168
|
+
unit.unitName
|
|
2169
|
+
], runtimeDir);
|
|
2170
|
+
if (start.kind !== "exited" || start.code !== 0) throw new LocalScopeError("HOST_MANAGER_START_FAILED", "managed Host: systemctl could not start the unit");
|
|
2171
|
+
return () => void 0;
|
|
2172
|
+
}
|
|
2173
|
+
/**
|
|
2174
|
+
* Collect the same validated installed facts for BOTH manager renderers; the
|
|
2175
|
+
* profile identity digest is the shared canonical-profile owner.
|
|
2176
|
+
*/
|
|
2177
|
+
function collectLaunchdUnitFacts(options) {
|
|
2178
|
+
return {
|
|
2179
|
+
...collectUnitFacts(options),
|
|
2180
|
+
scopeDir: options.scope.dir,
|
|
2181
|
+
profileIdentity: profileIdentityDigest(options.scope.profileRealpath)
|
|
2182
|
+
};
|
|
2183
|
+
}
|
|
2184
|
+
/**
|
|
2185
|
+
* Compatibility entry for the managed public-start policy.
|
|
2186
|
+
*
|
|
2187
|
+
* Linux follows the D0 public policy: the installed-unit fact decides between
|
|
2188
|
+
* the basic detached daemon and the verified systemd unit. On macOS only the
|
|
2189
|
+
* real public start consults the installed user LaunchAgent: no plist keeps the
|
|
2190
|
+
* historic detached process; an owned plist must start through the verified
|
|
2191
|
+
* launchd job and never degrades to a detached Host. The internal
|
|
2192
|
+
* qualification/peer/manual/reexec policies never consider a manager job.
|
|
2193
|
+
*/
|
|
2194
|
+
async function startManagedHostCandidate(options, deps = {}) {
|
|
2195
|
+
if (process.platform === "darwin") {
|
|
2196
|
+
if (options.hostStartPolicy !== "public") return spawnHostCandidate(options);
|
|
2197
|
+
const launchdDeps = deps.launchd ?? {};
|
|
2198
|
+
const facts = collectLaunchdUnitFacts(options);
|
|
2199
|
+
const inspected = inspectOwnedLaunchdUnit(facts, launchdDeps);
|
|
2200
|
+
if (inspected.kind === "none") return spawnHostCandidate(options);
|
|
2201
|
+
await startLaunchdService(facts, inspected.unit, launchdDeps);
|
|
2202
|
+
return () => void 0;
|
|
2203
|
+
}
|
|
2204
|
+
return startPublicHostCandidate(options, deps);
|
|
2205
|
+
}
|
|
2206
|
+
/**
|
|
2207
|
+
* Start one Host candidate as a detached OS process: the default basic daemon
|
|
2208
|
+
* whenever no profile unit is installed, and the internal qualification/peer/
|
|
2209
|
+
* manual path. It opens/creates the scope `host.log` (a NEW file is 0600; an
|
|
2210
|
+
* existing user-owned log is appended to as-is and never chmodded), validates
|
|
2211
|
+
* the installed Node/Host entry by its canonical regular-file target, runs with
|
|
2212
|
+
* the canonical profile as cwd, detaches/unrefs and never claims a periodic
|
|
2213
|
+
* auto-restart (that is systemd-only).
|
|
2214
|
+
*/
|
|
2215
|
+
function spawnHostCandidate(options) {
|
|
2216
|
+
if (!isAbsolute(options.hostEntryPath)) throw new LocalScopeError("HOST_START_FAILED", "managed Host: the installed Host entry path must be absolute");
|
|
2217
|
+
let realEntry;
|
|
2218
|
+
try {
|
|
2219
|
+
realEntry = realpathSync(options.hostEntryPath);
|
|
2220
|
+
} catch (error) {
|
|
2221
|
+
throw new LocalScopeError("HOST_START_FAILED", "managed Host: the installed Host entry is not readable", error);
|
|
2222
|
+
}
|
|
2223
|
+
if (!lstatSync(realEntry).isFile()) throw new LocalScopeError("HOST_START_FAILED", "managed Host: the installed Host entry must be a regular file");
|
|
2224
|
+
assertEntrySelfLocation(options.hostEntryPath, "HOST_START_FAILED", "installed Host entry");
|
|
2225
|
+
const logPath = join(options.scope.dir, "host.log");
|
|
2226
|
+
let fd;
|
|
2227
|
+
try {
|
|
2228
|
+
fd = openSync(logPath, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 384);
|
|
2229
|
+
const env = {
|
|
2230
|
+
...process.env,
|
|
2231
|
+
SPLIT_PROCESS_DSH_ANCHOR: options.dshAnchor,
|
|
2232
|
+
SPLIT_PROCESS_PROFILE: options.profile
|
|
2233
|
+
};
|
|
2234
|
+
delete env.SPLIT_PROCESS_EXTRA_PATCH;
|
|
2235
|
+
delete env.DSH_PI_TUI_ROLE;
|
|
2236
|
+
delete env.DSH_PI_TUI_HOST_ENTRY;
|
|
2237
|
+
delete env.DSH_PI_TUI_BACKEND;
|
|
2238
|
+
const child = spawn(process.execPath, [options.hostEntryPath], {
|
|
2239
|
+
cwd: options.scope.profileRealpath,
|
|
2240
|
+
detached: true,
|
|
2241
|
+
stdio: [
|
|
2242
|
+
"ignore",
|
|
2243
|
+
fd,
|
|
2244
|
+
fd
|
|
2245
|
+
],
|
|
2246
|
+
env
|
|
2247
|
+
});
|
|
2248
|
+
let spawnFailure;
|
|
2249
|
+
child.once("error", (error) => {
|
|
2250
|
+
spawnFailure = error;
|
|
2251
|
+
});
|
|
2252
|
+
child.unref();
|
|
2253
|
+
return () => spawnFailure;
|
|
2254
|
+
} catch (error) {
|
|
2255
|
+
if (error instanceof LocalScopeError) throw error;
|
|
2256
|
+
throw new LocalScopeError("HOST_START_FAILED", "managed Host: the Host candidate could not be spawned", error);
|
|
2257
|
+
} finally {
|
|
2258
|
+
if (fd !== void 0) closeSync(fd);
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
2261
|
+
//#endregion
|
|
2262
|
+
//#region src/app/remote-process/local-discovery.ts
|
|
2263
|
+
/**
|
|
2264
|
+
* Local Host discovery and official authentication.
|
|
2265
|
+
*
|
|
2266
|
+
* The registry is an unauthenticated hint: it selects a candidate origin and
|
|
2267
|
+
* PID, while the only readiness proof is the official `/connect` launch-token
|
|
2268
|
+
* exchange followed by the authenticated identity Fetch route. This module
|
|
2269
|
+
* never creates a Host Context, a Session, an Agent or a second transport
|
|
2270
|
+
* authority, and it never removes another process's files.
|
|
2271
|
+
*
|
|
2272
|
+
* @module app/remote-process/local-discovery
|
|
2273
|
+
*/
|
|
2274
|
+
/** Registry file name inside the private scope directory. */
|
|
2275
|
+
const REGISTRY_FILE = "instance.json";
|
|
2276
|
+
/** Launch-material file name inside the private scope directory. */
|
|
2277
|
+
const LAUNCH_FILE = "launch.json";
|
|
2278
|
+
/** Hard read limit for the registry record. */
|
|
2279
|
+
const MAX_REGISTRY_BYTES = 8192;
|
|
2280
|
+
/** Hard read limit for the launch material. */
|
|
2281
|
+
const MAX_LAUNCH_BYTES = 4096;
|
|
2282
|
+
/** Bounded registry wait used by ensureLocalHost. */
|
|
2283
|
+
const REGISTRY_WAIT_TIMEOUT_MS = 6e4;
|
|
2284
|
+
/** Bounded registry re-read interval. */
|
|
2285
|
+
const REGISTRY_POLL_INTERVAL_MS = 250;
|
|
2286
|
+
/** Per-request bound for the official HTTP handshake. */
|
|
2287
|
+
const AUTH_REQUEST_TIMEOUT_MS = 1e4;
|
|
2288
|
+
/** Exact Linux registry keys; unknown fields are rejected, not ignored. */
|
|
2289
|
+
const RECORD_KEYS = [
|
|
2290
|
+
"schema",
|
|
2291
|
+
"scopeId",
|
|
2292
|
+
"profileRealpath",
|
|
2293
|
+
"instanceId",
|
|
2294
|
+
"hostPid",
|
|
2295
|
+
"hostStarttime",
|
|
2296
|
+
"origin",
|
|
2297
|
+
"protocol",
|
|
2298
|
+
"bundleVersion",
|
|
2299
|
+
"dshVersion",
|
|
2300
|
+
"buildId"
|
|
2301
|
+
];
|
|
2302
|
+
/** Exact Darwin registry keys; `hostKernelIdentity` replaces `hostStarttime`. */
|
|
2303
|
+
const DARWIN_RECORD_KEYS = [
|
|
2304
|
+
"schema",
|
|
2305
|
+
"scopeId",
|
|
2306
|
+
"profileRealpath",
|
|
2307
|
+
"instanceId",
|
|
2308
|
+
"hostPid",
|
|
2309
|
+
"hostKernelIdentity",
|
|
2310
|
+
"origin",
|
|
2311
|
+
"protocol",
|
|
2312
|
+
"bundleVersion",
|
|
2313
|
+
"dshVersion",
|
|
2314
|
+
"buildId"
|
|
2315
|
+
];
|
|
2316
|
+
/** Exact Darwin kernel-identity keys (the complete PR-1 identity ABI). */
|
|
2317
|
+
const DARWIN_IDENTITY_KEYS = [
|
|
2318
|
+
"platform",
|
|
2319
|
+
"pid",
|
|
2320
|
+
"bootUUID",
|
|
2321
|
+
"uniqueId",
|
|
2322
|
+
"parentUniqueId",
|
|
2323
|
+
"processUUID",
|
|
2324
|
+
"startSec",
|
|
2325
|
+
"startUsec",
|
|
2326
|
+
"ppid",
|
|
2327
|
+
"pgid",
|
|
2328
|
+
"sid",
|
|
2329
|
+
"uid",
|
|
2330
|
+
"state"
|
|
2331
|
+
];
|
|
2332
|
+
/** Exact launch-material keys. */
|
|
2333
|
+
const LAUNCH_KEYS = [
|
|
2334
|
+
"schema",
|
|
2335
|
+
"instanceId",
|
|
2336
|
+
"connectUrl"
|
|
2337
|
+
];
|
|
2338
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
|
|
2339
|
+
const HEX_64 = /^[0-9a-f]{64}$/u;
|
|
2340
|
+
const HEX_32 = /^[0-9a-f]{32}$/u;
|
|
2341
|
+
const DECIMAL = /^\d+$/u;
|
|
2342
|
+
const COOKIE_PAIR = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+=[^;\s]*$/u;
|
|
2343
|
+
/** A strict object with exactly the expected own keys. */
|
|
2344
|
+
function assertExactObject(value, keys, label) {
|
|
2345
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} must be a JSON object`);
|
|
2346
|
+
const record = value;
|
|
2347
|
+
const actual = Object.keys(record).sort();
|
|
2348
|
+
const expected = [...keys].sort();
|
|
2349
|
+
if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} has unexpected fields`);
|
|
2350
|
+
return record;
|
|
2351
|
+
}
|
|
2352
|
+
function requireString(record, key, label) {
|
|
2353
|
+
const value = record[key];
|
|
2354
|
+
if (typeof value !== "string" || value === "") throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label}.${key} must be a non-empty string`);
|
|
2355
|
+
return value;
|
|
2356
|
+
}
|
|
2357
|
+
/** Validate the loopback-only origin shape B1 accepts. */
|
|
2358
|
+
function assertLoopbackOrigin(origin) {
|
|
2359
|
+
let url;
|
|
2360
|
+
try {
|
|
2361
|
+
url = new URL(origin);
|
|
2362
|
+
} catch (error) {
|
|
2363
|
+
throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: origin is not a URL", error);
|
|
2364
|
+
}
|
|
2365
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.username !== "" || url.password !== "" || url.pathname !== "/" || url.search !== "" || url.hash !== "" || url.port === "" || Number(url.port) < 1 || Number(url.port) > 65535 || url.origin !== origin) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: origin must be one canonical http://127.0.0.1:<port>`);
|
|
2366
|
+
}
|
|
2367
|
+
/**
|
|
2368
|
+
* Build one Host publication record in the canonical serialization order. The
|
|
2369
|
+
* authenticated identity echo and `writeLocalRecord` must share this ONE
|
|
2370
|
+
* insertion order: Linux schema 1 is a frozen bytes contract, so
|
|
2371
|
+
* `hostStarttime` stays between `hostPid` and `origin`.
|
|
2372
|
+
*/
|
|
2373
|
+
function buildHostInstanceRecord(shared, hostIdentity) {
|
|
2374
|
+
if (hostIdentity.schema === 1) return {
|
|
2375
|
+
schema: 1,
|
|
2376
|
+
scopeId: shared.scopeId,
|
|
2377
|
+
profileRealpath: shared.profileRealpath,
|
|
2378
|
+
instanceId: shared.instanceId,
|
|
2379
|
+
hostPid: shared.hostPid,
|
|
2380
|
+
hostStarttime: hostIdentity.hostStarttime,
|
|
2381
|
+
origin: shared.origin,
|
|
2382
|
+
protocol: shared.protocol,
|
|
2383
|
+
bundleVersion: shared.bundleVersion,
|
|
2384
|
+
dshVersion: shared.dshVersion,
|
|
2385
|
+
buildId: shared.buildId
|
|
2386
|
+
};
|
|
2387
|
+
return {
|
|
2388
|
+
schema: 2,
|
|
2389
|
+
scopeId: shared.scopeId,
|
|
2390
|
+
profileRealpath: shared.profileRealpath,
|
|
2391
|
+
instanceId: shared.instanceId,
|
|
2392
|
+
hostPid: shared.hostPid,
|
|
2393
|
+
hostKernelIdentity: hostIdentity.hostKernelIdentity,
|
|
2394
|
+
origin: shared.origin,
|
|
2395
|
+
protocol: shared.protocol,
|
|
2396
|
+
bundleVersion: shared.bundleVersion,
|
|
2397
|
+
dshVersion: shared.dshVersion,
|
|
2398
|
+
buildId: shared.buildId
|
|
2399
|
+
};
|
|
2400
|
+
}
|
|
2401
|
+
function requirePositiveInteger(record, key, label) {
|
|
2402
|
+
const value = record[key];
|
|
2403
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label}.${key} must be a positive integer`);
|
|
2404
|
+
return value;
|
|
2405
|
+
}
|
|
2406
|
+
function requireDecimal(record, key, label) {
|
|
2407
|
+
const value = requireString(record, key, label);
|
|
2408
|
+
if (!DECIMAL.test(value)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label}.${key} must be an exact decimal string`);
|
|
2409
|
+
return value;
|
|
2410
|
+
}
|
|
2411
|
+
/** Parse the complete Darwin kernel identity. Every field is required, typed
|
|
2412
|
+
* and exact: a malformed/truncated identity can never stand in for a live
|
|
2413
|
+
* process. `pid` must be the same numeric Host pid the record names. */
|
|
2414
|
+
function parseDarwinKernelIdentity(value, hostPid) {
|
|
2415
|
+
const identity = assertExactObject(value, DARWIN_IDENTITY_KEYS, "registry.hostKernelIdentity");
|
|
2416
|
+
if (identity.platform !== "darwin") throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.platform must be darwin");
|
|
2417
|
+
const pid = requirePositiveInteger(identity, "pid", "registry.hostKernelIdentity");
|
|
2418
|
+
if (pid !== hostPid) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.pid must equal registry.hostPid");
|
|
2419
|
+
const bootUUID = requireString(identity, "bootUUID", "registry.hostKernelIdentity");
|
|
2420
|
+
if (!UUID_PATTERN.test(bootUUID)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.bootUUID must be a UUID");
|
|
2421
|
+
const processUUID = requireString(identity, "processUUID", "registry.hostKernelIdentity");
|
|
2422
|
+
if (!HEX_32.test(processUUID)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostKernelIdentity.processUUID must be 32 lowercase hex characters");
|
|
2423
|
+
return {
|
|
2424
|
+
platform: "darwin",
|
|
2425
|
+
pid,
|
|
2426
|
+
bootUUID,
|
|
2427
|
+
uniqueId: requireDecimal(identity, "uniqueId", "registry.hostKernelIdentity"),
|
|
2428
|
+
parentUniqueId: requireDecimal(identity, "parentUniqueId", "registry.hostKernelIdentity"),
|
|
2429
|
+
processUUID,
|
|
2430
|
+
startSec: requireDecimal(identity, "startSec", "registry.hostKernelIdentity"),
|
|
2431
|
+
startUsec: requireDecimal(identity, "startUsec", "registry.hostKernelIdentity"),
|
|
2432
|
+
ppid: requirePositiveInteger(identity, "ppid", "registry.hostKernelIdentity"),
|
|
2433
|
+
pgid: requirePositiveInteger(identity, "pgid", "registry.hostKernelIdentity"),
|
|
2434
|
+
sid: requirePositiveInteger(identity, "sid", "registry.hostKernelIdentity"),
|
|
2435
|
+
uid: requireDecimalInteger(identity, "uid", "registry.hostKernelIdentity"),
|
|
2436
|
+
state: requireDecimalInteger(identity, "state", "registry.hostKernelIdentity")
|
|
2437
|
+
};
|
|
2438
|
+
}
|
|
2439
|
+
function requireDecimalInteger(record, key, label) {
|
|
2440
|
+
const value = record[key];
|
|
2441
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label}.${key} must be a non-negative integer`);
|
|
2442
|
+
return value;
|
|
2443
|
+
}
|
|
2444
|
+
/** The shared fields both schemas serialize, in their exact key order. */
|
|
2445
|
+
function parseSharedRecord(record, scope) {
|
|
2446
|
+
const scopeId = requireString(record, "scopeId", "registry");
|
|
2447
|
+
const profileRealpath = requireString(record, "profileRealpath", "registry");
|
|
2448
|
+
const instanceId = requireString(record, "instanceId", "registry");
|
|
2449
|
+
const origin = requireString(record, "origin", "registry");
|
|
2450
|
+
const protocol = requireString(record, "protocol", "registry");
|
|
2451
|
+
const bundleVersion = requireString(record, "bundleVersion", "registry");
|
|
2452
|
+
const dshVersion = requireString(record, "dshVersion", "registry");
|
|
2453
|
+
const buildId = requireString(record, "buildId", "registry");
|
|
2454
|
+
const hostPid = requirePositiveInteger(record, "hostPid", "registry");
|
|
2455
|
+
if (!UUID_PATTERN.test(instanceId)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.instanceId must be a UUID");
|
|
2456
|
+
if (!HEX_64.test(buildId)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.buildId must be 64 hex characters");
|
|
2457
|
+
assertLoopbackOrigin(origin);
|
|
2458
|
+
if (scopeId !== scope.scopeId || profileRealpath !== scope.profileRealpath) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: registry names another profile scope");
|
|
2459
|
+
return {
|
|
2460
|
+
scopeId,
|
|
2461
|
+
profileRealpath,
|
|
2462
|
+
instanceId,
|
|
2463
|
+
hostPid,
|
|
2464
|
+
origin,
|
|
2465
|
+
protocol,
|
|
2466
|
+
bundleVersion,
|
|
2467
|
+
dshVersion,
|
|
2468
|
+
buildId
|
|
2469
|
+
};
|
|
2470
|
+
}
|
|
2471
|
+
/** Parse the strict registry schema without judging build compatibility. */
|
|
2472
|
+
function parseRecord(value, scope) {
|
|
2473
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry must be a JSON object");
|
|
2474
|
+
const schema = value.schema;
|
|
2475
|
+
if (schema === 1) {
|
|
2476
|
+
const record = assertExactObject(value, RECORD_KEYS, "registry");
|
|
2477
|
+
const shared = parseSharedRecord(record, scope);
|
|
2478
|
+
const hostStarttime = requireString(record, "hostStarttime", "registry");
|
|
2479
|
+
if (!DECIMAL.test(hostStarttime)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostStarttime must be numeric");
|
|
2480
|
+
return {
|
|
2481
|
+
schema: 1,
|
|
2482
|
+
scopeId: shared.scopeId,
|
|
2483
|
+
profileRealpath: shared.profileRealpath,
|
|
2484
|
+
instanceId: shared.instanceId,
|
|
2485
|
+
hostPid: shared.hostPid,
|
|
2486
|
+
hostStarttime,
|
|
2487
|
+
origin: shared.origin,
|
|
2488
|
+
protocol: shared.protocol,
|
|
2489
|
+
bundleVersion: shared.bundleVersion,
|
|
2490
|
+
dshVersion: shared.dshVersion,
|
|
2491
|
+
buildId: shared.buildId
|
|
2492
|
+
};
|
|
2493
|
+
}
|
|
2494
|
+
if (schema === 2) {
|
|
2495
|
+
const record = assertExactObject(value, DARWIN_RECORD_KEYS, "registry");
|
|
2496
|
+
const shared = parseSharedRecord(record, scope);
|
|
2497
|
+
return {
|
|
2498
|
+
schema: 2,
|
|
2499
|
+
scopeId: shared.scopeId,
|
|
2500
|
+
profileRealpath: shared.profileRealpath,
|
|
2501
|
+
instanceId: shared.instanceId,
|
|
2502
|
+
hostPid: shared.hostPid,
|
|
2503
|
+
hostKernelIdentity: parseDarwinKernelIdentity(record.hostKernelIdentity, shared.hostPid),
|
|
2504
|
+
origin: shared.origin,
|
|
2505
|
+
protocol: shared.protocol,
|
|
2506
|
+
bundleVersion: shared.bundleVersion,
|
|
2507
|
+
dshVersion: shared.dshVersion,
|
|
2508
|
+
buildId: shared.buildId
|
|
2509
|
+
};
|
|
2510
|
+
}
|
|
2511
|
+
throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.schema must be 1 or 2");
|
|
2512
|
+
}
|
|
2513
|
+
/** Reject a schema that cannot belong to the running local platform. A Linux
|
|
2514
|
+
* schema1 record on macOS (or the reverse) is not a candidate this process may
|
|
2515
|
+
* authenticate, spawn around or treat as a readiness proof. */
|
|
2516
|
+
function assertRecordSchemaPlatform(record) {
|
|
2517
|
+
if (record.schema === 1 && process.platform !== "linux") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 1 is a Linux Host publication");
|
|
2518
|
+
if (record.schema === 2 && process.platform !== "darwin") throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: schema 2 is a macOS Host publication");
|
|
2519
|
+
}
|
|
2520
|
+
/** The ONE record equality used by authentication and transport currentness:
|
|
2521
|
+
* the shared fields plus the schema-specific kernel identity. */
|
|
2522
|
+
function sameLocalInstanceRecord(left, right) {
|
|
2523
|
+
if (left.schema !== right.schema || left.scopeId !== right.scopeId || left.profileRealpath !== right.profileRealpath || left.instanceId !== right.instanceId || left.hostPid !== right.hostPid || left.origin !== right.origin || left.protocol !== right.protocol || left.bundleVersion !== right.bundleVersion || left.dshVersion !== right.dshVersion || left.buildId !== right.buildId) return false;
|
|
2524
|
+
if (left.schema === 1 && right.schema === 1) return left.hostStarttime === right.hostStarttime;
|
|
2525
|
+
if (left.schema === 2 && right.schema === 2) {
|
|
2526
|
+
const a = left.hostKernelIdentity;
|
|
2527
|
+
const b = right.hostKernelIdentity;
|
|
2528
|
+
return a.platform === b.platform && a.pid === b.pid && a.bootUUID === b.bootUUID && a.uniqueId === b.uniqueId && a.parentUniqueId === b.parentUniqueId && a.processUUID === b.processUUID && a.startSec === b.startSec && a.startUsec === b.startUsec && a.ppid === b.ppid && a.pgid === b.pgid && a.sid === b.sid && a.uid === b.uid && a.state === b.state;
|
|
2529
|
+
}
|
|
2530
|
+
return false;
|
|
2531
|
+
}
|
|
2532
|
+
/** Can this Client speak the live Host's required local wire contract? */
|
|
2533
|
+
function assertClientHostCompatible(record, scope) {
|
|
2534
|
+
if (record.protocol !== "dsh-pi-tui/local/2" || record.dshVersion !== scope.dshVersion) throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: the live Host uses a different local protocol or DSH runtime");
|
|
2535
|
+
}
|
|
2536
|
+
/** Does this Host publish the exact installed identity of its OWN build? */
|
|
2537
|
+
function assertHostPublicationIdentity(record, scope) {
|
|
2538
|
+
assertRecordSchemaPlatform(record);
|
|
2539
|
+
if (record.protocol !== "dsh-pi-tui/local/2" || record.bundleVersion !== scope.bundleVersion || record.dshVersion !== scope.dshVersion || record.buildId !== scope.buildId) throw new LocalScopeError("HOST_BUILD_INCOMPATIBLE", "local discovery: the Host cannot publish identity for a different local protocol or installed build");
|
|
2540
|
+
}
|
|
2541
|
+
/**
|
|
2542
|
+
* Read one managed scope file with `O_NOFOLLOW`, a regular-file/type check and a
|
|
2543
|
+
* hard byte cap. The user's existing owner/mode is NOT a read policy; the
|
|
2544
|
+
* content still must pass the strict JSON/schema/instance checks. Returns
|
|
2545
|
+
* `undefined` for a missing file; every unreadable or malformed file is a hard
|
|
2546
|
+
* failure.
|
|
2547
|
+
*/
|
|
2548
|
+
function readPrivateJsonFile(path, maxBytes, label) {
|
|
2549
|
+
let fd;
|
|
2550
|
+
try {
|
|
2551
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
2552
|
+
} catch (error) {
|
|
2553
|
+
if (error.code === "ENOENT") return void 0;
|
|
2554
|
+
throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} is not readable without following a link`, error);
|
|
2555
|
+
}
|
|
2556
|
+
try {
|
|
2557
|
+
const info = fstatSync(fd);
|
|
2558
|
+
if (!info.isFile()) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} must be a regular file`);
|
|
2559
|
+
if (info.size > maxBytes) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} exceeds ${String(maxBytes)} bytes`);
|
|
2560
|
+
const text = readFileSync(fd, "utf8");
|
|
2561
|
+
try {
|
|
2562
|
+
return JSON.parse(text);
|
|
2563
|
+
} catch (error) {
|
|
2564
|
+
throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} is not valid JSON`, error);
|
|
2565
|
+
}
|
|
2566
|
+
} finally {
|
|
2567
|
+
closeSync(fd);
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
/**
|
|
2571
|
+
* Strictly read `<scope>/instance.json`. The record is an unauthenticated
|
|
2572
|
+
* candidate only; this function performs no liveness or build decision.
|
|
2573
|
+
*/
|
|
2574
|
+
function readLocalRecord(scope) {
|
|
2575
|
+
const value = readPrivateJsonFile(join(scope.dir, REGISTRY_FILE), MAX_REGISTRY_BYTES, "instance.json");
|
|
2576
|
+
if (value === void 0) return void 0;
|
|
2577
|
+
return parseRecord(value, scope);
|
|
2578
|
+
}
|
|
2579
|
+
/** Strictly read `<scope>/launch.json` after its registry candidate matched. */
|
|
2580
|
+
function readLaunchMaterial(scope, record) {
|
|
2581
|
+
const value = readPrivateJsonFile(join(scope.dir, LAUNCH_FILE), MAX_LAUNCH_BYTES, "launch.json");
|
|
2582
|
+
if (value === void 0) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: instance.json has no matching launch.json");
|
|
2583
|
+
const launch = assertExactObject(value, LAUNCH_KEYS, "launch.json");
|
|
2584
|
+
if (launch.schema !== 1) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: launch.json.schema must be 1");
|
|
2585
|
+
const instanceId = requireString(launch, "instanceId", "launch.json");
|
|
2586
|
+
const connectUrl = requireString(launch, "connectUrl", "launch.json");
|
|
2587
|
+
if (instanceId !== record.instanceId) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: launch.json names a different Host instance");
|
|
2588
|
+
assertConnectUrl(connectUrl, record);
|
|
2589
|
+
return {
|
|
2590
|
+
schema: 1,
|
|
2591
|
+
instanceId,
|
|
2592
|
+
connectUrl
|
|
2593
|
+
};
|
|
2594
|
+
}
|
|
2595
|
+
/** Validate the exact `/connect` URL shape without exposing its token. */
|
|
2596
|
+
function assertConnectUrl(connectUrl, record) {
|
|
2597
|
+
let url;
|
|
2598
|
+
try {
|
|
2599
|
+
url = new URL(connectUrl);
|
|
2600
|
+
} catch (error) {
|
|
2601
|
+
throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: launch.json.connectUrl is not a URL", error);
|
|
2602
|
+
}
|
|
2603
|
+
const tokens = url.searchParams.getAll("token");
|
|
2604
|
+
const keys = [...url.searchParams.keys()];
|
|
2605
|
+
if (url.origin !== record.origin || url.pathname !== "/connect" || url.username !== "" || url.password !== "" || url.hash !== "" || tokens.length !== 1 || tokens[0] === "" || keys.length !== 1) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: launch.json.connectUrl is not the Host-owned /connect token URL");
|
|
2606
|
+
}
|
|
2607
|
+
/**
|
|
2608
|
+
* Liveness is a negative selection fact, never readiness. A missing
|
|
2609
|
+
* `/proc/<pid>/stat` (ENOENT) is a definite dead PID; an unreadable or
|
|
2610
|
+
* malformed file is UNKNOWN and is a hard failure, never permission to spawn.
|
|
2611
|
+
* `procRoot` exists only so the fail-closed classification is testable.
|
|
2612
|
+
*/
|
|
2613
|
+
function inspectHostProcess(record, procRoot = "/proc", readKernel = readKernelProcess) {
|
|
2614
|
+
assertRecordSchemaPlatform(record);
|
|
2615
|
+
if (record.schema === 2) {
|
|
2616
|
+
const observed = readKernel(record.hostPid);
|
|
2617
|
+
if (observed.kind === "unknown") throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", `local discovery: the kernel identity of Host pid ${String(record.hostPid)} is unavailable`);
|
|
2618
|
+
return sameKernelProcess(record.hostKernelIdentity, observed) === "same" ? "alive" : "dead";
|
|
2619
|
+
}
|
|
2620
|
+
let stat;
|
|
2621
|
+
try {
|
|
2622
|
+
stat = readFileSync(join(procRoot, String(record.hostPid), "stat"), "utf8");
|
|
2623
|
+
} catch (error) {
|
|
2624
|
+
if (error.code === "ENOENT") return "dead";
|
|
2625
|
+
throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", `local discovery: /proc/${String(record.hostPid)}/stat is not readable`, error);
|
|
2626
|
+
}
|
|
2627
|
+
const parsed = parseProcessStat(stat);
|
|
2628
|
+
if (parsed === void 0) throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", `local discovery: /proc/${String(record.hostPid)}/stat has no usable state/starttime`);
|
|
2629
|
+
if (parsed.starttime !== record.hostStarttime) return "dead";
|
|
2630
|
+
if (parsed.state === "Z" || parsed.state === "X" || parsed.state === "x") return "dead";
|
|
2631
|
+
return "alive";
|
|
2632
|
+
}
|
|
2633
|
+
/** Read a bounded UTF-8 body; an over-limit identity response is a mismatch. */
|
|
2634
|
+
async function readBoundedText(response, maxBytes, label) {
|
|
2635
|
+
if (response.body === null) return "";
|
|
2636
|
+
const reader = response.body.getReader();
|
|
2637
|
+
const chunks = [];
|
|
2638
|
+
let total = 0;
|
|
2639
|
+
try {
|
|
2640
|
+
for (;;) {
|
|
2641
|
+
const { done, value } = await reader.read();
|
|
2642
|
+
if (done) break;
|
|
2643
|
+
total += value.byteLength;
|
|
2644
|
+
if (total > maxBytes) {
|
|
2645
|
+
await reader.cancel();
|
|
2646
|
+
throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local discovery: ${label} exceeds ${String(maxBytes)} bytes`);
|
|
2647
|
+
}
|
|
2648
|
+
chunks.push(value);
|
|
2649
|
+
}
|
|
2650
|
+
} finally {
|
|
2651
|
+
reader.releaseLock();
|
|
2652
|
+
}
|
|
2653
|
+
return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
|
|
2654
|
+
}
|
|
2655
|
+
/** Discard a response body without leaking it to logs. */
|
|
2656
|
+
async function discard(response) {
|
|
2657
|
+
try {
|
|
2658
|
+
await response.body?.cancel();
|
|
2659
|
+
} catch {}
|
|
2660
|
+
}
|
|
2661
|
+
/** Fetch with the bounded auth timeout; network failure is HOST_UNRESPONSIVE. */
|
|
2662
|
+
async function authFetch(url, init, signal) {
|
|
2663
|
+
const timeout = AbortSignal.timeout(AUTH_REQUEST_TIMEOUT_MS);
|
|
2664
|
+
const request = {
|
|
2665
|
+
...init,
|
|
2666
|
+
signal: signal === void 0 ? timeout : AbortSignal.any([signal, timeout])
|
|
2667
|
+
};
|
|
2668
|
+
try {
|
|
2669
|
+
return await fetch(url, request);
|
|
2670
|
+
} catch (error) {
|
|
2671
|
+
throw new LocalScopeError("HOST_UNRESPONSIVE", "local discovery: the Host did not answer the official HTTP handshake", error);
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
/** Exchange the launch token for this Client process's own signed cookie. */
|
|
2675
|
+
async function connectForCookie(record, launch, signal) {
|
|
2676
|
+
const url = new URL(launch.connectUrl);
|
|
2677
|
+
url.searchParams.set("interactions", "answer");
|
|
2678
|
+
const response = await authFetch(url, {
|
|
2679
|
+
method: "GET",
|
|
2680
|
+
redirect: "manual",
|
|
2681
|
+
cache: "no-store"
|
|
2682
|
+
}, signal);
|
|
2683
|
+
if (response.status !== 302) {
|
|
2684
|
+
await discard(response);
|
|
2685
|
+
throw new LocalScopeError("HOST_AUTH_FAILED", `local discovery: /connect rejected this Client with HTTP ${String(response.status)}`);
|
|
2686
|
+
}
|
|
2687
|
+
const cacheControl = response.headers.get("cache-control") ?? "";
|
|
2688
|
+
if (!/\bno-store\b/iu.test(cacheControl)) {
|
|
2689
|
+
await discard(response);
|
|
2690
|
+
throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect response was not marked no-store");
|
|
2691
|
+
}
|
|
2692
|
+
const location = response.headers.get("location");
|
|
2693
|
+
await discard(response);
|
|
2694
|
+
if (location === null) throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect returned no mux redirect");
|
|
2695
|
+
let redirect;
|
|
2696
|
+
try {
|
|
2697
|
+
redirect = new URL(location, url);
|
|
2698
|
+
} catch (error) {
|
|
2699
|
+
throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect returned an unparsable redirect", error);
|
|
2700
|
+
}
|
|
2701
|
+
if (redirect.origin !== record.origin || redirect.pathname !== "/api/remote.mux") throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect redirected outside the authenticated local mux");
|
|
2702
|
+
const raw = response.headers.getSetCookie?.() ?? (response.headers.get("set-cookie") === null ? [] : [response.headers.get("set-cookie")]);
|
|
2703
|
+
if (raw.length === 0) throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect returned no signed cookie");
|
|
2704
|
+
const pair = raw[0].split(";", 1)[0].trim();
|
|
2705
|
+
if (!COOKIE_PAIR.test(pair)) throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect returned an invalid cookie pair");
|
|
2706
|
+
return pair;
|
|
2707
|
+
}
|
|
2708
|
+
/** Read and compare the authenticated identity echo with the registry. */
|
|
2709
|
+
async function readAuthenticatedIdentity(record, cookie, signal) {
|
|
2710
|
+
const response = await authFetch(`${record.origin}/api/pi-tui.local-host`, {
|
|
2711
|
+
method: "GET",
|
|
2712
|
+
headers: { cookie },
|
|
2713
|
+
redirect: "manual",
|
|
2714
|
+
cache: "no-store"
|
|
2715
|
+
}, signal);
|
|
2716
|
+
if (response.status === 401 || response.status === 403) {
|
|
2717
|
+
await discard(response);
|
|
2718
|
+
throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: the identity route rejected the signed cookie");
|
|
2719
|
+
}
|
|
2720
|
+
if (response.status !== 200) {
|
|
2721
|
+
await discard(response);
|
|
2722
|
+
throw new LocalScopeError("HOST_UNRESPONSIVE", `local discovery: identity route answered HTTP ${String(response.status)}`);
|
|
2723
|
+
}
|
|
2724
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
2725
|
+
const cacheControl = response.headers.get("cache-control") ?? "";
|
|
2726
|
+
if (!/^application\/json\b/iu.test(contentType) || !/\bno-store\b/iu.test(cacheControl)) {
|
|
2727
|
+
await discard(response);
|
|
2728
|
+
throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: identity route response has the wrong shape");
|
|
2729
|
+
}
|
|
2730
|
+
const text = await readBoundedText(response, MAX_REGISTRY_BYTES, "identity route response");
|
|
2731
|
+
let value;
|
|
2732
|
+
try {
|
|
2733
|
+
value = JSON.parse(text);
|
|
2734
|
+
} catch (error) {
|
|
2735
|
+
throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: identity route response is not JSON", error);
|
|
2736
|
+
}
|
|
2737
|
+
const identity = parseRecord(value, record);
|
|
2738
|
+
if (!sameLocalInstanceRecord(identity, record)) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: authenticated identity differs from the registry");
|
|
2739
|
+
return identity;
|
|
2740
|
+
}
|
|
2741
|
+
/**
|
|
2742
|
+
* Re-read the live kernel identity of the recorded Host and require it to be
|
|
2743
|
+
* the SAME process. Linux uses the frozen `/proc` starttime; Darwin uses the
|
|
2744
|
+
* complete PR-1 identity. `unknown` is always `PROCESS_STARTTIME_UNAVAILABLE`;
|
|
2745
|
+
* a different/absent process is `HOST_IDENTITY_MISMATCH` (never a kill permit).
|
|
2746
|
+
*/
|
|
2747
|
+
function assertRecordedHostKernelIdentityCurrent(record, readKernel = readKernelProcess) {
|
|
2748
|
+
assertRecordSchemaPlatform(record);
|
|
2749
|
+
if (record.schema === 2) {
|
|
2750
|
+
const observed = readKernel(record.hostPid);
|
|
2751
|
+
if (observed.kind === "unknown") throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", "local discovery: the Host kernel identity is unavailable");
|
|
2752
|
+
if (sameKernelProcess(record.hostKernelIdentity, observed) !== "same") throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: the Host PID is no longer the recorded process");
|
|
2753
|
+
return;
|
|
2754
|
+
}
|
|
2755
|
+
const liveStarttime = readProcessStarttime(record.hostPid);
|
|
2756
|
+
if (liveStarttime === void 0) throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", "local discovery: the Host process starttime is unavailable");
|
|
2757
|
+
if (liveStarttime !== record.hostStarttime) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: the Host PID is no longer the registry process");
|
|
2758
|
+
}
|
|
2759
|
+
/**
|
|
2760
|
+
* Read the identity material THIS Host process publishes for its own
|
|
2761
|
+
* platform. The kernel fact is captured here and re-proved before Ready; it is
|
|
2762
|
+
* never inferred from a path, a registry file or a bare numeric pid.
|
|
2763
|
+
*/
|
|
2764
|
+
function readHostProcessIdentity(pid = process.pid) {
|
|
2765
|
+
if (process.platform === "linux") return {
|
|
2766
|
+
schema: 1,
|
|
2767
|
+
hostStarttime: readLinuxStarttime(pid)
|
|
2768
|
+
};
|
|
2769
|
+
if (process.platform === "darwin") {
|
|
2770
|
+
const observed = readKernelProcess(pid);
|
|
2771
|
+
if (observed.kind !== "alive" || observed.identity.platform !== "darwin") throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", "local discovery: the Host kernel identity is unavailable");
|
|
2772
|
+
return {
|
|
2773
|
+
schema: 2,
|
|
2774
|
+
hostKernelIdentity: observed.identity
|
|
2775
|
+
};
|
|
2776
|
+
}
|
|
2777
|
+
throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", `local discovery: no Host process identity is implemented for ${process.platform}`);
|
|
2778
|
+
}
|
|
2779
|
+
/**
|
|
2780
|
+
* Run the full authenticated handshake: launch material, official `/connect`
|
|
2781
|
+
* cookie, identity echo, then a fresh kernel identity check. The returned
|
|
2782
|
+
* cookie stays in this Client process only.
|
|
2783
|
+
*/
|
|
2784
|
+
async function authenticateLocalHost(record, scope, signal) {
|
|
2785
|
+
const cookie = await connectForCookie(record, readLaunchMaterial(scope, record), signal);
|
|
2786
|
+
const identity = await readAuthenticatedIdentity(record, cookie, signal);
|
|
2787
|
+
signal?.throwIfAborted();
|
|
2788
|
+
assertRecordedHostKernelIdentityCurrent(identity);
|
|
2789
|
+
return {
|
|
2790
|
+
record,
|
|
2791
|
+
cookie,
|
|
2792
|
+
identity
|
|
2793
|
+
};
|
|
2794
|
+
}
|
|
2795
|
+
/** Bound the registry wait without a fixed readiness sleep. */
|
|
2796
|
+
function delay(ms) {
|
|
2797
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2798
|
+
}
|
|
2799
|
+
/**
|
|
2800
|
+
* Ensure one authenticated Host for this scope. A live registry candidate is
|
|
2801
|
+
* never killed and never replaced; a dead one may be replaced by a new Host
|
|
2802
|
+
* whose kernel seat is the only winner. Authentication failure is terminal.
|
|
2803
|
+
*/
|
|
2804
|
+
async function ensureLocalHost(options) {
|
|
2805
|
+
const { scope } = options;
|
|
2806
|
+
if (options.expectedInstanceId !== void 0) {
|
|
2807
|
+
const record = readLocalRecord(scope);
|
|
2808
|
+
if (record === void 0 || inspectHostProcess(record) === "dead") throw new LocalScopeError("HOST_HANDOFF_UNAVAILABLE", "local discovery: the expected Host is no longer available for Client handoff");
|
|
2809
|
+
if (record.instanceId !== options.expectedInstanceId) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: the live Host is not the expected handoff instance");
|
|
2810
|
+
assertClientHostCompatible(record, scope);
|
|
2811
|
+
return await authenticateLocalHost(record, scope, options.signal);
|
|
2812
|
+
}
|
|
2813
|
+
const existing = readLocalRecord(scope);
|
|
2814
|
+
if (existing !== void 0 && inspectHostProcess(existing) === "alive") {
|
|
2815
|
+
assertClientHostCompatible(existing, scope);
|
|
2816
|
+
return await authenticateLocalHost(existing, scope, options.signal);
|
|
2817
|
+
}
|
|
2818
|
+
const spawnFailure = options.hostStartPolicy === "public" || options.hostStartPolicy === "public-managed" ? await startManagedHostCandidate(options) : spawnHostCandidate(options);
|
|
2819
|
+
const deadline = Date.now() + REGISTRY_WAIT_TIMEOUT_MS;
|
|
2820
|
+
while (Date.now() < deadline) {
|
|
2821
|
+
options.signal?.throwIfAborted();
|
|
2822
|
+
const failure = spawnFailure();
|
|
2823
|
+
if (failure !== void 0) throw new LocalScopeError("HOST_START_FAILED", "local discovery: the Host candidate failed to start", failure);
|
|
2824
|
+
const candidate = readLocalRecord(scope);
|
|
2825
|
+
if (candidate !== void 0 && inspectHostProcess(candidate) === "alive") {
|
|
2826
|
+
assertClientHostCompatible(candidate, scope);
|
|
2827
|
+
return await authenticateLocalHost(candidate, scope, options.signal);
|
|
2828
|
+
}
|
|
2829
|
+
await delay(REGISTRY_POLL_INTERVAL_MS);
|
|
2830
|
+
}
|
|
2831
|
+
throw new LocalScopeError("HOST_START_TIMEOUT", `local discovery: no ready Host registry appeared within ${String(REGISTRY_WAIT_TIMEOUT_MS / 1e3)}s`);
|
|
2832
|
+
}
|
|
2833
|
+
/** Write one 0600 file through an exclusively-created same-directory temp file. */
|
|
2834
|
+
function writePrivateJsonFile(path, value) {
|
|
2835
|
+
const text = `${JSON.stringify(value)}\n`;
|
|
2836
|
+
const temp = join(dirname(path), `.${basename(path)}.${String(process.pid)}.${randomUUID()}.tmp`);
|
|
2837
|
+
let fd;
|
|
2838
|
+
try {
|
|
2839
|
+
fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
|
|
2840
|
+
fchmodSync(fd, 384);
|
|
2841
|
+
writeFileSync(fd, text, "utf8");
|
|
2842
|
+
fsyncSync(fd);
|
|
2843
|
+
closeSync(fd);
|
|
2844
|
+
fd = void 0;
|
|
2845
|
+
renameSync(temp, path);
|
|
2846
|
+
} catch (error) {
|
|
2847
|
+
if (fd !== void 0) closeSync(fd);
|
|
2848
|
+
try {
|
|
2849
|
+
unlinkSync(temp);
|
|
2850
|
+
} catch {}
|
|
2851
|
+
if (error instanceof LocalScopeError) throw error;
|
|
2852
|
+
throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${basename(path)} could not be written atomically`, error);
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
/** Publish the one registry record; the Host calls this as its Ready commit. */
|
|
2856
|
+
function writeLocalRecord(scope, record) {
|
|
2857
|
+
const parsed = parseRecord(record, scope);
|
|
2858
|
+
assertHostPublicationIdentity(parsed, scope);
|
|
2859
|
+
writePrivateJsonFile(join(scope.dir, REGISTRY_FILE), parsed);
|
|
2860
|
+
}
|
|
2861
|
+
/** Publish the official launch material before the registry is visible. */
|
|
2862
|
+
function writeLaunchMaterial(scope, record, material) {
|
|
2863
|
+
const parsed = parseRecord(record, scope);
|
|
2864
|
+
assertHostPublicationIdentity(parsed, scope);
|
|
2865
|
+
if (material.schema !== 1 || material.instanceId !== parsed.instanceId) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: launch material does not name the published instance");
|
|
2866
|
+
assertConnectUrl(material.connectUrl, parsed);
|
|
2867
|
+
writePrivateJsonFile(join(scope.dir, LAUNCH_FILE), material);
|
|
2868
|
+
}
|
|
2869
|
+
/**
|
|
2870
|
+
* Remove only the files this exact instance published. Used after the official
|
|
2871
|
+
* shutdown owner has run and as a synchronous process-exit backstop; a new
|
|
2872
|
+
* Host instance's files are never touched.
|
|
2873
|
+
*/
|
|
2874
|
+
function cleanupOwnedFiles(scope, instanceId) {
|
|
2875
|
+
for (const file of [REGISTRY_FILE, LAUNCH_FILE]) {
|
|
2876
|
+
const path = join(scope.dir, file);
|
|
2877
|
+
try {
|
|
2878
|
+
if (JSON.parse(readFileSync(path, "utf8")).instanceId === instanceId) unlinkSync(path);
|
|
2879
|
+
} catch {}
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
//#endregion
|
|
2883
|
+
export { launchdLogPaths as A, runSystemctl as C, inspectLaunchdService as D, uninstallOwnedProfileUnit as E, prepareOwnedLaunchdForCurrentInstall as M, stopLaunchdService as N, inspectOwnedLaunchdUnit as O, uninstallLaunchdUnit as P, queryOwnedProfileUnit as S, stopOwnedProfileUnit as T, collectUnitFacts as _, buildHostInstanceRecord as a, prepareOwnedProfileUnitForCurrentInstall as b, ensureLocalHost as c, readHostProcessIdentity as d, readLaunchMaterial as f, writeLocalRecord as g, writeLaunchMaterial as h, authenticateLocalHost as i, launchdServiceMatches as j, installLaunchdUnit as k, inspectHostProcess as l, sameLocalInstanceRecord as m, assertHostPublicationIdentity as n, cleanupOwnedFiles as o, readLocalRecord as p, assertRecordedHostKernelIdentityCurrent as r, connectForCookie as s, assertClientHostCompatible as t, readAuthenticatedIdentity as u, inspectOwnedProfileUnit as v, selectRuntimeDir as w, profileIdentityDigest as x, installProfileHostUnit as y };
|