send-to-paseo 1.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.
@@ -0,0 +1,404 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { hostname } from "node:os";
3
+ import {
4
+ BridgeError,
5
+ CONTRACT_VERSION,
6
+ ERROR_STATUS,
7
+ PLUGIN_NAME,
8
+ externalBridgeUrlProblem,
9
+ normalizeExternalBridgeUrl,
10
+ type AdditionalMachine,
11
+ type ErrorBody,
12
+ type ErrorCode,
13
+ type PingResponse,
14
+ type ResolveRequest,
15
+ type ResolveResponse,
16
+ type ResolveRoute,
17
+ type SendRequest,
18
+ type SendResponse,
19
+ } from "../shared/contracts";
20
+ import { readDaemonStatus } from "./daemon";
21
+ import { resolveBinary, runProcess } from "./deps";
22
+ import { previewToken, settings, type Settings } from "./settings";
23
+
24
+ const CONNECTION_CODE_PREFIX = "stp1_";
25
+ /**
26
+ * The extension gives resolve 10 seconds and send 60 seconds. A routed
27
+ * operation performs an authenticated ping before the real request, so these
28
+ * are total route budgets shared by both calls rather than per-fetch timers.
29
+ * That keeps a dead Additional machine from making the Primary miss the
30
+ * browser's deadline, while allowing workspace creation to take longer than
31
+ * the old 12-second per-request limit.
32
+ */
33
+ const RESOLVE_ROUTE_TIMEOUT_MS = 9_000;
34
+ const SEND_ROUTE_TIMEOUT_MS = 55_000;
35
+
36
+ type SavedMachine = Settings["additionalMachines"][number];
37
+
38
+ interface ConnectionCodePayload {
39
+ v: 1;
40
+ url: string;
41
+ token: string;
42
+ label: string;
43
+ /** Optional for compatibility with v1 codes created before Paseo 0.9. */
44
+ serverId?: string | null;
45
+ }
46
+
47
+ interface DecodedConnectionCode extends Omit<ConnectionCodePayload, "serverId"> {
48
+ serverId: string | null;
49
+ }
50
+
51
+ export interface ConnectionCodeResult {
52
+ ready: boolean;
53
+ code: string | null;
54
+ bridgeUrl: string | null;
55
+ command: string;
56
+ error: string | null;
57
+ }
58
+
59
+ export function encodeConnectionCode(payload: ConnectionCodePayload): string {
60
+ return `${CONNECTION_CODE_PREFIX}${Buffer.from(JSON.stringify(payload), "utf8").toString("base64url")}`;
61
+ }
62
+
63
+ export function decodeConnectionCode(code: string): DecodedConnectionCode {
64
+ const trimmed = code.trim();
65
+ if (!trimmed.startsWith(CONNECTION_CODE_PREFIX)) {
66
+ throw new Error("This is not a Send to Paseo connection code (expected stp1_…).");
67
+ }
68
+ let raw: unknown;
69
+ try {
70
+ raw = JSON.parse(Buffer.from(trimmed.slice(CONNECTION_CODE_PREFIX.length), "base64url").toString("utf8"));
71
+ } catch {
72
+ throw new Error("The connection code is damaged or incomplete. Copy it again.");
73
+ }
74
+ if (raw === null || typeof raw !== "object") throw new Error("The connection code is invalid.");
75
+ const payload = raw as Partial<ConnectionCodePayload>;
76
+ if (payload.v !== 1 || typeof payload.url !== "string" || typeof payload.token !== "string") {
77
+ throw new Error("The connection code uses an unsupported format.");
78
+ }
79
+ if (payload.token.trim() === "") throw new Error("The connection code has no pairing token.");
80
+ const problem = externalBridgeUrlProblem(payload.url);
81
+ if (problem !== null) throw new Error(`The connection code has an invalid private bridge address: ${problem}`);
82
+ return {
83
+ v: 1,
84
+ url: normalizeExternalBridgeUrl(payload.url),
85
+ token: payload.token,
86
+ label: typeof payload.label === "string" ? payload.label.trim().slice(0, 120) : "",
87
+ serverId:
88
+ typeof payload.serverId === "string" && payload.serverId.trim() !== ""
89
+ ? payload.serverId.trim()
90
+ : null,
91
+ };
92
+ }
93
+
94
+ function displayName(machine: SavedMachine): string {
95
+ return machine.label.trim() || machine.machineName.trim() || new URL(machine.bridgeUrl).host;
96
+ }
97
+
98
+ export function publicMachine(machine: SavedMachine): AdditionalMachine {
99
+ return {
100
+ id: machine.id,
101
+ serverId: machine.serverId,
102
+ label: machine.label,
103
+ bridgeUrl: machine.bridgeUrl,
104
+ enabled: machine.enabled,
105
+ machineName: machine.machineName,
106
+ tokenPreview: previewToken(machine.token),
107
+ };
108
+ }
109
+
110
+ export async function addMachineFromCode(code: string): Promise<AdditionalMachine> {
111
+ const payload = decodeConnectionCode(code);
112
+ const current = await settings.read();
113
+ const duplicate = current.additionalMachines.find(
114
+ (machine) =>
115
+ (payload.serverId !== null && machine.serverId === payload.serverId) ||
116
+ machine.bridgeUrl === payload.url,
117
+ );
118
+ const machine: SavedMachine = {
119
+ id: duplicate?.id ?? randomUUID(),
120
+ serverId: payload.serverId ?? duplicate?.serverId ?? null,
121
+ label: payload.label || duplicate?.label || "",
122
+ bridgeUrl: payload.url,
123
+ token: payload.token,
124
+ enabled: true,
125
+ machineName: duplicate?.machineName ?? "",
126
+ };
127
+ await settings.addAdditionalMachine(machine);
128
+ return publicMachine(machine);
129
+ }
130
+
131
+ function connectionCodeFor(current: Settings, serverId: string | null): string | null {
132
+ if (current.externalBridgeUrl === null) return null;
133
+ return encodeConnectionCode({
134
+ v: 1,
135
+ url: current.externalBridgeUrl,
136
+ token: current.token,
137
+ label: hostname() || new URL(current.externalBridgeUrl).hostname,
138
+ serverId,
139
+ });
140
+ }
141
+
142
+ export async function getMachineConnectionCode(): Promise<ConnectionCodeResult> {
143
+ const current = await settings.read();
144
+ const { serverId } = await readDaemonStatus();
145
+ const command = `tailscale serve --bg ${current.port}`;
146
+ const code = connectionCodeFor(current, serverId);
147
+ return {
148
+ ready: code !== null,
149
+ code,
150
+ bridgeUrl: current.externalBridgeUrl,
151
+ command,
152
+ error:
153
+ code === null
154
+ ? "Private access is not enabled yet. Enable it here, or run the command on this Paseo machine."
155
+ : null,
156
+ };
157
+ }
158
+
159
+ function processMessage(error: unknown): string {
160
+ if (!(error instanceof Error)) return String(error);
161
+ const withStderr = error as Error & { stderr?: string };
162
+ return (withStderr.stderr ?? error.message).trim() || error.message;
163
+ }
164
+
165
+ export async function enableMachinePrivateAccess(): Promise<ConnectionCodeResult> {
166
+ const current = await settings.read();
167
+ const command = `tailscale serve --bg ${current.port}`;
168
+ const tailscale = await resolveBinary("tailscale", [process.env.SEND_TO_PASEO_TAILSCALE_PATH ?? ""]);
169
+ if (tailscale === null) {
170
+ return {
171
+ ready: false,
172
+ code: null,
173
+ bridgeUrl: current.externalBridgeUrl,
174
+ command,
175
+ error: "Tailscale was not found. Install it, then run the command on this Paseo machine.",
176
+ };
177
+ }
178
+
179
+ try {
180
+ await runProcess(tailscale, ["serve", "--bg", String(current.port)], { timeoutMs: 12_000 });
181
+ const { stdout } = await runProcess(tailscale, ["status", "--json"], { timeoutMs: 8_000 });
182
+ const parsed = JSON.parse(stdout) as { Self?: { DNSName?: unknown } };
183
+ const dnsName = typeof parsed.Self?.DNSName === "string" ? parsed.Self.DNSName.replace(/\.$/, "") : "";
184
+ if (dnsName === "") throw new Error("Tailscale did not report this machine's private DNS name.");
185
+ const bridgeUrl = normalizeExternalBridgeUrl(`https://${dnsName}`);
186
+ const next = await settings.update({ externalBridgeUrl: bridgeUrl });
187
+ const { serverId } = await readDaemonStatus();
188
+ return {
189
+ ready: true,
190
+ code: connectionCodeFor(next, serverId),
191
+ bridgeUrl,
192
+ command,
193
+ error: null,
194
+ };
195
+ } catch (error) {
196
+ return {
197
+ ready: false,
198
+ code: null,
199
+ bridgeUrl: current.externalBridgeUrl,
200
+ command,
201
+ error: `Tailscale could not enable private access: ${processMessage(error)}`,
202
+ };
203
+ }
204
+ }
205
+
206
+ async function fetchJson(
207
+ machine: SavedMachine,
208
+ path: string,
209
+ init: RequestInit | undefined,
210
+ timeoutMs: number,
211
+ ): Promise<unknown> {
212
+ let response: Response;
213
+ const controller = new AbortController();
214
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
215
+ try {
216
+ response = await fetch(`${machine.bridgeUrl}${path}`, {
217
+ ...init,
218
+ headers: {
219
+ Authorization: `Bearer ${machine.token}`,
220
+ ...(init?.body === undefined ? {} : { "Content-Type": "application/json" }),
221
+ ...(init?.headers ?? {}),
222
+ },
223
+ signal: controller.signal,
224
+ });
225
+ } catch {
226
+ throw new Error(
227
+ controller.signal.aborted
228
+ ? `${displayName(machine)} did not answer at its private bridge address within ${Math.ceil(timeoutMs / 1000)}s.`
229
+ : `Can't reach ${displayName(machine)} at its private bridge address.`,
230
+ );
231
+ } finally {
232
+ clearTimeout(timeout);
233
+ }
234
+ const json = (await response.json().catch(() => null)) as unknown;
235
+ if (!response.ok) {
236
+ const body = json as Partial<ErrorBody> | null;
237
+ const code = body?.error?.code;
238
+ if (typeof code === "string" && code in ERROR_STATUS) {
239
+ throw new BridgeError(
240
+ code as ErrorCode,
241
+ body?.error?.message ?? `${displayName(machine)} returned HTTP ${response.status}.`,
242
+ body?.error?.hint,
243
+ );
244
+ }
245
+ throw new Error(body?.error?.message ?? `${displayName(machine)} returned HTTP ${response.status}.`);
246
+ }
247
+ return json;
248
+ }
249
+
250
+ function remainingMs(deadline: number): number {
251
+ return Math.max(1, deadline - Date.now());
252
+ }
253
+
254
+ async function checkedPing(machine: SavedMachine, deadline: number): Promise<PingResponse> {
255
+ const json = (await fetchJson(
256
+ machine,
257
+ "/v1/ping",
258
+ undefined,
259
+ remainingMs(deadline),
260
+ )) as Partial<PingResponse>;
261
+ if (json.ok !== true || json.name !== PLUGIN_NAME || typeof json.contract !== "number") {
262
+ throw new Error(`${displayName(machine)} did not return a Send to Paseo bridge response.`);
263
+ }
264
+ if (json.contract !== CONTRACT_VERSION) {
265
+ throw new Error(
266
+ `${displayName(machine)} uses bridge contract v${json.contract}; this machine uses v${CONTRACT_VERSION}. Update the older plugin.`,
267
+ );
268
+ }
269
+ if (json.paired !== true) throw new Error(`${displayName(machine)} rejected its connection code.`);
270
+ const actualServerId = json.daemon?.serverId?.trim() || null;
271
+ if (
272
+ machine.serverId !== null &&
273
+ actualServerId !== null &&
274
+ machine.serverId !== actualServerId
275
+ ) {
276
+ throw new Error(
277
+ `${displayName(machine)} answered as Paseo host ${actualServerId}, but this route targets ${machine.serverId}. Reconnect that host instead of retrying.`,
278
+ );
279
+ }
280
+ return json as PingResponse;
281
+ }
282
+
283
+ export async function testMachine(machine: SavedMachine): Promise<{
284
+ ok: boolean;
285
+ machineName: string | null;
286
+ detail: string;
287
+ }> {
288
+ try {
289
+ const ping = await checkedPing(machine, Date.now() + RESOLVE_ROUTE_TIMEOUT_MS);
290
+ const machineName = ping.machine?.name?.trim() || null;
291
+ const serverId = ping.daemon.serverId?.trim() || null;
292
+ if (
293
+ (machineName !== null && machineName !== machine.machineName) ||
294
+ (serverId !== null && serverId !== machine.serverId)
295
+ ) {
296
+ await settings.updateAdditionalMachine(machine.id, {
297
+ ...(machineName === null ? {} : { machineName }),
298
+ ...(serverId === null ? {} : { serverId }),
299
+ });
300
+ }
301
+ return {
302
+ ok: ping.daemon.reachable,
303
+ machineName,
304
+ detail: ping.daemon.reachable
305
+ ? `Connected to ${machineName ?? displayName(machine)}; Paseo daemon ${ping.daemon.version ?? "version unknown"}.`
306
+ : `The bridge on ${machineName ?? displayName(machine)} answered, but its Paseo daemon is unreachable.`,
307
+ };
308
+ } catch (error) {
309
+ return { ok: false, machineName: null, detail: error instanceof Error ? error.message : String(error) };
310
+ }
311
+ }
312
+
313
+ function looksResolved(value: unknown): value is ResolveResponse {
314
+ if (value === null || typeof value !== "object") return false;
315
+ const candidate = value as Partial<ResolveResponse>;
316
+ return (
317
+ candidate.pr !== undefined &&
318
+ candidate.project !== undefined &&
319
+ Array.isArray(candidate.candidates) &&
320
+ Array.isArray(candidate.providers)
321
+ );
322
+ }
323
+
324
+ export async function resolveOnMachine(
325
+ machine: SavedMachine,
326
+ request: ResolveRequest,
327
+ timeoutMs = RESOLVE_ROUTE_TIMEOUT_MS,
328
+ ): Promise<ResolveRoute> {
329
+ const route: ResolveRoute = {
330
+ routeId: machine.id,
331
+ routeLabel: displayName(machine),
332
+ bridgeAuthority: new URL(machine.bridgeUrl).host,
333
+ resolved: null,
334
+ error: null,
335
+ };
336
+ try {
337
+ const deadline = Date.now() + timeoutMs;
338
+ const ping = await checkedPing(machine, deadline);
339
+ const machineName = ping.machine?.name?.trim() || "";
340
+ const serverId = ping.daemon.serverId?.trim() || null;
341
+ if (
342
+ (machineName && machineName !== machine.machineName) ||
343
+ (serverId !== null && serverId !== machine.serverId)
344
+ ) {
345
+ await settings.updateAdditionalMachine(machine.id, {
346
+ ...(machineName ? { machineName } : {}),
347
+ ...(serverId === null ? {} : { serverId }),
348
+ });
349
+ if (!machine.label.trim()) route.routeLabel = machineName;
350
+ }
351
+ const json = await fetchJson(
352
+ machine,
353
+ "/v1/resolve?local=1",
354
+ {
355
+ method: "POST",
356
+ body: JSON.stringify(request),
357
+ },
358
+ remainingMs(deadline),
359
+ );
360
+ if (!looksResolved(json)) throw new Error(`${displayName(machine)} returned an invalid resolve response.`);
361
+ // A primary machine never imports another primary's routes. The explicit
362
+ // local-only request prevents loops; deleting defensively also handles a
363
+ // bridge that does not understand the query yet.
364
+ const { routes: _nested, ...local } = json;
365
+ route.resolved = local;
366
+ } catch (error) {
367
+ route.error =
368
+ error instanceof BridgeError
369
+ ? error.toBody().error
370
+ : {
371
+ code: "bridge_unreachable",
372
+ message: error instanceof Error ? error.message : String(error),
373
+ };
374
+ }
375
+ return route;
376
+ }
377
+
378
+ export async function sendToMachine(
379
+ machine: SavedMachine,
380
+ request: SendRequest,
381
+ timeoutMs = SEND_ROUTE_TIMEOUT_MS,
382
+ ): Promise<SendResponse> {
383
+ const deadline = Date.now() + timeoutMs;
384
+ await checkedPing(machine, deadline);
385
+ const target = { ...request.target };
386
+ delete target.routeId;
387
+ const json = await fetchJson(
388
+ machine,
389
+ "/v1/send?local=1",
390
+ {
391
+ method: "POST",
392
+ body: JSON.stringify({ ...request, target }),
393
+ },
394
+ remainingMs(deadline),
395
+ );
396
+ if (json === null || typeof json !== "object" || (json as Partial<SendResponse>).ok !== true) {
397
+ throw new BridgeError("daemon_unreachable", `${displayName(machine)} returned an invalid send response.`);
398
+ }
399
+ return json as SendResponse;
400
+ }
401
+
402
+ export async function machineById(id: string): Promise<SavedMachine | null> {
403
+ return (await settings.read()).additionalMachines.find((machine) => machine.id === id) ?? null;
404
+ }