@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
|
@@ -1,759 +0,0 @@
|
|
|
1
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { basename, dirname, join, relative, sep } from "node:path";
|
|
4
|
-
import { fileURLToPath } from "node:url";
|
|
5
|
-
import { createServer } from "node:net";
|
|
6
|
-
import { Buffer as Buffer$1 } from "node:buffer";
|
|
7
|
-
import { spawn } from "node:child_process";
|
|
8
|
-
//#region src/app/remote-process/local-scope.ts
|
|
9
|
-
/**
|
|
10
|
-
* Local Host/Client scope, process seats and installed-build identity.
|
|
11
|
-
*
|
|
12
|
-
* The ordinary DSH profile is the scope authority: this module derives a
|
|
13
|
-
* stable id from the canonical profile directory and the current UID, then
|
|
14
|
-
* owns the private run directory, the Host Singleton seat and the
|
|
15
|
-
* qualification-only Client seat. The installed-build fingerprint remains the
|
|
16
|
-
* Host's own publication/identity material; `LOCAL_PROTOCOL` below is the
|
|
17
|
-
* Host/Client compatibility contract and is independent of package builds.
|
|
18
|
-
*
|
|
19
|
-
* The abstract sockets are admission primitives only. No business traffic
|
|
20
|
-
* travels over them, and no PID file, registry record or `O_EXCL` marker can
|
|
21
|
-
* substitute for the kernel's exclusive bind.
|
|
22
|
-
*
|
|
23
|
-
* @module app/remote-process/local-scope
|
|
24
|
-
*/
|
|
25
|
-
/**
|
|
26
|
-
* The required local Host/Client wire contract, independent of package builds.
|
|
27
|
-
* Both sides must name exactly this value and the same DSH runtime version.
|
|
28
|
-
*/
|
|
29
|
-
const LOCAL_PROTOCOL = "dsh-pi-tui/local/1";
|
|
30
|
-
/** Private scope directory below the official DSH home. */
|
|
31
|
-
const RUN_ROOT_NAME = "run";
|
|
32
|
-
const SCOPE_ROOT_NAME = "dsh-pi-tui";
|
|
33
|
-
/** Linux abstract-socket prefixes; both names stay well below `sun_path`. The
|
|
34
|
-
* Host prefix is the singleton admission seat; the Client prefix is held by
|
|
35
|
-
* the frozen `qualification` mode only. */
|
|
36
|
-
const HOST_SEAT_PREFIX = "\0dsh-pi-tui-h-";
|
|
37
|
-
const CLIENT_SEAT_PREFIX = "\0dsh-pi-tui-c-";
|
|
38
|
-
/** A failure that carries one stable B1 classification code. */
|
|
39
|
-
var LocalScopeError = class extends Error {
|
|
40
|
-
/** Stable classification asserted by callers and the qualification lane. */
|
|
41
|
-
code;
|
|
42
|
-
constructor(code, message, cause) {
|
|
43
|
-
super(message, cause === void 0 ? void 0 : { cause });
|
|
44
|
-
this.name = "LocalScopeError";
|
|
45
|
-
this.code = code;
|
|
46
|
-
}
|
|
47
|
-
};
|
|
48
|
-
/** Fail before any runtime file is written on a platform B1 does not implement. */
|
|
49
|
-
function assertLinux() {
|
|
50
|
-
if (process.platform !== "linux" || typeof process.getuid !== "function") throw new LocalScopeError("B1_PLATFORM_UNSUPPORTED", "local B1 split process requires Linux abstract AF_UNIX sockets");
|
|
51
|
-
return process.getuid();
|
|
52
|
-
}
|
|
53
|
-
/** Read a real directory and reject a non-directory or a different owner. */
|
|
54
|
-
function canonicalOwnedDirectory(path, uid, label) {
|
|
55
|
-
let real;
|
|
56
|
-
try {
|
|
57
|
-
real = realpathSync(path);
|
|
58
|
-
} catch (error) {
|
|
59
|
-
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} is not a readable directory`, error);
|
|
60
|
-
}
|
|
61
|
-
const info = lstatSync(real);
|
|
62
|
-
if (!info.isDirectory() || info.uid !== uid) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${label} must be a real directory owned by uid ${String(uid)}`);
|
|
63
|
-
return real;
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Create and prove the private run chain WITHOUT following a pre-existing
|
|
67
|
-
* symlink. Each component is lstat-checked before its child is created; the
|
|
68
|
-
* final run/scope/instance directories must be real directories owned by the
|
|
69
|
-
* current UID with no group/other access.
|
|
70
|
-
*/
|
|
71
|
-
function ensureScopeDirectory(dshHome, scopeId, uid) {
|
|
72
|
-
const runRoot = join(dshHome, RUN_ROOT_NAME);
|
|
73
|
-
const scopeRoot = join(runRoot, SCOPE_ROOT_NAME);
|
|
74
|
-
const dir = join(scopeRoot, scopeId);
|
|
75
|
-
for (const path of [
|
|
76
|
-
runRoot,
|
|
77
|
-
scopeRoot,
|
|
78
|
-
dir
|
|
79
|
-
]) {
|
|
80
|
-
let info;
|
|
81
|
-
try {
|
|
82
|
-
info = lstatSync(path);
|
|
83
|
-
} catch (error) {
|
|
84
|
-
if (error.code !== "ENOENT") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not accessible`, error);
|
|
85
|
-
try {
|
|
86
|
-
mkdirSync(path, { mode: 448 });
|
|
87
|
-
} catch (mkdirError) {
|
|
88
|
-
if (mkdirError.code !== "EEXIST") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} could not be created safely`, mkdirError);
|
|
89
|
-
}
|
|
90
|
-
try {
|
|
91
|
-
info = lstatSync(path);
|
|
92
|
-
} catch (lstatError) {
|
|
93
|
-
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} is not accessible after creation`, lstatError);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
if (info.isSymbolicLink() || !info.isDirectory() || info.uid !== uid) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} must be a real directory owned by uid ${String(uid)}`);
|
|
97
|
-
if ((info.mode & 63) !== 0) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: ${path} must not be readable or writable by group/other`);
|
|
98
|
-
}
|
|
99
|
-
return dir;
|
|
100
|
-
}
|
|
101
|
-
/** Resolve the installed package root from this built entry's own URL. */
|
|
102
|
-
function installedPackageRootFromEntry(entryUrl) {
|
|
103
|
-
const root = realpathSync(dirname(dirname(fileURLToPath(entryUrl))));
|
|
104
|
-
let manifest;
|
|
105
|
-
try {
|
|
106
|
-
manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
107
|
-
} catch (error) {
|
|
108
|
-
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: this entry is not running from an installed package root", error);
|
|
109
|
-
}
|
|
110
|
-
if (manifest === null || typeof manifest !== "object" || manifest.name !== "@xmoon76/dsh-pi-tui") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: this entry is not running from an installed @xmoon76/dsh-pi-tui package");
|
|
111
|
-
return root;
|
|
112
|
-
}
|
|
113
|
-
/** Read the installed DSH version from the launcher's package anchor. */
|
|
114
|
-
function readInstalledDshVersion(dshAnchor) {
|
|
115
|
-
let manifest;
|
|
116
|
-
try {
|
|
117
|
-
manifest = JSON.parse(readFileSync(realpathSync(dshAnchor), "utf8"));
|
|
118
|
-
} catch (error) {
|
|
119
|
-
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed DSH manifest is unreadable", error);
|
|
120
|
-
}
|
|
121
|
-
const version = manifest === null || typeof manifest !== "object" ? void 0 : manifest.version;
|
|
122
|
-
if (typeof version !== "string" || version === "") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed DSH manifest has no version");
|
|
123
|
-
return version;
|
|
124
|
-
}
|
|
125
|
-
/** Read and validate the installed bundle manifest. */
|
|
126
|
-
function readBundleVersion(packageRoot) {
|
|
127
|
-
let manifest;
|
|
128
|
-
try {
|
|
129
|
-
manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
|
|
130
|
-
} catch (error) {
|
|
131
|
-
throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed package manifest is unreadable", error);
|
|
132
|
-
}
|
|
133
|
-
if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed package manifest is not an object");
|
|
134
|
-
const record = manifest;
|
|
135
|
-
if (record.name !== "@xmoon76/dsh-pi-tui" || typeof record.version !== "string" || record.version === "") throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", "local scope: the installed package manifest is not @xmoon76/dsh-pi-tui");
|
|
136
|
-
return record.version;
|
|
137
|
-
}
|
|
138
|
-
/** Every regular `.mjs` file below `dist`, sorted by UTF-8 bytes. */
|
|
139
|
-
function listInstalledDistFiles(packageRoot) {
|
|
140
|
-
const distDir = join(packageRoot, "dist");
|
|
141
|
-
const files = [];
|
|
142
|
-
const walk = (dir) => {
|
|
143
|
-
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
144
|
-
const path = join(dir, entry.name);
|
|
145
|
-
if (entry.isSymbolicLink()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains a symlink: ${path}`);
|
|
146
|
-
if (entry.isDirectory()) {
|
|
147
|
-
walk(path);
|
|
148
|
-
continue;
|
|
149
|
-
}
|
|
150
|
-
if (!entry.isFile()) throw new LocalScopeError("SCOPE_DIRECTORY_UNSAFE", `local scope: installed payload contains a non-file: ${path}`);
|
|
151
|
-
if (entry.name.endsWith(".mjs")) files.push(relative(packageRoot, path).split(sep).join("/"));
|
|
152
|
-
}
|
|
153
|
-
};
|
|
154
|
-
walk(distDir);
|
|
155
|
-
files.sort((left, right) => Buffer$1.compare(Buffer$1.from(left, "utf8"), Buffer$1.from(right, "utf8")));
|
|
156
|
-
return files;
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* Fingerprint the actual installed payload. Every regular `dist/**` `.mjs`
|
|
160
|
-
* contributes `relative-posix-name NUL sha256(content) LF` in UTF-8 byte
|
|
161
|
-
* order; the bundle and DSH versions close the stream. The value is computed
|
|
162
|
-
* once by the Host at startup and once by each Client from its own install.
|
|
163
|
-
*/
|
|
164
|
-
function computeBuildId(packageRoot, dshVersion) {
|
|
165
|
-
if (dshVersion === "") throw new Error("local scope: the installed DSH version must not be empty");
|
|
166
|
-
const hash = createHash("sha256");
|
|
167
|
-
for (const relativeName of listInstalledDistFiles(packageRoot)) {
|
|
168
|
-
const content = readFileSync(join(packageRoot, ...relativeName.split("/")));
|
|
169
|
-
hash.update(relativeName);
|
|
170
|
-
hash.update("\0");
|
|
171
|
-
hash.update(createHash("sha256").update(content).digest("hex"));
|
|
172
|
-
hash.update("\n");
|
|
173
|
-
}
|
|
174
|
-
const manifest = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
|
|
175
|
-
hash.update("package.json\0");
|
|
176
|
-
hash.update(manifest.name);
|
|
177
|
-
hash.update("\0");
|
|
178
|
-
hash.update(manifest.version);
|
|
179
|
-
hash.update("\n");
|
|
180
|
-
hash.update("@deepseek-ai/dsh\0");
|
|
181
|
-
hash.update(dshVersion);
|
|
182
|
-
hash.update("\n");
|
|
183
|
-
return hash.digest("hex");
|
|
184
|
-
}
|
|
185
|
-
/**
|
|
186
|
-
* Build the one scope for an installed profile. The caller supplies the
|
|
187
|
-
* official DSH home/profile resolution results; this module never guesses a
|
|
188
|
-
* path. The run directory is created here, before any process seat or Host
|
|
189
|
-
* Context exists.
|
|
190
|
-
*/
|
|
191
|
-
function scopeFromInstalledProfile(facts) {
|
|
192
|
-
const uid = assertLinux();
|
|
193
|
-
const dshHome = canonicalOwnedDirectory(facts.dshHome, uid, "DSH home");
|
|
194
|
-
const profileRealpath = canonicalOwnedDirectory(facts.profileDir, uid, "profile directory");
|
|
195
|
-
const bundleVersion = readBundleVersion(facts.packageRoot);
|
|
196
|
-
const scopeId = createHash("sha256").update(`dsh-pi-tui/local-scope/1\0${String(uid)}\0${profileRealpath}`).digest("hex");
|
|
197
|
-
const dir = ensureScopeDirectory(dshHome, scopeId, uid);
|
|
198
|
-
return Object.freeze({
|
|
199
|
-
scopeId,
|
|
200
|
-
profileRealpath,
|
|
201
|
-
dir,
|
|
202
|
-
hostSocketName: `${HOST_SEAT_PREFIX}${scopeId.slice(0, 40)}`,
|
|
203
|
-
clientSeatSocketName: `${CLIENT_SEAT_PREFIX}${scopeId.slice(0, 40)}`,
|
|
204
|
-
buildId: computeBuildId(facts.packageRoot, facts.dshVersion),
|
|
205
|
-
bundleVersion,
|
|
206
|
-
dshVersion: facts.dshVersion
|
|
207
|
-
});
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* Parse field 3 (`state`) and field 22 (`starttime`) from one
|
|
211
|
-
* `/proc/<pid>/stat` text. The comm field may contain spaces and parentheses;
|
|
212
|
-
* everything after the LAST ')' is the fixed positional tail whose first entry
|
|
213
|
-
* is field 3. A stat without a single-letter state and a numeric starttime is
|
|
214
|
-
* malformed, never a usable liveness observation.
|
|
215
|
-
*/
|
|
216
|
-
function parseProcessStat(stat) {
|
|
217
|
-
const close = stat.lastIndexOf(")");
|
|
218
|
-
if (close < 0) return void 0;
|
|
219
|
-
const fields = stat.slice(close + 2).trim().split(/\s+/);
|
|
220
|
-
const state = fields[0];
|
|
221
|
-
const value = fields[19];
|
|
222
|
-
if (state === void 0 || !/^[A-Za-z]$/u.test(state)) return void 0;
|
|
223
|
-
if (value === void 0 || !/^\d+$/u.test(value)) return void 0;
|
|
224
|
-
return {
|
|
225
|
-
state,
|
|
226
|
-
starttime: value
|
|
227
|
-
};
|
|
228
|
-
}
|
|
229
|
-
/** Parse only field 22 (`starttime`) from one `/proc/<pid>/stat`. */
|
|
230
|
-
function parseProcessStatStarttime(stat) {
|
|
231
|
-
return parseProcessStat(stat)?.starttime;
|
|
232
|
-
}
|
|
233
|
-
/** Best-effort Linux `starttime` read used by A0 status surfaces (may be undefined). */
|
|
234
|
-
function readProcessStarttime(pid = process.pid) {
|
|
235
|
-
try {
|
|
236
|
-
return parseProcessStatStarttime(readFileSync(`/proc/${String(pid)}/stat`, "utf8"));
|
|
237
|
-
} catch {
|
|
238
|
-
return;
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
/**
|
|
242
|
-
* Strict Linux process-start identity. B1 identity comparison never falls
|
|
243
|
-
* back to a bare PID: a missing `/proc` value is a hard failure.
|
|
244
|
-
*/
|
|
245
|
-
function readLinuxStarttime(pid = process.pid) {
|
|
246
|
-
assertLinux();
|
|
247
|
-
const value = readProcessStarttime(pid);
|
|
248
|
-
if (value === void 0) throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", `local scope: /proc/${String(pid)}/stat does not expose a starttime`);
|
|
249
|
-
return value;
|
|
250
|
-
}
|
|
251
|
-
/**
|
|
252
|
-
* Claim one kernel abstract-socket seat. `EADDRINUSE` means another process
|
|
253
|
-
* of this scope already holds the seat and is the sole winner; any other
|
|
254
|
-
* listen error is a real failure. The Host Singleton and the frozen
|
|
255
|
-
* `qualification` Client are the two live users; a real `surface` Client holds
|
|
256
|
-
* no seat. The returned close is idempotent.
|
|
257
|
-
*/
|
|
258
|
-
function bindProcessSeat(name, conflictCode) {
|
|
259
|
-
assertLinux();
|
|
260
|
-
if (!name.startsWith("\0")) return Promise.reject(/* @__PURE__ */ new Error("local scope: process seats require a Linux abstract socket name"));
|
|
261
|
-
return new Promise((resolve, reject) => {
|
|
262
|
-
const server = createServer();
|
|
263
|
-
let settled = false;
|
|
264
|
-
let closed;
|
|
265
|
-
server.once("error", (error) => {
|
|
266
|
-
if (settled) return;
|
|
267
|
-
settled = true;
|
|
268
|
-
if (error.code === "EADDRINUSE") {
|
|
269
|
-
reject(new LocalScopeError(conflictCode, `local scope: ${name.slice(1)} is already owned by another live process`, error));
|
|
270
|
-
return;
|
|
271
|
-
}
|
|
272
|
-
reject(error);
|
|
273
|
-
});
|
|
274
|
-
server.listen(name, () => {
|
|
275
|
-
if (settled) return;
|
|
276
|
-
settled = true;
|
|
277
|
-
resolve({ close() {
|
|
278
|
-
if (closed !== void 0) return closed;
|
|
279
|
-
closed = new Promise((resolveClose, rejectClose) => {
|
|
280
|
-
server.close((error) => {
|
|
281
|
-
if (error === void 0) resolveClose();
|
|
282
|
-
else rejectClose(error);
|
|
283
|
-
});
|
|
284
|
-
});
|
|
285
|
-
return closed;
|
|
286
|
-
} });
|
|
287
|
-
});
|
|
288
|
-
});
|
|
289
|
-
}
|
|
290
|
-
/**
|
|
291
|
-
* Remove one scratch directory only when it is exactly a Client-created
|
|
292
|
-
* `host-scratch-*` child of this scope. A SIGKILL leaves it for deferred
|
|
293
|
-
* cleanup; an active Host's scratch is never touched by a new Client.
|
|
294
|
-
*/
|
|
295
|
-
function removeOwnedScratch(scopeDir, scratchDir) {
|
|
296
|
-
if (dirname(scratchDir) !== scopeDir) return;
|
|
297
|
-
if (!basename(scratchDir).startsWith("host-scratch-")) return;
|
|
298
|
-
rmSync(scratchDir, {
|
|
299
|
-
recursive: true,
|
|
300
|
-
force: true
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
//#endregion
|
|
304
|
-
//#region src/app/remote-process/local-discovery.ts
|
|
305
|
-
/**
|
|
306
|
-
* Local Host discovery and official authentication.
|
|
307
|
-
*
|
|
308
|
-
* The registry is an unauthenticated hint: it selects a candidate origin and
|
|
309
|
-
* PID, while the only readiness proof is the official `/connect` launch-token
|
|
310
|
-
* exchange followed by the authenticated identity Fetch route. This module
|
|
311
|
-
* never creates a Host Context, a Session, an Agent or a second transport
|
|
312
|
-
* authority, and it never removes another process's files.
|
|
313
|
-
*
|
|
314
|
-
* @module app/remote-process/local-discovery
|
|
315
|
-
*/
|
|
316
|
-
/** Registry file name inside the private scope directory. */
|
|
317
|
-
const REGISTRY_FILE = "instance.json";
|
|
318
|
-
/** Launch-material file name inside the private scope directory. */
|
|
319
|
-
const LAUNCH_FILE = "launch.json";
|
|
320
|
-
/** Hard read limit for the registry record. */
|
|
321
|
-
const MAX_REGISTRY_BYTES = 8192;
|
|
322
|
-
/** Hard read limit for the launch material. */
|
|
323
|
-
const MAX_LAUNCH_BYTES = 4096;
|
|
324
|
-
/** Bounded registry wait used by ensureLocalHost. */
|
|
325
|
-
const REGISTRY_WAIT_TIMEOUT_MS = 6e4;
|
|
326
|
-
/** Bounded registry re-read interval. */
|
|
327
|
-
const REGISTRY_POLL_INTERVAL_MS = 250;
|
|
328
|
-
/** Per-request bound for the official HTTP handshake. */
|
|
329
|
-
const AUTH_REQUEST_TIMEOUT_MS = 1e4;
|
|
330
|
-
/** Exact registry keys; unknown fields are rejected, not ignored. */
|
|
331
|
-
const RECORD_KEYS = [
|
|
332
|
-
"schema",
|
|
333
|
-
"scopeId",
|
|
334
|
-
"profileRealpath",
|
|
335
|
-
"instanceId",
|
|
336
|
-
"hostPid",
|
|
337
|
-
"hostStarttime",
|
|
338
|
-
"origin",
|
|
339
|
-
"protocol",
|
|
340
|
-
"bundleVersion",
|
|
341
|
-
"dshVersion",
|
|
342
|
-
"buildId"
|
|
343
|
-
];
|
|
344
|
-
/** Exact launch-material keys. */
|
|
345
|
-
const LAUNCH_KEYS = [
|
|
346
|
-
"schema",
|
|
347
|
-
"instanceId",
|
|
348
|
-
"connectUrl"
|
|
349
|
-
];
|
|
350
|
-
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;
|
|
351
|
-
const HEX_64 = /^[0-9a-f]{64}$/u;
|
|
352
|
-
const COOKIE_PAIR = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+=[^;\s]*$/u;
|
|
353
|
-
/** A strict object with exactly the expected own keys. */
|
|
354
|
-
function assertExactObject(value, keys, label) {
|
|
355
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} must be a JSON object`);
|
|
356
|
-
const record = value;
|
|
357
|
-
const actual = Object.keys(record).sort();
|
|
358
|
-
const expected = [...keys].sort();
|
|
359
|
-
if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} has unexpected fields`);
|
|
360
|
-
return record;
|
|
361
|
-
}
|
|
362
|
-
function requireString(record, key, label) {
|
|
363
|
-
const value = record[key];
|
|
364
|
-
if (typeof value !== "string" || value === "") throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label}.${key} must be a non-empty string`);
|
|
365
|
-
return value;
|
|
366
|
-
}
|
|
367
|
-
/** Validate the loopback-only origin shape B1 accepts. */
|
|
368
|
-
function assertLoopbackOrigin(origin) {
|
|
369
|
-
let url;
|
|
370
|
-
try {
|
|
371
|
-
url = new URL(origin);
|
|
372
|
-
} catch (error) {
|
|
373
|
-
throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: origin is not a URL", error);
|
|
374
|
-
}
|
|
375
|
-
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>`);
|
|
376
|
-
}
|
|
377
|
-
/** Parse the strict registry schema without judging build compatibility. */
|
|
378
|
-
function parseRecord(value, scope) {
|
|
379
|
-
const record = assertExactObject(value, RECORD_KEYS, "registry");
|
|
380
|
-
if (record.schema !== 1) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.schema must be 1");
|
|
381
|
-
const scopeId = requireString(record, "scopeId", "registry");
|
|
382
|
-
const profileRealpath = requireString(record, "profileRealpath", "registry");
|
|
383
|
-
const instanceId = requireString(record, "instanceId", "registry");
|
|
384
|
-
const hostStarttime = requireString(record, "hostStarttime", "registry");
|
|
385
|
-
const origin = requireString(record, "origin", "registry");
|
|
386
|
-
const protocol = requireString(record, "protocol", "registry");
|
|
387
|
-
const bundleVersion = requireString(record, "bundleVersion", "registry");
|
|
388
|
-
const dshVersion = requireString(record, "dshVersion", "registry");
|
|
389
|
-
const buildId = requireString(record, "buildId", "registry");
|
|
390
|
-
const hostPid = record.hostPid;
|
|
391
|
-
if (typeof hostPid !== "number" || !Number.isSafeInteger(hostPid) || hostPid < 1) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostPid must be a positive integer");
|
|
392
|
-
if (!UUID_PATTERN.test(instanceId)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.instanceId must be a UUID");
|
|
393
|
-
if (!/^\d+$/u.test(hostStarttime)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.hostStarttime must be numeric");
|
|
394
|
-
if (!HEX_64.test(buildId)) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: registry.buildId must be 64 hex characters");
|
|
395
|
-
assertLoopbackOrigin(origin);
|
|
396
|
-
if (scopeId !== scope.scopeId || profileRealpath !== scope.profileRealpath) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: registry names another profile scope");
|
|
397
|
-
return {
|
|
398
|
-
schema: 1,
|
|
399
|
-
scopeId,
|
|
400
|
-
profileRealpath,
|
|
401
|
-
instanceId,
|
|
402
|
-
hostPid,
|
|
403
|
-
hostStarttime,
|
|
404
|
-
origin,
|
|
405
|
-
protocol,
|
|
406
|
-
bundleVersion,
|
|
407
|
-
dshVersion,
|
|
408
|
-
buildId
|
|
409
|
-
};
|
|
410
|
-
}
|
|
411
|
-
/** Can this Client speak the live Host's required local wire contract? */
|
|
412
|
-
function assertClientHostCompatible(record, scope) {
|
|
413
|
-
if (record.protocol !== "dsh-pi-tui/local/1" || record.dshVersion !== scope.dshVersion) throw new LocalScopeError("HOST_PROTOCOL_INCOMPATIBLE", "local discovery: the live Host uses a different local protocol or DSH runtime");
|
|
414
|
-
}
|
|
415
|
-
/** Does this Host publish the exact installed identity of its OWN build? */
|
|
416
|
-
function assertHostPublicationIdentity(record, scope) {
|
|
417
|
-
if (record.protocol !== "dsh-pi-tui/local/1" || 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");
|
|
418
|
-
}
|
|
419
|
-
/**
|
|
420
|
-
* Read one private scope file with `O_NOFOLLOW`, an owner/mode check and a hard
|
|
421
|
-
* byte cap. Returns `undefined` for a missing file; every unsafe or malformed
|
|
422
|
-
* file is a hard failure.
|
|
423
|
-
*/
|
|
424
|
-
function readPrivateJsonFile(path, maxBytes, label) {
|
|
425
|
-
let fd;
|
|
426
|
-
try {
|
|
427
|
-
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
428
|
-
} catch (error) {
|
|
429
|
-
if (error.code === "ENOENT") return void 0;
|
|
430
|
-
throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} is not readable without following a link`, error);
|
|
431
|
-
}
|
|
432
|
-
try {
|
|
433
|
-
const info = fstatSync(fd);
|
|
434
|
-
if (!info.isFile() || info.uid !== process.getuid?.() || (info.mode & 511) !== 384) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} must be a 0600 regular file owned by this uid`);
|
|
435
|
-
if (info.size > maxBytes) throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} exceeds ${String(maxBytes)} bytes`);
|
|
436
|
-
const text = readFileSync(fd, "utf8");
|
|
437
|
-
try {
|
|
438
|
-
return JSON.parse(text);
|
|
439
|
-
} catch (error) {
|
|
440
|
-
throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${label} is not valid JSON`, error);
|
|
441
|
-
}
|
|
442
|
-
} finally {
|
|
443
|
-
closeSync(fd);
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
/**
|
|
447
|
-
* Strictly read `<scope>/instance.json`. The record is an unauthenticated
|
|
448
|
-
* candidate only; this function performs no liveness or build decision.
|
|
449
|
-
*/
|
|
450
|
-
function readLocalRecord(scope) {
|
|
451
|
-
const value = readPrivateJsonFile(join(scope.dir, REGISTRY_FILE), MAX_REGISTRY_BYTES, "instance.json");
|
|
452
|
-
if (value === void 0) return void 0;
|
|
453
|
-
return parseRecord(value, scope);
|
|
454
|
-
}
|
|
455
|
-
/** Strictly read `<scope>/launch.json` after its registry candidate matched. */
|
|
456
|
-
function readLaunchMaterial(scope, record) {
|
|
457
|
-
const value = readPrivateJsonFile(join(scope.dir, LAUNCH_FILE), MAX_LAUNCH_BYTES, "launch.json");
|
|
458
|
-
if (value === void 0) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: instance.json has no matching launch.json");
|
|
459
|
-
const launch = assertExactObject(value, LAUNCH_KEYS, "launch.json");
|
|
460
|
-
if (launch.schema !== 1) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: launch.json.schema must be 1");
|
|
461
|
-
const instanceId = requireString(launch, "instanceId", "launch.json");
|
|
462
|
-
const connectUrl = requireString(launch, "connectUrl", "launch.json");
|
|
463
|
-
if (instanceId !== record.instanceId) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: launch.json names a different Host instance");
|
|
464
|
-
assertConnectUrl(connectUrl, record);
|
|
465
|
-
return {
|
|
466
|
-
schema: 1,
|
|
467
|
-
instanceId,
|
|
468
|
-
connectUrl
|
|
469
|
-
};
|
|
470
|
-
}
|
|
471
|
-
/** Validate the exact `/connect` URL shape without exposing its token. */
|
|
472
|
-
function assertConnectUrl(connectUrl, record) {
|
|
473
|
-
let url;
|
|
474
|
-
try {
|
|
475
|
-
url = new URL(connectUrl);
|
|
476
|
-
} catch (error) {
|
|
477
|
-
throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: launch.json.connectUrl is not a URL", error);
|
|
478
|
-
}
|
|
479
|
-
const tokens = url.searchParams.getAll("token");
|
|
480
|
-
const keys = [...url.searchParams.keys()];
|
|
481
|
-
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");
|
|
482
|
-
}
|
|
483
|
-
/**
|
|
484
|
-
* Liveness is a negative selection fact, never readiness. A missing
|
|
485
|
-
* `/proc/<pid>/stat` (ENOENT) is a definite dead PID; an unreadable or
|
|
486
|
-
* malformed file is UNKNOWN and is a hard failure, never permission to spawn.
|
|
487
|
-
* `procRoot` exists only so the fail-closed classification is testable.
|
|
488
|
-
*/
|
|
489
|
-
function inspectHostProcess(record, procRoot = "/proc") {
|
|
490
|
-
let stat;
|
|
491
|
-
try {
|
|
492
|
-
stat = readFileSync(join(procRoot, String(record.hostPid), "stat"), "utf8");
|
|
493
|
-
} catch (error) {
|
|
494
|
-
if (error.code === "ENOENT") return "dead";
|
|
495
|
-
throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", `local discovery: /proc/${String(record.hostPid)}/stat is not readable`, error);
|
|
496
|
-
}
|
|
497
|
-
const parsed = parseProcessStat(stat);
|
|
498
|
-
if (parsed === void 0) throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", `local discovery: /proc/${String(record.hostPid)}/stat has no usable state/starttime`);
|
|
499
|
-
if (parsed.starttime !== record.hostStarttime) return "dead";
|
|
500
|
-
if (parsed.state === "Z" || parsed.state === "X" || parsed.state === "x") return "dead";
|
|
501
|
-
return "alive";
|
|
502
|
-
}
|
|
503
|
-
/** Read a bounded UTF-8 body; an over-limit identity response is a mismatch. */
|
|
504
|
-
async function readBoundedText(response, maxBytes, label) {
|
|
505
|
-
if (response.body === null) return "";
|
|
506
|
-
const reader = response.body.getReader();
|
|
507
|
-
const chunks = [];
|
|
508
|
-
let total = 0;
|
|
509
|
-
try {
|
|
510
|
-
for (;;) {
|
|
511
|
-
const { done, value } = await reader.read();
|
|
512
|
-
if (done) break;
|
|
513
|
-
total += value.byteLength;
|
|
514
|
-
if (total > maxBytes) {
|
|
515
|
-
await reader.cancel();
|
|
516
|
-
throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local discovery: ${label} exceeds ${String(maxBytes)} bytes`);
|
|
517
|
-
}
|
|
518
|
-
chunks.push(value);
|
|
519
|
-
}
|
|
520
|
-
} finally {
|
|
521
|
-
reader.releaseLock();
|
|
522
|
-
}
|
|
523
|
-
return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
|
|
524
|
-
}
|
|
525
|
-
/** Discard a response body without leaking it to logs. */
|
|
526
|
-
async function discard(response) {
|
|
527
|
-
try {
|
|
528
|
-
await response.body?.cancel();
|
|
529
|
-
} catch {}
|
|
530
|
-
}
|
|
531
|
-
/** Fetch with the bounded auth timeout; network failure is HOST_UNRESPONSIVE. */
|
|
532
|
-
async function authFetch(url, init) {
|
|
533
|
-
const request = {
|
|
534
|
-
...init,
|
|
535
|
-
signal: AbortSignal.timeout(AUTH_REQUEST_TIMEOUT_MS)
|
|
536
|
-
};
|
|
537
|
-
try {
|
|
538
|
-
return await fetch(url, request);
|
|
539
|
-
} catch (error) {
|
|
540
|
-
throw new LocalScopeError("HOST_UNRESPONSIVE", "local discovery: the Host did not answer the official HTTP handshake", error);
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
/** Exchange the launch token for this Client process's own signed cookie. */
|
|
544
|
-
async function connectForCookie(record, launch) {
|
|
545
|
-
const url = new URL(launch.connectUrl);
|
|
546
|
-
url.searchParams.set("interactions", "answer");
|
|
547
|
-
const response = await authFetch(url, {
|
|
548
|
-
method: "GET",
|
|
549
|
-
redirect: "manual",
|
|
550
|
-
cache: "no-store"
|
|
551
|
-
});
|
|
552
|
-
if (response.status !== 302) {
|
|
553
|
-
await discard(response);
|
|
554
|
-
throw new LocalScopeError("HOST_AUTH_FAILED", `local discovery: /connect rejected this Client with HTTP ${String(response.status)}`);
|
|
555
|
-
}
|
|
556
|
-
const cacheControl = response.headers.get("cache-control") ?? "";
|
|
557
|
-
if (!/\bno-store\b/iu.test(cacheControl)) {
|
|
558
|
-
await discard(response);
|
|
559
|
-
throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect response was not marked no-store");
|
|
560
|
-
}
|
|
561
|
-
const location = response.headers.get("location");
|
|
562
|
-
await discard(response);
|
|
563
|
-
if (location === null) throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect returned no mux redirect");
|
|
564
|
-
let redirect;
|
|
565
|
-
try {
|
|
566
|
-
redirect = new URL(location, url);
|
|
567
|
-
} catch (error) {
|
|
568
|
-
throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect returned an unparsable redirect", error);
|
|
569
|
-
}
|
|
570
|
-
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");
|
|
571
|
-
const raw = response.headers.getSetCookie?.() ?? (response.headers.get("set-cookie") === null ? [] : [response.headers.get("set-cookie")]);
|
|
572
|
-
if (raw.length === 0) throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect returned no signed cookie");
|
|
573
|
-
const pair = raw[0].split(";", 1)[0].trim();
|
|
574
|
-
if (!COOKIE_PAIR.test(pair)) throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: /connect returned an invalid cookie pair");
|
|
575
|
-
return pair;
|
|
576
|
-
}
|
|
577
|
-
/** Read and compare the authenticated identity echo with the registry. */
|
|
578
|
-
async function readAuthenticatedIdentity(record, cookie) {
|
|
579
|
-
const response = await authFetch(`${record.origin}/api/pi-tui.local-host`, {
|
|
580
|
-
method: "GET",
|
|
581
|
-
headers: { cookie },
|
|
582
|
-
redirect: "manual",
|
|
583
|
-
cache: "no-store"
|
|
584
|
-
});
|
|
585
|
-
if (response.status === 401 || response.status === 403) {
|
|
586
|
-
await discard(response);
|
|
587
|
-
throw new LocalScopeError("HOST_AUTH_FAILED", "local discovery: the identity route rejected the signed cookie");
|
|
588
|
-
}
|
|
589
|
-
if (response.status !== 200) {
|
|
590
|
-
await discard(response);
|
|
591
|
-
throw new LocalScopeError("HOST_UNRESPONSIVE", `local discovery: identity route answered HTTP ${String(response.status)}`);
|
|
592
|
-
}
|
|
593
|
-
const contentType = response.headers.get("content-type") ?? "";
|
|
594
|
-
const cacheControl = response.headers.get("cache-control") ?? "";
|
|
595
|
-
if (!/^application\/json\b/iu.test(contentType) || !/\bno-store\b/iu.test(cacheControl)) {
|
|
596
|
-
await discard(response);
|
|
597
|
-
throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: identity route response has the wrong shape");
|
|
598
|
-
}
|
|
599
|
-
const text = await readBoundedText(response, MAX_REGISTRY_BYTES, "identity route response");
|
|
600
|
-
let value;
|
|
601
|
-
try {
|
|
602
|
-
value = JSON.parse(text);
|
|
603
|
-
} catch (error) {
|
|
604
|
-
throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: identity route response is not JSON", error);
|
|
605
|
-
}
|
|
606
|
-
const identity = parseRecord(value, record);
|
|
607
|
-
for (const key of RECORD_KEYS) if (identity[key] !== record[key]) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", `local discovery: authenticated identity differs from the registry at ${key}`);
|
|
608
|
-
return identity;
|
|
609
|
-
}
|
|
610
|
-
/**
|
|
611
|
-
* Run the full authenticated handshake: launch material, official `/connect`
|
|
612
|
-
* cookie, identity echo, then a fresh kernel starttime check. The returned
|
|
613
|
-
* cookie stays in this Client process only.
|
|
614
|
-
*/
|
|
615
|
-
async function authenticateLocalHost(record, scope) {
|
|
616
|
-
const cookie = await connectForCookie(record, readLaunchMaterial(scope, record));
|
|
617
|
-
const identity = await readAuthenticatedIdentity(record, cookie);
|
|
618
|
-
const liveStarttime = readProcessStarttime(identity.hostPid);
|
|
619
|
-
if (liveStarttime === void 0) throw new LocalScopeError("PROCESS_STARTTIME_UNAVAILABLE", "local discovery: the authenticated Host process starttime is unavailable");
|
|
620
|
-
if (liveStarttime !== identity.hostStarttime) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: the authenticated Host PID is no longer the registry process");
|
|
621
|
-
return {
|
|
622
|
-
record,
|
|
623
|
-
cookie,
|
|
624
|
-
identity
|
|
625
|
-
};
|
|
626
|
-
}
|
|
627
|
-
/** Bound the registry wait without a fixed readiness sleep. */
|
|
628
|
-
function delay(ms) {
|
|
629
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
630
|
-
}
|
|
631
|
-
/** Start one Host candidate; the Host's own OS seat decides the winner. */
|
|
632
|
-
function spawnHostCandidate(options) {
|
|
633
|
-
let info;
|
|
634
|
-
try {
|
|
635
|
-
info = lstatSync(options.hostEntryPath);
|
|
636
|
-
} catch (error) {
|
|
637
|
-
throw new LocalScopeError("HOST_START_FAILED", "local discovery: the installed Host entry is not readable", error);
|
|
638
|
-
}
|
|
639
|
-
if (info.isSymbolicLink() || !info.isFile() || info.uid !== process.getuid?.()) throw new LocalScopeError("HOST_START_FAILED", "local discovery: the installed Host entry must be a regular file owned by this uid");
|
|
640
|
-
const logPath = join(options.scope.dir, "host.log");
|
|
641
|
-
let fd;
|
|
642
|
-
try {
|
|
643
|
-
fd = openSync(logPath, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 384);
|
|
644
|
-
fchmodSync(fd, 384);
|
|
645
|
-
const env = {
|
|
646
|
-
...process.env,
|
|
647
|
-
SPLIT_PROCESS_DSH_ANCHOR: options.dshAnchor,
|
|
648
|
-
SPLIT_PROCESS_PROFILE: options.profile
|
|
649
|
-
};
|
|
650
|
-
delete env.SPLIT_PROCESS_EXTRA_PATCH;
|
|
651
|
-
delete env.DSH_PI_TUI_ROLE;
|
|
652
|
-
delete env.DSH_PI_TUI_HOST_ENTRY;
|
|
653
|
-
const child = spawn(process.execPath, [options.hostEntryPath], {
|
|
654
|
-
cwd: options.scope.profileRealpath,
|
|
655
|
-
detached: true,
|
|
656
|
-
stdio: [
|
|
657
|
-
"ignore",
|
|
658
|
-
fd,
|
|
659
|
-
fd
|
|
660
|
-
],
|
|
661
|
-
env
|
|
662
|
-
});
|
|
663
|
-
let spawnFailure;
|
|
664
|
-
child.once("error", (error) => {
|
|
665
|
-
spawnFailure = error;
|
|
666
|
-
});
|
|
667
|
-
child.unref();
|
|
668
|
-
return () => spawnFailure;
|
|
669
|
-
} catch (error) {
|
|
670
|
-
if (error instanceof LocalScopeError) throw error;
|
|
671
|
-
throw new LocalScopeError("HOST_START_FAILED", "local discovery: the Host candidate could not be spawned", error);
|
|
672
|
-
} finally {
|
|
673
|
-
if (fd !== void 0) closeSync(fd);
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
/**
|
|
677
|
-
* Ensure one authenticated Host for this scope. A live registry candidate is
|
|
678
|
-
* never killed and never replaced; a dead one may be replaced by a new Host
|
|
679
|
-
* whose kernel seat is the only winner. Authentication failure is terminal.
|
|
680
|
-
*/
|
|
681
|
-
async function ensureLocalHost(options) {
|
|
682
|
-
const { scope } = options;
|
|
683
|
-
if (options.expectedInstanceId !== void 0) {
|
|
684
|
-
const record = readLocalRecord(scope);
|
|
685
|
-
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");
|
|
686
|
-
if (record.instanceId !== options.expectedInstanceId) throw new LocalScopeError("HOST_IDENTITY_MISMATCH", "local discovery: the live Host is not the expected handoff instance");
|
|
687
|
-
assertClientHostCompatible(record, scope);
|
|
688
|
-
return await authenticateLocalHost(record, scope);
|
|
689
|
-
}
|
|
690
|
-
const existing = readLocalRecord(scope);
|
|
691
|
-
if (existing !== void 0 && inspectHostProcess(existing) === "alive") {
|
|
692
|
-
assertClientHostCompatible(existing, scope);
|
|
693
|
-
return await authenticateLocalHost(existing, scope);
|
|
694
|
-
}
|
|
695
|
-
const spawnFailure = spawnHostCandidate(options);
|
|
696
|
-
const deadline = Date.now() + REGISTRY_WAIT_TIMEOUT_MS;
|
|
697
|
-
while (Date.now() < deadline) {
|
|
698
|
-
const failure = spawnFailure();
|
|
699
|
-
if (failure !== void 0) throw new LocalScopeError("HOST_START_FAILED", "local discovery: the Host candidate failed to start", failure);
|
|
700
|
-
const candidate = readLocalRecord(scope);
|
|
701
|
-
if (candidate !== void 0 && inspectHostProcess(candidate) === "alive") {
|
|
702
|
-
assertClientHostCompatible(candidate, scope);
|
|
703
|
-
return await authenticateLocalHost(candidate, scope);
|
|
704
|
-
}
|
|
705
|
-
await delay(REGISTRY_POLL_INTERVAL_MS);
|
|
706
|
-
}
|
|
707
|
-
throw new LocalScopeError("HOST_START_TIMEOUT", `local discovery: no ready Host registry appeared within ${String(REGISTRY_WAIT_TIMEOUT_MS / 1e3)}s`);
|
|
708
|
-
}
|
|
709
|
-
/** Write one 0600 file through an exclusively-created same-directory temp file. */
|
|
710
|
-
function writePrivateJsonFile(path, value) {
|
|
711
|
-
const text = `${JSON.stringify(value)}\n`;
|
|
712
|
-
const temp = join(dirname(path), `.${basename(path)}.${String(process.pid)}.${randomUUID()}.tmp`);
|
|
713
|
-
let fd;
|
|
714
|
-
try {
|
|
715
|
-
fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
|
|
716
|
-
fchmodSync(fd, 384);
|
|
717
|
-
writeFileSync(fd, text, "utf8");
|
|
718
|
-
fsyncSync(fd);
|
|
719
|
-
closeSync(fd);
|
|
720
|
-
fd = void 0;
|
|
721
|
-
renameSync(temp, path);
|
|
722
|
-
} catch (error) {
|
|
723
|
-
if (fd !== void 0) closeSync(fd);
|
|
724
|
-
try {
|
|
725
|
-
unlinkSync(temp);
|
|
726
|
-
} catch {}
|
|
727
|
-
if (error instanceof LocalScopeError) throw error;
|
|
728
|
-
throw new LocalScopeError("LOCAL_FILE_UNSAFE", `local discovery: ${basename(path)} could not be written atomically`, error);
|
|
729
|
-
}
|
|
730
|
-
}
|
|
731
|
-
/** Publish the one registry record; the Host calls this as its Ready commit. */
|
|
732
|
-
function writeLocalRecord(scope, record) {
|
|
733
|
-
const parsed = parseRecord(record, scope);
|
|
734
|
-
assertHostPublicationIdentity(parsed, scope);
|
|
735
|
-
writePrivateJsonFile(join(scope.dir, REGISTRY_FILE), parsed);
|
|
736
|
-
}
|
|
737
|
-
/** Publish the official launch material before the registry is visible. */
|
|
738
|
-
function writeLaunchMaterial(scope, record, material) {
|
|
739
|
-
const parsed = parseRecord(record, scope);
|
|
740
|
-
assertHostPublicationIdentity(parsed, scope);
|
|
741
|
-
if (material.schema !== 1 || material.instanceId !== parsed.instanceId) throw new LocalScopeError("LOCAL_FILE_UNSAFE", "local discovery: launch material does not name the published instance");
|
|
742
|
-
assertConnectUrl(material.connectUrl, parsed);
|
|
743
|
-
writePrivateJsonFile(join(scope.dir, LAUNCH_FILE), material);
|
|
744
|
-
}
|
|
745
|
-
/**
|
|
746
|
-
* Remove only the files this exact instance published. Used after the official
|
|
747
|
-
* shutdown owner has run and as a synchronous process-exit backstop; a new
|
|
748
|
-
* Host instance's files are never touched.
|
|
749
|
-
*/
|
|
750
|
-
function cleanupOwnedFiles(scope, instanceId) {
|
|
751
|
-
for (const file of [REGISTRY_FILE, LAUNCH_FILE]) {
|
|
752
|
-
const path = join(scope.dir, file);
|
|
753
|
-
try {
|
|
754
|
-
if (JSON.parse(readFileSync(path, "utf8")).instanceId === instanceId) unlinkSync(path);
|
|
755
|
-
} catch {}
|
|
756
|
-
}
|
|
757
|
-
}
|
|
758
|
-
//#endregion
|
|
759
|
-
export { scopeFromInstalledProfile as S, installedPackageRootFromEntry as _, connectForCookie as a, readProcessStarttime as b, readAuthenticatedIdentity as c, writeLaunchMaterial as d, writeLocalRecord as f, computeBuildId as g, bindProcessSeat as h, cleanupOwnedFiles as i, readLaunchMaterial as l, LocalScopeError as m, assertHostPublicationIdentity as n, ensureLocalHost as o, LOCAL_PROTOCOL as p, authenticateLocalHost as r, inspectHostProcess as s, assertClientHostCompatible as t, readLocalRecord as u, readInstalledDshVersion as v, removeOwnedScratch as x, readLinuxStarttime as y };
|