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,725 @@
1
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
2
+ import type { Socket } from "node:net";
3
+ import { hostname } from "node:os";
4
+ import {
5
+ BridgeError,
6
+ CONTRACT_VERSION,
7
+ DEFAULT_PORT,
8
+ externalBridgeHostAuthorities,
9
+ MAX_BODY_BYTES,
10
+ PLUGIN_NAME,
11
+ PLUGIN_VERSION,
12
+ RATE_LIMIT_MAX,
13
+ RATE_LIMIT_WINDOW_MS,
14
+ ResolveRequestSchema,
15
+ SendRequestSchema,
16
+ type BridgeStatus,
17
+ type ErrorBody,
18
+ type ModeOption,
19
+ type PingResponse,
20
+ type ProviderOption,
21
+ type ResolveRoute,
22
+ } from "../shared/contracts";
23
+ import { readDaemonStatus, withPaseo } from "./daemon";
24
+ import { logDependencySelfCheck } from "./deps";
25
+ import {
26
+ handleResolve,
27
+ listEffectiveProviders,
28
+ listModes,
29
+ resolveSelectedProfile,
30
+ } from "./resolve";
31
+ import { handleSend, isDryRun, recordFailedSend } from "./send";
32
+ import { previewToken, settings, tokenMatches } from "./settings";
33
+ import { machineById, resolveOnMachine, sendToMachine } from "./peers";
34
+
35
+ /**
36
+ * The local HTTP bridge the Chrome extension talks to.
37
+ *
38
+ * This endpoint can start agents that run arbitrary code on this machine, so it
39
+ * is treated as a real privilege boundary rather than a convenience:
40
+ *
41
+ * - it binds `127.0.0.1` only, never `0.0.0.0`;
42
+ * - it rejects any request carrying a non-extension `Origin`, on the preflight
43
+ * as well as the real request, because CORS only stops a page *reading* a
44
+ * response and would not stop the side effect;
45
+ * - it rejects any `Host` whose hostname is not loopback (or explicitly
46
+ * allow-listed), which closes DNS rebinding;
47
+ * - it requires a bearer token everywhere except `GET /v1/ping`;
48
+ * - it caps bodies and rate limits per origin.
49
+ *
50
+ * It also owns the reload story. A listening HTTP server keeps the plugin
51
+ * subprocess event loop alive, which wedges Paseo's "Stopping plugin" step, so
52
+ * teardown closes the listener *and* every keep-alive socket and waits for the
53
+ * close to complete. The v0.8 server entry owns that lifecycle directly.
54
+ */
55
+
56
+ const BIND_HOST = "127.0.0.1";
57
+ /** Bounded drain so an oversized upload gets a real 413 instead of a reset. */
58
+ const DRAIN_CEILING_BYTES = MAX_BODY_BYTES * 16;
59
+ const SHUTDOWN_GRACE_MS = 3_000;
60
+
61
+ type BridgeState = "starting" | "running" | "failed" | "stopped";
62
+
63
+ interface Runtime {
64
+ server: Server;
65
+ sockets: Set<Socket>;
66
+ port: number;
67
+ }
68
+
69
+ let runtime: Runtime | null = null;
70
+ let startPromise: Promise<void> | null = null;
71
+ let stopping = false;
72
+
73
+ const status = {
74
+ state: "starting" as BridgeState,
75
+ port: DEFAULT_PORT,
76
+ configuredPort: DEFAULT_PORT,
77
+ error: null as string | null,
78
+ startedAt: null as string | null,
79
+ lastRequestAt: null as string | null,
80
+ requestCount: 0,
81
+ };
82
+
83
+ // ---------------------------------------------------------------------------
84
+ // Rate limiting
85
+ // ---------------------------------------------------------------------------
86
+
87
+ /**
88
+ * Sliding window per origin. Pruned lazily on each request rather than on a
89
+ * timer, because a live `setInterval` in this subprocess is exactly what hangs
90
+ * plugin teardown.
91
+ */
92
+ const hits = new Map<string, number[]>();
93
+
94
+ function rateLimited(key: string): boolean {
95
+ const now = Date.now();
96
+ const window = (hits.get(key) ?? []).filter((at) => now - at < RATE_LIMIT_WINDOW_MS);
97
+ if (window.length >= RATE_LIMIT_MAX) {
98
+ hits.set(key, window);
99
+ return true;
100
+ }
101
+ window.push(now);
102
+ hits.set(key, window);
103
+ if (hits.size > 64) {
104
+ for (const [otherKey, timestamps] of hits) {
105
+ if (timestamps.every((at) => now - at >= RATE_LIMIT_WINDOW_MS)) hits.delete(otherKey);
106
+ }
107
+ }
108
+ return false;
109
+ }
110
+
111
+ // ---------------------------------------------------------------------------
112
+ // Request plumbing
113
+ // ---------------------------------------------------------------------------
114
+
115
+ function writeJson(
116
+ res: ServerResponse,
117
+ code: number,
118
+ body: unknown,
119
+ headers: Record<string, string>,
120
+ ): void {
121
+ const payload = JSON.stringify(body);
122
+ res.writeHead(code, {
123
+ "Content-Type": "application/json; charset=utf-8",
124
+ "Content-Length": Buffer.byteLength(payload),
125
+ "Cache-Control": "no-store",
126
+ "X-Content-Type-Options": "nosniff",
127
+ // Sent on every response, allowed or not, so no cache can mix them up.
128
+ Vary: "Origin",
129
+ ...headers,
130
+ });
131
+ res.end(payload);
132
+ }
133
+
134
+ /** CORS echo for an origin that already passed the extension-origin check. */
135
+ function corsHeaders(origin: string | undefined): Record<string, string> {
136
+ if (origin === undefined) return {};
137
+ return {
138
+ "Access-Control-Allow-Origin": origin,
139
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
140
+ "Access-Control-Allow-Headers": "Authorization, Content-Type",
141
+ "Access-Control-Max-Age": "600",
142
+ // Deliberately no Access-Control-Allow-Credentials.
143
+ };
144
+ }
145
+
146
+ function fail(
147
+ res: ServerResponse,
148
+ error: BridgeError,
149
+ headers: Record<string, string> = {},
150
+ ): void {
151
+ const body: ErrorBody = error.toBody();
152
+ writeJson(res, error.status, body, headers);
153
+ }
154
+
155
+ /** Hostnames that can only ever mean this machine. */
156
+ const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
157
+
158
+ /** The hostname half of a `Host` header. IPv6 keeps its brackets. */
159
+ function hostnameOf(hostHeader: string): string {
160
+ const h = hostHeader.trim().toLowerCase();
161
+ if (h.startsWith("[")) {
162
+ const close = h.indexOf("]");
163
+ return close === -1 ? h : h.slice(0, close + 1);
164
+ }
165
+ const colon = h.indexOf(":");
166
+ return colon === -1 ? h : h.slice(0, colon);
167
+ }
168
+
169
+ /**
170
+ * DNS-rebinding guard on the `Host` header.
171
+ *
172
+ * The rule is **loopback hostname, any port** — deliberately not "the exact
173
+ * `host:port` this listener bound", which is what it used to be. That older
174
+ * form broke the supported way to reach a second Paseo machine: an `ssh -L
175
+ * 7789:127.0.0.1:7788 devbox` tunnel makes the browser send `Host:
176
+ * 127.0.0.1:7789` while the remote bridge is bound on 7788, and the request was
177
+ * refused with `forbidden_host` even though it came from the extension over a
178
+ * loopback socket the user themselves opened.
179
+ *
180
+ * Pinning the port added no security on top of the hostname test. Rebinding
181
+ * works by making an attacker-controlled *name* resolve to 127.0.0.1; the
182
+ * request then carries `Host: evil.com` and `Origin: https://evil.com`, and both
183
+ * are already refused here — the hostname is not loopback, and the origin is not
184
+ * `chrome-extension://`. A port number was never what stood in the way.
185
+ *
186
+ * `externalBridgeUrl` is the declared reverse-proxy origin. Saving it is an
187
+ * explicit allowlist decision in the Paseo surface; the listener still binds
188
+ * 127.0.0.1 only, so the user must separately run that proxy. `allowedHosts`
189
+ * remains as a backwards-compatible file-only escape hatch.
190
+ */
191
+ function hostAllowed(
192
+ host: string | undefined,
193
+ externalBridgeUrl: string | null,
194
+ extraAllowed: readonly string[],
195
+ ): boolean {
196
+ if (host === undefined) return false;
197
+ const h = host.trim().toLowerCase();
198
+ if (LOOPBACK_HOSTNAMES.has(hostnameOf(h))) return true;
199
+ return [...externalBridgeHostAuthorities(externalBridgeUrl), ...extraAllowed].some(
200
+ (allowed) => allowed.trim().toLowerCase() === h,
201
+ );
202
+ }
203
+
204
+ /**
205
+ * Reads at most `MAX_BODY_BYTES`, but keeps draining past that so an oversized
206
+ * request still receives its 413 rather than a connection reset.
207
+ */
208
+ function readBody(req: IncomingMessage): Promise<{ body: Buffer; tooLarge: boolean }> {
209
+ return new Promise((resolve, reject) => {
210
+ const declared = Number(req.headers["content-length"] ?? "");
211
+ let tooLarge = Number.isFinite(declared) && declared > MAX_BODY_BYTES;
212
+ const chunks: Buffer[] = [];
213
+ let total = 0;
214
+ let drained = 0;
215
+
216
+ req.on("data", (chunk: Buffer) => {
217
+ total += chunk.length;
218
+ drained += chunk.length;
219
+ if (total > MAX_BODY_BYTES) {
220
+ tooLarge = true;
221
+ chunks.length = 0;
222
+ if (drained > DRAIN_CEILING_BYTES) req.destroy();
223
+ return;
224
+ }
225
+ chunks.push(chunk);
226
+ });
227
+ req.on("end", () => resolve({ body: Buffer.concat(chunks), tooLarge }));
228
+ req.on("error", reject);
229
+ req.on("aborted", () => resolve({ body: Buffer.alloc(0), tooLarge }));
230
+ });
231
+ }
232
+
233
+ function parseJsonBody(body: Buffer): unknown {
234
+ if (body.length === 0) {
235
+ throw new BridgeError("bad_request", "A JSON body is required.");
236
+ }
237
+ try {
238
+ return JSON.parse(body.toString("utf8"));
239
+ } catch {
240
+ throw new BridgeError("bad_request", "The request body is not valid JSON.");
241
+ }
242
+ }
243
+
244
+ /** Turns a Zod failure into one readable sentence for the popover. */
245
+ function badRequest(issues: { path: PropertyKey[]; message: string }[]): BridgeError {
246
+ const first = issues[0];
247
+ const where = first === undefined ? "" : first.path.map(String).join(".");
248
+ const detail =
249
+ first === undefined
250
+ ? "The request body did not match the expected shape."
251
+ : where === ""
252
+ ? first.message
253
+ : `${where}: ${first.message}`;
254
+ return new BridgeError("bad_request", detail);
255
+ }
256
+
257
+ /** True when the caller sent any `Authorization` header at all. */
258
+ function hasAuthHeader(req: IncomingMessage): boolean {
259
+ const header = req.headers.authorization;
260
+ return typeof header === "string" && header.trim() !== "";
261
+ }
262
+
263
+ async function requireToken(req: IncomingMessage): Promise<void> {
264
+ const header = req.headers.authorization;
265
+ const presented =
266
+ typeof header === "string" && header.startsWith("Bearer ") ? header.slice(7).trim() : "";
267
+ if (presented === "") {
268
+ throw new BridgeError(
269
+ "unauthorized",
270
+ "This request needs the Send to Paseo pairing token.",
271
+ "Copy the token from Paseo -> Send to Paseo into the extension options page.",
272
+ );
273
+ }
274
+ const current = await settings.read();
275
+ if (!tokenMatches(current.token, presented)) {
276
+ throw new BridgeError(
277
+ "unauthorized",
278
+ "That pairing token is not valid for this Paseo bridge.",
279
+ "Copy the current token from Paseo -> Send to Paseo.",
280
+ );
281
+ }
282
+ if (!current.paired) await settings.markPaired().catch(() => undefined);
283
+ }
284
+
285
+ // ---------------------------------------------------------------------------
286
+ // Routes
287
+ // ---------------------------------------------------------------------------
288
+
289
+ /**
290
+ * This machine's own name, for a bridge to introduce itself with.
291
+ *
292
+ * The point is the extension's host list: with two Paseo machines reached
293
+ * through loopback tunnels, every bridge URL is some `127.0.0.1:<port>`, and
294
+ * "127.0.0.1:7789" is a useless name for "devbox". Sending the hostname lets
295
+ * the extension label a host the way the user thinks of it without them typing
296
+ * anything. Unauthenticated too, so it is available while pairing.
297
+ *
298
+ * Not a secret: it is already all over the deep links and the daemon's own
299
+ * status endpoint, and the request had to clear the extension-origin check to
300
+ * get here. Falls back to "" rather than throwing on a host with no name.
301
+ */
302
+ function machineName(): string {
303
+ try {
304
+ return hostname() || "";
305
+ } catch {
306
+ return "";
307
+ }
308
+ }
309
+
310
+ /**
311
+ * Health, and the one place the extension can validate a pasted token.
312
+ *
313
+ * Auth is optional but not ignored, per CONTRACT.md "Token validation on ping":
314
+ * no header is the unauthenticated liveness check (so the options page can tell
315
+ * "bridge down" from "bad token"), a valid token also returns the provider list,
316
+ * and an invalid token is a 401 rather than a cheerful 200.
317
+ */
318
+ async function ping(authenticated: boolean): Promise<PingResponse> {
319
+ const daemon = await readDaemonStatus();
320
+ let providers: ProviderOption[] = [];
321
+ let modes: ModeOption[] = [];
322
+ if (authenticated) {
323
+ try {
324
+ ({ providers, modes } = await withPaseo(async (paseo) => {
325
+ // The same effective default the popover preselects, so ping and
326
+ // resolve never disagree about which model is "the" default.
327
+ const profile = await resolveSelectedProfile(paseo);
328
+ const [providerResult, catalog] = await Promise.all([
329
+ listEffectiveProviders(paseo, profile),
330
+ listModes(paseo),
331
+ ]);
332
+ return { providers: providerResult.providers, modes: catalog.modes };
333
+ }));
334
+ } catch (error) {
335
+ // Ping reports status; it does not fail. An unreachable daemon already
336
+ // shows up in `daemon.reachable`.
337
+ console.error("[send-to-paseo] could not list providers for ping", String(error));
338
+ }
339
+ }
340
+ return {
341
+ ok: true,
342
+ name: PLUGIN_NAME,
343
+ version: PLUGIN_VERSION,
344
+ contract: CONTRACT_VERSION,
345
+ daemon,
346
+ machine: { name: machineName() },
347
+ paired: authenticated,
348
+ providers,
349
+ modes,
350
+ };
351
+ }
352
+
353
+ async function route(
354
+ req: IncomingMessage,
355
+ res: ServerResponse,
356
+ path: string,
357
+ localOnly: boolean,
358
+ ): Promise<void> {
359
+ const cors = corsHeaders(req.headers.origin);
360
+
361
+ if (path === "/v1/ping") {
362
+ if (req.method !== "GET") throw methodNotAllowed();
363
+ // An Authorization header, once sent, is validated: a garbage token must not
364
+ // come back as a 200 that the options page would read as "paired".
365
+ const authenticated = hasAuthHeader(req);
366
+ if (authenticated) await requireToken(req);
367
+ writeJson(res, 200, await ping(authenticated), cors);
368
+ return;
369
+ }
370
+
371
+ if (path === "/v1/resolve" || path === "/v1/send") {
372
+ if (req.method !== "POST") throw methodNotAllowed();
373
+ const { body, tooLarge } = await readBody(req);
374
+ if (tooLarge) {
375
+ throw new BridgeError(
376
+ "payload_too_large",
377
+ `The request body is larger than the ${MAX_BODY_BYTES / 1024} KiB limit.`,
378
+ );
379
+ }
380
+ await requireToken(req);
381
+ const json = parseJsonBody(body);
382
+
383
+ if (path === "/v1/resolve") {
384
+ const parsed = ResolveRequestSchema.safeParse(json);
385
+ if (!parsed.success) throw badRequest(parsed.error.issues);
386
+ if (localOnly) {
387
+ writeJson(res, 200, await handleResolve(parsed.data), cors);
388
+ return;
389
+ }
390
+
391
+ const configured = (await settings.read()).additionalMachines.filter(
392
+ (machine) => machine.enabled,
393
+ );
394
+ if (configured.length === 0) {
395
+ writeJson(res, 200, await handleResolve(parsed.data), cors);
396
+ return;
397
+ }
398
+
399
+ let localError: unknown = null;
400
+ const localAttempt = handleResolve(parsed.data).catch((error: unknown) => {
401
+ localError = error;
402
+ return null;
403
+ });
404
+ // Local and Additional machines run together. A dev VM should add no
405
+ // more latency than whichever machine is slowest.
406
+ const [local, peerRoutes] = await Promise.all([
407
+ localAttempt,
408
+ Promise.all(configured.map((machine) => resolveOnMachine(machine, parsed.data))),
409
+ ]);
410
+ const localRoute: ResolveRoute = {
411
+ routeId: "local",
412
+ routeLabel: machineName() || "Primary Paseo machine",
413
+ bridgeAuthority: `127.0.0.1:${runtime?.port ?? status.port}`,
414
+ resolved: local,
415
+ error:
416
+ local === null
417
+ ? errorPayload(localError, "The primary Paseo machine could not resolve this pull request.")
418
+ : null,
419
+ };
420
+ const routes = [localRoute, ...peerRoutes];
421
+ const base = local ?? peerRoutes.find((item) => item.resolved !== null)?.resolved ?? null;
422
+ if (base === null) {
423
+ if (localError instanceof BridgeError) throw localError;
424
+ throw new BridgeError(
425
+ "daemon_unreachable",
426
+ "No connected Paseo machine could resolve this pull request.",
427
+ );
428
+ }
429
+ writeJson(res, 200, { ...base, routes }, cors);
430
+ return;
431
+ }
432
+
433
+ const parsed = SendRequestSchema.safeParse(json);
434
+ if (!parsed.success) throw badRequest(parsed.error.issues);
435
+ try {
436
+ const routeId = parsed.data.target.routeId;
437
+ if (!localOnly && routeId !== undefined && routeId !== "local") {
438
+ const machine = await machineById(routeId);
439
+ if (machine === null || !machine.enabled) {
440
+ throw new BridgeError(
441
+ "bad_request",
442
+ "The additional Paseo machine for this target is no longer connected. Reopen the composer.",
443
+ );
444
+ }
445
+ try {
446
+ writeJson(res, 200, await sendToMachine(machine, parsed.data), cors);
447
+ } catch (error) {
448
+ if (error instanceof BridgeError) throw error;
449
+ throw new BridgeError(
450
+ "daemon_unreachable",
451
+ error instanceof Error ? error.message : String(error),
452
+ "Check Tailscale and the Send to Paseo plugin on the Additional machine. If this followed Send, check Paseo there before retrying because the request may still have completed.",
453
+ );
454
+ }
455
+ return;
456
+ }
457
+ writeJson(res, 200, await handleSend(parsed.data), cors);
458
+ } catch (error) {
459
+ // Validation noise does not belong in the surface's send history; a real
460
+ // failure to create a workspace or an agent does.
461
+ const isValidation = error instanceof BridgeError && error.code === "bad_request";
462
+ if (error instanceof Error && !isValidation) await recordFailedSend(parsed.data, error);
463
+ throw error;
464
+ }
465
+ return;
466
+ }
467
+
468
+ // The path is not echoed back: it is caller-controlled, and a response body
469
+ // is no place to reflect it.
470
+ throw new BridgeError(
471
+ "bad_request",
472
+ "No such endpoint on this bridge.",
473
+ "Valid paths are /v1/ping, /v1/resolve and /v1/send.",
474
+ );
475
+ }
476
+
477
+ function errorPayload(error: unknown, fallback: string): ErrorBody["error"] {
478
+ if (error instanceof BridgeError) return error.toBody().error;
479
+ return { code: "internal", message: fallback };
480
+ }
481
+
482
+ function methodNotAllowed(): BridgeError {
483
+ return new BridgeError("bad_request", "That method is not allowed on this endpoint.");
484
+ }
485
+
486
+ async function onRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
487
+ const port = runtime?.port ?? status.port;
488
+ const origin = req.headers.origin;
489
+ const cors = corsHeaders(origin);
490
+ // Read once: both the Origin pin and the Host allowlist come from settings,
491
+ // and the store is memory-cached so this does not touch the filesystem.
492
+ const current = await settings.read().catch(() => null);
493
+
494
+ // 1. Origin. A page origin is refused outright, on the preflight too, so the
495
+ // real request is never even sent by the browser.
496
+ if (origin !== undefined) {
497
+ const pinned = current?.allowedExtensionIds ?? [];
498
+ const isExtension = origin.startsWith("chrome-extension://");
499
+ const isPinned =
500
+ pinned.length === 0 || pinned.some((id) => origin === `chrome-extension://${id}`);
501
+ if (!isExtension || !isPinned) {
502
+ console.error(`[send-to-paseo] refused a request from a non-extension origin`);
503
+ fail(
504
+ res,
505
+ new BridgeError(
506
+ "forbidden_origin",
507
+ "This bridge only accepts requests from the Send to Paseo browser extension.",
508
+ ),
509
+ );
510
+ return;
511
+ }
512
+ }
513
+
514
+ // 2. Host. Closes DNS rebinding from a page that resolves a name to 127.0.0.1.
515
+ if (
516
+ !hostAllowed(
517
+ req.headers.host,
518
+ current?.externalBridgeUrl ?? null,
519
+ current?.allowedHosts ?? [],
520
+ )
521
+ ) {
522
+ fail(
523
+ res,
524
+ new BridgeError(
525
+ "forbidden_host",
526
+ "This Host header is not allowed by the bridge configuration.",
527
+ "Set the Private bridge address under Share this Paseo machine, then reconnect it on the Primary Paseo machine.",
528
+ ),
529
+ cors,
530
+ );
531
+ return;
532
+ }
533
+
534
+ // 3. Rate limit, before any work is done. Keyed on Origin when there is one
535
+ // and on the remote address otherwise, so a curl flood from the CLI cannot
536
+ // consume the extension's budget.
537
+ if (rateLimited(origin ?? `ip:${req.socket.remoteAddress ?? "unknown"}`)) {
538
+ fail(res, new BridgeError("rate_limited", "Too many requests; slow down."), {
539
+ ...cors,
540
+ "Retry-After": String(Math.ceil(RATE_LIMIT_WINDOW_MS / 1000)),
541
+ });
542
+ return;
543
+ }
544
+
545
+ status.requestCount += 1;
546
+ status.lastRequestAt = new Date().toISOString();
547
+
548
+ // 4. Preflight. Browsers never attach Authorization to it.
549
+ if (req.method === "OPTIONS") {
550
+ res.writeHead(204, { Vary: "Origin", "Cache-Control": "no-store", ...cors });
551
+ res.end();
552
+ return;
553
+ }
554
+
555
+ const requestUrl = new URL(req.url ?? "/", `http://${BIND_HOST}:${port}`);
556
+ const path = requestUrl.pathname;
557
+ try {
558
+ await route(req, res, path, requestUrl.searchParams.get("local") === "1");
559
+ } catch (error) {
560
+ if (error instanceof BridgeError) {
561
+ fail(res, error, cors);
562
+ return;
563
+ }
564
+ // Anything unexpected is generic on the wire; the detail goes to the log.
565
+ console.error("[send-to-paseo] request failed", String(error));
566
+ fail(res, new BridgeError("internal", "The Send to Paseo bridge hit an unexpected error."), cors);
567
+ }
568
+ }
569
+
570
+ // ---------------------------------------------------------------------------
571
+ // Lifecycle
572
+ // ---------------------------------------------------------------------------
573
+
574
+ function describeListenError(error: NodeJS.ErrnoException, port: number): string {
575
+ if (error.code === "EADDRINUSE") {
576
+ return `Port ${port} is already in use, so the Send to Paseo bridge did not start. Pick another port in Paseo -> Send to Paseo.`;
577
+ }
578
+ if (error.code === "EACCES") {
579
+ return `Port ${port} needs elevated privileges, so the Send to Paseo bridge did not start. Pick a port above 1024.`;
580
+ }
581
+ return `The Send to Paseo bridge could not listen on 127.0.0.1:${port}: ${error.message}`;
582
+ }
583
+
584
+ async function startBridge(): Promise<void> {
585
+ if (stopping) return;
586
+ const current = await settings.read().catch(() => null);
587
+ const port = current?.port ?? DEFAULT_PORT;
588
+ status.configuredPort = port;
589
+ status.port = port;
590
+ status.state = "starting";
591
+ status.error = null;
592
+
593
+ const sockets = new Set<Socket>();
594
+ const server = createServer((req, res) => {
595
+ void onRequest(req, res).catch((error: unknown) => {
596
+ console.error("[send-to-paseo] request handler crashed", String(error));
597
+ if (!res.headersSent) {
598
+ fail(res, new BridgeError("internal", "The Send to Paseo bridge hit an unexpected error."));
599
+ }
600
+ });
601
+ });
602
+ // Keep-alive sockets are what hold a plugin subprocess open; keep them short
603
+ // lived and track every one so teardown can destroy them.
604
+ server.keepAliveTimeout = 5_000;
605
+ server.headersTimeout = 10_000;
606
+ server.requestTimeout = 60_000;
607
+ server.on("connection", (socket) => {
608
+ sockets.add(socket);
609
+ socket.on("close", () => sockets.delete(socket));
610
+ });
611
+
612
+ try {
613
+ await new Promise<void>((resolveListen, rejectListen) => {
614
+ const onError = (error: Error) => {
615
+ server.removeListener("listening", onListening);
616
+ rejectListen(error);
617
+ };
618
+ const onListening = () => {
619
+ server.removeListener("error", onError);
620
+ resolveListen();
621
+ };
622
+ server.once("error", onError);
623
+ server.once("listening", onListening);
624
+ server.listen(port, BIND_HOST);
625
+ });
626
+ } catch (error) {
627
+ status.state = "failed";
628
+ status.error = describeListenError(error as NodeJS.ErrnoException, port);
629
+ console.error(`[send-to-paseo] ${status.error}`);
630
+ server.close();
631
+ return;
632
+ }
633
+
634
+ // A late error must not take the subprocess down with it.
635
+ server.on("error", (error) => {
636
+ console.error("[send-to-paseo] bridge server error", String(error));
637
+ });
638
+
639
+ runtime = { server, sockets, port };
640
+ status.state = "running";
641
+ status.startedAt = new Date().toISOString();
642
+ console.log(
643
+ `[send-to-paseo] bridge listening on http://${BIND_HOST}:${port}${isDryRun() ? " (dry run)" : ""}`,
644
+ );
645
+
646
+ // One line per external command, once, to `paseo plugin logs send-to-paseo`.
647
+ // Deliberately not awaited: the bridge is already serving, and a slow
648
+ // `gh auth status` must not delay that. Runs once per plugin start.
649
+ void logDependencySelfCheck();
650
+
651
+ if (stopping) await stopBridge();
652
+ }
653
+
654
+ async function stopBridge(): Promise<void> {
655
+ const active = runtime;
656
+ runtime = null;
657
+ if (active === null) {
658
+ status.state = "stopped";
659
+ return;
660
+ }
661
+ const closed = new Promise<void>((done) => {
662
+ active.server.close(() => done());
663
+ });
664
+ // `close()` alone waits forever on idle keep-alive sockets, which is exactly
665
+ // the failure that wedges "Stopping plugin".
666
+ active.server.closeAllConnections();
667
+ for (const socket of active.sockets) socket.destroy();
668
+ active.sockets.clear();
669
+
670
+ const timeout = new Promise<void>((done) => {
671
+ const timer = setTimeout(done, SHUTDOWN_GRACE_MS);
672
+ timer.unref?.();
673
+ });
674
+ await Promise.race([closed, timeout]);
675
+ status.state = "stopped";
676
+ console.log("[send-to-paseo] bridge stopped");
677
+ }
678
+
679
+ /** Rebinds the listener, used when the port changes from the Paseo surface. */
680
+ export async function restartBridge(): Promise<BridgeStatus> {
681
+ await startPromise?.catch(() => undefined);
682
+ await stopBridge();
683
+ stopping = false;
684
+ startPromise = startBridge();
685
+ await startPromise;
686
+ return getBridgeStatus();
687
+ }
688
+
689
+ export async function getBridgeStatus(): Promise<BridgeStatus> {
690
+ const [current, daemon] = await Promise.all([settings.read(), readDaemonStatus()]);
691
+ return {
692
+ state: status.state,
693
+ port: status.port,
694
+ configuredPort: current.port,
695
+ error: status.error,
696
+ startedAt: status.startedAt,
697
+ lastRequestAt: status.lastRequestAt,
698
+ requestCount: status.requestCount,
699
+ paired: current.paired,
700
+ dryRun: isDryRun(),
701
+ tokenPreview: previewToken(current.token),
702
+ defaultProvider: current.defaultProvider,
703
+ defaultProfileId: current.defaultProfileId,
704
+ defaultModeId: current.defaultModeId,
705
+ agentDispatch: current.agentDispatch,
706
+ externalBridgeUrl: current.externalBridgeUrl,
707
+ daemon,
708
+ };
709
+ }
710
+
711
+ /** Start the bridge for the v0.8 server entry and return its cleanup. */
712
+ export function runBridge(): () => Promise<void> {
713
+ stopping = false;
714
+ startPromise = startBridge().catch((error: unknown) => {
715
+ status.state = "failed";
716
+ status.error = error instanceof Error ? error.message : String(error);
717
+ console.error("[send-to-paseo] bridge failed to start", status.error);
718
+ });
719
+
720
+ return async () => {
721
+ stopping = true;
722
+ await startPromise?.catch(() => undefined);
723
+ await stopBridge();
724
+ };
725
+ }