@mostra/runtime 0.6.1 → 0.7.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.
@@ -0,0 +1,217 @@
1
+ /**
2
+ * The Tailscale driver (D158 item 4): Tailscale Serve for tailnet shares and Funnel for public
3
+ * ones, through foreground `tailscale serve` and `tailscale funnel` children, one per address.
4
+ * A foreground configuration lives as long as its command, so a stopped or crashed share leaves
5
+ * nothing exposed. The device's name comes from `tailscale status --json`; a port this device's
6
+ * own configuration already uses is never taken over.
7
+ */
8
+ import { createDiagnostic, RpcError } from "@mostra/protocol";
9
+ import type { Log } from "../log.ts";
10
+ import { installHint, type ToolCommand, toolCommand } from "../platform/index.ts";
11
+ import type { ProcessManager } from "../processes/index.ts";
12
+ import { type LineVerdict, runToCompletion, runTunnel, type Tunnel } from "./tunnel.ts";
13
+
14
+ /** Funnel's ports (VERIFIED_FACTS): the shell takes 443, two artifacts the others (D158 item 4). */
15
+ export const FUNNEL_SHELL_PORT = 443;
16
+ export const FUNNEL_ARTIFACT_PORTS: readonly number[] = [8443, 10000];
17
+
18
+ /** How long `tailscale serve` or `funnel` may take to serve. */
19
+ const SERVE_TIMEOUT_MS = 30_000;
20
+
21
+ /** What the driver needs. */
22
+ export interface TailscaleContext {
23
+ readonly processes: ProcessManager;
24
+ readonly log: Log;
25
+ /** The environment the tool runs in (the artifact allowlist) and is looked up in. */
26
+ readonly env: Readonly<Record<string, string | undefined>>;
27
+ }
28
+
29
+ /** This device on its tailnet. */
30
+ export interface TailnetDevice {
31
+ /** How the tool runs. */
32
+ readonly tool: ToolCommand;
33
+ /** The device's MagicDNS name, such as `laptop.tail1234.ts.net`. */
34
+ readonly hostname: string;
35
+ /** The ports this device serves already (any configuration, its own or Mostra's). */
36
+ readonly served: ReadonlySet<number>;
37
+ }
38
+
39
+ const missing = (): RpcError =>
40
+ new RpcError(
41
+ createDiagnostic("MOSTRA_SHARE_TOOL_MISSING", {
42
+ message: `Tailscale isn't installed on this machine (no \`tailscale\` found). ${installHint("tailscale")}`,
43
+ }),
44
+ );
45
+
46
+ /** Finds Tailscale and this device, or explains what is missing. */
47
+ export async function tailnetDevice(context: TailscaleContext): Promise<TailnetDevice> {
48
+ const tool = toolCommand("tailscale", context.env);
49
+ if (!tool) throw missing();
50
+ const status = await runToCompletion({
51
+ processes: context.processes,
52
+ kind: "tunnel-query",
53
+ ownerRef: "tailscale",
54
+ command: tool.command,
55
+ args: [...tool.args, "status", "--json"],
56
+ env: context.env,
57
+ timeoutMs: 15_000,
58
+ label: "Tailscale",
59
+ });
60
+ let parsed: {
61
+ BackendState?: string;
62
+ Self?: { DNSName?: string };
63
+ CurrentTailnet?: { MagicDNSEnabled?: boolean };
64
+ };
65
+ try {
66
+ parsed = JSON.parse(status.stdout) as typeof parsed;
67
+ } catch {
68
+ throw new RpcError(
69
+ createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", {
70
+ message: `Tailscale didn't report its status: ${(status.stderr || status.stdout).trim().slice(0, 400) || `exit ${status.code}`}. Start Tailscale and sign in (\`tailscale up\`).`,
71
+ }),
72
+ );
73
+ }
74
+ if (parsed.BackendState !== "Running") {
75
+ throw new RpcError(
76
+ createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", {
77
+ message: `Tailscale is ${parsed.BackendState ?? "not running"} on this machine. Start it and sign in (\`tailscale up\`).`,
78
+ }),
79
+ );
80
+ }
81
+ const dns = parsed.Self?.DNSName?.replace(/\.$/, "").toLowerCase();
82
+ if (!dns || parsed.CurrentTailnet?.MagicDNSEnabled === false) {
83
+ throw new RpcError(
84
+ createDiagnostic("MOSTRA_SHARE_NOT_ENABLED", {
85
+ message:
86
+ "This tailnet has MagicDNS off, which Tailscale Serve and Funnel need for the device's name. Turn it on in the tailnet's DNS settings (https://login.tailscale.com/admin/dns).",
87
+ }),
88
+ );
89
+ }
90
+ return { tool, hostname: dns, served: await servedPorts(context, tool) };
91
+ }
92
+
93
+ /** The ports this device's Serve and Funnel configuration uses now. */
94
+ async function servedPorts(context: TailscaleContext, tool: ToolCommand): Promise<Set<number>> {
95
+ const status = await runToCompletion({
96
+ processes: context.processes,
97
+ kind: "tunnel-query",
98
+ ownerRef: "tailscale",
99
+ command: tool.command,
100
+ args: [...tool.args, "serve", "status", "--json"],
101
+ env: context.env,
102
+ timeoutMs: 15_000,
103
+ label: "Tailscale",
104
+ });
105
+ const ports = new Set<number>();
106
+ try {
107
+ const config = JSON.parse(status.stdout || "{}") as {
108
+ TCP?: Record<string, unknown>;
109
+ Foreground?: Record<string, { TCP?: Record<string, unknown> }>;
110
+ };
111
+ for (const key of Object.keys(config.TCP ?? {})) ports.add(Number(key));
112
+ for (const session of Object.values(config.Foreground ?? {})) {
113
+ for (const key of Object.keys(session.TCP ?? {})) ports.add(Number(key));
114
+ }
115
+ } catch {
116
+ // An unreadable configuration hides nothing Tailscale itself would refuse.
117
+ }
118
+ return ports;
119
+ }
120
+
121
+ /**
122
+ * Reads `tailscale serve` and `funnel` output: they serve once they print where; a tailnet
123
+ * without the feature prints the address where an admin turns it on, which the share reports.
124
+ */
125
+ function serveReader(
126
+ feature: "Serve" | "Funnel",
127
+ device: TailnetDevice,
128
+ port: number,
129
+ ): (line: string) => LineVerdict {
130
+ let notEnabled = false;
131
+ const expected = tailnetOrigin(device.hostname, port);
132
+ return (line) => {
133
+ const text = line.trim();
134
+ // The address it prints is the one it serves: the device's name at the port asked for, or,
135
+ // from the test fakes only, plain HTTP on loopback.
136
+ const printed = /^(https?:\/\/\S+?)\/?$/.exec(text)?.[1]?.toLowerCase();
137
+ if (
138
+ printed !== undefined &&
139
+ (printed === expected ||
140
+ (device.tool.fake && /^http:\/\/(\[::1\]|127\.0\.0\.1|localhost):\d+$/.test(printed)))
141
+ ) {
142
+ return { kind: "origin", origin: printed };
143
+ }
144
+ if (/not enabled on your tailnet|isn't enabled|is not enabled/i.test(text)) {
145
+ notEnabled = true;
146
+ return undefined;
147
+ }
148
+ const consent = /https:\/\/login\.tailscale\.com\/\S+/.exec(text);
149
+ if (consent && notEnabled) {
150
+ return {
151
+ kind: "failed",
152
+ diagnostic: createDiagnostic("MOSTRA_SHARE_NOT_ENABLED", {
153
+ message: `Tailscale ${feature} isn't enabled for this device's tailnet. An admin of the tailnet turns it on at ${consent[0]}`,
154
+ }),
155
+ };
156
+ }
157
+ if (
158
+ /^Available (within your tailnet|on the internet)/i.test(text) ||
159
+ /Press Ctrl\+C to exit/i.test(text)
160
+ ) {
161
+ return { kind: "serving" };
162
+ }
163
+ if (/already|in use|conflict/i.test(text) && /port|serve|listen/i.test(text)) {
164
+ return {
165
+ kind: "failed",
166
+ diagnostic: createDiagnostic("MOSTRA_SHARE_PORTS_EXHAUSTED", {
167
+ message: `Tailscale refused the port: ${text.slice(0, 300)}`,
168
+ }),
169
+ };
170
+ }
171
+ if (/^(error|failed)|permission denied|access denied/i.test(text)) {
172
+ return {
173
+ kind: "failed",
174
+ diagnostic: createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", {
175
+ message: `Tailscale ${feature} refused the share: ${text.slice(0, 300)}`,
176
+ }),
177
+ };
178
+ }
179
+ return undefined;
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Serves `local` at `https://<device>:<port>` on the tailnet (`serve`) or on the internet
185
+ * (`funnel`), until the tunnel is stopped.
186
+ */
187
+ export function expose(
188
+ context: TailscaleContext,
189
+ device: TailnetDevice,
190
+ input: {
191
+ readonly feature: "serve" | "funnel";
192
+ readonly port: number;
193
+ readonly local: string;
194
+ readonly ownerRef: string;
195
+ },
196
+ ): Promise<Tunnel> {
197
+ const label = input.feature === "serve" ? "Tailscale Serve" : "Tailscale Funnel";
198
+ return runTunnel({
199
+ processes: context.processes,
200
+ log: context.log,
201
+ kind: `tunnel-${input.feature}`,
202
+ ownerRef: input.ownerRef,
203
+ command: device.tool.command,
204
+ args: [...device.tool.args, input.feature, `--https=${input.port}`, input.local],
205
+ env: context.env,
206
+ read: serveReader(input.feature === "serve" ? "Serve" : "Funnel", device, input.port),
207
+ // A release that doesn't print its address still serves the device's name at that port.
208
+ ...(device.tool.fake ? {} : { origin: tailnetOrigin(device.hostname, input.port) }),
209
+ timeoutMs: SERVE_TIMEOUT_MS,
210
+ label,
211
+ });
212
+ }
213
+
214
+ /** `https://<device>` with the port only when it isn't 443, as a browser writes the origin. */
215
+ export function tailnetOrigin(hostname: string, port: number): string {
216
+ return port === 443 ? `https://${hostname}` : `https://${hostname}:${port}`;
217
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * A tunnel tool's process (D158 item 4): `tailscale serve`, `tailscale funnel` or `cloudflared`,
3
+ * started through the process manager (recorded, gated, reaped after a crash, RT-09), its output
4
+ * read line by line until it says it serves, fails, or runs out of time. A tunnel that serves
5
+ * keeps running until it is stopped; `ended` says when it ends by itself.
6
+ */
7
+ import { createDiagnostic, type Diagnostic, RpcError } from "@mostra/protocol";
8
+ import type { Log } from "../log.ts";
9
+ import type { ChildHandle, ProcessManager } from "../processes/index.ts";
10
+
11
+ /** What a tunnel's output line means while it starts. */
12
+ export type LineVerdict =
13
+ | { readonly kind: "serving"; readonly origin?: string }
14
+ | { readonly kind: "origin"; readonly origin: string }
15
+ | { readonly kind: "failed"; readonly diagnostic: Diagnostic }
16
+ | undefined;
17
+
18
+ /** A tunnel that serves. */
19
+ export interface Tunnel {
20
+ /** The tunnel's external origin. */
21
+ readonly origin: string;
22
+ /** Resolves when the tunnel's process ends by itself (a stop doesn't resolve it). */
23
+ readonly ended: Promise<{ readonly code: number | null; readonly lines: readonly string[] }>;
24
+ /** Stops the tunnel's process. */
25
+ stop(): Promise<void>;
26
+ }
27
+
28
+ /** Options for {@link runTunnel}. */
29
+ export interface TunnelOptions {
30
+ readonly processes: ProcessManager;
31
+ readonly log: Log;
32
+ /** The child's kind in the process manager's records. */
33
+ readonly kind: string;
34
+ /** What it serves (a face's key). */
35
+ readonly ownerRef: string;
36
+ readonly command: string;
37
+ readonly args: readonly string[];
38
+ readonly env: Readonly<Record<string, string | undefined>>;
39
+ /** Reads each line of output: it serves, it names its address, it failed, or nothing yet. */
40
+ readonly read: (line: string) => LineVerdict;
41
+ /** The origin when the tool never names one (Tailscale's comes from the device's name). */
42
+ readonly origin?: string;
43
+ /** How long it may take to serve. */
44
+ readonly timeoutMs: number;
45
+ /** What the tunnel is, for messages: "Tailscale Serve", "a Cloudflare quick tunnel". */
46
+ readonly label: string;
47
+ }
48
+
49
+ const TAIL = 20;
50
+
51
+ /** Starts a tunnel tool and resolves once it serves; rejects with a `MOSTRA_SHARE_*` RpcError. */
52
+ export async function runTunnel(options: TunnelOptions): Promise<Tunnel> {
53
+ const lines: string[] = [];
54
+ let origin = options.origin;
55
+ let settle: ((outcome: { ok: true } | { ok: false; diagnostic: Diagnostic }) => void) | undefined;
56
+ const settled = new Promise<{ ok: true } | { ok: false; diagnostic: Diagnostic }>((resolve) => {
57
+ settle = resolve;
58
+ });
59
+ let serving = false;
60
+ const onLine = (line: string): void => {
61
+ lines.push(line);
62
+ if (lines.length > TAIL) lines.shift();
63
+ if (serving) return;
64
+ const verdict = options.read(line);
65
+ if (verdict === undefined) return;
66
+ if (verdict.kind === "origin") {
67
+ origin = verdict.origin;
68
+ return;
69
+ }
70
+ if (verdict.kind === "failed") {
71
+ settle?.({ ok: false, diagnostic: verdict.diagnostic });
72
+ return;
73
+ }
74
+ if (verdict.origin !== undefined) origin = verdict.origin;
75
+ if (origin !== undefined) {
76
+ serving = true;
77
+ settle?.({ ok: true });
78
+ }
79
+ };
80
+ let child: ChildHandle;
81
+ try {
82
+ child = await options.processes.spawn({
83
+ kind: options.kind,
84
+ ownerRef: options.ownerRef,
85
+ command: options.command,
86
+ args: options.args,
87
+ env: options.env,
88
+ onStdout: onLine,
89
+ onStderr: onLine,
90
+ });
91
+ } catch (error) {
92
+ throw new RpcError(
93
+ createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", {
94
+ message: `${options.label} couldn't start: ${(error as Error).message}`,
95
+ }),
96
+ );
97
+ }
98
+ let stopping = false;
99
+ const exited = child.exited.then((exit) => {
100
+ if (!serving) {
101
+ settle?.({
102
+ ok: false,
103
+ diagnostic: createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", {
104
+ message: `${options.label} ended before it served (exit ${exit.code ?? exit.signal}): ${lastWords(lines)}`,
105
+ }),
106
+ });
107
+ }
108
+ return exit;
109
+ });
110
+ const timer = setTimeout(() => {
111
+ settle?.({
112
+ ok: false,
113
+ diagnostic: createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", {
114
+ message: `${options.label} didn't serve within ${Math.round(options.timeoutMs / 1000)} s: ${lastWords(lines)}`,
115
+ }),
116
+ });
117
+ }, options.timeoutMs);
118
+ const outcome = await settled;
119
+ clearTimeout(timer);
120
+ if (!outcome.ok) {
121
+ stopping = true;
122
+ await child.stop(3000).catch(() => undefined);
123
+ throw new RpcError(outcome.diagnostic);
124
+ }
125
+ options.log.info("share.tunnel_serving", { kind: options.kind, owner: options.ownerRef, origin });
126
+ const ended = exited.then(
127
+ (exit) =>
128
+ new Promise<{ code: number | null; lines: readonly string[] }>((resolve) => {
129
+ if (!stopping) resolve({ code: exit.code, lines: [...lines] });
130
+ }),
131
+ );
132
+ return {
133
+ origin: origin as string,
134
+ ended,
135
+ async stop() {
136
+ stopping = true;
137
+ await child.stop(3000).catch(() => undefined);
138
+ },
139
+ };
140
+ }
141
+
142
+ /** The last meaningful lines of a tool's output, for a message. */
143
+ function lastWords(lines: readonly string[]): string {
144
+ const meaningful = lines.filter((line) => line.trim() !== "").slice(-3);
145
+ return meaningful.length === 0 ? "it said nothing" : meaningful.join(" / ").slice(0, 600);
146
+ }
147
+
148
+ /**
149
+ * Runs a tool to its end and resolves with its standard output (a status query), or rejects with
150
+ * `MOSTRA_SHARE_TOOL_NOT_READY` naming what it said.
151
+ */
152
+ export async function runToCompletion(options: {
153
+ readonly processes: ProcessManager;
154
+ readonly kind: string;
155
+ readonly ownerRef: string;
156
+ readonly command: string;
157
+ readonly args: readonly string[];
158
+ readonly env: Readonly<Record<string, string | undefined>>;
159
+ readonly timeoutMs: number;
160
+ readonly label: string;
161
+ }): Promise<{ readonly code: number | null; readonly stdout: string; readonly stderr: string }> {
162
+ const stdout: string[] = [];
163
+ const stderr: string[] = [];
164
+ let child: ChildHandle;
165
+ try {
166
+ child = await options.processes.spawn({
167
+ kind: options.kind,
168
+ ownerRef: options.ownerRef,
169
+ command: options.command,
170
+ args: options.args,
171
+ env: options.env,
172
+ onStdout: (line) => stdout.push(line),
173
+ onStderr: (line) => stderr.push(line),
174
+ });
175
+ } catch (error) {
176
+ throw new RpcError(
177
+ createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", {
178
+ message: `${options.label} couldn't start: ${(error as Error).message}`,
179
+ }),
180
+ );
181
+ }
182
+ const timer = setTimeout(() => void child.stop(1000), options.timeoutMs);
183
+ const exit = await child.exited;
184
+ clearTimeout(timer);
185
+ return { code: exit.code, stdout: stdout.join("\n"), stderr: stderr.join("\n") };
186
+ }