localgate 0.5.0 → 0.6.1

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,491 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { LocalgateNames } from "../config/localgateNames.ts";
3
+ import { LocalgateHealth } from "./localgateHealth.ts";
4
+ import { LocalgatePortProbe } from "./localgatePortProbe.ts";
5
+ import type { LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
6
+ import type { LocalgateReach, LocalgateRegistry, LocalgateRoute, LocalgateRouteState } from "./localgateRegistry.ts";
7
+ import { LocalgateUrl, type LocalgateAddress } from "./localgateUrl.ts";
8
+
9
+ // How the page ends what a route points at, and how it knows whether it can. One object rather than two
10
+ // callbacks, because the button and the action behind it must not drift apart: a button that appears for
11
+ // something nothing can stop is a click that fails, and the reverse is a verb nobody can find.
12
+ //
13
+ // An app is ended by asking its runner. An alias has no runner, so it can be ended only where the
14
+ // machine's owner wrote down how, which is `stop` in ~/.localgate/aliases.json - hence the names rather
15
+ // than a flag on the route: that file is the only source, and nothing reaching the proxy over a socket
16
+ // can add to it.
17
+ export type LocalgateRouteStopper =
18
+ {
19
+ aliasStopCommands(): ReadonlyMap<string, string>;
20
+ stop(route: LocalgateRoute): Promise<void>;
21
+ };
22
+
23
+ // What the current request asks the page to show on top of the list: one card awaiting confirmation,
24
+ // and the name of whatever was just stopped. Both come from the query string and name a route.
25
+ export type LocalgateStartPageView =
26
+ {
27
+ confirming?: string | null;
28
+ stopped?: string | null;
29
+ // Route id to "something accepts a connection on its port". A route missing from the map was not
30
+ // probed, and then the card falls back to the health the proxy learned from forwarded traffic.
31
+ listening?: ReadonlyMap<string, boolean>;
32
+ };
33
+
34
+ // The one page localgate serves from itself: every route on this machine and the addresses each one
35
+ // answers on, so a person has somewhere to start that does not depend on remembering a name.
36
+ //
37
+ // It is reach-aware for the same reason the route table is. On loopback it shows everything, including
38
+ // the upstream port and the directory a route was started from. On the LAN listener it answers only on
39
+ // the machine's own domain and lists only what a LAN caller can actually open: a route in mode `local`
40
+ // has no address off this machine, so it does not appear at all, and neither do the local paths and
41
+ // ports, which are nobody else's business.
42
+ export class LocalgateStartPage
43
+ {
44
+ private static readonly refreshSecondsConst = 5;
45
+ private static readonly stopPathConst = "/stop";
46
+
47
+ // A hub and three routes, which is what the proxy is. Inline, because the page is served to the LAN
48
+ // and must not fetch anything: a tab icon is not worth a request that could fail or be logged.
49
+ private static readonly faviconConst = "data:image/svg+xml,"
50
+ + "%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E"
51
+ + "%3Crect width='32' height='32' rx='8' fill='%232f6df6'/%3E"
52
+ + "%3Ccircle cx='10' cy='16' r='3.2' fill='white'/%3E"
53
+ + "%3Crect x='17' y='8' width='7' height='4' rx='2' fill='white'/%3E"
54
+ + "%3Crect x='17' y='14' width='7' height='4' rx='2' fill='white'/%3E"
55
+ + "%3Crect x='17' y='20' width='7' height='4' rx='2' fill='white'/%3E%3C/svg%3E";
56
+
57
+ private static readonly styleConst = `
58
+ :root { color-scheme: light dark; --bg: #f4f5f9; --fg: #16161b; --muted: #6b6b78; --card: #ffffff;
59
+ --line: #e3e3ec; --link: #1b52c0; --shadow: 0 1px 2px rgba(16, 16, 32, .06);
60
+ --shadow-lift: 0 8px 24px rgba(16, 16, 32, .13); --mark-l: 42%; --mark-s: 58%;
61
+ --ok: #17914f; --warn: #a37000; --bad: #c03028; }
62
+ @media (prefers-color-scheme: dark) {
63
+ :root { --bg: #131317; --fg: #ededf2; --muted: #9797a4; --card: #1d1d23; --line: #2d2d37;
64
+ --link: #8ab0ff; --shadow: none; --shadow-lift: 0 8px 24px rgba(0, 0, 0, .5);
65
+ --mark-l: 58%; --mark-s: 52%; --ok: #3ecf8e; --warn: #e0a92e; --bad: #ff6f62; } }
66
+ * { box-sizing: border-box; }
67
+ body { margin: 0; padding: 2.25rem 1.25rem 3rem; background: var(--bg); color: var(--fg);
68
+ font: 15px/1.5 ui-sans-serif, system-ui, "Segoe UI", sans-serif; }
69
+ main { max-width: 62rem; margin: 0 auto; }
70
+ header { display: flex; align-items: center; gap: .7rem; margin-bottom: .3rem; }
71
+ .logo { width: 1.9rem; height: 1.9rem; border-radius: .5rem; flex: none; }
72
+ h1 { margin: 0; font-size: 1.3rem; font-weight: 650; letter-spacing: .01em; }
73
+ .sub, footer { color: var(--muted); font-size: .85rem; }
74
+ .sub { margin: 0 0 1.6rem; }
75
+ ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 1rem;
76
+ grid-template-columns: repeat(auto-fill, minmax(19rem, 1fr)); }
77
+ /* A column, so the cards in one row line their footers up however many addresses each one has. */
78
+ .card { position: relative; display: flex; flex-direction: column; background: var(--card);
79
+ border: 1px solid var(--line); border-radius: .9rem; padding: 1rem 1.1rem; box-shadow: var(--shadow);
80
+ transition: transform .12s ease, box-shadow .12s ease, border-color .12s ease; }
81
+ .card:hover { transform: translateY(-2px); box-shadow: var(--shadow-lift); border-color: var(--link); }
82
+ /* Nothing answers on its port. Still listed, because the name exists and an alias comes back at the
83
+ next proxy start, but it should not read like the apps that are actually up. */
84
+ .card.down { opacity: .62; }
85
+ .card.down:hover { opacity: 1; }
86
+ .head { display: flex; align-items: flex-start; gap: .7rem; }
87
+ .mark { flex: none; width: 2.4rem; height: 2.4rem; border-radius: .65rem; display: grid;
88
+ place-items: center; font-size: .78rem; font-weight: 700; letter-spacing: .02em; color: white;
89
+ background: hsl(var(--hue) var(--mark-s) var(--mark-l)); }
90
+ .title { min-width: 0; }
91
+ /* The whole card opens the address this listener can reach, and the stretched overlay is what makes
92
+ the padding clickable too. Every other link sits above it, so they still open their own address.
93
+ The name wraps rather than truncating: it is what the reader is looking for, and real project names
94
+ are long enough (web-myapp-customer-frontend) that an ellipsis would cut the distinguishing half. */
95
+ .name { display: block; font-size: 1.06rem; font-weight: 640; color: var(--fg);
96
+ line-height: 1.25; overflow-wrap: anywhere; }
97
+ .name::after { content: ""; position: absolute; inset: 0; border-radius: .9rem; }
98
+ .card:hover .name { color: var(--link); }
99
+ .primary { display: block; font-size: .82rem; color: var(--link); overflow: hidden;
100
+ text-overflow: ellipsis; white-space: nowrap; }
101
+ .state { margin-left: auto; flex: none; display: flex; align-items: center; gap: .35rem;
102
+ padding-top: .2rem; font-size: .72rem; text-transform: uppercase; letter-spacing: .05em;
103
+ color: var(--muted); }
104
+ .dot { width: .5rem; height: .5rem; border-radius: 50%; background: currentColor; }
105
+ .state.healthy { color: var(--ok); }
106
+ .state.starting { color: var(--warn); }
107
+ .state.unresponsive, .state.dead { color: var(--bad); }
108
+ .chips { display: flex; flex-wrap: wrap; gap: .35rem; margin: .75rem 0 .75rem; }
109
+ .chip { position: relative; z-index: 1; font-size: .76rem; padding: .2rem .55rem; border-radius: 1rem;
110
+ border: 1px solid var(--line); color: var(--muted); background: var(--bg); }
111
+ a.chip { color: var(--link); }
112
+ a.chip:hover { border-color: var(--link); }
113
+ a { text-decoration: none; }
114
+ a:hover { text-decoration: underline; }
115
+ .meta { margin-top: auto; padding-top: .7rem; border-top: 1px solid var(--line); color: var(--muted);
116
+ font-family: ui-monospace, "Cascadia Code", Consolas, monospace; font-size: .76rem;
117
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
118
+ a.chip.danger { color: var(--bad); }
119
+ a.chip.danger:hover { border-color: var(--bad); }
120
+ .confirm { position: relative; z-index: 1; margin: .75rem 0; }
121
+ .confirm p { margin: 0 0 .6rem; font-size: .85rem; }
122
+ .confirm form { display: inline; }
123
+ .kill { font: inherit; font-size: .76rem; padding: .25rem .7rem; margin-right: .35rem; cursor: pointer;
124
+ color: white; background: var(--bad); border: 1px solid var(--bad); border-radius: 1rem; }
125
+ .notice { margin: -.9rem 0 1.4rem; font-size: .85rem; color: var(--muted); }
126
+ .empty { background: var(--card); border: 1px dashed var(--line); border-radius: .9rem;
127
+ padding: 2rem 1.1rem; text-align: center; color: var(--muted); }
128
+ footer { margin-top: 1.9rem; font-family: ui-monospace, "Cascadia Code", Consolas, monospace; }
129
+ `;
130
+
131
+ constructor(
132
+ private readonly registry: LocalgateRegistry,
133
+ private readonly machine: LocalgateMachineSettings | null,
134
+ private readonly proxyPort: number,
135
+ private readonly stopper: LocalgateRouteStopper
136
+ ) {}
137
+
138
+ // What to print in a terminal so the reader can click it. The page is always on `.localhost`, whatever
139
+ // the machine is called, because that name needs no configuration and no DNS.
140
+ static localUrl(proxyPort: number): string
141
+ {
142
+ return LocalgateUrl.forName(LocalgateNames.local(LocalgateNames.startNameConst), proxyPort);
143
+ }
144
+
145
+ handles(hostHeader: string, reachedFrom: LocalgateReach): boolean
146
+ {
147
+ const host = LocalgateUrl.hostnameOf(hostHeader);
148
+ if (!host) return false;
149
+
150
+ if (reachedFrom == "loopback") return host == this.localName() || host == this.lanName();
151
+ else if (reachedFrom == "lan") return host == this.lanName();
152
+ else
153
+ throw new Error(`unknown localgate reach: ${JSON.stringify(reachedFrom)}`);
154
+ }
155
+
156
+ // The page serves two verbs of its own, so the proxy hands it the request rather than a rendering
157
+ // call: a GET draws the list, and the POST behind the confirm button ends a dev server.
158
+ async handle(request: IncomingMessage, response: ServerResponse, reachedFrom: LocalgateReach): Promise<void>
159
+ {
160
+ const url = new URL(request.url ?? "/", "http://localgate.invalid");
161
+
162
+ if (request.method == "POST") return this.handleStop(request, response, url, reachedFrom);
163
+
164
+ LocalgateStartPage.sendHtml(response, 200, this.render(reachedFrom, {
165
+ confirming: url.searchParams.get("confirm"),
166
+ stopped: url.searchParams.get("stopped"),
167
+ listening: await LocalgatePortProbe.listeningRoutes(this.registry.all())
168
+ }));
169
+ }
170
+
171
+ render(reachedFrom: LocalgateReach, view: LocalgateStartPageView = {}): string
172
+ {
173
+ const loopback = reachedFrom == "loopback";
174
+ const entries = this.visible(reachedFrom);
175
+ const confirming = loopback ? view.confirming ?? null : null;
176
+ // Once per render rather than once per card: this reads the alias file, and it is the same answer
177
+ // for every card on the page.
178
+ const aliasStops = this.stopper.aliasStopCommands();
179
+
180
+ return [
181
+ "<!doctype html>",
182
+ "<html lang=\"en\">",
183
+ "<head>",
184
+ "<meta charset=\"utf-8\">",
185
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
186
+ // A route appears the moment a dev server registers and its state changes while you look at the
187
+ // page, so a list that only tells the truth at load time is the one thing this page must not be.
188
+ // It reloads the plain list, which is how the "stopped" note clears itself; and it is left out
189
+ // entirely while a card is asking a question, because that question must not expire under the
190
+ // cursor of whoever is reading it.
191
+ confirming ? "" : `<meta http-equiv="refresh" content="${LocalgateStartPage.refreshSecondsConst}; url=/">`,
192
+ "<title>localgate</title>",
193
+ `<link rel="icon" href="${LocalgateStartPage.faviconConst}">`,
194
+ `<style>${LocalgateStartPage.styleConst}</style>`,
195
+ "</head>",
196
+ "<body><main>",
197
+ `<header><img class="logo" alt="" src="${LocalgateStartPage.faviconConst}"><h1>localgate</h1></header>`,
198
+ `<p class="sub">${LocalgateStartPage.escape(this.subtitle(entries.length, loopback))}</p>`,
199
+ loopback && view.stopped ? `<p class="notice">${LocalgateStartPage.escape(view.stopped)} was stopped. `
200
+ + "Start it again from the editor it was launched in.</p>" : "",
201
+ entries.length == 0
202
+ ? `<p class="empty">${LocalgateStartPage.escape(LocalgateStartPage.emptyMessage(loopback))}</p>`
203
+ : `<ul>${entries.map(entry => LocalgateStartPage.card(entry, loopback, confirming,
204
+ view.listening?.get(entry.route.id), LocalgateStartPage.stopsWith(entry.route, aliasStops))).join("")}</ul>`,
205
+ `<footer>${LocalgateStartPage.escape(LocalgateStartPage.footer(loopback, confirming))}</footer>`,
206
+ "</main></body>",
207
+ "</html>",
208
+ ""
209
+ ].join("\n");
210
+ }
211
+
212
+ // Ending a dev server is process control, which belongs to the loopback listener alone - the same
213
+ // boundary the control API sits behind. A POST that arrives on the LAN listener is refused whatever
214
+ // it carries, and the button that makes one is never rendered there in the first place.
215
+ private async handleStop(request: IncomingMessage, response: ServerResponse, url: URL,
216
+ reachedFrom: LocalgateReach): Promise<void>
217
+ {
218
+ if (reachedFrom != "loopback")
219
+ return LocalgateStartPage.sendHtml(response, 404, LocalgateStartPage.refusal("not found here"));
220
+
221
+ if (url.pathname != LocalgateStartPage.stopPathConst)
222
+ return LocalgateStartPage.sendHtml(response, 404, LocalgateStartPage.refusal("no such page"));
223
+
224
+ // The page is reachable by any site the developer happens to be browsing, and a form POST needs no
225
+ // permission to leave one. Without this check a page anywhere could end every dev server on the
226
+ // machine; with it, only a form served from this page can. Browsers always send Origin on a POST.
227
+ if (request.headers.origin != `http://${request.headers.host ?? ""}`)
228
+ return LocalgateStartPage.sendHtml(response, 403,
229
+ LocalgateStartPage.refusal("this request did not come from the start page"));
230
+
231
+ // By name rather than by the route id: ids are handed out per proxy process, so a tab left open
232
+ // across a proxy restart could otherwise confirm r3 and end whatever r3 has become. A name that no
233
+ // longer exists simply stops nothing, which is the state the click was asking for anyway.
234
+ const name = url.searchParams.get("name") ?? "";
235
+ const route = name ? this.registry.byName(name) : null;
236
+
237
+ const stopsWith = route ? LocalgateStartPage.stopsWith(route, this.stopper.aliasStopCommands()) : null;
238
+ if (!route || !stopsWith)
239
+ {
240
+ response.writeHead(303, { location: "/" });
241
+ response.end();
242
+ return;
243
+ }
244
+
245
+ // What a runner or a shell command reports back is the only account of what happened, and swallowing
246
+ // it would leave the reader with a page that quietly still lists the thing they asked to end.
247
+ try
248
+ {
249
+ await this.stopper.stop(route);
250
+ }
251
+ catch (error)
252
+ {
253
+ return LocalgateStartPage.sendHtml(response, 502,
254
+ LocalgateStartPage.refusal(`${name} could not be stopped: ${error instanceof Error ? error.message : String(error)}`));
255
+ }
256
+
257
+ response.writeHead(303, { location: `/?stopped=${encodeURIComponent(name)}` });
258
+ response.end();
259
+ }
260
+
261
+ private localName(): string
262
+ {
263
+ return LocalgateNames.local(LocalgateNames.startNameConst);
264
+ }
265
+
266
+ // null when the machine has no config, and compared against a hostname that is never null, so the page
267
+ // simply has no shared name on a machine that has none either.
268
+ private lanName(): string | null
269
+ {
270
+ return this.machine ? LocalgateNames.lan(LocalgateNames.startNameConst, this.machine) : null;
271
+ }
272
+
273
+ // The routes this listener may show, each with the addresses that listener can reach. A route left
274
+ // with no address - mode `local`, seen from the LAN - is not listed at all, name included.
275
+ private visible(reachedFrom: LocalgateReach): { route: LocalgateRoute; addresses: LocalgateAddress[] }[]
276
+ {
277
+ return this.registry.all()
278
+ .map(route => ({ route, addresses: LocalgateStartPage.addressesOf(route, this.proxyPort, reachedFrom) }))
279
+ .filter(entry => entry.addresses.length > 0)
280
+ .sort((left, right) => LocalgateStartPage.appName(left.route).localeCompare(LocalgateStartPage.appName(right.route)));
281
+ }
282
+
283
+ private static addressesOf(route: LocalgateRoute, proxyPort: number, reachedFrom: LocalgateReach): LocalgateAddress[]
284
+ {
285
+ const addresses = LocalgateUrl.routeAddresses(route, proxyPort);
286
+
287
+ if (reachedFrom == "loopback") return addresses;
288
+ // The `.localhost` address is the local one by construction, and off this machine it names the
289
+ // computer that reads it, so printing it there would be an invitation to a dead link at best.
290
+ else if (reachedFrom == "lan") return addresses.filter(address => address.label != "local");
291
+ else
292
+ throw new Error(`unknown localgate reach: ${JSON.stringify(reachedFrom)}`);
293
+ }
294
+
295
+ // One card per route, opening on a click anywhere in it. The address it opens is the first one this
296
+ // listener can reach - the `.localhost` name on this machine, the shared name off it - because a card
297
+ // that opened the wrong one would be a dead link for exactly the person who clicked it.
298
+ // What ends this route, as a sentence for the person about to click: the runner for an app, and the
299
+ // machine's own line for an alias. null means nothing can, and then there is no button.
300
+ private static stopsWith(route: LocalgateRoute, aliasStops: ReadonlyMap<string, string>): string | null
301
+ {
302
+ if (route.controlUrl) return "its dev server and the terminal it runs in end with it";
303
+
304
+ const command = aliasStops.get(LocalgateStartPage.appName(route));
305
+ return command ? `localgate runs: ${command}` : null;
306
+ }
307
+
308
+ private static card(entry: { route: LocalgateRoute; addresses: LocalgateAddress[] },
309
+ loopback: boolean, confirming: string | null, listening: boolean | undefined,
310
+ stopsWith: string | null): string
311
+ {
312
+ const { route, addresses } = entry;
313
+ const name = LocalgateStartPage.appName(route);
314
+ const [primary, ...rest] = addresses;
315
+ const meta = (reachable: boolean | undefined) => LocalgateStartPage.meta(route, reachable);
316
+ // A card asking the question must not also be one big link to the app, or the click meant for
317
+ // "no, go back" opens the dev server instead.
318
+ const asking = confirming == name;
319
+
320
+ const status = LocalgateStartPage.statusOf(route, listening);
321
+
322
+ const parts = [
323
+ `<li class="card${listening === false ? " down" : ""}">`,
324
+ "<div class=\"head\">",
325
+ `<span class="mark" style="--hue: ${LocalgateStartPage.hueOf(name)}">`
326
+ + `${LocalgateStartPage.escape(LocalgateStartPage.monogram(name))}</span>`,
327
+ "<span class=\"title\">",
328
+ asking
329
+ ? `<span class="name">${LocalgateStartPage.escape(name)}</span>`
330
+ : `<a class="name" href="${LocalgateStartPage.escape(primary!.url)}">${LocalgateStartPage.escape(name)}</a>`,
331
+ `<span class="primary">${LocalgateStartPage.escape(primary!.hostname)}</span>`,
332
+ "</span>",
333
+ `<span class="state ${status.shade}"><span class="dot"></span>`
334
+ + `${LocalgateStartPage.escape(status.word)}</span>`,
335
+ "</div>"
336
+ ];
337
+
338
+ if (asking && stopsWith) parts.push(LocalgateStartPage.confirmBlock(name, stopsWith));
339
+ else
340
+ {
341
+ const chips = rest.map(address => `<a class="chip" href="${LocalgateStartPage.escape(address.url)}">`
342
+ + `${LocalgateStartPage.escape(address.label)} · ${LocalgateStartPage.escape(address.hostname)}</a>`);
343
+
344
+ if (route.kind == "alias") chips.push("<span class=\"chip\">alias</span>");
345
+ if (loopback && route.debuggerAttached) chips.push("<span class=\"chip\">debugger</span>");
346
+ // Off this machine there is no stopping at all: that is process control, and it stays on loopback.
347
+ if (loopback && stopsWith)
348
+ chips.push(`<a class="chip danger" href="/?confirm=${encodeURIComponent(name)}">stop</a>`);
349
+
350
+ if (chips.length > 0) parts.push(`<div class="chips">${chips.join("")}</div>`);
351
+ }
352
+
353
+ // The full line in `title` as well as on the card: the directory is the long part, and it is the
354
+ // part a person hovers to read when the card has cut it off.
355
+ if (loopback) parts.push(`<div class="meta" title="${LocalgateStartPage.escape(meta(listening))}">`
356
+ + `${LocalgateStartPage.escape(meta(listening))}</div>`);
357
+
358
+ parts.push("</li>");
359
+ return parts.join("");
360
+ }
361
+
362
+ // The second step of the stop, and the only form on the page. A POST, because it ends a process:
363
+ // a link would be followed by a prefetch, a crawler or a restored tab.
364
+ private static confirmBlock(name: string, stopsWith: string): string
365
+ {
366
+ const safe = LocalgateStartPage.escape(name);
367
+ return "<div class=\"confirm\">"
368
+ + `<p>Stop ${safe}? ${LocalgateStartPage.escape(stopsWith)}.</p>`
369
+ + `<form method="post" action="${LocalgateStartPage.stopPathConst}?name=${encodeURIComponent(name)}">`
370
+ + "<button class=\"kill\" type=\"submit\">yes, stop it</button></form>"
371
+ + "<a class=\"chip\" href=\"/\">cancel</a>"
372
+ + "</div>";
373
+ }
374
+
375
+ private static refusal(reason: string): string
376
+ {
377
+ return `<!doctype html><meta charset="utf-8"><title>localgate</title>`
378
+ + `<p>localgate: ${LocalgateStartPage.escape(reason)}.</p>`;
379
+ }
380
+
381
+ // The first letter of the name plus the start of its last word, because our names share their
382
+ // beginning and differ at the end: web-myapp-admin and web-myapp-app are WAD and WAP, while
383
+ // initials of the leading words would make both of them WM.
384
+ private static monogram(name: string): string
385
+ {
386
+ const words = name.split("-").filter(word => word.length > 0);
387
+ if (words.length == 0) return "?";
388
+ if (words.length == 1) return words[0]!.slice(0, 2).toUpperCase();
389
+ return `${words[0]![0]!}${words[words.length - 1]!.slice(0, 2)}`.toUpperCase();
390
+ }
391
+
392
+ // A colour the name always gets back, so a card keeps its look across a refresh and a person finds an
393
+ // app by where the colour is rather than by reading every tile.
394
+ private static hueOf(name: string): number
395
+ {
396
+ let hash = 0;
397
+ for (const character of name) hash = (hash * 31 + character.charCodeAt(0)) % 360;
398
+ return hash;
399
+ }
400
+
401
+ private static meta(route: LocalgateRoute, listening: boolean | undefined): string
402
+ {
403
+ const parts = [`127.0.0.1:${route.port}`];
404
+
405
+ // An alias outlives whatever it points at, on purpose, so a dead one is not a fault to report but a
406
+ // row the reader may simply be done with. The way out belongs next to it.
407
+ if (listening === false && route.kind == "alias")
408
+ parts.push(`nothing there · localgate alias --remove ${LocalgateStartPage.appName(route)}`);
409
+
410
+ if (route.command) parts.push(route.command);
411
+ if (route.cwd) parts.push(route.cwd);
412
+ return parts.join(" · ");
413
+ }
414
+
415
+ // What the badge says. The probe answers the question the reader is actually asking - is this thing
416
+ // up - and the traffic-learned state refines it: a port that accepts connections while every request
417
+ // times out is wedged, not running. Without a probe result the state is all there is.
418
+ private static statusOf(route: LocalgateRoute, listening: boolean | undefined): { word: string; shade: string }
419
+ {
420
+ if (listening === undefined)
421
+ return { word: LocalgateStartPage.stateWord(route.state), shade: route.state };
422
+
423
+ if (listening)
424
+ return route.state == "unresponsive"
425
+ ? { word: "not responding", shade: "unresponsive" }
426
+ : { word: "running", shade: "healthy" };
427
+
428
+ // Nothing on the port. For an app just launched that is normal - the dev server binds its port a
429
+ // moment later - and the same grace window the proxy uses for a refused request applies here. An
430
+ // alias starts nothing, so for it there is no such moment.
431
+ const since = Date.parse(route.lastResponseAt ?? route.startedAt);
432
+ const starting = route.kind == "app" && Date.now() - since < LocalgateHealth.startupGraceMs();
433
+ return starting ? { word: "starting", shade: "starting" } : { word: "not running", shade: "dead" };
434
+ }
435
+
436
+ private static stateWord(state: LocalgateRouteState): string
437
+ {
438
+ if (state == "starting") return "starting";
439
+ else if (state == "healthy") return "running";
440
+ else if (state == "unresponsive") return "not responding";
441
+ else if (state == "dead") return "not running";
442
+ else
443
+ throw new Error(`unknown localgate route state: ${JSON.stringify(state)}`);
444
+ }
445
+
446
+ private static appName(route: LocalgateRoute): string
447
+ {
448
+ return LocalgateNames.shortName(route.names[0]!);
449
+ }
450
+
451
+ private subtitle(count: number, loopback: boolean): string
452
+ {
453
+ const routes = count == 1 ? "1 route" : `${count} routes`;
454
+ if (!loopback) return `${routes} on ${this.machine?.label ?? "this machine"}, reachable from this network`;
455
+ return this.machine ? `${routes} on ${this.machine.label}` : `${routes} on this machine`;
456
+ }
457
+
458
+ private static emptyMessage(loopback: boolean): string
459
+ {
460
+ return loopback
461
+ ? "No routes yet. Start one with: localgate run npm run dev"
462
+ : "No shared routes. Everything running here is in mode local.";
463
+ }
464
+
465
+ private static footer(loopback: boolean, confirming: string | null): string
466
+ {
467
+ // The refresh is off while a card is asking, so the footer must not keep promising one.
468
+ if (confirming) return "localgate list";
469
+ return loopback
470
+ ? `localgate list · refreshes every ${LocalgateStartPage.refreshSecondsConst} s`
471
+ : `refreshes every ${LocalgateStartPage.refreshSecondsConst} s`;
472
+ }
473
+
474
+ private static sendHtml(response: ServerResponse, status: number, body: string): void
475
+ {
476
+ response.writeHead(status, { "content-type": "text/html; charset=utf-8", "content-length": Buffer.byteLength(body) });
477
+ response.end(body);
478
+ }
479
+
480
+ // A command line and a working directory are free text from whatever was started, and they are printed
481
+ // into a page, so nothing goes in unescaped - including the values that look safe today.
482
+ private static escape(value: string): string
483
+ {
484
+ return value
485
+ .replace(/&/g, "&amp;")
486
+ .replace(/</g, "&lt;")
487
+ .replace(/>/g, "&gt;")
488
+ .replace(/"/g, "&quot;")
489
+ .replace(/'/g, "&#39;");
490
+ }
491
+ }
@@ -1,4 +1,15 @@
1
1
  import type { LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
2
+ import type { LocalgateRoute } from "./localgateRegistry.ts";
3
+
4
+ // How far an address reaches, which is also the word every surface prints in front of it.
5
+ export type LocalgateAddressLabel = "local" | "network" | "internet";
6
+
7
+ export type LocalgateAddress =
8
+ {
9
+ label: LocalgateAddressLabel;
10
+ hostname: string;
11
+ url: string;
12
+ };
2
13
 
3
14
  // Where the proxy listens, and how a route's name is written down for a person to paste. One place,
4
15
  // because the two have to agree: every URL localgate prints is a name plus this port, and every
@@ -22,4 +33,36 @@ export class LocalgateUrl
22
33
  {
23
34
  return port == LocalgateUrl.defaultHttpPortConst ? `http://${name}` : `http://${name}:${port}`;
24
35
  }
36
+
37
+ // A route's names as URLs a person can paste, each labelled with how far it reaches. The banner, the
38
+ // CLI listing and the start page all show the same three lines, and each one deciding for itself is
39
+ // how the public address ends up written with the proxy's internal port, which never serves it.
40
+ static routeAddresses(route: LocalgateRoute, port: number): LocalgateAddress[]
41
+ {
42
+ return route.names.map((hostname, index) =>
43
+ {
44
+ const label = LocalgateUrl.labelAt(index);
45
+ return { label, hostname, url: label == "internet" ? `https://${hostname}` : LocalgateUrl.forName(hostname, port) };
46
+ });
47
+ }
48
+
49
+ // The `Host` header as a bare hostname: the port the client used is not how a route is found, and a
50
+ // header that carries none is not an error. Lowercased, because a hostname is case-insensitive and
51
+ // every name in the table is written in lower case.
52
+ static hostnameOf(hostHeader: string): string | null
53
+ {
54
+ const host = hostHeader.trim().toLowerCase().split(":")[0];
55
+ return host ? host : null;
56
+ }
57
+
58
+ // The position in `names` IS the reach: LocalgateNames.routeNames appends the shared name and then the
59
+ // public one as the mode grants them, so a route never has a fourth.
60
+ private static labelAt(index: number): LocalgateAddressLabel
61
+ {
62
+ if (index == 0) return "local";
63
+ else if (index == 1) return "network";
64
+ else if (index == 2) return "internet";
65
+ else
66
+ throw new Error(`a route cannot have a name at position ${index}`);
67
+ }
25
68
  }
@@ -6,9 +6,8 @@ import { LocalgateUrl } from "../proxy/localgateUrl.ts";
6
6
  // Keeps repositories machine-agnostic: a committed env file says `.localhost` everywhere, and what this
7
7
  // machine actually answers on is substituted here, in memory, on the way into the child process.
8
8
  //
9
- // Only the variables a browser reads are rewritten. A remote viewer's browser resolves `.localhost` to
10
- // its own machine, so those URLs must carry the shared name; server-side variables stay on `.localhost`,
11
- // which is faster and works with no DNS at all.
9
+ // A remote viewer's browser resolves `.localhost` to its own machine, so browser-facing URLs must carry
10
+ // the shared name. Server-side URLs keep `.localhost`, but still need the proxy's non-default port.
12
11
  //
13
12
  // The job is "point this at the proxy", not "swap the suffix". That distinction is what the port makes:
14
13
  // where the proxy cannot have 80 the value needs `:8080` even in mode local, where no suffix exists and
@@ -16,7 +15,6 @@ import { LocalgateUrl } from "../proxy/localgateUrl.ts";
16
15
  export class LocalgateEnvRewrite
17
16
  {
18
17
  private static readonly localSuffixConst = ".localhost";
19
- private static readonly browserFacingNamesConst = ["AUTH_URL", "NEXTAUTH_URL"];
20
18
 
21
19
  static apply(env: NodeJS.ProcessEnv, mode: LocalgateMode, machine: LocalgateMachineSettings | null,
22
20
  proxyPort: number): NodeJS.ProcessEnv
@@ -25,9 +23,11 @@ export class LocalgateEnvRewrite
25
23
 
26
24
  for (const [key, value] of Object.entries(result))
27
25
  {
28
- if (!value || !LocalgateEnvRewrite.isBrowserFacing(key)) continue;
26
+ if (!value) continue;
29
27
 
30
- const rewritten = LocalgateEnvRewrite.rewriteAuthority(value, mode, machine, proxyPort);
28
+ const rewritten = LocalgateEnvRewrite.isBrowserFacing(key)
29
+ ? LocalgateEnvRewrite.rewriteBrowserAuthority(value, mode, machine, proxyPort)
30
+ : LocalgateEnvRewrite.rewriteServerAuthority(value, proxyPort);
31
31
  if (rewritten) result[key] = rewritten;
32
32
  }
33
33
 
@@ -36,16 +36,14 @@ export class LocalgateEnvRewrite
36
36
 
37
37
  static isBrowserFacing(key: string): boolean
38
38
  {
39
- return key.startsWith("NEXT_PUBLIC_")
40
- || key.endsWith("_PUBLIC_URL")
41
- || LocalgateEnvRewrite.browserFacingNamesConst.includes(key);
39
+ return key.startsWith("NEXT_PUBLIC_") || key.endsWith("_PUBLIC_URL");
42
40
  }
43
41
 
44
42
  // Substitutes the authority only, and by string replacement rather than URL.toString(), so a value
45
43
  // keeps its exact original shape - notably no trailing slash appears on a bare origin, which app code
46
44
  // concatenates onto. A port already in the value is replaced rather than kept: behind a proxy that
47
45
  // multiplexes by name, a browser-facing URL has exactly one correct port.
48
- private static rewriteAuthority(value: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null,
46
+ private static rewriteBrowserAuthority(value: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null,
49
47
  proxyPort: number): string | null
50
48
  {
51
49
  let url: URL;
@@ -73,4 +71,25 @@ export class LocalgateEnvRewrite
73
71
  const withAuthority = value.replace(url.host, authority);
74
72
  return `${protocol}${withAuthority.slice(url.protocol.length)}`;
75
73
  }
74
+
75
+ private static rewriteServerAuthority(value: string, proxyPort: number): string | null
76
+ {
77
+ let url: URL;
78
+ try
79
+ {
80
+ url = new URL(value);
81
+ }
82
+ catch
83
+ {
84
+ return null;
85
+ }
86
+
87
+ if (!url.hostname.endsWith(LocalgateEnvRewrite.localSuffixConst)) return null;
88
+ const label = url.hostname.slice(0, -LocalgateEnvRewrite.localSuffixConst.length);
89
+ if (label.length == 0) return null;
90
+
91
+ const authority = LocalgateUrl.forName(url.hostname, proxyPort).replace("http://", "");
92
+ if (url.host == authority) return null;
93
+ return value.replace(url.host, authority);
94
+ }
76
95
  }
@@ -0,0 +1,29 @@
1
+ import dns from "node:dns";
2
+
3
+ class LocalgateNodeBootstrap
4
+ {
5
+ static install()
6
+ {
7
+ const originalLookup = dns.lookup.bind(dns);
8
+
9
+ // Browsers reserve *.localhost for loopback, but some system resolvers used by Node do not.
10
+ dns.lookup = (hostname, options, callback) =>
11
+ {
12
+ if (typeof hostname != "string" || !hostname.toLowerCase().endsWith(".localhost"))
13
+ {
14
+ if (typeof options == "function") return originalLookup(hostname, options);
15
+ return originalLookup(hostname, options, callback);
16
+ }
17
+
18
+ const done = typeof options == "function" ? options : callback;
19
+ if (typeof done != "function") return originalLookup(hostname, options, callback);
20
+
21
+ if (typeof options == "object" && options?.all === true)
22
+ return process.nextTick(done, null, [{ address: "127.0.0.1", family: 4 }]);
23
+
24
+ return process.nextTick(done, null, "127.0.0.1", 4);
25
+ };
26
+ }
27
+ }
28
+
29
+ LocalgateNodeBootstrap.install();
@@ -0,0 +1,15 @@
1
+ export class LocalgateNodeOptions
2
+ {
3
+ private static readonly bootstrapUrlConst = new URL("./localgateNodeBootstrap.mjs", import.meta.url).href;
4
+
5
+ static apply(env: NodeJS.ProcessEnv, bootstrapUrl = LocalgateNodeOptions.bootstrapUrlConst): NodeJS.ProcessEnv
6
+ {
7
+ const result = { ...env };
8
+ const importOption = `--import=${bootstrapUrl}`;
9
+ const options = result.NODE_OPTIONS?.trim();
10
+
11
+ if (options?.split(/\s+/).includes(importOption)) return result;
12
+ result.NODE_OPTIONS = options ? `${options} ${importOption}` : importOption;
13
+ return result;
14
+ }
15
+ }