@mostra/runtime 0.0.0-stage → 0.2.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/LICENSE +202 -0
- package/README.md +39 -2
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +236 -0
- package/dist/bin.js.map +1 -0
- package/dist/builder/child/main.d.ts +1 -0
- package/dist/builder/child/main.js +1408 -0
- package/dist/builder/child/main.js.map +1 -0
- package/dist/child-xrHmytks.js +49 -0
- package/dist/child-xrHmytks.js.map +1 -0
- package/dist/deps/child/install.d.ts +1 -0
- package/dist/deps/child/install.js +33 -0
- package/dist/deps/child/install.js.map +1 -0
- package/dist/index.d.ts +221 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/instance-CzBkUyHu.js +15920 -0
- package/dist/instance-CzBkUyHu.js.map +1 -0
- package/dist/types-NjNy7gXX.js +57 -0
- package/dist/types-NjNy7gXX.js.map +1 -0
- package/package.json +87 -3
- package/src/actions/index.ts +622 -0
- package/src/addressing/index.ts +281 -0
- package/src/bin.ts +240 -0
- package/src/builder/child/dev.ts +383 -0
- package/src/builder/child/fields.ts +363 -0
- package/src/builder/child/main.ts +47 -0
- package/src/builder/child/plugins.ts +195 -0
- package/src/builder/child/scan.ts +459 -0
- package/src/builder/child/spa.ts +348 -0
- package/src/builder/coverage.ts +72 -0
- package/src/builder/index.ts +406 -0
- package/src/builder/types.ts +180 -0
- package/src/deps/child/install.ts +30 -0
- package/src/deps/index.ts +918 -0
- package/src/deps/installer.ts +321 -0
- package/src/deps/lock.ts +82 -0
- package/src/deps/scan.ts +266 -0
- package/src/deps/specifier.ts +64 -0
- package/src/deps/warm.ts +57 -0
- package/src/dev/index.ts +518 -0
- package/src/faults.ts +65 -0
- package/src/gate.ts +55 -0
- package/src/gateway/actions.ts +268 -0
- package/src/gateway/browser.ts +650 -0
- package/src/gateway/capabilities.ts +760 -0
- package/src/gateway/controls.ts +91 -0
- package/src/gateway/dev.ts +119 -0
- package/src/gateway/http.ts +229 -0
- package/src/gateway/identity.ts +101 -0
- package/src/gateway/index.ts +1299 -0
- package/src/gateway/integrity.ts +117 -0
- package/src/gateway/listener.ts +217 -0
- package/src/gateway/routes.ts +197 -0
- package/src/gateway/serve.ts +138 -0
- package/src/gc/index.ts +451 -0
- package/src/home/acquire.ts +276 -0
- package/src/home/index.ts +16 -0
- package/src/home/paths.ts +192 -0
- package/src/home/platform.ts +34 -0
- package/src/home/record.ts +76 -0
- package/src/home/settings.ts +113 -0
- package/src/index.ts +30 -0
- package/src/instance/index.ts +979 -0
- package/src/interaction/ephemeral.ts +300 -0
- package/src/interaction/events.ts +355 -0
- package/src/interaction/fields.ts +392 -0
- package/src/interaction/index.ts +1013 -0
- package/src/interaction/outbox.ts +493 -0
- package/src/interaction/policy.ts +26 -0
- package/src/interaction/results.ts +341 -0
- package/src/interaction/runs.ts +313 -0
- package/src/interaction/signals.ts +120 -0
- package/src/interaction/submissions.ts +585 -0
- package/src/interaction/subscriptions.ts +258 -0
- package/src/interaction/viewers.ts +187 -0
- package/src/interaction/wait.ts +201 -0
- package/src/ledger/index.ts +442 -0
- package/src/ledger/migrations.ts +596 -0
- package/src/ledger/requests.ts +105 -0
- package/src/ledger/types.ts +28 -0
- package/src/live/index.ts +573 -0
- package/src/log.ts +316 -0
- package/src/processes/child.ts +67 -0
- package/src/processes/environment.ts +64 -0
- package/src/processes/identity.ts +191 -0
- package/src/processes/index.ts +19 -0
- package/src/processes/manager.ts +543 -0
- package/src/protocol-server/client.ts +94 -0
- package/src/protocol-server/index.ts +91 -0
- package/src/protocol-server/server.ts +518 -0
- package/src/protocol-server/streams.ts +81 -0
- package/src/publish/checks.ts +92 -0
- package/src/publish/digest.ts +87 -0
- package/src/publish/index.ts +23 -0
- package/src/publish/manifest.ts +409 -0
- package/src/publish/methods.ts +96 -0
- package/src/publish/publisher.ts +913 -0
- package/src/publish/source.ts +272 -0
- package/src/publish/tar.ts +110 -0
- package/src/registry/index.ts +481 -0
- package/src/registry/store.ts +136 -0
- package/src/secrets/index.ts +223 -0
- package/src/service/idle.ts +64 -0
- package/src/service/index.ts +3 -0
- package/src/service/unit.ts +250 -0
- package/src/verify/fields.ts +125 -0
- package/src/verify/index.ts +913 -0
- package/src/verify/regression.ts +157 -0
- package/src/verify/runner.ts +230 -0
- package/src/verify/sandbox.ts +407 -0
- package/src/verify/typecheck.ts +371 -0
- package/src/workers/index.ts +17 -0
- package/src/workers/launcher.ts +260 -0
- package/src/workers/pool.ts +708 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The submit channels and trusted controls in force for a view (D40, D108). A host that
|
|
3
|
+
* registered the `trustedControls` port answers per artifact; otherwise the home's
|
|
4
|
+
* `HomeConfig.submitChannels` holds; otherwise both channels, as D40's standalone default.
|
|
5
|
+
*/
|
|
6
|
+
import {
|
|
7
|
+
type ArtifactDetail,
|
|
8
|
+
type ControlsPolicy,
|
|
9
|
+
portTrustedControlsPolicyMethod,
|
|
10
|
+
type SubmitChannel,
|
|
11
|
+
} from "@mostra/protocol";
|
|
12
|
+
import type { Log } from "../log.ts";
|
|
13
|
+
|
|
14
|
+
/** How long a host has to answer `port/trustedControls.policy`: a page waits for it (D108). */
|
|
15
|
+
export const CONTROLS_POLICY_TIMEOUT_MS = 5_000;
|
|
16
|
+
|
|
17
|
+
/** Both channels, every control. */
|
|
18
|
+
const STANDALONE: ControlsPolicy = { submitChannels: ["shell", "artifact"] };
|
|
19
|
+
|
|
20
|
+
/** The shell channel only: what a host's failed answer narrows a view to. */
|
|
21
|
+
const SHELL_ONLY: ControlsPolicy = { submitChannels: ["shell"] };
|
|
22
|
+
|
|
23
|
+
/** What {@link controlsPolicy} reads. */
|
|
24
|
+
export interface ControlsPolicyInput {
|
|
25
|
+
/** The artifact a frame is about to show. */
|
|
26
|
+
readonly artifact: ArtifactDetail;
|
|
27
|
+
readonly log: Log;
|
|
28
|
+
/** The home's `submitChannels`, if a host set them. */
|
|
29
|
+
readonly home: () => readonly SubmitChannel[] | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Hosts that always provide `trustedControls` (`HomeConfig.ports`, D105), by client name: one
|
|
32
|
+
* that is away decides nothing, so its views get the shell channel only.
|
|
33
|
+
*/
|
|
34
|
+
readonly expected: () => readonly string[];
|
|
35
|
+
/** The newest connection that registered `trustedControls`, if any. */
|
|
36
|
+
readonly registrant: () => { readonly session: number; readonly owner: string } | undefined;
|
|
37
|
+
/** Calls the port on that connection; rejects on a transport failure or the timeout. */
|
|
38
|
+
readonly call: (session: number, params: unknown) => Promise<unknown>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The policy for a new view (D108). A host's answer wins; a host that registered the port but
|
|
43
|
+
* fails to answer, or that always provides it (`HomeConfig.ports`) and isn't connected, narrows
|
|
44
|
+
* the view to the shell channel, so its outage never widens what it allows.
|
|
45
|
+
*/
|
|
46
|
+
export async function controlsPolicy(input: ControlsPolicyInput): Promise<ControlsPolicy> {
|
|
47
|
+
const registrant = input.registrant();
|
|
48
|
+
if (registrant) {
|
|
49
|
+
const { versions: _versions, manifest: _manifest, ...summary } = input.artifact;
|
|
50
|
+
try {
|
|
51
|
+
const answer = await input.call(registrant.session, { artifact: summary });
|
|
52
|
+
const parsed = portTrustedControlsPolicyMethod.result.safeParse(answer);
|
|
53
|
+
if (parsed.success) return normalize(parsed.data);
|
|
54
|
+
input.log.warn("gateway.controls_policy_invalid", {
|
|
55
|
+
owner: registrant.owner,
|
|
56
|
+
artifactId: input.artifact.id,
|
|
57
|
+
});
|
|
58
|
+
} catch (error) {
|
|
59
|
+
input.log.warn("gateway.controls_policy_failed", {
|
|
60
|
+
owner: registrant.owner,
|
|
61
|
+
artifactId: input.artifact.id,
|
|
62
|
+
error: (error as Error).message,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
return SHELL_ONLY;
|
|
66
|
+
}
|
|
67
|
+
// A host that takes the policy over but is away right now (restarting, or the link opened
|
|
68
|
+
// first) never has it widened by its absence: the view lives on after it returns (Claude
|
|
69
|
+
// review finding 10).
|
|
70
|
+
const away = input.expected();
|
|
71
|
+
if (away.length > 0) {
|
|
72
|
+
input.log.warn("gateway.controls_policy_host_away", {
|
|
73
|
+
owners: away,
|
|
74
|
+
artifactId: input.artifact.id,
|
|
75
|
+
});
|
|
76
|
+
return SHELL_ONLY;
|
|
77
|
+
}
|
|
78
|
+
const channels = input.home();
|
|
79
|
+
return channels === undefined ? STANDALONE : normalize({ submitChannels: channels });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Channels deduplicated and in a stable order. */
|
|
83
|
+
function normalize(policy: ControlsPolicy): ControlsPolicy {
|
|
84
|
+
const submitChannels = (["shell", "artifact"] as const).filter((channel) =>
|
|
85
|
+
policy.submitChannels.includes(channel),
|
|
86
|
+
);
|
|
87
|
+
return {
|
|
88
|
+
submitChannels: submitChannels.length > 0 ? submitChannels : ["shell"],
|
|
89
|
+
...(policy.controls !== undefined ? { controls: [...new Set(policy.controls)] } : {}),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dev sandbox's artifact origin in front of `mostra dev`'s Vite server (D140 item 12): every
|
|
3
|
+
* file request and the HMR WebSocket pass the gateway's checks first (exact Host and Origin, the
|
|
4
|
+
* origin-bound frame session), then reach the dev server on loopback with the session's secret,
|
|
5
|
+
* which nothing else holds. Mostra's cookies never go upstream (D38).
|
|
6
|
+
*/
|
|
7
|
+
import { request as httpRequest, type IncomingMessage } from "node:http";
|
|
8
|
+
import { connect } from "node:net";
|
|
9
|
+
import type { Duplex } from "node:stream";
|
|
10
|
+
import { DEV_SECRET_HEADER } from "../builder/index.ts";
|
|
11
|
+
|
|
12
|
+
/** Where a dev session's server listens, and the secret it wants. */
|
|
13
|
+
export interface DevUpstream {
|
|
14
|
+
readonly port: number;
|
|
15
|
+
readonly secret: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Request headers the gateway passes to the dev server; everything else stays (cookies above all). */
|
|
19
|
+
const FORWARDED = [
|
|
20
|
+
"accept",
|
|
21
|
+
"accept-language",
|
|
22
|
+
"if-none-match",
|
|
23
|
+
"if-modified-since",
|
|
24
|
+
"user-agent",
|
|
25
|
+
"sec-fetch-dest",
|
|
26
|
+
"sec-fetch-mode",
|
|
27
|
+
"sec-fetch-site",
|
|
28
|
+
] as const;
|
|
29
|
+
|
|
30
|
+
/** Response headers the gateway passes back; its own security headers are added by the caller. */
|
|
31
|
+
const RETURNED = [
|
|
32
|
+
"content-type",
|
|
33
|
+
"etag",
|
|
34
|
+
"last-modified",
|
|
35
|
+
"cache-control",
|
|
36
|
+
"content-length",
|
|
37
|
+
] as const;
|
|
38
|
+
|
|
39
|
+
/** Fetches `path` from the dev server; resolves with its status, headers and body. */
|
|
40
|
+
export function devFetch(
|
|
41
|
+
upstream: DevUpstream,
|
|
42
|
+
request: Request,
|
|
43
|
+
path: string,
|
|
44
|
+
): Promise<{ status: number; headers: Record<string, string>; body: Buffer }> {
|
|
45
|
+
const headers: Record<string, string> = {
|
|
46
|
+
host: `127.0.0.1:${upstream.port}`,
|
|
47
|
+
[DEV_SECRET_HEADER]: upstream.secret,
|
|
48
|
+
};
|
|
49
|
+
for (const name of FORWARDED) {
|
|
50
|
+
const value = request.headers.get(name);
|
|
51
|
+
if (value !== null) headers[name] = value;
|
|
52
|
+
}
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
const outgoing = httpRequest(
|
|
55
|
+
{
|
|
56
|
+
host: "127.0.0.1",
|
|
57
|
+
port: upstream.port,
|
|
58
|
+
method: request.method,
|
|
59
|
+
path,
|
|
60
|
+
headers,
|
|
61
|
+
agent: false,
|
|
62
|
+
},
|
|
63
|
+
(response) => {
|
|
64
|
+
const chunks: Buffer[] = [];
|
|
65
|
+
response.on("data", (chunk: Buffer) => chunks.push(chunk));
|
|
66
|
+
response.on("end", () => {
|
|
67
|
+
const back: Record<string, string> = {};
|
|
68
|
+
for (const name of RETURNED) {
|
|
69
|
+
const value = response.headers[name];
|
|
70
|
+
if (typeof value === "string") back[name] = value;
|
|
71
|
+
}
|
|
72
|
+
resolve({
|
|
73
|
+
status: response.statusCode ?? 502,
|
|
74
|
+
headers: back,
|
|
75
|
+
body: Buffer.concat(chunks),
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
response.on("error", reject);
|
|
79
|
+
},
|
|
80
|
+
);
|
|
81
|
+
outgoing.on("error", reject);
|
|
82
|
+
outgoing.end();
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Hands an upgrade the gateway accepted to the dev server: the request line and its headers, with
|
|
88
|
+
* the secret added, the Host rewritten and Mostra's cookies removed, then both directions piped.
|
|
89
|
+
*/
|
|
90
|
+
export function devUpgrade(
|
|
91
|
+
upstream: DevUpstream,
|
|
92
|
+
incoming: IncomingMessage,
|
|
93
|
+
socket: Duplex,
|
|
94
|
+
head: Buffer,
|
|
95
|
+
): void {
|
|
96
|
+
const target = connect({ host: "127.0.0.1", port: upstream.port });
|
|
97
|
+
const lines = [`${incoming.method ?? "GET"} ${incoming.url ?? "/"} HTTP/1.1`];
|
|
98
|
+
for (let index = 0; index + 1 < incoming.rawHeaders.length; index += 2) {
|
|
99
|
+
const name = incoming.rawHeaders[index] as string;
|
|
100
|
+
const lower = name.toLowerCase();
|
|
101
|
+
if (lower === "cookie" || lower === "host" || lower === DEV_SECRET_HEADER) continue;
|
|
102
|
+
lines.push(`${name}: ${incoming.rawHeaders[index + 1] as string}`);
|
|
103
|
+
}
|
|
104
|
+
lines.push(`Host: 127.0.0.1:${upstream.port}`, `${DEV_SECRET_HEADER}: ${upstream.secret}`);
|
|
105
|
+
const close = (): void => {
|
|
106
|
+
target.destroy();
|
|
107
|
+
socket.destroy();
|
|
108
|
+
};
|
|
109
|
+
target.on("error", close);
|
|
110
|
+
socket.on("error", close);
|
|
111
|
+
target.on("close", () => socket.destroy());
|
|
112
|
+
socket.on("close", () => target.destroy());
|
|
113
|
+
target.on("connect", () => {
|
|
114
|
+
target.write(`${lines.join("\r\n")}\r\n\r\n`);
|
|
115
|
+
if (head.length > 0) target.write(head);
|
|
116
|
+
target.pipe(socket);
|
|
117
|
+
socket.pipe(target);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP plumbing shared by the gateway's listeners: the headers every response carries (D98 item
|
|
3
|
+
* 6, D98 item 4), refusal responses, cookies and JSON bodies. No policy lives here beyond the
|
|
4
|
+
* response shapes; the checks themselves are `@mostra/protocol`'s `checkRequest` and the route
|
|
5
|
+
* declarations in `routes.ts`.
|
|
6
|
+
*/
|
|
7
|
+
import type { IncomingMessage } from "node:http";
|
|
8
|
+
import type { HttpBindings } from "@hono/node-server";
|
|
9
|
+
import type { Diagnostic, Refusal } from "@mostra/protocol";
|
|
10
|
+
import { refusal } from "@mostra/protocol";
|
|
11
|
+
|
|
12
|
+
/** The Hono environment of a listener: Node's request and response objects. */
|
|
13
|
+
export type HttpEnv = { Bindings: HttpBindings };
|
|
14
|
+
|
|
15
|
+
/** The longest JSON body a gateway endpoint reads. */
|
|
16
|
+
export const MAX_JSON_BODY: number = 64 * 1024;
|
|
17
|
+
|
|
18
|
+
/** Headers on every gateway response (D98 item 6). */
|
|
19
|
+
export const BASE_HEADERS: Readonly<Record<string, string>> = {
|
|
20
|
+
"cross-origin-resource-policy": "same-origin",
|
|
21
|
+
"referrer-policy": "no-referrer",
|
|
22
|
+
"x-content-type-options": "nosniff",
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** A listener's identity, which decides its framing headers. */
|
|
26
|
+
export interface ListenerKind {
|
|
27
|
+
readonly kind: "shell" | "artifact";
|
|
28
|
+
/** The listener's own origin. */
|
|
29
|
+
readonly origin: string;
|
|
30
|
+
/** The shell's origin: the only page that may frame an artifact (D98 item 4). */
|
|
31
|
+
readonly shellOrigin: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The framing and content-security headers of a document: the shell is never framed, and its own
|
|
36
|
+
* page loads only from itself; an artifact page may be framed by the shell alone. An artifact's
|
|
37
|
+
* content is otherwise unrestricted (D05): only `frame-ancestors` is set.
|
|
38
|
+
*/
|
|
39
|
+
export function documentHeaders(
|
|
40
|
+
listener: ListenerKind,
|
|
41
|
+
frameOrigins: string,
|
|
42
|
+
): Record<string, string> {
|
|
43
|
+
if (listener.kind === "shell") {
|
|
44
|
+
return {
|
|
45
|
+
"content-security-policy": [
|
|
46
|
+
"default-src 'self'",
|
|
47
|
+
"script-src 'self'",
|
|
48
|
+
"style-src 'self'",
|
|
49
|
+
"img-src 'self' data:",
|
|
50
|
+
"connect-src 'self'",
|
|
51
|
+
`frame-src ${frameOrigins}`,
|
|
52
|
+
"frame-ancestors 'none'",
|
|
53
|
+
"base-uri 'none'",
|
|
54
|
+
"form-action 'none'",
|
|
55
|
+
"object-src 'none'",
|
|
56
|
+
].join("; "),
|
|
57
|
+
"x-frame-options": "DENY",
|
|
58
|
+
// Popups the artifact frame opens get no opener, so none can navigate this page (D98
|
|
59
|
+
// item 7): Firefox lets even a sandboxed popup navigate `opener.top`.
|
|
60
|
+
"cross-origin-opener-policy": "same-origin",
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
return { "content-security-policy": `frame-ancestors ${listener.shellOrigin}` };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Every header of a request as `[name, value]` pairs, repeats kept. */
|
|
67
|
+
export function headerPairs(incoming: IncomingMessage): [string, string][] {
|
|
68
|
+
const pairs: [string, string][] = [];
|
|
69
|
+
const raw = incoming.rawHeaders;
|
|
70
|
+
for (let index = 0; index + 1 < raw.length; index += 2) {
|
|
71
|
+
pairs.push([raw[index] as string, raw[index + 1] as string]);
|
|
72
|
+
}
|
|
73
|
+
return pairs;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Whether a request is a navigation that should get an HTML page rather than JSON. */
|
|
77
|
+
export function wantsDocument(headers: Headers): boolean {
|
|
78
|
+
const dest = headers.get("sec-fetch-dest");
|
|
79
|
+
if (dest !== null) return dest === "document" || dest === "iframe" || dest === "frame";
|
|
80
|
+
return (headers.get("accept") ?? "").includes("text/html");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Escapes text for HTML. */
|
|
84
|
+
function escapeHtml(text: string): string {
|
|
85
|
+
return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A plain page for a refused navigation: no scripts, no external resources. */
|
|
89
|
+
function refusalPage(diagnostic: Diagnostic): string {
|
|
90
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Mostra</title><style>body{font-family:system-ui,sans-serif;margin:0;min-height:100vh;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:.25rem;padding:2rem;text-align:center;color-scheme:light dark}h1{font-size:1.25rem;margin:0}p{margin:0;opacity:.8}code{opacity:.5;font-size:.75rem;margin-top:1rem}</style></head><body><h1>${escapeHtml(diagnostic.message)}</h1>${diagnostic.hint ? `<p>${escapeHtml(diagnostic.hint)}</p>` : ""}<code>${escapeHtml(diagnostic.code)}</code></body></html>`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The response for a refusal: the diagnostic as JSON, or a plain page for a navigation. */
|
|
94
|
+
export function refusalResponse(
|
|
95
|
+
refused: Refusal & { readonly retryAfter?: number },
|
|
96
|
+
options: {
|
|
97
|
+
readonly document: boolean;
|
|
98
|
+
readonly method?: string;
|
|
99
|
+
readonly frameAncestors?: string;
|
|
100
|
+
},
|
|
101
|
+
): Response {
|
|
102
|
+
const headers: Record<string, string> = { ...BASE_HEADERS, "cache-control": "no-store" };
|
|
103
|
+
if (refused.retryAfter !== undefined) headers["retry-after"] = String(refused.retryAfter);
|
|
104
|
+
if (refused.status === 405) headers["allow"] = "GET, HEAD, POST";
|
|
105
|
+
const head = options.method === "HEAD";
|
|
106
|
+
if (options.document) {
|
|
107
|
+
headers["content-type"] = "text/html; charset=utf-8";
|
|
108
|
+
// The page has an inline style and nothing else; only the shell may frame it (on artifacts).
|
|
109
|
+
headers["content-security-policy"] = [
|
|
110
|
+
"default-src 'none'",
|
|
111
|
+
"style-src 'unsafe-inline'",
|
|
112
|
+
`frame-ancestors ${options.frameAncestors ?? "'none'"}`,
|
|
113
|
+
"base-uri 'none'",
|
|
114
|
+
].join("; ");
|
|
115
|
+
return new Response(head ? null : refusalPage(refused.diagnostic), {
|
|
116
|
+
status: refused.status,
|
|
117
|
+
headers,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
headers["content-type"] = "application/json; charset=utf-8";
|
|
121
|
+
return new Response(head ? null : JSON.stringify(refused.diagnostic), {
|
|
122
|
+
status: refused.status,
|
|
123
|
+
headers,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** A JSON response with the base headers, never cached. */
|
|
128
|
+
export function jsonResponse(
|
|
129
|
+
body: unknown,
|
|
130
|
+
init: { readonly status?: number; readonly headers?: Record<string, string> } = {},
|
|
131
|
+
): Response {
|
|
132
|
+
return new Response(JSON.stringify(body), {
|
|
133
|
+
status: init.status ?? 200,
|
|
134
|
+
headers: {
|
|
135
|
+
...BASE_HEADERS,
|
|
136
|
+
"cache-control": "no-store",
|
|
137
|
+
"content-type": "application/json; charset=utf-8",
|
|
138
|
+
...init.headers,
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Every value of the cookie `name` in a `Cookie` header, in order (D98: there may be several). */
|
|
144
|
+
export function cookieValues(header: string | null, name: string): string[] {
|
|
145
|
+
if (header === null) return [];
|
|
146
|
+
const values: string[] = [];
|
|
147
|
+
for (const part of header.split(";")) {
|
|
148
|
+
const index = part.indexOf("=");
|
|
149
|
+
if (index < 0) continue;
|
|
150
|
+
if (part.slice(0, index).trim() === name) values.push(part.slice(index + 1).trim());
|
|
151
|
+
}
|
|
152
|
+
return values;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The `Set-Cookie` value of a session cookie (D98 item 1); never `Secure` over loopback HTTP. */
|
|
156
|
+
export function sessionCookie(
|
|
157
|
+
name: string,
|
|
158
|
+
value: string,
|
|
159
|
+
path: string,
|
|
160
|
+
maxAgeSeconds: number,
|
|
161
|
+
): string {
|
|
162
|
+
return `${name}=${value}; Path=${path}; Max-Age=${maxAgeSeconds}; HttpOnly; SameSite=Strict`;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Reads a JSON object body of at most `maxBytes` (default {@link MAX_JSON_BODY}) bytes; a larger,
|
|
167
|
+
* unreadable or non-object body is `MOSTRA_HYGIENE_REQUEST_MALFORMED`.
|
|
168
|
+
*/
|
|
169
|
+
export async function readJsonObject(
|
|
170
|
+
request: Request,
|
|
171
|
+
maxBytes: number = MAX_JSON_BODY,
|
|
172
|
+
): Promise<Record<string, unknown> | Refusal> {
|
|
173
|
+
const length = Number(request.headers.get("content-length") ?? "0");
|
|
174
|
+
if (length > maxBytes) {
|
|
175
|
+
return refusal(
|
|
176
|
+
"MOSTRA_HYGIENE_REQUEST_MALFORMED",
|
|
177
|
+
"The request body is larger than this endpoint reads.",
|
|
178
|
+
413,
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
let text: string;
|
|
182
|
+
try {
|
|
183
|
+
const chunks: Uint8Array[] = [];
|
|
184
|
+
let size = 0;
|
|
185
|
+
const reader = request.body?.getReader();
|
|
186
|
+
for (;;) {
|
|
187
|
+
if (!reader) break;
|
|
188
|
+
const { done, value } = await reader.read();
|
|
189
|
+
if (done) break;
|
|
190
|
+
size += value.byteLength;
|
|
191
|
+
// A body sent without Content-Length is cut off as soon as it passes the limit.
|
|
192
|
+
if (size > maxBytes) {
|
|
193
|
+
await reader.cancel();
|
|
194
|
+
return refusal(
|
|
195
|
+
"MOSTRA_HYGIENE_REQUEST_MALFORMED",
|
|
196
|
+
"The request body is larger than this endpoint reads.",
|
|
197
|
+
413,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
chunks.push(value);
|
|
201
|
+
}
|
|
202
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks));
|
|
203
|
+
} catch {
|
|
204
|
+
return refusal(
|
|
205
|
+
"MOSTRA_HYGIENE_REQUEST_MALFORMED",
|
|
206
|
+
"The request body couldn't be read as UTF-8.",
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
try {
|
|
210
|
+
const value: unknown = text === "" ? {} : JSON.parse(text);
|
|
211
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
212
|
+
return refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "The request body must be a JSON object.");
|
|
213
|
+
}
|
|
214
|
+
return value as Record<string, unknown>;
|
|
215
|
+
} catch {
|
|
216
|
+
return refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "The request body isn't valid JSON.");
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Whether a value is a {@link Refusal}. */
|
|
221
|
+
export function isRefusal(value: unknown): value is Refusal {
|
|
222
|
+
return (
|
|
223
|
+
typeof value === "object" &&
|
|
224
|
+
value !== null &&
|
|
225
|
+
"status" in value &&
|
|
226
|
+
"diagnostic" in value &&
|
|
227
|
+
typeof (value as { status: unknown }).status === "number"
|
|
228
|
+
);
|
|
229
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who a browser is (D143 item 2). A link minted with a viewer acts for that viewer (D104) and asks
|
|
3
|
+
* nothing. For a link without one, a host that registered the `identity` port names the person
|
|
4
|
+
* from the request's headers; without such a host, the session acts as the home's local user.
|
|
5
|
+
*/
|
|
6
|
+
import {
|
|
7
|
+
createDiagnostic,
|
|
8
|
+
type Diagnostic,
|
|
9
|
+
type IdentityVia,
|
|
10
|
+
portIdentityResolveMethod,
|
|
11
|
+
type ViewerSpec,
|
|
12
|
+
} from "@mostra/protocol";
|
|
13
|
+
import type { Log } from "../log.ts";
|
|
14
|
+
|
|
15
|
+
/** How long a host has to answer `port/identity.resolve`: a page waits for it, as for D108. */
|
|
16
|
+
export const IDENTITY_TIMEOUT_MS = 5_000;
|
|
17
|
+
|
|
18
|
+
/** What {@link resolveIdentity} reads. */
|
|
19
|
+
export interface IdentityInput {
|
|
20
|
+
/** The artifact whose link is being exchanged. */
|
|
21
|
+
readonly artifactId: string;
|
|
22
|
+
/** How the request reached the gateway. */
|
|
23
|
+
readonly via: IdentityVia;
|
|
24
|
+
/** The request's headers. */
|
|
25
|
+
readonly headers: Headers;
|
|
26
|
+
readonly log: Log;
|
|
27
|
+
/** Hosts that always provide `identity` (`HomeConfig.ports`), by client name. */
|
|
28
|
+
readonly expected: () => readonly string[];
|
|
29
|
+
/** The newest connection that registered `identity`, if any. */
|
|
30
|
+
readonly registrant: () => { readonly session: number; readonly owner: string } | undefined;
|
|
31
|
+
/** Calls the port on that connection; rejects on a transport failure or the timeout. */
|
|
32
|
+
readonly call: (session: number, params: unknown) => Promise<unknown>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The person a host named, the standalone default, or why nobody can be named. */
|
|
36
|
+
export type IdentityOutcome =
|
|
37
|
+
| { readonly kind: "person"; readonly viewer: ViewerSpec }
|
|
38
|
+
| { readonly kind: "default" }
|
|
39
|
+
| { readonly kind: "unavailable"; readonly diagnostic: Diagnostic };
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The headers a host sees: names in lower case, without `cookie` (Mostra's sessions and every
|
|
43
|
+
* other page's of this host) and without Mostra's own `x-mostra-*` headers.
|
|
44
|
+
*/
|
|
45
|
+
export function identityHeaders(headers: Headers): Record<string, string> {
|
|
46
|
+
const seen: Record<string, string> = {};
|
|
47
|
+
headers.forEach((value, name) => {
|
|
48
|
+
const key = name.toLowerCase();
|
|
49
|
+
if (key === "cookie" || key.startsWith("x-mostra-")) return;
|
|
50
|
+
seen[key] = value;
|
|
51
|
+
});
|
|
52
|
+
return seen;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Asks the host that took identity over. Its outage never makes the session someone else: a
|
|
57
|
+
* failure, a timeout, an answer the schema refuses, or an expected host that isn't connected is
|
|
58
|
+
* `unavailable`, and the exchange is refused.
|
|
59
|
+
*/
|
|
60
|
+
export async function resolveIdentity(input: IdentityInput): Promise<IdentityOutcome> {
|
|
61
|
+
const registrant = input.registrant();
|
|
62
|
+
const unavailable = (message: string): IdentityOutcome => ({
|
|
63
|
+
kind: "unavailable",
|
|
64
|
+
diagnostic: createDiagnostic("MOSTRA_HOST_IDENTITY_UNAVAILABLE", { message }),
|
|
65
|
+
});
|
|
66
|
+
if (registrant) {
|
|
67
|
+
try {
|
|
68
|
+
const answer = await input.call(registrant.session, {
|
|
69
|
+
artifactId: input.artifactId,
|
|
70
|
+
via: input.via,
|
|
71
|
+
headers: identityHeaders(input.headers),
|
|
72
|
+
});
|
|
73
|
+
const parsed = portIdentityResolveMethod.result.safeParse(answer);
|
|
74
|
+
if (parsed.success) {
|
|
75
|
+
return parsed.data === null ? { kind: "default" } : { kind: "person", viewer: parsed.data };
|
|
76
|
+
}
|
|
77
|
+
input.log.warn("gateway.identity_invalid", {
|
|
78
|
+
owner: registrant.owner,
|
|
79
|
+
artifactId: input.artifactId,
|
|
80
|
+
});
|
|
81
|
+
return unavailable(
|
|
82
|
+
`The host ${registrant.owner} answered who this is in a form Mostra refuses.`,
|
|
83
|
+
);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
input.log.warn("gateway.identity_failed", {
|
|
86
|
+
owner: registrant.owner,
|
|
87
|
+
artifactId: input.artifactId,
|
|
88
|
+
error: (error as Error).message,
|
|
89
|
+
});
|
|
90
|
+
return unavailable(`The host ${registrant.owner} didn't say who this is.`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const away = input.expected();
|
|
94
|
+
if (away.length > 0) {
|
|
95
|
+
input.log.warn("gateway.identity_host_away", { owners: away, artifactId: input.artifactId });
|
|
96
|
+
return unavailable(
|
|
97
|
+
`The host that identifies this home's viewers (${away.join(", ")}) isn't running.`,
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
return { kind: "default" };
|
|
101
|
+
}
|