@mostra/runtime 0.1.0 → 0.3.0
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/dist/bin.js +7 -7
- package/dist/bin.js.map +1 -1
- package/dist/builder/child/main.js +18 -17
- package/dist/builder/child/main.js.map +1 -1
- package/dist/{child-xrHmytks.js → child-BQc3arf7.js} +5 -2
- package/dist/{child-xrHmytks.js.map → child-BQc3arf7.js.map} +1 -1
- package/dist/deps/child/install.js +9 -6
- package/dist/deps/child/install.js.map +1 -1
- package/dist/files-KxzOxckl.js +674 -0
- package/dist/files-KxzOxckl.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/{instance-D7_UVdoN.js → instance-DiKSe7s6.js} +1331 -752
- package/dist/instance-DiKSe7s6.js.map +1 -0
- package/package.json +5 -5
- package/src/bin.ts +4 -10
- package/src/builder/child/dev.ts +4 -3
- package/src/builder/child/plugins.ts +12 -7
- package/src/builder/child/spa.ts +15 -9
- package/src/builder/index.ts +3 -6
- package/src/deps/child/install.ts +3 -2
- package/src/deps/index.ts +21 -16
- package/src/deps/warm.ts +3 -16
- package/src/faults.ts +9 -2
- package/src/gateway/actions.ts +1 -1
- package/src/gateway/browser.ts +1 -1
- package/src/gateway/capabilities.ts +28 -7
- package/src/gateway/identity.ts +101 -0
- package/src/gateway/index.ts +96 -6
- package/src/home/acquire.ts +27 -11
- package/src/home/paths.ts +45 -135
- package/src/home/platform.ts +17 -9
- package/src/home/record.ts +3 -3
- package/src/home/settings.ts +5 -16
- package/src/instance/index.ts +73 -12
- package/src/interaction/index.ts +4 -0
- package/src/interaction/viewers.ts +16 -2
- package/src/ledger/index.ts +5 -27
- package/src/ledger/migrations.ts +13 -0
- package/src/platform/control.ts +409 -0
- package/src/platform/directories.ts +212 -0
- package/src/platform/environment.ts +64 -0
- package/src/platform/files.ts +368 -0
- package/src/platform/helper.ts +152 -0
- package/src/{processes → platform}/identity.ts +40 -8
- package/src/platform/index.ts +46 -0
- package/src/platform/launch.ts +373 -0
- package/src/processes/child.ts +4 -1
- package/src/processes/environment.ts +22 -3
- package/src/processes/index.ts +2 -1
- package/src/processes/manager.ts +76 -179
- package/src/protocol-server/client.ts +19 -18
- package/src/protocol-server/server.ts +84 -54
- package/src/publish/publisher.ts +16 -9
- package/src/publish/source.ts +7 -4
- package/src/registry/store.ts +7 -65
- package/src/secrets/index.ts +3 -3
- package/src/service/unit.ts +3 -2
- package/src/verify/index.ts +5 -3
- package/src/verify/typecheck.ts +3 -2
- package/src/workers/launcher.ts +3 -1
- package/dist/instance-D7_UVdoN.js.map +0 -1
- package/dist/types-NjNy7gXX.js +0 -57
- package/dist/types-NjNy7gXX.js.map +0 -1
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The home's control endpoint (D81, D82; RT-06, RT-10): how attached clients reach the
|
|
3
|
+
* supervisor. On POSIX it is a Unix socket in the owner-only runtime directory; on Windows a named
|
|
4
|
+
* pipe that only the user can open and that refuses remote clients, which the helper creates and
|
|
5
|
+
* forwards to the supervisor over its descriptor 4 (`crates/mostra-win/src/win/pipe.rs`), because
|
|
6
|
+
* Node.js's own pipes let any local user open them for reading (VERIFIED_FACTS, WP-W1).
|
|
7
|
+
*
|
|
8
|
+
* Either way the caller gets one stream per client and a listener it can check and replace: a
|
|
9
|
+
* socket file that disappeared, or a pipe whose helper stopped, is bound again (D81 item 4).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { spawn } from "node:child_process";
|
|
13
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
14
|
+
import { chmodSync, mkdirSync, type Stats, statSync, unlinkSync } from "node:fs";
|
|
15
|
+
import { createConnection, createServer, type Server, type Socket } from "node:net";
|
|
16
|
+
import { dirname } from "node:path";
|
|
17
|
+
import { Duplex } from "node:stream";
|
|
18
|
+
import { createDiagnostic, RpcError } from "@mostra/protocol";
|
|
19
|
+
import { type OperatingSystem, OS, pathsOf, socketPathLimit, WINDOWS } from "./directories.ts";
|
|
20
|
+
import { helperPath } from "./helper.ts";
|
|
21
|
+
import { launch } from "./launch.ts";
|
|
22
|
+
|
|
23
|
+
/** Called once per client with the client's stream. */
|
|
24
|
+
export type OnConnection = (stream: Duplex) => void;
|
|
25
|
+
|
|
26
|
+
/** A started helper pipe: its frame channel and its end. */
|
|
27
|
+
export interface PipeProcess {
|
|
28
|
+
readonly channel: Duplex;
|
|
29
|
+
readonly exited: Promise<unknown>;
|
|
30
|
+
stop(): Promise<unknown>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Starts `mostra-win pipe <name>` (through the process manager, so it is gated and recorded). */
|
|
34
|
+
export type LaunchPipe = (name: string) => Promise<PipeProcess>;
|
|
35
|
+
|
|
36
|
+
/** A bound control endpoint. */
|
|
37
|
+
export interface ControlListener {
|
|
38
|
+
/** What clients connect to, as `instance.json` records it. */
|
|
39
|
+
readonly path: string;
|
|
40
|
+
/** Whether it still serves; false when its socket file is gone or its pipe's helper stopped. */
|
|
41
|
+
intact(): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Stops serving and removes what it created. Client streams the caller ended first are handed
|
|
44
|
+
* over before the endpoint goes; any still open are ended here, after what they were sent.
|
|
45
|
+
*/
|
|
46
|
+
close(): Promise<void>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The endpoint for a home. POSIX: `<runtime dir>/<home hash>.sock`, refused with
|
|
51
|
+
* `MOSTRA_HOME_SOCKET_TOO_LONG` past the system's limit. Windows: `\\.\pipe\mostra-<home hash>`,
|
|
52
|
+
* to which each bind adds a random part, so no other program can create the name before the
|
|
53
|
+
* supervisor does; clients learn the full name from `instance.json`.
|
|
54
|
+
*/
|
|
55
|
+
export function controlEndpoint(
|
|
56
|
+
runtimeDir: string | undefined,
|
|
57
|
+
hash: string,
|
|
58
|
+
os: OperatingSystem = OS,
|
|
59
|
+
): string {
|
|
60
|
+
if (os === "win32" || runtimeDir === undefined) return `\\\\.\\pipe\\mostra-${hash}`;
|
|
61
|
+
const path = pathsOf(os).join(runtimeDir, `${hash}.sock`);
|
|
62
|
+
const limit = socketPathLimit(os);
|
|
63
|
+
const length = Buffer.byteLength(path);
|
|
64
|
+
if (length > limit) {
|
|
65
|
+
throw new RpcError(
|
|
66
|
+
createDiagnostic("MOSTRA_HOME_SOCKET_TOO_LONG", {
|
|
67
|
+
message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,
|
|
68
|
+
fix: { kind: "command", command: "export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER" },
|
|
69
|
+
}),
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
return path;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** What a listener reports besides its clients. */
|
|
76
|
+
export interface ListenOptions {
|
|
77
|
+
/** Starts the pipe's helper (Windows); default: behind a gate, unrecorded. */
|
|
78
|
+
readonly launchPipe?: LaunchPipe;
|
|
79
|
+
/** Receives the listener's errors after it is bound (a socket's `error` events). */
|
|
80
|
+
readonly onError?: (error: unknown) => void;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Binds `endpoint` and calls `onConnection` for every client. */
|
|
84
|
+
export function listenControl(
|
|
85
|
+
endpoint: string,
|
|
86
|
+
onConnection: OnConnection,
|
|
87
|
+
options: ListenOptions = {},
|
|
88
|
+
): Promise<ControlListener> {
|
|
89
|
+
if (WINDOWS) return listenPipe(endpoint, onConnection, options.launchPipe ?? launchPipeDirectly);
|
|
90
|
+
return listenSocket(endpoint, onConnection, options.onError ?? (() => {}));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const PIPE_PREFIX = "\\\\.\\pipe\\";
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Starts the pipe's helper behind its gate without a process manager to record it: for a
|
|
97
|
+
* protocol server outside an instance (the instance always records its helper).
|
|
98
|
+
*/
|
|
99
|
+
const launchPipeDirectly: LaunchPipe = async (name) => {
|
|
100
|
+
const launched = launch(
|
|
101
|
+
{
|
|
102
|
+
kind: "control-pipe",
|
|
103
|
+
command: helperPath(),
|
|
104
|
+
args: ["pipe", name],
|
|
105
|
+
env: process.env,
|
|
106
|
+
extra: "channel",
|
|
107
|
+
},
|
|
108
|
+
() => {},
|
|
109
|
+
);
|
|
110
|
+
const exited = new Promise((resolve) => launched.process.once("exit", resolve));
|
|
111
|
+
await launched.identify();
|
|
112
|
+
launched.release();
|
|
113
|
+
const channel = launched.process.stdio[4] as Duplex | null;
|
|
114
|
+
if (!channel) throw new Error("The control pipe's helper has no channel.");
|
|
115
|
+
return { channel, exited, stop: () => launched.end(2000, []) };
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
async function listenSocket(
|
|
119
|
+
path: string,
|
|
120
|
+
onConnection: OnConnection,
|
|
121
|
+
onError: (error: unknown) => void,
|
|
122
|
+
): Promise<ControlListener> {
|
|
123
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
124
|
+
try {
|
|
125
|
+
unlinkSync(path);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
128
|
+
}
|
|
129
|
+
const server: Server = createServer((socket: Socket) => onConnection(socket));
|
|
130
|
+
await new Promise<void>((resolve, reject) => {
|
|
131
|
+
server.once("error", reject);
|
|
132
|
+
server.listen(path, () => {
|
|
133
|
+
server.off("error", reject);
|
|
134
|
+
resolve();
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
chmodSync(path, 0o600);
|
|
138
|
+
server.on("error", onError);
|
|
139
|
+
const stats: Stats = statSync(path);
|
|
140
|
+
const same = (): boolean => {
|
|
141
|
+
try {
|
|
142
|
+
const current = statSync(path);
|
|
143
|
+
return current.ino === stats.ino && current.dev === stats.dev;
|
|
144
|
+
} catch {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
return {
|
|
149
|
+
path,
|
|
150
|
+
intact: same,
|
|
151
|
+
async close() {
|
|
152
|
+
// Node removes a Unix socket's file when its server closes, even a newer server's file at
|
|
153
|
+
// the same path, so it closes first and removes only its own file.
|
|
154
|
+
const ours = same();
|
|
155
|
+
server.close();
|
|
156
|
+
if (ours) {
|
|
157
|
+
try {
|
|
158
|
+
unlinkSync(path);
|
|
159
|
+
} catch {
|
|
160
|
+
// Already gone.
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The helper's frames: [connection u32 LE][kind u8][length u32 LE][payload].
|
|
168
|
+
const OPEN = 1;
|
|
169
|
+
const DATA = 2;
|
|
170
|
+
const CLOSE = 3;
|
|
171
|
+
const READY = 4;
|
|
172
|
+
const FATAL = 5;
|
|
173
|
+
/** The largest payload the supervisor sends in one frame. */
|
|
174
|
+
const MAX_FRAME = 1 << 20;
|
|
175
|
+
/** How long the helper may take to create the pipe. */
|
|
176
|
+
const READY_MS = 10_000;
|
|
177
|
+
/** How long a closing listener waits for its helper to hand clients their bytes (its own 5 s). */
|
|
178
|
+
const DRAIN_MS = 6000;
|
|
179
|
+
|
|
180
|
+
function frame(connection: number, kind: number, payload?: Uint8Array): Buffer {
|
|
181
|
+
const header = Buffer.alloc(9);
|
|
182
|
+
header.writeUInt32LE(connection, 0);
|
|
183
|
+
header[4] = kind;
|
|
184
|
+
header.writeUInt32LE(payload?.length ?? 0, 5);
|
|
185
|
+
return payload ? Buffer.concat([header, payload]) : header;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function listenPipe(
|
|
189
|
+
base: string,
|
|
190
|
+
onConnection: OnConnection,
|
|
191
|
+
launchPipe: LaunchPipe,
|
|
192
|
+
): Promise<ControlListener> {
|
|
193
|
+
// An endpoint that isn't a pipe name (a socket path a caller chose) names one by its hash.
|
|
194
|
+
const stem = base.startsWith(PIPE_PREFIX)
|
|
195
|
+
? base.slice(PIPE_PREFIX.length)
|
|
196
|
+
: `mostra-${createHash("sha256").update(base).digest("hex").slice(0, 16)}`;
|
|
197
|
+
const name = `${stem}-${randomBytes(8).toString("hex")}`;
|
|
198
|
+
const helper = await launchPipe(name);
|
|
199
|
+
const streams = new Map<number, Duplex>();
|
|
200
|
+
let exited = false;
|
|
201
|
+
let failed = false;
|
|
202
|
+
// Set once READY arrived; a FATAL after it means the listener failed rather than never started.
|
|
203
|
+
let path: string | undefined;
|
|
204
|
+
void helper.exited.then(() => {
|
|
205
|
+
exited = true;
|
|
206
|
+
for (const stream of streams.values()) stream.destroy();
|
|
207
|
+
streams.clear();
|
|
208
|
+
});
|
|
209
|
+
const send = (bytes: Buffer): void => {
|
|
210
|
+
if (!exited && !helper.channel.destroyed) helper.channel.write(bytes);
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const ready = new Promise<string>((resolve, reject) => {
|
|
214
|
+
const timer = setTimeout(
|
|
215
|
+
() => reject(new Error("The control pipe's helper didn't create the pipe in time.")),
|
|
216
|
+
READY_MS,
|
|
217
|
+
);
|
|
218
|
+
let pending: Buffer = Buffer.alloc(0);
|
|
219
|
+
helper.channel.on("data", (chunk: Buffer) => {
|
|
220
|
+
pending = pending.length === 0 ? chunk : Buffer.concat([pending, chunk]);
|
|
221
|
+
while (pending.length >= 9) {
|
|
222
|
+
const length = pending.readUInt32LE(5);
|
|
223
|
+
if (pending.length < 9 + length) break;
|
|
224
|
+
const id = pending.readUInt32LE(0);
|
|
225
|
+
const kind = pending[4];
|
|
226
|
+
const payload = pending.subarray(9, 9 + length);
|
|
227
|
+
pending = pending.subarray(9 + length);
|
|
228
|
+
if (kind === READY) {
|
|
229
|
+
clearTimeout(timer);
|
|
230
|
+
// Recorded here, not after the await: a FATAL in the same chunk must see it.
|
|
231
|
+
path = payload.toString("utf8");
|
|
232
|
+
resolve(path);
|
|
233
|
+
} else if (kind === FATAL) {
|
|
234
|
+
clearTimeout(timer);
|
|
235
|
+
const why = `The control pipe can't be served: ${payload.toString("utf8")}`;
|
|
236
|
+
if (path === undefined) {
|
|
237
|
+
reject(new Error(why));
|
|
238
|
+
} else {
|
|
239
|
+
// Ready earlier, failed since (no further instance could be created): the endpoint
|
|
240
|
+
// is unusable though the helper lives, so the listener is no longer intact and is
|
|
241
|
+
// replaced by the server's next check (D81 item 4).
|
|
242
|
+
failed = true;
|
|
243
|
+
void helper.stop();
|
|
244
|
+
}
|
|
245
|
+
} else if (kind === OPEN) {
|
|
246
|
+
const stream = clientStream(id, send, () => streams.delete(id));
|
|
247
|
+
streams.set(id, stream);
|
|
248
|
+
onConnection(stream);
|
|
249
|
+
} else if (kind === DATA) {
|
|
250
|
+
// A copy: the chunk's buffer is reused by later frames.
|
|
251
|
+
streams.get(id)?.push(Buffer.from(payload));
|
|
252
|
+
} else if (kind === CLOSE) {
|
|
253
|
+
const stream = streams.get(id);
|
|
254
|
+
streams.delete(id);
|
|
255
|
+
if (stream) {
|
|
256
|
+
stream.push(null);
|
|
257
|
+
stream.end();
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
void helper.exited.then(() => {
|
|
263
|
+
clearTimeout(timer);
|
|
264
|
+
reject(new Error("The control pipe's helper exited."));
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
helper.channel.on("error", () => {});
|
|
268
|
+
let bound: string;
|
|
269
|
+
try {
|
|
270
|
+
bound = await ready;
|
|
271
|
+
} catch (error) {
|
|
272
|
+
await helper.stop();
|
|
273
|
+
throw error;
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
path: bound,
|
|
277
|
+
intact: () => !exited && !failed,
|
|
278
|
+
async close() {
|
|
279
|
+
// Every client's stream ends after what it was sent, in order on the one channel; then
|
|
280
|
+
// connection 0's CLOSE asks the helper to hand all of it over and exit (at most its 5 s
|
|
281
|
+
// drain). Only a helper that doesn't is stopped, which ends its job.
|
|
282
|
+
for (const stream of streams.values()) stream.end();
|
|
283
|
+
if (!exited) send(frame(0, CLOSE));
|
|
284
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
285
|
+
await Promise.race([
|
|
286
|
+
helper.exited,
|
|
287
|
+
new Promise<void>((resolve) => {
|
|
288
|
+
timer = setTimeout(resolve, DRAIN_MS);
|
|
289
|
+
}),
|
|
290
|
+
]);
|
|
291
|
+
clearTimeout(timer);
|
|
292
|
+
for (const stream of streams.values()) stream.destroy();
|
|
293
|
+
streams.clear();
|
|
294
|
+
await helper.stop();
|
|
295
|
+
},
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** One client's stream over the helper's channel. */
|
|
300
|
+
function clientStream(id: number, send: (bytes: Buffer) => void, forget: () => void): Duplex {
|
|
301
|
+
let closed = false;
|
|
302
|
+
const close = (): void => {
|
|
303
|
+
if (closed) return;
|
|
304
|
+
closed = true;
|
|
305
|
+
forget();
|
|
306
|
+
send(frame(id, CLOSE));
|
|
307
|
+
};
|
|
308
|
+
return new Duplex({
|
|
309
|
+
read() {},
|
|
310
|
+
write(chunk: Buffer, _encoding, callback) {
|
|
311
|
+
for (let offset = 0; offset < chunk.length; offset += MAX_FRAME) {
|
|
312
|
+
send(frame(id, DATA, chunk.subarray(offset, offset + MAX_FRAME)));
|
|
313
|
+
}
|
|
314
|
+
callback();
|
|
315
|
+
},
|
|
316
|
+
final(callback) {
|
|
317
|
+
close();
|
|
318
|
+
callback();
|
|
319
|
+
},
|
|
320
|
+
destroy(error, callback) {
|
|
321
|
+
close();
|
|
322
|
+
callback(error);
|
|
323
|
+
},
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Why a client couldn't open a control endpoint. */
|
|
328
|
+
export class ControlConnectError extends Error {
|
|
329
|
+
/** `unreachable` (nothing serves it, or it timed out) or `not-owned` (another user's pipe). */
|
|
330
|
+
readonly reason: "unreachable" | "not-owned";
|
|
331
|
+
constructor(reason: "unreachable" | "not-owned", message: string) {
|
|
332
|
+
super(message);
|
|
333
|
+
this.name = "ControlConnectError";
|
|
334
|
+
this.reason = reason;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Connects to a home's control endpoint as a client. On Windows through `mostra-win connect`,
|
|
340
|
+
* which refuses a pipe another user created under the name (an old name `instance.json` still
|
|
341
|
+
* names may be free for anyone to take), and never lets the server act as this process: Node.js
|
|
342
|
+
* can check neither (Opus review of WP-W1). Rejects with a {@link ControlConnectError}.
|
|
343
|
+
*/
|
|
344
|
+
export function connectControl(endpoint: string, timeoutMs = 5000): Promise<Duplex> {
|
|
345
|
+
return WINDOWS ? connectPipe(endpoint, timeoutMs) : connectSocket(endpoint, timeoutMs);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function connectSocket(path: string, timeoutMs: number): Promise<Duplex> {
|
|
349
|
+
return new Promise((resolve, reject) => {
|
|
350
|
+
const socket: Socket = createConnection(path);
|
|
351
|
+
const timer = setTimeout(() => {
|
|
352
|
+
socket.destroy();
|
|
353
|
+
reject(new ControlConnectError("unreachable", "timed out"));
|
|
354
|
+
}, timeoutMs);
|
|
355
|
+
socket.once("error", (error: NodeJS.ErrnoException) => {
|
|
356
|
+
clearTimeout(timer);
|
|
357
|
+
reject(new ControlConnectError("unreachable", error.code ?? "failed"));
|
|
358
|
+
});
|
|
359
|
+
socket.once("connect", () => {
|
|
360
|
+
clearTimeout(timer);
|
|
361
|
+
resolve(socket);
|
|
362
|
+
});
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function connectPipe(endpoint: string, timeoutMs: number): Promise<Duplex> {
|
|
367
|
+
const name = endpoint.startsWith(PIPE_PREFIX) ? endpoint.slice(PIPE_PREFIX.length) : endpoint;
|
|
368
|
+
return new Promise((resolve, reject) => {
|
|
369
|
+
const child = spawn(helperPath(), ["connect", name], {
|
|
370
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
371
|
+
windowsHide: true,
|
|
372
|
+
});
|
|
373
|
+
let settled = false;
|
|
374
|
+
const fail = (reason: "unreachable" | "not-owned", message: string): void => {
|
|
375
|
+
if (settled) return;
|
|
376
|
+
settled = true;
|
|
377
|
+
clearTimeout(timer);
|
|
378
|
+
child.kill();
|
|
379
|
+
reject(new ControlConnectError(reason, message));
|
|
380
|
+
};
|
|
381
|
+
const timer = setTimeout(() => fail("unreachable", "timed out"), timeoutMs);
|
|
382
|
+
child.once("error", (error) => fail("unreachable", error.message));
|
|
383
|
+
child.once("exit", (code) => fail(code === 3 ? "not-owned" : "unreachable", `exit ${code}`));
|
|
384
|
+
let text = "";
|
|
385
|
+
child.stderr.setEncoding("utf8");
|
|
386
|
+
child.stderr.on("data", (chunk: string) => {
|
|
387
|
+
if (settled) return;
|
|
388
|
+
text += chunk;
|
|
389
|
+
const end = text.indexOf("\n");
|
|
390
|
+
if (end < 0) return;
|
|
391
|
+
let line: { connected?: boolean; code?: string; error?: string } = {};
|
|
392
|
+
try {
|
|
393
|
+
line = JSON.parse(text.slice(0, end)) as typeof line;
|
|
394
|
+
} catch {
|
|
395
|
+
// Treated as a failure below.
|
|
396
|
+
}
|
|
397
|
+
if (line.connected !== true) {
|
|
398
|
+
fail(
|
|
399
|
+
line.code === "not-owned" ? "not-owned" : "unreachable",
|
|
400
|
+
line.error ?? text.slice(0, end),
|
|
401
|
+
);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
settled = true;
|
|
405
|
+
clearTimeout(timer);
|
|
406
|
+
resolve(Duplex.from({ readable: child.stdout, writable: child.stdin }));
|
|
407
|
+
});
|
|
408
|
+
});
|
|
409
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a home and its control endpoint live on each operating system, and how a directory is
|
|
3
|
+
* made owner-only (DATA_MODEL §1; D82, D84, D85; RT-10). Resolving a path never touches the file
|
|
4
|
+
* system; `ownedDirectory` creates or checks one.
|
|
5
|
+
*
|
|
6
|
+
* - macOS: the home defaults to `~/.mostra`, the runtime directory to `~/.mostra/run`.
|
|
7
|
+
* - Linux: `${XDG_DATA_HOME:-~/.local/share}/mostra`; `$XDG_RUNTIME_DIR/mostra` when that
|
|
8
|
+
* directory is the user's and private, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`.
|
|
9
|
+
* - Windows: `%LOCALAPPDATA%\mostra`. The control endpoint is a named pipe, which lives in no
|
|
10
|
+
* directory, so there is no runtime directory and `MOSTRA_RUNTIME_DIR` doesn't apply.
|
|
11
|
+
*
|
|
12
|
+
* Owner-only means mode 0700 on POSIX, and on Windows a protected access list that grants only the
|
|
13
|
+
* user and `SYSTEM`, inherited by everything inside (the helper's `secure-dir`).
|
|
14
|
+
*/
|
|
15
|
+
import { chmodSync, mkdirSync, realpathSync, statSync } from "node:fs";
|
|
16
|
+
import { posix, win32 } from "node:path";
|
|
17
|
+
import { createDiagnostic, RpcError } from "@mostra/protocol";
|
|
18
|
+
import { runHelper } from "./helper.ts";
|
|
19
|
+
|
|
20
|
+
/** The operating systems the runtime knows. */
|
|
21
|
+
export type OperatingSystem = "darwin" | "linux" | "win32" | (string & {});
|
|
22
|
+
|
|
23
|
+
/** The operating system this process runs on. Every other module asks here. */
|
|
24
|
+
export const OS: OperatingSystem = process.platform;
|
|
25
|
+
|
|
26
|
+
/** Whether this process runs on Windows. */
|
|
27
|
+
export const WINDOWS: boolean = OS === "win32";
|
|
28
|
+
|
|
29
|
+
type Environment = Readonly<Record<string, string | undefined>>;
|
|
30
|
+
|
|
31
|
+
const nonEmpty = (value: string | undefined): string | undefined =>
|
|
32
|
+
value === undefined || value === "" ? undefined : value;
|
|
33
|
+
|
|
34
|
+
/** The path rules of an operating system, so resolution for another one can be computed and tested. */
|
|
35
|
+
export function pathsOf(os: OperatingSystem): typeof posix {
|
|
36
|
+
return os === "win32" ? win32 : posix;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The home a platform uses when neither `--home` nor `MOSTRA_HOME` names one. */
|
|
40
|
+
export function defaultHome(os: OperatingSystem, env: Environment, userHome: string): string {
|
|
41
|
+
if (os === "darwin") return posix.join(userHome, ".mostra");
|
|
42
|
+
if (os === "win32") {
|
|
43
|
+
const local = nonEmpty(env["LOCALAPPDATA"]);
|
|
44
|
+
return win32.join(
|
|
45
|
+
local !== undefined && win32.isAbsolute(local)
|
|
46
|
+
? local
|
|
47
|
+
: win32.join(userHome, "AppData", "Local"),
|
|
48
|
+
"mostra",
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
const data = nonEmpty(env["XDG_DATA_HOME"]);
|
|
52
|
+
return posix.join(
|
|
53
|
+
data !== undefined && posix.isAbsolute(data) ? data : posix.join(userHome, ".local", "share"),
|
|
54
|
+
"mostra",
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** What the runtime directory resolution decided, and why. */
|
|
59
|
+
export interface RuntimeDirChoice {
|
|
60
|
+
readonly dir: string;
|
|
61
|
+
/** `override` (MOSTRA_RUNTIME_DIR), `xdg` (the safe XDG runtime directory) or `fallback`. */
|
|
62
|
+
readonly source: "override" | "xdg" | "fallback";
|
|
63
|
+
/** Why `$XDG_RUNTIME_DIR` wasn't used, when it was set. */
|
|
64
|
+
readonly rejected?: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The runtime directory for control sockets (D82), or `undefined` on Windows, whose control pipe
|
|
69
|
+
* lives in the system's pipe namespace.
|
|
70
|
+
*/
|
|
71
|
+
export function runtimeDirFor(inputs: {
|
|
72
|
+
readonly os: OperatingSystem;
|
|
73
|
+
readonly env: Environment;
|
|
74
|
+
readonly userHome: string;
|
|
75
|
+
readonly cwd: string;
|
|
76
|
+
}): RuntimeDirChoice | undefined {
|
|
77
|
+
if (inputs.os === "win32") return undefined;
|
|
78
|
+
const override = nonEmpty(inputs.env["MOSTRA_RUNTIME_DIR"]);
|
|
79
|
+
if (override !== undefined)
|
|
80
|
+
return { dir: posix.resolve(inputs.cwd, override), source: "override" };
|
|
81
|
+
if (inputs.os === "darwin")
|
|
82
|
+
return { dir: posix.join(inputs.userHome, ".mostra", "run"), source: "fallback" };
|
|
83
|
+
const xdg = nonEmpty(inputs.env["XDG_RUNTIME_DIR"]);
|
|
84
|
+
let rejected: string | undefined;
|
|
85
|
+
if (xdg !== undefined) {
|
|
86
|
+
rejected = unsafeXdgRuntimeDir(xdg);
|
|
87
|
+
if (rejected === undefined) return { dir: posix.join(xdg, "mostra"), source: "xdg" };
|
|
88
|
+
}
|
|
89
|
+
const state = nonEmpty(inputs.env["XDG_STATE_HOME"]);
|
|
90
|
+
const base =
|
|
91
|
+
state !== undefined && posix.isAbsolute(state)
|
|
92
|
+
? state
|
|
93
|
+
: posix.join(inputs.userHome, ".local", "state");
|
|
94
|
+
const dir = posix.join(base, "mostra", "run");
|
|
95
|
+
return rejected === undefined
|
|
96
|
+
? { dir, source: "fallback" }
|
|
97
|
+
: { dir, source: "fallback", rejected };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The current user's ID on POSIX. */
|
|
101
|
+
function uid(): number {
|
|
102
|
+
return process.getuid?.() ?? -1;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */
|
|
106
|
+
function unsafeXdgRuntimeDir(dir: string): string | undefined {
|
|
107
|
+
if (!posix.isAbsolute(dir)) return "it isn't an absolute path";
|
|
108
|
+
let stats: ReturnType<typeof statSync>;
|
|
109
|
+
try {
|
|
110
|
+
stats = statSync(dir);
|
|
111
|
+
} catch {
|
|
112
|
+
return "it doesn't exist";
|
|
113
|
+
}
|
|
114
|
+
if (!stats.isDirectory()) return "it isn't a directory";
|
|
115
|
+
if (stats.uid !== uid()) return "another user owns it";
|
|
116
|
+
if ((stats.mode & 0o077) !== 0) return "other users can access it";
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */
|
|
121
|
+
export function socketPathLimit(os: OperatingSystem): number {
|
|
122
|
+
return os === "darwin" ? 103 : 107;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The outcome of {@link ownedDirectory}. */
|
|
126
|
+
export interface PreparedDirectory {
|
|
127
|
+
/** The directory's real path. */
|
|
128
|
+
readonly realPath: string;
|
|
129
|
+
/** Whether Mostra created it. */
|
|
130
|
+
readonly created: boolean;
|
|
131
|
+
/**
|
|
132
|
+
* What it allowed before Mostra made it owner-only, when it did: the octal mode on POSIX, the
|
|
133
|
+
* security descriptor (SDDL) on Windows.
|
|
134
|
+
*/
|
|
135
|
+
readonly tightenedFrom?: string;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function notOwned(path: string, why: string): RpcError {
|
|
139
|
+
return new RpcError(
|
|
140
|
+
createDiagnostic("MOSTRA_HOME_NOT_OWNED", { message: `Mostra can't use ${path}: ${why}.` }),
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Makes `path` a directory only its owner can use (D85): creates it owner-only when missing,
|
|
146
|
+
* tightens one the user owns, and throws `MOSTRA_HOME_NOT_OWNED` for one owned by another user or
|
|
147
|
+
* a path that isn't a directory. Symlinks are followed.
|
|
148
|
+
*/
|
|
149
|
+
export function ownedDirectory(path: string): PreparedDirectory {
|
|
150
|
+
if (WINDOWS) return ownedDirectoryWindows(path);
|
|
151
|
+
try {
|
|
152
|
+
return preparePosix(path);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
155
|
+
if (code === "ENOTDIR" || code === "EEXIST")
|
|
156
|
+
throw notOwned(path, "a part of the path isn't a directory");
|
|
157
|
+
if (code === "EACCES" || code === "EPERM")
|
|
158
|
+
throw notOwned(path, "you have no permission to use it");
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function preparePosix(path: string): PreparedDirectory {
|
|
164
|
+
let created = false;
|
|
165
|
+
try {
|
|
166
|
+
statSync(path);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
169
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
170
|
+
created = true;
|
|
171
|
+
}
|
|
172
|
+
const realPath = realpathSync(path);
|
|
173
|
+
const stats = statSync(realPath);
|
|
174
|
+
if (!stats.isDirectory()) throw notOwned(path, "it isn't a directory");
|
|
175
|
+
if (stats.uid !== uid()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);
|
|
176
|
+
const mode = stats.mode & 0o777;
|
|
177
|
+
if (mode !== 0o700) {
|
|
178
|
+
chmodSync(realPath, 0o700);
|
|
179
|
+
return created ? { realPath, created } : { realPath, created, tightenedFrom: mode.toString(8) };
|
|
180
|
+
}
|
|
181
|
+
return { realPath, created };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
type Secured =
|
|
185
|
+
| { readonly secured: "created" | "kept" }
|
|
186
|
+
| { readonly secured: "tightened"; readonly from: string }
|
|
187
|
+
| { readonly refused: "not-owned"; readonly owner: string }
|
|
188
|
+
| { readonly refused: "not-directory" };
|
|
189
|
+
|
|
190
|
+
function ownedDirectoryWindows(path: string): PreparedDirectory {
|
|
191
|
+
let answer: Secured;
|
|
192
|
+
try {
|
|
193
|
+
answer = runHelper<Secured>(["secure-dir", path]);
|
|
194
|
+
} catch (error) {
|
|
195
|
+
// Access denied while creating or reading it: someone else's directory, or one above it.
|
|
196
|
+
if ((error as { os?: number }).os === 5)
|
|
197
|
+
throw notOwned(path, "you have no permission to use it");
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
if ("refused" in answer) {
|
|
201
|
+
throw notOwned(
|
|
202
|
+
path,
|
|
203
|
+
answer.refused === "not-owned"
|
|
204
|
+
? `it belongs to ${answer.owner}, not to you`
|
|
205
|
+
: "it isn't a directory",
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
const realPath = realpathSync.native(path);
|
|
209
|
+
if (answer.secured === "tightened")
|
|
210
|
+
return { realPath, created: false, tightenedFrom: answer.from };
|
|
211
|
+
return { realPath, created: answer.secured === "created" };
|
|
212
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The smallest environment a child can run in (the builder's): `PATH`, `HOME` and `TMPDIR` on
|
|
3
|
+
* POSIX. Windows programs need more of what Windows itself gives every program (without
|
|
4
|
+
* `SystemRoot` Node.js can't load its cryptography, without `TEMP` it has no temporary folder),
|
|
5
|
+
* and Windows compares variable names without case, so they are found that way.
|
|
6
|
+
*/
|
|
7
|
+
import { WINDOWS } from "./directories.ts";
|
|
8
|
+
|
|
9
|
+
type Environment = Readonly<Record<string, string | undefined>>;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What Windows itself gives every program and programs rely on, besides `Path`: the system's
|
|
13
|
+
* directories, the user's profile folders, the shell and how it finds programs, who the user is
|
|
14
|
+
* and the processor. None names a secret. The one list both the base and the artifact environment
|
|
15
|
+
* pass on Windows (`processes/environment.ts`).
|
|
16
|
+
*/
|
|
17
|
+
export const WINDOWS_SYSTEM_VARIABLES: readonly string[] = [
|
|
18
|
+
"SystemRoot",
|
|
19
|
+
"SystemDrive",
|
|
20
|
+
"windir",
|
|
21
|
+
"ComSpec",
|
|
22
|
+
"PATHEXT",
|
|
23
|
+
"TEMP",
|
|
24
|
+
"TMP",
|
|
25
|
+
"USERPROFILE",
|
|
26
|
+
"HOMEDRIVE",
|
|
27
|
+
"HOMEPATH",
|
|
28
|
+
"APPDATA",
|
|
29
|
+
"LOCALAPPDATA",
|
|
30
|
+
"ProgramData",
|
|
31
|
+
"ProgramFiles",
|
|
32
|
+
"ProgramFiles(x86)",
|
|
33
|
+
"ProgramW6432",
|
|
34
|
+
"CommonProgramFiles",
|
|
35
|
+
"CommonProgramFiles(x86)",
|
|
36
|
+
"CommonProgramW6432",
|
|
37
|
+
"USERNAME",
|
|
38
|
+
"USERDOMAIN",
|
|
39
|
+
"COMPUTERNAME",
|
|
40
|
+
"OS",
|
|
41
|
+
"NUMBER_OF_PROCESSORS",
|
|
42
|
+
"PROCESSOR_ARCHITECTURE",
|
|
43
|
+
"PROCESSOR_IDENTIFIER",
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
const WINDOWS_BASE = ["Path", ...WINDOWS_SYSTEM_VARIABLES];
|
|
47
|
+
|
|
48
|
+
/** The base environment of a child, from the supervisor's `env`. */
|
|
49
|
+
export function baseEnvironment(env: Environment): Record<string, string> {
|
|
50
|
+
if (!WINDOWS) {
|
|
51
|
+
return {
|
|
52
|
+
PATH: env["PATH"] ?? "/usr/bin:/bin",
|
|
53
|
+
HOME: env["HOME"] ?? "/",
|
|
54
|
+
...(env["TMPDIR"] ? { TMPDIR: env["TMPDIR"] } : {}),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
const byName = new Map(Object.entries(env).map(([name, value]) => [name.toUpperCase(), value]));
|
|
58
|
+
const result: Record<string, string> = {};
|
|
59
|
+
for (const name of WINDOWS_BASE) {
|
|
60
|
+
const value = byName.get(name.toUpperCase());
|
|
61
|
+
if (value !== undefined) result[name] = value;
|
|
62
|
+
}
|
|
63
|
+
return result;
|
|
64
|
+
}
|