@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
package/src/gateway/index.ts
CHANGED
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
type Diagnostic,
|
|
31
31
|
durationMs,
|
|
32
32
|
type FrameTicket,
|
|
33
|
+
type IdentityVia,
|
|
33
34
|
type Refusal,
|
|
34
35
|
RpcError,
|
|
35
36
|
refusal,
|
|
@@ -76,6 +77,7 @@ import {
|
|
|
76
77
|
refusalResponse,
|
|
77
78
|
sessionCookie,
|
|
78
79
|
} from "./http.ts";
|
|
80
|
+
import type { IdentityOutcome } from "./identity.ts";
|
|
79
81
|
import { versionIntegrity } from "./integrity.ts";
|
|
80
82
|
import { createListener, type Listener } from "./listener.ts";
|
|
81
83
|
import { type ListenerChecks, mount, type RouteContext, type RouteSpec, refuse } from "./routes.ts";
|
|
@@ -84,6 +86,7 @@ import { fileResponse, findFile } from "./serve.ts";
|
|
|
84
86
|
export { Capabilities, capabilityKey } from "./capabilities.ts";
|
|
85
87
|
export { CONTROLS_POLICY_TIMEOUT_MS, controlsPolicy } from "./controls.ts";
|
|
86
88
|
export type { DevUpstream } from "./dev.ts";
|
|
89
|
+
export { IDENTITY_TIMEOUT_MS, resolveIdentity } from "./identity.ts";
|
|
87
90
|
|
|
88
91
|
/** What the gateway reads about artifacts and versions. */
|
|
89
92
|
export interface GatewayArtifacts {
|
|
@@ -113,6 +116,15 @@ export interface GatewayOptions {
|
|
|
113
116
|
readonly controls: (artifact: ArtifactDetail) => Promise<ControlsPolicy>;
|
|
114
117
|
/** Tells hosts with a `trustedControls` port that a trusted control was used (D108). */
|
|
115
118
|
readonly activated: BrowserRoutesOptions["activated"];
|
|
119
|
+
/**
|
|
120
|
+
* Who a browser is that exchanges a link minted without a viewer (D143 item 2): the person a
|
|
121
|
+
* host's identity port names, the standalone default, or a refusal. Absent: the default.
|
|
122
|
+
*/
|
|
123
|
+
readonly identity?: (input: {
|
|
124
|
+
readonly artifactId: string;
|
|
125
|
+
readonly via: IdentityVia;
|
|
126
|
+
readonly headers: Headers;
|
|
127
|
+
}) => Promise<IdentityOutcome>;
|
|
116
128
|
/** The browser-protocol revisions served; `BROWSER_PROTOCOL_REVISIONS` unless a test adds one. */
|
|
117
129
|
readonly revisions?: readonly string[];
|
|
118
130
|
/**
|
|
@@ -434,15 +446,32 @@ export function createGateway(options: GatewayOptions): Gateway {
|
|
|
434
446
|
return { artifact: { id: detail.id, title: detail.title }, ...access(grant) };
|
|
435
447
|
};
|
|
436
448
|
|
|
449
|
+
/**
|
|
450
|
+
* The sessions exchanges made, by artifact and browser (the shell's own random key, kept in its
|
|
451
|
+
* origin's storage and sent with every exchange), each with the order it was made in. An
|
|
452
|
+
* exchange that waited (the identity port answering) checks here whether another link's
|
|
453
|
+
* session was made for the same browser meanwhile: its request carried no cookie of that session,
|
|
454
|
+
* so D98 item 8's check alone would let the later answer silently replace it (Opus review of
|
|
455
|
+
* WP-12, finding 2). Only the last few thousand are kept; the window that matters is seconds.
|
|
456
|
+
*/
|
|
457
|
+
const madeSessions = new Map<string, { readonly order: number; readonly grant: Grant }>();
|
|
458
|
+
let exchangeOrder = 0;
|
|
459
|
+
const browserKey = (artifactId: string, browser: unknown): string | undefined =>
|
|
460
|
+
typeof browser === "string" && /^[A-Za-z0-9_-]{16,64}$/.test(browser)
|
|
461
|
+
? `${artifactId}\u0000${browser}`
|
|
462
|
+
: undefined;
|
|
463
|
+
|
|
437
464
|
const exchange = async (context: RouteContext): Promise<Response> => {
|
|
438
465
|
const artifactId = context.artifactId as string;
|
|
466
|
+
const startedAt = exchangeOrder;
|
|
439
467
|
const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
|
|
440
468
|
const body = await readJsonObject(context.request);
|
|
441
469
|
if (isRefusal(body)) return refuse(shellChecks, body, meta);
|
|
442
470
|
// A link's token, or a one-time launch ticket from `mostra open` (D140 item 15), which is
|
|
443
471
|
// spent only once it started (or reused) a session.
|
|
444
472
|
const launch = body["token"] === undefined && body["launch"] !== undefined;
|
|
445
|
-
const
|
|
473
|
+
const browser = browserKey(artifactId, body["browser"]);
|
|
474
|
+
let grant = launch
|
|
446
475
|
? capabilities.presentLaunch(body["launch"], artifactId, false)
|
|
447
476
|
: capabilities.presentToken(body["token"], artifactId);
|
|
448
477
|
if (isRefusal(grant)) return refuse(shellChecks, grant, meta);
|
|
@@ -473,8 +502,61 @@ export function createGateway(options: GatewayOptions): Gateway {
|
|
|
473
502
|
);
|
|
474
503
|
}
|
|
475
504
|
}
|
|
476
|
-
|
|
477
|
-
|
|
505
|
+
// A link without a viewer acts for whoever the host's identity port names (D143 item 2);
|
|
506
|
+
// a host that took identity over and can't answer refuses the link, never a guess.
|
|
507
|
+
let viewerId: string | undefined;
|
|
508
|
+
if (grant.viewerId === undefined && options.identity) {
|
|
509
|
+
const outcome = await options.identity({
|
|
510
|
+
artifactId,
|
|
511
|
+
via: "local",
|
|
512
|
+
headers: context.request.headers,
|
|
513
|
+
});
|
|
514
|
+
if (outcome.kind === "unavailable") {
|
|
515
|
+
log.warn("gateway.session_refused", { artifactId, code: outcome.diagnostic.code });
|
|
516
|
+
return jsonResponse(outcome.diagnostic, { status: 503 });
|
|
517
|
+
}
|
|
518
|
+
if (outcome.kind === "person") viewerId = interaction.viewerForHost(outcome.viewer);
|
|
519
|
+
}
|
|
520
|
+
// Everything is judged again after the await, in one synchronous step with the session's
|
|
521
|
+
// creation: a link revoked or expired meanwhile gets no session (Opus review of WP-12,
|
|
522
|
+
// finding 3), and a launch ticket is spent here, so it opens one session however many
|
|
523
|
+
// exchanges presented it while the identity port answered (GPT review finding 1).
|
|
524
|
+
const now = launch
|
|
525
|
+
? capabilities.presentLaunch(body["launch"], artifactId, true)
|
|
526
|
+
: capabilities.presentToken(body["token"], artifactId);
|
|
527
|
+
if (isRefusal(now)) return refuse(shellChecks, now, meta);
|
|
528
|
+
grant = now;
|
|
529
|
+
const made = browser === undefined ? undefined : madeSessions.get(browser);
|
|
530
|
+
if (
|
|
531
|
+
made !== undefined &&
|
|
532
|
+
made.order > startedAt &&
|
|
533
|
+
made.grant.tokenId !== grant.tokenId &&
|
|
534
|
+
body["replace"] !== true
|
|
535
|
+
) {
|
|
536
|
+
log.info("gateway.session_conflict", { artifactId, origin: shellOrigin() });
|
|
537
|
+
return jsonResponse(
|
|
538
|
+
{
|
|
539
|
+
...refusal(
|
|
540
|
+
"MOSTRA_HYGIENE_SESSION_CONFLICT",
|
|
541
|
+
"This browser already has this artifact open from another link.",
|
|
542
|
+
).diagnostic,
|
|
543
|
+
current: access(made.grant),
|
|
544
|
+
offered: access(grant),
|
|
545
|
+
},
|
|
546
|
+
{ status: 409 },
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
const session = capabilities.createSession({
|
|
550
|
+
tokenId: grant.tokenId,
|
|
551
|
+
origin: shellOrigin(),
|
|
552
|
+
viewerId,
|
|
553
|
+
});
|
|
554
|
+
if (browser !== undefined) {
|
|
555
|
+
exchangeOrder += 1;
|
|
556
|
+
madeSessions.delete(browser);
|
|
557
|
+
madeSessions.set(browser, { order: exchangeOrder, grant });
|
|
558
|
+
if (madeSessions.size > 4096) madeSessions.delete(madeSessions.keys().next().value as string);
|
|
559
|
+
}
|
|
478
560
|
log.info("gateway.session_started", {
|
|
479
561
|
origin: shellOrigin(),
|
|
480
562
|
artifactId,
|
|
@@ -566,11 +648,12 @@ export function createGateway(options: GatewayOptions): Gateway {
|
|
|
566
648
|
origin: artifactOrigin,
|
|
567
649
|
shellOrigin: shellOrigin(),
|
|
568
650
|
shellSessionId: session.id,
|
|
651
|
+
viewerId: session.viewerId,
|
|
569
652
|
});
|
|
570
653
|
// One frame load is one view, of exactly this version, by this link's viewer (D104), with
|
|
571
654
|
// the channels and controls in force for it (D108).
|
|
572
655
|
const controls = await options.controls(detail);
|
|
573
|
-
const viewerId = interaction.viewerOf(session.
|
|
656
|
+
const viewerId = interaction.viewerOf(session.viewerId);
|
|
574
657
|
const viewId = interaction.openView({
|
|
575
658
|
artifactId,
|
|
576
659
|
versionId: version.id,
|
|
@@ -732,13 +815,20 @@ export function createGateway(options: GatewayOptions): Gateway {
|
|
|
732
815
|
origin(),
|
|
733
816
|
artifactId,
|
|
734
817
|
);
|
|
735
|
-
|
|
818
|
+
// The frame acts as its shell session's viewer (D143 item 2): a session of the same link
|
|
819
|
+
// for someone else (the identity port named another person) is never reused.
|
|
820
|
+
if (
|
|
821
|
+
!isRefusal(existing) &&
|
|
822
|
+
existing.grant.tokenId === redeemed.tokenId &&
|
|
823
|
+
existing.viewerId === redeemed.viewerId
|
|
824
|
+
) {
|
|
736
825
|
capabilities.enterVersion(existing.id, redeemed.versionId);
|
|
737
826
|
} else {
|
|
738
827
|
const session = capabilities.createSession({
|
|
739
828
|
tokenId: redeemed.tokenId,
|
|
740
829
|
origin: origin(),
|
|
741
830
|
versionId: redeemed.versionId,
|
|
831
|
+
viewerId: redeemed.viewerId,
|
|
742
832
|
});
|
|
743
833
|
headers["set-cookie"] = sessionCookie(
|
|
744
834
|
checks().cookieName(),
|
|
@@ -767,7 +857,7 @@ export function createGateway(options: GatewayOptions): Gateway {
|
|
|
767
857
|
scopes: session.grant.scopes,
|
|
768
858
|
// The viewer the page acts as, so edits made before its first snapshot are journaled
|
|
769
859
|
// under it (WP-07; Claude review finding 4).
|
|
770
|
-
viewer: interaction.viewer(interaction.viewerOf(session.
|
|
860
|
+
viewer: interaction.viewer(interaction.viewerOf(session.viewerId)),
|
|
771
861
|
...(version ? { version: { id: version.id, number: version.number } } : {}),
|
|
772
862
|
});
|
|
773
863
|
};
|
package/src/home/acquire.ts
CHANGED
|
@@ -57,8 +57,13 @@ export interface AcquireHomeOptions {
|
|
|
57
57
|
export interface OwnedHome {
|
|
58
58
|
/** The home's real path. */
|
|
59
59
|
readonly path: string;
|
|
60
|
+
/**
|
|
61
|
+
* The control endpoint's base: the socket path on POSIX; on Windows the pipe name each bind
|
|
62
|
+
* completes. `instance.json` records the endpoint actually bound.
|
|
63
|
+
*/
|
|
60
64
|
readonly socketPath: string;
|
|
61
|
-
|
|
65
|
+
/** The runtime directory; `undefined` on Windows, which has none. */
|
|
66
|
+
readonly runtimeDir: RuntimeDirChoice | undefined;
|
|
62
67
|
readonly ledger: Ledger;
|
|
63
68
|
readonly log: Log;
|
|
64
69
|
/** Removes secrets and capability material from everything the instance logs or reports. */
|
|
@@ -67,8 +72,8 @@ export interface OwnedHome {
|
|
|
67
72
|
readonly self: { readonly pid: number; readonly startTime: string };
|
|
68
73
|
/** When this process took the home (RFC 3339). */
|
|
69
74
|
readonly startedAt: string;
|
|
70
|
-
/** Writes `instance.json
|
|
71
|
-
publish(mode: "host" | "daemon"): void;
|
|
75
|
+
/** Writes `instance.json` naming the bound endpoint; call it once it listens, and again when it moves. */
|
|
76
|
+
publish(mode: "host" | "daemon", socket: string): void;
|
|
72
77
|
/**
|
|
73
78
|
* Calls `onGone` once with `MOSTRA_HOME_GONE` if the home or its ledger disappears or is
|
|
74
79
|
* replaced. Checks every `intervalMs`, at most 10 s.
|
|
@@ -107,9 +112,15 @@ export async function acquireHome(options: AcquireHomeOptions): Promise<HomeAcqu
|
|
|
107
112
|
const home = prepared.realPath;
|
|
108
113
|
const runtimeDir = resolveRuntimeDir({ env: options.env });
|
|
109
114
|
// Check the length before creating anything in the runtime directory, then again with its real
|
|
110
|
-
// path, which is the one bound (on macOS, /tmp is /private/tmp).
|
|
111
|
-
|
|
112
|
-
|
|
115
|
+
// path, which is the one bound (on macOS, /tmp is /private/tmp). Windows has no runtime
|
|
116
|
+
// directory: its control pipe lives in the system's pipe namespace.
|
|
117
|
+
let socketPath: string;
|
|
118
|
+
if (runtimeDir === undefined) {
|
|
119
|
+
socketPath = socketPathFor(undefined, home);
|
|
120
|
+
} else {
|
|
121
|
+
socketPathFor(runtimeDir.dir, home);
|
|
122
|
+
socketPath = socketPathFor(prepareOwnedDirectory(runtimeDir.dir).realPath, home);
|
|
123
|
+
}
|
|
113
124
|
const redactor = new Redactor();
|
|
114
125
|
redactor.protectEnvironment(options.env);
|
|
115
126
|
const log = openFileLog({
|
|
@@ -118,9 +129,9 @@ export async function acquireHome(options: AcquireHomeOptions): Promise<HomeAcqu
|
|
|
118
129
|
...(options.mirror ? { mirror: options.mirror } : {}),
|
|
119
130
|
});
|
|
120
131
|
if (prepared.tightenedFrom !== undefined) {
|
|
121
|
-
log.warn("home.tightened", { home, from: prepared.tightenedFrom
|
|
132
|
+
log.warn("home.tightened", { home, from: prepared.tightenedFrom, to: "owner only" });
|
|
122
133
|
}
|
|
123
|
-
if (runtimeDir
|
|
134
|
+
if (runtimeDir?.rejected !== undefined) {
|
|
124
135
|
log.warn("home.xdg_runtime_dir_rejected", {
|
|
125
136
|
reason: runtimeDir.rejected,
|
|
126
137
|
using: runtimeDir.dir,
|
|
@@ -194,8 +205,13 @@ export async function acquireHome(options: AcquireHomeOptions): Promise<HomeAcqu
|
|
|
194
205
|
|
|
195
206
|
interface OwnInputs {
|
|
196
207
|
readonly home: string;
|
|
208
|
+
/**
|
|
209
|
+
* The control endpoint's base: the socket path on POSIX; on Windows the pipe name each bind
|
|
210
|
+
* completes. `instance.json` records the endpoint actually bound.
|
|
211
|
+
*/
|
|
197
212
|
readonly socketPath: string;
|
|
198
|
-
|
|
213
|
+
/** The runtime directory; `undefined` on Windows, which has none. */
|
|
214
|
+
readonly runtimeDir: RuntimeDirChoice | undefined;
|
|
199
215
|
readonly ledger: Ledger;
|
|
200
216
|
readonly log: Log;
|
|
201
217
|
readonly redactor: Redactor;
|
|
@@ -228,11 +244,11 @@ function own(inputs: OwnInputs): OwnedHome {
|
|
|
228
244
|
redactor,
|
|
229
245
|
self,
|
|
230
246
|
startedAt,
|
|
231
|
-
publish(mode) {
|
|
247
|
+
publish(mode, socket) {
|
|
232
248
|
writeInstanceRecord(home, {
|
|
233
249
|
pid: self.pid,
|
|
234
250
|
startTime: self.startTime,
|
|
235
|
-
socket
|
|
251
|
+
socket,
|
|
236
252
|
runtimeVersion: inputs.options.runtimeVersion,
|
|
237
253
|
revisions: [...HOST_PROTOCOL_REVISIONS],
|
|
238
254
|
mode,
|
package/src/home/paths.ts
CHANGED
|
@@ -1,14 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Where a home and its control
|
|
3
|
-
* touches the file system; preparing a directory creates it
|
|
4
|
-
* owns, and refuses one owned by someone else.
|
|
2
|
+
* Where a home and its control endpoint live (DATA_MODEL §1, D82, D84, D85). Resolving a path never
|
|
3
|
+
* touches the file system; preparing a directory creates it owner-only, tightens one the user
|
|
4
|
+
* owns, and refuses one owned by someone else. The per-system details are the platform layer's.
|
|
5
5
|
*/
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
|
-
import { chmodSync, mkdirSync, realpathSync, statSync } from "node:fs";
|
|
8
7
|
import { homedir } from "node:os";
|
|
9
|
-
import {
|
|
10
|
-
import { createDiagnostic, RpcError, VersionId } from "@mostra/protocol";
|
|
8
|
+
import { VersionId } from "@mostra/protocol";
|
|
11
9
|
import type { Environment } from "../log.ts";
|
|
10
|
+
import {
|
|
11
|
+
controlEndpoint,
|
|
12
|
+
defaultHome,
|
|
13
|
+
socketPathLimit as limitFor,
|
|
14
|
+
OS,
|
|
15
|
+
ownedDirectory,
|
|
16
|
+
type PreparedDirectory,
|
|
17
|
+
pathsOf,
|
|
18
|
+
type RuntimeDirChoice,
|
|
19
|
+
runtimeDirFor,
|
|
20
|
+
} from "../platform/index.ts";
|
|
21
|
+
|
|
22
|
+
export type { PreparedDirectory, RuntimeDirChoice };
|
|
12
23
|
|
|
13
24
|
/** What path resolution reads: the flag, the environment and the platform. */
|
|
14
25
|
export interface PathInputs {
|
|
@@ -27,82 +38,34 @@ const nonEmpty = (value: string | undefined): string | undefined =>
|
|
|
27
38
|
|
|
28
39
|
/**
|
|
29
40
|
* The home path, resolved in D84's order: `--home`, then `MOSTRA_HOME`, then the platform default
|
|
30
|
-
* (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux
|
|
31
|
-
* `home` option as `--home`.
|
|
41
|
+
* (`~/.mostra` on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux,
|
|
42
|
+
* `%LOCALAPPDATA%\mostra` on Windows). An SDK passes its `home` option as `--home`.
|
|
32
43
|
*/
|
|
33
44
|
export function resolveHomePath(inputs: PathInputs): string {
|
|
34
45
|
const cwd = inputs.cwd ?? process.cwd();
|
|
35
46
|
const chosen = nonEmpty(inputs.home) ?? nonEmpty(inputs.env["MOSTRA_HOME"]);
|
|
36
|
-
if (chosen !== undefined) return resolve(cwd, chosen);
|
|
37
|
-
|
|
38
|
-
if ((inputs.platform ?? process.platform) === "darwin") return join(user, ".mostra");
|
|
39
|
-
const data = nonEmpty(inputs.env["XDG_DATA_HOME"]);
|
|
40
|
-
return join(
|
|
41
|
-
data !== undefined && isAbsolute(data) ? data : join(user, ".local", "share"),
|
|
42
|
-
"mostra",
|
|
43
|
-
);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** What the runtime directory resolution decided, and why. */
|
|
47
|
-
export interface RuntimeDirChoice {
|
|
48
|
-
readonly dir: string;
|
|
49
|
-
/** `override` (MOSTRA_RUNTIME_DIR), `xdg` (the safe XDG runtime directory) or `fallback`. */
|
|
50
|
-
readonly source: "override" | "xdg" | "fallback";
|
|
51
|
-
/** Why `$XDG_RUNTIME_DIR` wasn't used, when it was set. */
|
|
52
|
-
readonly rejected?: string;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** The current user's ID. */
|
|
56
|
-
function uid(): number {
|
|
57
|
-
return process.getuid?.() ?? -1;
|
|
47
|
+
if (chosen !== undefined) return pathsOf(inputs.platform ?? OS).resolve(cwd, chosen);
|
|
48
|
+
return defaultHome(inputs.platform ?? OS, inputs.env, inputs.userHome ?? homedir());
|
|
58
49
|
}
|
|
59
50
|
|
|
60
51
|
/**
|
|
61
52
|
* The runtime directory for control sockets (D82): `MOSTRA_RUNTIME_DIR`; else `~/.mostra/run` on
|
|
62
53
|
* macOS; on Linux `$XDG_RUNTIME_DIR/mostra` when `$XDG_RUNTIME_DIR` is a directory the user owns
|
|
63
|
-
* that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`.
|
|
54
|
+
* that nobody else can read or write, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`. On
|
|
55
|
+
* Windows `undefined`: the control pipe lives in the system's pipe namespace.
|
|
64
56
|
*/
|
|
65
|
-
export function resolveRuntimeDir(inputs: Omit<PathInputs, "home">): RuntimeDirChoice {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
return { dir: join(user, ".mostra", "run"), source: "fallback" };
|
|
73
|
-
}
|
|
74
|
-
const xdg = nonEmpty(inputs.env["XDG_RUNTIME_DIR"]);
|
|
75
|
-
let rejected: string | undefined;
|
|
76
|
-
if (xdg !== undefined) {
|
|
77
|
-
rejected = unsafeXdgRuntimeDir(xdg);
|
|
78
|
-
if (rejected === undefined) return { dir: join(xdg, "mostra"), source: "xdg" };
|
|
79
|
-
}
|
|
80
|
-
const state = nonEmpty(inputs.env["XDG_STATE_HOME"]);
|
|
81
|
-
const base = state !== undefined && isAbsolute(state) ? state : join(user, ".local", "state");
|
|
82
|
-
const dir = join(base, "mostra", "run");
|
|
83
|
-
return rejected === undefined
|
|
84
|
-
? { dir, source: "fallback" }
|
|
85
|
-
: { dir, source: "fallback", rejected };
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */
|
|
89
|
-
function unsafeXdgRuntimeDir(dir: string): string | undefined {
|
|
90
|
-
if (!isAbsolute(dir)) return "it isn't an absolute path";
|
|
91
|
-
let stats: ReturnType<typeof statSync>;
|
|
92
|
-
try {
|
|
93
|
-
stats = statSync(dir);
|
|
94
|
-
} catch {
|
|
95
|
-
return "it doesn't exist";
|
|
96
|
-
}
|
|
97
|
-
if (!stats.isDirectory()) return "it isn't a directory";
|
|
98
|
-
if (stats.uid !== uid()) return "another user owns it";
|
|
99
|
-
if ((stats.mode & 0o077) !== 0) return "other users can access it";
|
|
100
|
-
return undefined;
|
|
57
|
+
export function resolveRuntimeDir(inputs: Omit<PathInputs, "home">): RuntimeDirChoice | undefined {
|
|
58
|
+
return runtimeDirFor({
|
|
59
|
+
os: inputs.platform ?? OS,
|
|
60
|
+
env: inputs.env,
|
|
61
|
+
userHome: inputs.userHome ?? homedir(),
|
|
62
|
+
cwd: inputs.cwd ?? process.cwd(),
|
|
63
|
+
});
|
|
101
64
|
}
|
|
102
65
|
|
|
103
66
|
/** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */
|
|
104
|
-
export function socketPathLimit(platform: string =
|
|
105
|
-
return platform
|
|
67
|
+
export function socketPathLimit(platform: string = OS): number {
|
|
68
|
+
return limitFor(platform);
|
|
106
69
|
}
|
|
107
70
|
|
|
108
71
|
/**
|
|
@@ -117,76 +80,23 @@ export function homeHash(realHome: string): string {
|
|
|
117
80
|
}
|
|
118
81
|
|
|
119
82
|
/**
|
|
120
|
-
* The control
|
|
121
|
-
* `MOSTRA_HOME_SOCKET_TOO_LONG`
|
|
83
|
+
* The control endpoint for a home (D82), named by its {@link homeHash}: the socket in `runtimeDir`
|
|
84
|
+
* on POSIX, throwing `MOSTRA_HOME_SOCKET_TOO_LONG` past the system's limit; on Windows the pipe
|
|
85
|
+
* name that each bind completes with a random part.
|
|
122
86
|
*/
|
|
123
|
-
export function socketPathFor(
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
throw new RpcError(
|
|
130
|
-
createDiagnostic("MOSTRA_HOME_SOCKET_TOO_LONG", {
|
|
131
|
-
message: `The control socket path ${path} is ${length} bytes; this system allows ${limit}.`,
|
|
132
|
-
fix: { kind: "command", command: "export MOSTRA_RUNTIME_DIR=/tmp/mostra-$USER" },
|
|
133
|
-
}),
|
|
134
|
-
);
|
|
135
|
-
}
|
|
136
|
-
return path;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
/** The outcome of {@link prepareOwnedDirectory}. */
|
|
140
|
-
export interface PreparedDirectory {
|
|
141
|
-
/** The directory's real path. */
|
|
142
|
-
readonly realPath: string;
|
|
143
|
-
/** Whether Mostra created it. */
|
|
144
|
-
readonly created: boolean;
|
|
145
|
-
/** The mode it had when Mostra tightened it to 0700, when it did. */
|
|
146
|
-
readonly tightenedFrom?: number;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
function notOwned(path: string, why: string): RpcError {
|
|
150
|
-
return new RpcError(
|
|
151
|
-
createDiagnostic("MOSTRA_HOME_NOT_OWNED", { message: `Mostra can't use ${path}: ${why}.` }),
|
|
152
|
-
);
|
|
87
|
+
export function socketPathFor(
|
|
88
|
+
runtimeDir: string | undefined,
|
|
89
|
+
realHome: string,
|
|
90
|
+
platform: string = OS,
|
|
91
|
+
): string {
|
|
92
|
+
return controlEndpoint(runtimeDir, homeHash(realHome), platform);
|
|
153
93
|
}
|
|
154
94
|
|
|
155
95
|
/**
|
|
156
|
-
* Makes `path` a directory only its owner can use (D85): creates it
|
|
157
|
-
* tightens one the user owns
|
|
158
|
-
* another user or a path that isn't a directory.
|
|
96
|
+
* Makes `path` a directory only its owner can use (D85): creates it owner-only when missing,
|
|
97
|
+
* tightens one the user owns (mode 0700, or an owner-only access list on Windows), and throws
|
|
98
|
+
* `MOSTRA_HOME_NOT_OWNED` for one owned by another user or a path that isn't a directory.
|
|
159
99
|
*/
|
|
160
100
|
export function prepareOwnedDirectory(path: string): PreparedDirectory {
|
|
161
|
-
|
|
162
|
-
return prepare(path);
|
|
163
|
-
} catch (error) {
|
|
164
|
-
const code = (error as NodeJS.ErrnoException).code;
|
|
165
|
-
if (code === "ENOTDIR" || code === "EEXIST")
|
|
166
|
-
throw notOwned(path, "a part of the path isn't a directory");
|
|
167
|
-
if (code === "EACCES" || code === "EPERM")
|
|
168
|
-
throw notOwned(path, "you have no permission to use it");
|
|
169
|
-
throw error;
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
function prepare(path: string): PreparedDirectory {
|
|
174
|
-
let created = false;
|
|
175
|
-
try {
|
|
176
|
-
statSync(path);
|
|
177
|
-
} catch (error) {
|
|
178
|
-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
179
|
-
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
180
|
-
created = true;
|
|
181
|
-
}
|
|
182
|
-
const realPath = realpathSync(path);
|
|
183
|
-
const stats = statSync(realPath);
|
|
184
|
-
if (!stats.isDirectory()) throw notOwned(path, "it isn't a directory");
|
|
185
|
-
if (stats.uid !== uid()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);
|
|
186
|
-
const mode = stats.mode & 0o777;
|
|
187
|
-
if (mode !== 0o700) {
|
|
188
|
-
chmodSync(realPath, 0o700);
|
|
189
|
-
return created ? { realPath, created } : { realPath, created, tightenedFrom: mode };
|
|
190
|
-
}
|
|
191
|
-
return { realPath, created };
|
|
101
|
+
return ownedDirectory(path);
|
|
192
102
|
}
|
package/src/home/platform.ts
CHANGED
|
@@ -1,29 +1,37 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The unsupported-platform gate (D35, RT-07). Every entry point calls it before it touches
|
|
3
|
-
* home: Mostra
|
|
2
|
+
* The unsupported-platform gate (D35, D146, RT-07). Every entry point calls it before it touches
|
|
3
|
+
* the home: Mostra runs on macOS and Linux, on x64 and arm64, and fails closed elsewhere. Windows
|
|
4
|
+
* (x64 and arm64) is being built (WP-W1 to WP-W3) and runs only behind the development switch
|
|
5
|
+
* `MOSTRA_DEV_WINDOWS=1`, which only Mostra's own CI sets, so no release exposes a partial port.
|
|
6
|
+
* WP-W3 removes the switch.
|
|
4
7
|
*/
|
|
5
8
|
import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
|
|
9
|
+
import { OS } from "../platform/index.ts";
|
|
6
10
|
|
|
7
11
|
const OPERATING_SYSTEMS: readonly string[] = ["darwin", "linux"];
|
|
8
12
|
const ARCHITECTURES: readonly string[] = ["x64", "arm64"];
|
|
9
13
|
|
|
14
|
+
/** The development switch that admits Windows until WP-W3 (D146). */
|
|
15
|
+
export const WINDOWS_DEV_SWITCH = "MOSTRA_DEV_WINDOWS";
|
|
16
|
+
|
|
10
17
|
/** The platform as `<os>-<arch>`, as `InstanceInfo.platform` reports it. */
|
|
11
|
-
export function platformName(
|
|
12
|
-
platform: string = process.platform,
|
|
13
|
-
arch: string = process.arch,
|
|
14
|
-
): string {
|
|
18
|
+
export function platformName(platform: string = OS, arch: string = process.arch): string {
|
|
15
19
|
return `${platform}-${arch}`;
|
|
16
20
|
}
|
|
17
21
|
|
|
18
22
|
/**
|
|
19
23
|
* Returns `MOSTRA_PLATFORM_UNSUPPORTED` for a platform Mostra doesn't run on, or `undefined` for
|
|
20
|
-
* a supported one.
|
|
24
|
+
* a supported one. Windows is supported only while `env` sets the development switch to `1`.
|
|
21
25
|
*/
|
|
22
26
|
export function checkPlatform(
|
|
23
|
-
platform: string =
|
|
27
|
+
platform: string = OS,
|
|
24
28
|
arch: string = process.arch,
|
|
29
|
+
env: Readonly<Record<string, string | undefined>> = process.env,
|
|
25
30
|
): Diagnostic | undefined {
|
|
26
|
-
if (
|
|
31
|
+
if (ARCHITECTURES.includes(arch)) {
|
|
32
|
+
if (OPERATING_SYSTEMS.includes(platform)) return undefined;
|
|
33
|
+
if (platform === "win32" && env[WINDOWS_DEV_SWITCH] === "1") return undefined;
|
|
34
|
+
}
|
|
27
35
|
const name =
|
|
28
36
|
platform === "win32"
|
|
29
37
|
? `Windows (${platformName(platform, arch)})`
|
package/src/home/record.ts
CHANGED
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
* atomically after binding its socket and removes it on a clean exit; a record whose PID and
|
|
5
5
|
* start time match no live process is stale.
|
|
6
6
|
*/
|
|
7
|
-
import { readFileSync,
|
|
7
|
+
import { readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
8
8
|
import { join } from "node:path";
|
|
9
9
|
import * as z from "zod";
|
|
10
|
-
import { isSameProcess } from "../
|
|
10
|
+
import { isSameProcess, renamePathSync } from "../platform/index.ts";
|
|
11
11
|
|
|
12
12
|
/** The record's file name in the home. */
|
|
13
13
|
export const INSTANCE_FILE = "instance.json";
|
|
@@ -64,7 +64,7 @@ export function writeInstanceRecord(home: string, record: InstanceRecord): void
|
|
|
64
64
|
const file = join(home, INSTANCE_FILE);
|
|
65
65
|
const temp = `${file}.${process.pid}.tmp`;
|
|
66
66
|
writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
|
|
67
|
-
|
|
67
|
+
renamePathSync(temp, file);
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
/** Removes the record when it is still this process's (a clean exit). */
|
package/src/home/settings.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* Written atomically (a temporary file, then a rename); read fresh by whoever needs a setting, so
|
|
7
7
|
* a host's change applies to the next request.
|
|
8
8
|
*/
|
|
9
|
-
import {
|
|
9
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
10
10
|
import { join } from "node:path";
|
|
11
11
|
import {
|
|
12
12
|
createDiagnostic,
|
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
SubmissionPolicy,
|
|
16
16
|
} from "@mostra/protocol";
|
|
17
17
|
import * as z from "zod";
|
|
18
|
+
import { fsyncPath, renamePathSync } from "../platform/index.ts";
|
|
18
19
|
|
|
19
20
|
/** The settings `config.json` holds. Unknown keys are kept, so newer settings survive. */
|
|
20
21
|
export interface HomeSettings {
|
|
@@ -85,21 +86,9 @@ export function writeHomeSettings(home: string, change: HomeSettings): void {
|
|
|
85
86
|
const file = join(home, SETTINGS_FILE);
|
|
86
87
|
const temporary = `${file}.${process.pid}.tmp`;
|
|
87
88
|
writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
} finally {
|
|
92
|
-
closeSync(handle);
|
|
93
|
-
}
|
|
94
|
-
renameSync(temporary, file);
|
|
95
|
-
const dir = openSync(home, "r");
|
|
96
|
-
try {
|
|
97
|
-
fsyncSync(dir);
|
|
98
|
-
} catch {
|
|
99
|
-
// Some file systems can't sync a directory; the rename itself is atomic.
|
|
100
|
-
} finally {
|
|
101
|
-
closeSync(dir);
|
|
102
|
-
}
|
|
89
|
+
fsyncPath(temporary);
|
|
90
|
+
renamePathSync(temporary, file);
|
|
91
|
+
fsyncPath(home, true);
|
|
103
92
|
}
|
|
104
93
|
|
|
105
94
|
/**
|