localgate 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,52 @@
1
+ import type { IncomingHttpHeaders } from "node:http";
2
+
3
+ // Next.js blocks cross-origin requests to its dev endpoints unless the origin is allow-listed, and it
4
+ // allows `**.localhost` unconditionally. It inspects Origin (and Referer for no-cors requests), never
5
+ // Host, and only on `/_next/*` and `/__nextjs*`. Mapping the external suffix back to `.localhost` on
6
+ // exactly those requests keeps HMR and dev assets working from a shared name, with no
7
+ // `allowedDevOrigins` entry in any project - which is what keeps our domain out of every repository.
8
+ export class LocalgateHeaderRewrite
9
+ {
10
+ private static readonly localSuffixConst = ".localhost";
11
+ private static readonly internalPrefixesConst = ["/_next", "/__nextjs"];
12
+
13
+ static isInternalPath(requestUrl: string): boolean
14
+ {
15
+ const path = requestUrl.split("?")[0] ?? "";
16
+ return LocalgateHeaderRewrite.internalPrefixesConst.some(prefix => path.startsWith(prefix));
17
+ }
18
+
19
+ static apply(requestUrl: string, headers: IncomingHttpHeaders, externalSuffix: string | null): void
20
+ {
21
+ if (!externalSuffix || !LocalgateHeaderRewrite.isInternalPath(requestUrl)) return;
22
+
23
+ for (const name of ["origin", "referer"] as const)
24
+ {
25
+ const value = headers[name];
26
+ if (typeof value != "string") continue;
27
+
28
+ const rewritten = LocalgateHeaderRewrite.toLocalName(value, externalSuffix);
29
+ if (rewritten) headers[name] = rewritten;
30
+ }
31
+ }
32
+
33
+ private static toLocalName(value: string, externalSuffix: string): string | null
34
+ {
35
+ let url: URL;
36
+ try
37
+ {
38
+ url = new URL(value);
39
+ }
40
+ catch
41
+ {
42
+ return null;
43
+ }
44
+
45
+ if (!url.hostname.endsWith(externalSuffix)) return null;
46
+
47
+ const label = url.hostname.slice(0, -externalSuffix.length);
48
+ if (label.length == 0) return null;
49
+
50
+ return value.replace(url.hostname, `${label}${LocalgateHeaderRewrite.localSuffixConst}`);
51
+ }
52
+ }
@@ -0,0 +1,121 @@
1
+ import type { LocalgateRegistry, LocalgateRoute } from "./localgateRegistry.ts";
2
+
3
+ export type LocalgateRestartRequest = (route: LocalgateRoute) => Promise<void>;
4
+
5
+ // Detection is free: the proxy already forwards every request, so a wedged dev server shows up as
6
+ // consecutive timeouts on a connection that still opens. Acting on it is the risky half - a process
7
+ // paused at a breakpoint is externally indistinguishable from a wedged one - so the automatic restart is
8
+ // off unless the machine asks for it, never fires while a debugger is attached, and is bounded by a
9
+ // cooldown and an attempt cap. Reporting always happens.
10
+ export class LocalgateHealth
11
+ {
12
+ private static readonly requestTimeoutMsConst = 30_000;
13
+ private static readonly failuresBeforeUnresponsiveConst = 3;
14
+ private static readonly startupGraceMsConst = 90_000;
15
+ private static readonly cooldownMsConst = 5 * 60_000;
16
+ private static readonly maxAutomaticAttemptsConst = 2;
17
+
18
+ private readonly failures = new Map<string, number>();
19
+ private readonly lastAutomaticRestart = new Map<string, number>();
20
+ private readonly automaticAttempts = new Map<string, number>();
21
+
22
+ constructor(
23
+ private readonly registry: LocalgateRegistry,
24
+ private readonly autoRestart: boolean,
25
+ private readonly requestRestart: LocalgateRestartRequest,
26
+ private readonly now: () => number = () => Date.now()
27
+ ) {}
28
+
29
+ static requestTimeoutMs(): number
30
+ {
31
+ return LocalgateHealth.requestTimeoutMsConst;
32
+ }
33
+
34
+ noteSuccess(route: LocalgateRoute): void
35
+ {
36
+ this.failures.delete(route.id);
37
+ this.automaticAttempts.delete(route.id);
38
+ this.registry.update(route.id, { state: "healthy", lastResponseAt: new Date(this.now()).toISOString() });
39
+ }
40
+
41
+ noteTimeout(route: LocalgateRoute): void
42
+ {
43
+ const count = (this.failures.get(route.id) ?? 0) + 1;
44
+ this.failures.set(route.id, count);
45
+ if (count < LocalgateHealth.failuresBeforeUnresponsiveConst) return;
46
+
47
+ this.registry.update(route.id, { state: "unresponsive" });
48
+ void this.considerAutomaticRestart(route);
49
+ }
50
+
51
+ // A refused connection during start-up is normal: the dev server has not bound its port yet. Past the
52
+ // grace window with no response ever seen, the child is gone rather than slow.
53
+ noteConnectionRefused(route: LocalgateRoute): void
54
+ {
55
+ const reference = Date.parse(route.lastResponseAt ?? route.startedAt);
56
+ const withinGrace = this.now() - reference < LocalgateHealth.startupGraceMsConst;
57
+ this.registry.update(route.id, { state: withinGrace ? "starting" : "dead" });
58
+ }
59
+
60
+ unresponsiveMessage(route: LocalgateRoute): string
61
+ {
62
+ const target = route.cwd ?? route.names[0];
63
+ return [
64
+ `localgate: ${route.names[0]} is not responding.`,
65
+ "",
66
+ `The dev server accepted the connection but did not answer ${LocalgateHealth.failuresBeforeUnresponsiveConst} requests in a row`,
67
+ `(${LocalgateHealth.requestTimeoutMsConst / 1000} s each). It is wedged, or it is paused in a debugger.`,
68
+ "",
69
+ "Restart it with:",
70
+ ` localgate restart ${route.names[0].split(".")[0]}`,
71
+ ` (or run localgate restart in ${target})`,
72
+ ""
73
+ ].join("\n");
74
+ }
75
+
76
+ deadMessage(route: LocalgateRoute): string
77
+ {
78
+ return [
79
+ `localgate: nothing is listening for ${route.names[0]}.`,
80
+ "",
81
+ "The route is registered but its dev server is gone. Start it again from your editor,",
82
+ "or run localgate prune to drop the route.",
83
+ ""
84
+ ].join("\n");
85
+ }
86
+
87
+ startingMessage(route: LocalgateRoute): string
88
+ {
89
+ return `localgate: ${route.names[0]} is still starting. Reload in a moment.\n`;
90
+ }
91
+
92
+ private async considerAutomaticRestart(route: LocalgateRoute): Promise<void>
93
+ {
94
+ if (!this.autoRestart) return;
95
+
96
+ // The one refusal that is not a threshold: a paused debug session looks exactly like a wedge, and
97
+ // killing it would destroy the session the developer is standing in.
98
+ if (route.debuggerAttached) return;
99
+ if (!route.controlUrl) return;
100
+
101
+ const attempts = this.automaticAttempts.get(route.id) ?? 0;
102
+ if (attempts >= LocalgateHealth.maxAutomaticAttemptsConst) return;
103
+
104
+ const previous = this.lastAutomaticRestart.get(route.id);
105
+ if (previous !== undefined && this.now() - previous < LocalgateHealth.cooldownMsConst) return;
106
+
107
+ this.lastAutomaticRestart.set(route.id, this.now());
108
+ this.automaticAttempts.set(route.id, attempts + 1);
109
+ this.failures.delete(route.id);
110
+
111
+ process.stderr.write(`localgate: ${route.names[0]} unresponsive, automatic restart ${attempts + 1}\n`);
112
+ try
113
+ {
114
+ await this.requestRestart(route);
115
+ }
116
+ catch (error)
117
+ {
118
+ process.stderr.write(`localgate: automatic restart of ${route.names[0]} failed: ${String(error)}\n`);
119
+ }
120
+ }
121
+ }
@@ -0,0 +1,271 @@
1
+ import { createServer, request as httpRequest, type IncomingMessage, type Server, type ServerResponse } from "node:http";
2
+ import type { Duplex } from "node:stream";
3
+ import { LocalgateControlApi } from "./localgateControlApi.ts";
4
+ import { LocalgateHeaderRewrite } from "./localgateHeaderRewrite.ts";
5
+ import { LocalgateHealth } from "./localgateHealth.ts";
6
+ import type { LocalgateReach, LocalgateRegistry, LocalgateRoute } from "./localgateRegistry.ts";
7
+
8
+ export type LocalgateProxyOptions =
9
+ {
10
+ port: number;
11
+ // null keeps the proxy on loopback only, which is what a machine with no localgate config gets.
12
+ lanIp: string | null;
13
+ externalSuffix: string | null;
14
+ gracePeriodMs: number;
15
+ onIdle: () => void;
16
+ };
17
+
18
+ export class LocalgateProxy
19
+ {
20
+ private readonly servers: Server[] = [];
21
+ // An upgraded socket is handed to us and stops being tracked by the http server, so
22
+ // closeAllConnections cannot reach it. The proxy keeps its own set, or a single open browser tab
23
+ // holding an HMR websocket would keep it alive forever and defeat the self-exit.
24
+ private readonly upgraded = new Set<Duplex>();
25
+ private idleTimer: NodeJS.Timeout | null = null;
26
+
27
+ constructor(
28
+ private readonly registry: LocalgateRegistry,
29
+ private readonly health: LocalgateHealth,
30
+ private readonly controlApi: LocalgateControlApi,
31
+ private readonly options: LocalgateProxyOptions
32
+ ) {}
33
+
34
+ async start(): Promise<void>
35
+ {
36
+ await this.listen("127.0.0.1", true);
37
+ if (this.options.lanIp) await this.listen(this.options.lanIp, false);
38
+ this.checkIdle();
39
+ }
40
+
41
+ // The ports actually bound, in listen order: loopback first, the LAN address second when there is
42
+ // one. They differ from the requested port only when 0 was asked for (tests).
43
+ boundPorts(): number[]
44
+ {
45
+ if (this.servers.length == 0) throw new Error("proxy is not listening");
46
+
47
+ return this.servers.map(server =>
48
+ {
49
+ const address = server.address();
50
+ if (!address || typeof address == "string") throw new Error("proxy is not listening");
51
+ return address.port;
52
+ });
53
+ }
54
+
55
+ async stop(): Promise<void>
56
+ {
57
+ if (this.idleTimer) clearTimeout(this.idleTimer);
58
+ this.idleTimer = null;
59
+
60
+ // Without dropping live sockets the proxy would never finish closing: a browser tab holding an HMR
61
+ // websocket keeps the server open forever, and the self-exit in `checkIdle` would never complete.
62
+ for (const socket of this.upgraded) socket.destroy();
63
+ this.upgraded.clear();
64
+ for (const server of this.servers) server.closeAllConnections();
65
+
66
+ await Promise.all(this.servers.map(server => new Promise<void>(resolve => server.close(() => resolve()))));
67
+ this.servers.length = 0;
68
+ }
69
+
70
+ // Called after every control-API mutation: the proxy exists to serve routes, so when the last one goes
71
+ // it has no reason to stay resident. The grace period is what keeps it alive across a restart, between
72
+ // the child being killed and the new one registering.
73
+ checkIdle(): void
74
+ {
75
+ if (this.idleTimer)
76
+ {
77
+ clearTimeout(this.idleTimer);
78
+ this.idleTimer = null;
79
+ }
80
+
81
+ if (!this.registry.isEmpty()) return;
82
+
83
+ this.idleTimer = setTimeout(() =>
84
+ {
85
+ this.idleTimer = null;
86
+ if (this.registry.isEmpty()) this.options.onIdle();
87
+ }, this.options.gracePeriodMs);
88
+ this.idleTimer.unref();
89
+ }
90
+
91
+ private listen(address: string, loopback: boolean): Promise<void>
92
+ {
93
+ const reachedFrom: LocalgateReach = loopback ? "loopback" : "lan";
94
+ const server = createServer((request, response) => void this.handleRequest(request, response, loopback, reachedFrom));
95
+ server.on("upgrade", (request, socket, head) => this.handleUpgrade(request, socket as Duplex, head, reachedFrom));
96
+
97
+ return new Promise<void>((resolve, reject) =>
98
+ {
99
+ server.once("error", reject);
100
+ server.listen(this.options.port, address, () =>
101
+ {
102
+ server.removeListener("error", reject);
103
+ this.servers.push(server);
104
+ resolve();
105
+ });
106
+ });
107
+ }
108
+
109
+ private async handleRequest(request: IncomingMessage, response: ServerResponse, loopback: boolean,
110
+ reachedFrom: LocalgateReach): Promise<void>
111
+ {
112
+ const requestUrl = request.url ?? "/";
113
+
114
+ // The control API is loopback-only. On the LAN listener the path is just a path, and since no route
115
+ // claims it the request falls through to the not-found answer below.
116
+ if (loopback && LocalgateControlApi.handles(requestUrl))
117
+ return this.controlApi.handle(request, response);
118
+
119
+ const route = this.registry.byHostname(request.headers.host ?? "", reachedFrom);
120
+ if (!route)
121
+ {
122
+ if (loopback) return LocalgateProxy.sendText(response, 404, this.indexPage(request.headers.host ?? ""));
123
+ return LocalgateProxy.sendText(response, 404, LocalgateProxy.offMachineMessage(request.headers.host ?? ""));
124
+ }
125
+
126
+ this.forward(route, request, response);
127
+ }
128
+
129
+ private forward(route: LocalgateRoute, request: IncomingMessage, response: ServerResponse): void
130
+ {
131
+ const headers = { ...request.headers };
132
+ LocalgateHeaderRewrite.apply(request.url ?? "/", headers, this.options.externalSuffix);
133
+
134
+ const upstream = httpRequest({
135
+ host: "127.0.0.1",
136
+ port: route.port,
137
+ method: request.method,
138
+ path: request.url,
139
+ headers
140
+ });
141
+
142
+ upstream.setTimeout(LocalgateHealth.requestTimeoutMs(), () =>
143
+ {
144
+ upstream.destroy();
145
+ if (response.headersSent) return;
146
+ this.health.noteTimeout(route);
147
+ LocalgateProxy.sendText(response, 504, this.health.unresponsiveMessage(route));
148
+ });
149
+
150
+ upstream.once("response", upstreamResponse =>
151
+ {
152
+ // A stream that stays open on purpose (SSE, a long poll) must not be judged unresponsive, so the
153
+ // inactivity timeout only guards the wait for the first byte.
154
+ upstream.setTimeout(0);
155
+ this.health.noteSuccess(route);
156
+ response.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.headers);
157
+ upstreamResponse.pipe(response);
158
+ });
159
+
160
+ upstream.once("error", (error: NodeJS.ErrnoException) =>
161
+ {
162
+ if (response.headersSent)
163
+ {
164
+ response.destroy();
165
+ return;
166
+ }
167
+
168
+ if (error.code == "ECONNREFUSED" || error.code == "ECONNRESET")
169
+ {
170
+ this.health.noteConnectionRefused(route);
171
+ const state = this.registry.byId(route.id)?.state;
172
+ const message = state == "starting" ? this.health.startingMessage(route) : this.health.deadMessage(route);
173
+ return LocalgateProxy.sendText(response, 503, message);
174
+ }
175
+
176
+ LocalgateProxy.sendText(response, 502, `localgate: upstream error for ${route.names[0]}: ${error.message}\n`);
177
+ });
178
+
179
+ request.pipe(upstream);
180
+ }
181
+
182
+ // Hot module reload runs over a websocket, so the upgrade has to be proxied or every edit needs a
183
+ // manual reload. It carries the reach for the same reason a plain request does: an upgrade is a
184
+ // request first, and a listener that refuses a name must refuse it here too.
185
+ private handleUpgrade(request: IncomingMessage, clientSocket: Duplex, head: Buffer,
186
+ reachedFrom: LocalgateReach): void
187
+ {
188
+ const route = this.registry.byHostname(request.headers.host ?? "", reachedFrom);
189
+ if (!route)
190
+ {
191
+ clientSocket.destroy();
192
+ return;
193
+ }
194
+
195
+ const headers = { ...request.headers };
196
+ LocalgateHeaderRewrite.apply(request.url ?? "/", headers, this.options.externalSuffix);
197
+
198
+ const upstream = httpRequest({
199
+ host: "127.0.0.1",
200
+ port: route.port,
201
+ method: request.method,
202
+ path: request.url,
203
+ headers
204
+ });
205
+
206
+ upstream.once("upgrade", (upstreamResponse, upstreamSocket, upstreamHead) =>
207
+ {
208
+ const lines = [`HTTP/1.1 ${upstreamResponse.statusCode ?? 101} ${upstreamResponse.statusMessage ?? "Switching Protocols"}`];
209
+ for (const [key, value] of Object.entries(upstreamResponse.headers))
210
+ lines.push(`${key}: ${Array.isArray(value) ? value.join(", ") : String(value)}`);
211
+
212
+ clientSocket.write(`${lines.join("\r\n")}\r\n\r\n`);
213
+ if (upstreamHead.length > 0) clientSocket.write(upstreamHead);
214
+ if (head.length > 0) upstreamSocket.write(head);
215
+
216
+ this.upgraded.add(clientSocket).add(upstreamSocket);
217
+ const forget = () =>
218
+ {
219
+ this.upgraded.delete(clientSocket);
220
+ this.upgraded.delete(upstreamSocket);
221
+ };
222
+
223
+ upstreamSocket.on("error", () => clientSocket.destroy());
224
+ clientSocket.on("error", () => upstreamSocket.destroy());
225
+ upstreamSocket.once("close", forget);
226
+ clientSocket.once("close", forget);
227
+ upstreamSocket.pipe(clientSocket);
228
+ clientSocket.pipe(upstreamSocket);
229
+ });
230
+
231
+ upstream.once("error", () => clientSocket.destroy());
232
+ upstream.end();
233
+ }
234
+
235
+ // Nothing about what is running: this answer goes to the network. The `.localhost` hint is safe
236
+ // because it is true of every machine, and it is the one mistake a colleague actually makes -
237
+ // copying a URL that only ever meant "my own computer".
238
+ private static offMachineMessage(requestedHost: string): string
239
+ {
240
+ const host = requestedHost.trim().toLowerCase().split(":")[0] ?? "";
241
+ if (host.endsWith(".localhost"))
242
+ return "localgate: no route for this hostname. Names on .localhost only ever mean the machine "
243
+ + "asking, so this one cannot be served from here - ask for the shared name instead.\n";
244
+
245
+ return "localgate: no route for this hostname\n";
246
+ }
247
+
248
+ private indexPage(requestedHost: string): string
249
+ {
250
+ const routes = this.registry.all();
251
+ const lines = [`localgate: nothing is registered for "${requestedHost}".`, ""];
252
+
253
+ if (routes.length == 0)
254
+ lines.push("No routes. Start one with: localgate run npm run dev");
255
+ else
256
+ {
257
+ lines.push("Active routes:");
258
+ for (const route of routes)
259
+ lines.push(` ${route.names.join(" ")} -> 127.0.0.1:${route.port} [${route.state}]`);
260
+ }
261
+
262
+ lines.push("");
263
+ return lines.join("\n");
264
+ }
265
+
266
+ private static sendText(response: ServerResponse, status: number, body: string): void
267
+ {
268
+ response.writeHead(status, { "content-type": "text/plain; charset=utf-8", "content-length": Buffer.byteLength(body) });
269
+ response.end(body);
270
+ }
271
+ }
@@ -0,0 +1,52 @@
1
+ import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
2
+ import { LocalgateControlApi } from "./localgateControlApi.ts";
3
+ import { LocalgateHealth } from "./localgateHealth.ts";
4
+ import { LocalgateProxy } from "./localgateProxy.ts";
5
+ import { LocalgateRegistry, type LocalgateRoute } from "./localgateRegistry.ts";
6
+
7
+ // Boots the long-lived half of localgate. Started on demand by the first `run` or `alias`, and it exits
8
+ // once the last route disappears, so nothing is installed and nothing runs when no dev server does.
9
+ export class LocalgateProxyHost
10
+ {
11
+ static readonly portConst = 80;
12
+ private static readonly gracePeriodMsConst = 20_000;
13
+
14
+ static async run(): Promise<void>
15
+ {
16
+ const machine = LocalgateMachineConfig.load();
17
+ const registry = new LocalgateRegistry();
18
+ const health = new LocalgateHealth(registry, machine?.autoRestart === true, LocalgateProxyHost.requestRestart);
19
+
20
+ const proxy: LocalgateProxy = new LocalgateProxy(
21
+ registry,
22
+ health,
23
+ new LocalgateControlApi(registry, () => proxy.checkIdle()),
24
+ {
25
+ port: LocalgateProxyHost.portConst,
26
+ lanIp: machine?.lanIp ?? null,
27
+ externalSuffix: machine ? LocalgateMachineConfig.externalSuffix(machine) : null,
28
+ gracePeriodMs: LocalgateProxyHost.gracePeriodMsConst,
29
+ onIdle: () =>
30
+ {
31
+ process.stdout.write("localgate: no routes left, stopping\n");
32
+ void proxy.stop().then(() => process.exit(0));
33
+ }
34
+ }
35
+ );
36
+
37
+ await proxy.start();
38
+ process.stdout.write(`localgate proxy listening on 127.0.0.1:${LocalgateProxyHost.portConst}`
39
+ + `${machine?.lanIp ? ` and ${machine.lanIp}:${LocalgateProxyHost.portConst}` : ""}\n`);
40
+
41
+ for (const signal of ["SIGINT", "SIGTERM"] as const)
42
+ process.on(signal, () => void proxy.stop().then(() => process.exit(0)));
43
+ }
44
+
45
+ private static async requestRestart(route: LocalgateRoute): Promise<void>
46
+ {
47
+ if (!route.controlUrl) throw new Error(`route ${route.names[0]} has no control endpoint`);
48
+
49
+ const response = await fetch(`${route.controlUrl}/restart`, { method: "POST" });
50
+ if (!response.ok) throw new Error(`control endpoint answered ${response.status}`);
51
+ }
52
+ }