localgate 0.6.0 → 0.6.2

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.
package/README.md CHANGED
@@ -237,6 +237,12 @@ The takeover above is the one place this matters for safety. **With no terminal
237
237
  the developer's session by accident; `localgate run --force` takes over deliberately. To pick up a
238
238
  change, use `localgate restart`, which keeps the runner, the terminal and the debugger.
239
239
 
240
+ A dev server lives as long as the terminal that started it. When an agent's command ends and takes its
241
+ console along, the runner notices within 10 s and stops the dev server the way Ctrl+C does, instead of
242
+ leaving it running on a console that no longer exists. On Windows such a server could start no child
243
+ process, and a Next.js dev server then restarted its worker processes in a loop. See
244
+ [docs/architecture/terminal-loss.md](docs/architecture/terminal-loss.md).
245
+
240
246
  ## Names, and who can reach them
241
247
 
242
248
  A project gets its name from `package.json`, and nothing else is needed to work locally:
@@ -278,12 +284,24 @@ their own names without either name being in the repository:
278
284
 
279
285
  With that file present, `myapp` in mode `lan` also answers on `myapp.dev.example.com`, while mode
280
286
  `internet` additionally answers on `pub-myapp.example.com`. Browser-facing
281
- environment variables (`NEXT_PUBLIC_*`, `*_PUBLIC_URL`, `AUTH_URL`, `NEXTAUTH_URL`) are rewritten from
287
+ environment variables (`NEXT_PUBLIC_*`, `*_PUBLIC_URL`) are rewritten from
282
288
  `.localhost` to the name selected by the current mode on the way into the dev server. Public URLs use
283
289
  HTTPS and never carry the proxy's internal LAN port. Server-side variables stay on `.localhost`.
284
290
  Node children get a lookup hook for that reserved suffix, so Fetch and the standard HTTP clients reach
285
291
  the local proxy even when the operating system resolver does not expand nested localhost names.
286
292
 
293
+ For Auth.js applications that serve several origins, omit `AUTH_URL` and `NEXTAUTH_URL` from the
294
+ application's development env files and launch environment, and configure `trustHost: true` or
295
+ `AUTH_TRUST_HOST=true`. Authentication can then follow each request's origin. Localgate sets
296
+ `X-Forwarded-Host` to the routed `Host`, including its port, and defaults `X-Forwarded-Proto` to `http`,
297
+ preserving a tunnel's single `http` or `https` value. Each origin keeps its own session cookie.
298
+
299
+ Localgate does not delete auth settings, set trust flags or intercept env-file loading. Explicit auth
300
+ URLs keep their configured hostname; as with other server URLs, a `.localhost` value receives the
301
+ proxy port. This replaces the earlier behavior that rewrote auth URLs to the LAN or public hostname.
302
+ Custom auth paths, cookie prefixes and older NextAuth server helpers remain application configuration.
303
+ See [docs/architecture/auth-origin.md](docs/architecture/auth-origin.md) for compatibility and restart steps.
304
+
287
305
  For reaching an app from outside the LAN, `localgate cloudflare-info` prints the exact prefixed DNS
288
306
  record and tunnel ingress entry. It prints them and stops: localgate holds no API token and sends
289
307
  nothing anywhere. In Atomix projects, use `axtoolsv2 expose <dir> off|network|internet`; AtomixToolsV2
@@ -303,6 +321,9 @@ get a readable page instead of a browser error, and it says what to do next:
303
321
  | `dead` | 503, "nothing is listening" plus the `prune` hint - the route outlived its dev server |
304
322
  | `unresponsive` | 504, after three requests in a row went unanswered, with the exact `localgate restart` line to run |
305
323
 
324
+ A reset on a kept-alive connection is not one of these states: the proxy sends a `GET`, `HEAD` or
325
+ `OPTIONS` request once more on a fresh connection first ([upstream keep-alive](docs/architecture/upstream-keep-alive.md)).
326
+
306
327
  Acting on it is the risky half, so it is opt-in: `"autoRestart": true` in `~/.localgate/config.json`
307
328
  lets the proxy restart an unresponsive app by itself, bounded by two attempts and a five-minute
308
329
  cooldown. **It never fires while a debugger is attached** - a process paused at a breakpoint is
@@ -17,6 +17,12 @@ export class LocalgateHeaderRewrite
17
17
 
18
18
  static apply(requestUrl: string, headers: IncomingHttpHeaders, requestHost: string, canonicalName: string): void
19
19
  {
20
+ // Routing has already validated Host. Auth libraries prefer forwarded headers, so an unrelated
21
+ // forwarded host must not override it. A TLS-terminating tunnel supplies the original protocol.
22
+ headers["x-forwarded-host"] = requestHost;
23
+ if (headers["x-forwarded-proto"] != "http" && headers["x-forwarded-proto"] != "https")
24
+ headers["x-forwarded-proto"] = "http";
25
+
20
26
  if (!LocalgateHeaderRewrite.isInternalPath(requestUrl)) return;
21
27
 
22
28
  const requestHostname = LocalgateHeaderRewrite.hostnameOf(requestHost);
@@ -1,4 +1,5 @@
1
- import { createServer, request as httpRequest, type IncomingMessage, type Server, type ServerResponse } from "node:http";
1
+ import { Agent, createServer, request as httpRequest, type IncomingMessage, type OutgoingHttpHeaders, type Server,
2
+ type ServerResponse } from "node:http";
2
3
  import type { Duplex } from "node:stream";
3
4
  import { LocalgateControlApi } from "./localgateControlApi.ts";
4
5
  import { LocalgateHeaderRewrite } from "./localgateHeaderRewrite.ts";
@@ -17,7 +18,13 @@ export type LocalgateProxyOptions =
17
18
 
18
19
  export class LocalgateProxy
19
20
  {
21
+ // Node servers, Next included, close a kept-alive socket after 5 s without a request. Dropping ours after
22
+ // 1 s keeps a page load on warm sockets while leaving the dev server's timer far behind.
23
+ private static readonly idleSocketMsConst = 1_000;
24
+ private static readonly replayableMethodsConst = ["GET", "HEAD", "OPTIONS"];
25
+
20
26
  private readonly servers: Server[] = [];
27
+ private readonly upstreamAgent = new Agent({ keepAlive: true, timeout: LocalgateProxy.idleSocketMsConst });
21
28
  // An upgraded socket is handed to us and stops being tracked by the http server, so
22
29
  // closeAllConnections cannot reach it. The proxy keeps its own set, or a single open browser tab
23
30
  // holding an HMR websocket would keep it alive forever and defeat the self-exit.
@@ -66,6 +73,7 @@ export class LocalgateProxy
66
73
 
67
74
  await Promise.all(this.servers.map(server => new Promise<void>(resolve => server.close(() => resolve()))));
68
75
  this.servers.length = 0;
76
+ this.upstreamAgent.destroy();
69
77
  }
70
78
 
71
79
  // Called after every control-API mutation: the proxy exists to serve routes, so when the last one goes
@@ -146,12 +154,25 @@ export class LocalgateProxy
146
154
  const headers = { ...request.headers };
147
155
  LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
148
156
 
157
+ // Only a request that may be sent twice takes a kept-alive socket: a body is streamed through once, and
158
+ // a method that changes state must not run again because the first attempt might have reached the server.
159
+ const replayable = LocalgateProxy.replayableMethodsConst.includes(request.method ?? "")
160
+ && request.headers["content-length"] === undefined && request.headers["transfer-encoding"] === undefined;
161
+ if (replayable) request.resume();
162
+ this.dial(route, request, response, headers, replayable, false);
163
+ }
164
+
165
+ private dial(route: LocalgateRoute, request: IncomingMessage, response: ServerResponse, headers: OutgoingHttpHeaders,
166
+ replayable: boolean, retry: boolean): void
167
+ {
168
+ const reuse = replayable && !retry;
149
169
  const upstream = httpRequest({
150
170
  host: "127.0.0.1",
151
171
  port: route.port,
152
172
  method: request.method,
153
173
  path: request.url,
154
- headers
174
+ headers,
175
+ agent: reuse ? this.upstreamAgent : false
155
176
  });
156
177
 
157
178
  upstream.setTimeout(LocalgateHealth.requestTimeoutMs(), () =>
@@ -192,6 +213,13 @@ export class LocalgateProxy
192
213
  return;
193
214
  }
194
215
 
216
+ // The dev server closed a kept-alive socket while this request was on its way. A server whose event
217
+ // loop is blocked (a debugger, a long compile) runs its idle timer late, so the close can come seconds
218
+ // after the request arrived. The reset says nothing about the route, so the request goes once more on
219
+ // a fresh connection before the route is judged.
220
+ if (reuse && upstream.reusedSocket && error.code == "ECONNRESET")
221
+ return this.dial(route, request, response, headers, replayable, true);
222
+
195
223
  if (error.code == "ECONNREFUSED" || error.code == "ECONNRESET")
196
224
  {
197
225
  this.health.noteConnectionRefused(route);
@@ -203,7 +231,9 @@ export class LocalgateProxy
203
231
  LocalgateProxy.sendText(response, 502, `localgate: upstream error for ${route.names[0]}: ${error.message}\n`);
204
232
  });
205
233
 
206
- request.pipe(upstream);
234
+ // A replayable request has already ended by the time of a retry, so piping it would never end the new one.
235
+ if (replayable) upstream.end();
236
+ else request.pipe(upstream);
207
237
  }
208
238
 
209
239
  // Hot module reload runs over a websocket, so the upgrade has to be proxied or every edit needs a
@@ -0,0 +1,55 @@
1
+ import { closeSync, openSync } from "node:fs";
2
+
3
+ // Whether the Windows console this process is attached to still exists. The runner and its dev tree
4
+ // share the console of whoever started `localgate run`. When an agent's command ends, its console host
5
+ // can go without any event reaching the processes attached to it, and from then on every child spawned
6
+ // without its own console fails to start with 0xC0000142 - Next's worker pool restarts such a child
7
+ // forever. Opening the console device is the cheapest question that tells: about 0.1 ms, no process.
8
+ export class LocalgateConsole
9
+ {
10
+ // `CONOUT$` alone resolves against the working directory; only the device path reaches the console.
11
+ static readonly devicePathConst = "\\\\.\\CONOUT$";
12
+
13
+ private readonly platform: NodeJS.Platform;
14
+ private readonly open: (path: string) => void;
15
+ private readonly watched: boolean;
16
+
17
+ constructor(platform: NodeJS.Platform = process.platform, open: (path: string) => void = LocalgateConsole.openDevice)
18
+ {
19
+ this.platform = platform;
20
+ this.open = open;
21
+ // A runner started without a console, or on a console this probe cannot read, keeps working the way
22
+ // it always did; only a console that was there and went is the loss this class reports.
23
+ try { this.watched = this.attached(); }
24
+ catch { this.watched = false; }
25
+ }
26
+
27
+ // POSIX reports a lost terminal as SIGHUP, which the runner handles, so only Windows needs the probe.
28
+ attached(): boolean
29
+ {
30
+ if (this.platform != "win32") return true;
31
+
32
+ try
33
+ {
34
+ this.open(LocalgateConsole.devicePathConst);
35
+ return true;
36
+ }
37
+ catch (error)
38
+ {
39
+ const code = (error as NodeJS.ErrnoException).code;
40
+ // EPIPE: the console host is gone. EBADF: this process has no console at all.
41
+ if (code == "EPIPE" || code == "EBADF") return false;
42
+ throw error;
43
+ }
44
+ }
45
+
46
+ lost(): boolean
47
+ {
48
+ return this.watched && !this.attached();
49
+ }
50
+
51
+ private static openDevice(path: string): void
52
+ {
53
+ closeSync(openSync(path, "r+"));
54
+ }
55
+ }
@@ -15,7 +15,6 @@ import { LocalgateUrl } from "../proxy/localgateUrl.ts";
15
15
  export class LocalgateEnvRewrite
16
16
  {
17
17
  private static readonly localSuffixConst = ".localhost";
18
- private static readonly browserFacingNamesConst = ["AUTH_URL", "NEXTAUTH_URL"];
19
18
 
20
19
  static apply(env: NodeJS.ProcessEnv, mode: LocalgateMode, machine: LocalgateMachineSettings | null,
21
20
  proxyPort: number): NodeJS.ProcessEnv
@@ -37,9 +36,7 @@ export class LocalgateEnvRewrite
37
36
 
38
37
  static isBrowserFacing(key: string): boolean
39
38
  {
40
- return key.startsWith("NEXT_PUBLIC_")
41
- || key.endsWith("_PUBLIC_URL")
42
- || LocalgateEnvRewrite.browserFacingNamesConst.includes(key);
39
+ return key.startsWith("NEXT_PUBLIC_") || key.endsWith("_PUBLIC_URL");
43
40
  }
44
41
 
45
42
  // Substitutes the authority only, and by string replacement rather than URL.toString(), so a value
@@ -9,6 +9,7 @@ import { LocalgateNames } from "../config/localgateNames.ts";
9
9
  import { LocalgateProjectConfig, type LocalgateProjectSettings } from "../config/localgateProjectConfig.ts";
10
10
  import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
11
11
  import type { LocalgateRoute, LocalgateRouteRegistration } from "../proxy/localgateRegistry.ts";
12
+ import { LocalgateConsole } from "./localgateConsole.ts";
12
13
  import { LocalgateEnvRewrite } from "./localgateEnvRewrite.ts";
13
14
  import { LocalgateNodeOptions } from "./localgateNodeOptions.ts";
14
15
  import { LocalgateProcessTree, type LocalgateKillOutcome } from "./localgateProcessTree.ts";
@@ -40,6 +41,7 @@ export class LocalgateRunner
40
41
  private stopping = false;
41
42
  private restarting = false;
42
43
  private reportedLostRoute = false;
44
+ private reportedConsoleProbe = false;
43
45
  private exitCode = 0;
44
46
 
45
47
  constructor(
@@ -511,14 +513,25 @@ export class LocalgateRunner
511
513
  // The proxy holds the route table in memory, so if it dies the route dies with it. Another runner may
512
514
  // start the proxy before this heartbeat, so a successful ping is not enough: this runner verifies that
513
515
  // its own route is present and re-registers when it is missing.
516
+ //
517
+ // The same beat notices a terminal that went without a signal: an agent's command ending takes its
518
+ // console host along, nothing tells the processes attached to it, and the dev tree is left unable to
519
+ // start any child. That is the operator leaving, so it ends the way Ctrl+C does.
514
520
  private startHeartbeat(): NodeJS.Timeout
515
521
  {
522
+ const terminal = new LocalgateConsole();
516
523
  const timer = setInterval(() =>
517
524
  {
518
525
  void (async () =>
519
526
  {
520
527
  if (this.stopping || !this.route) return;
521
528
 
529
+ if (this.terminalLost(terminal))
530
+ {
531
+ await this.shutdown(0);
532
+ return;
533
+ }
534
+
522
535
  const registered = await LocalgateProxyClient.resolve({ name: this.route.names[0] }).catch(() => null);
523
536
  if (LocalgateRunner.routeRegistrationMatches(this.route, registered, process.pid))
524
537
  {
@@ -567,15 +580,38 @@ export class LocalgateRunner
567
580
  return timer;
568
581
  }
569
582
 
583
+ private terminalLost(terminal: LocalgateConsole): boolean
584
+ {
585
+ try
586
+ {
587
+ return terminal.lost();
588
+ }
589
+ catch (error)
590
+ {
591
+ // Said once: an error this probe does not know repeats on every beat, and the runner keeps working.
592
+ if (!this.reportedConsoleProbe)
593
+ process.stderr.write(`localgate: could not check the terminal: ${String(error)}\n`);
594
+ this.reportedConsoleProbe = true;
595
+ return false;
596
+ }
597
+ }
598
+
599
+ // SIGHUP is the terminal window closing (on Windows the console close event). Without a handler Node
600
+ // exits at once and skips the kill, the port check and the route release.
570
601
  private installSignalHandlers(): void
571
602
  {
572
- for (const signal of ["SIGINT", "SIGTERM"] as const)
603
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const)
573
604
  process.on(signal, () => void this.shutdown(0));
605
+ // A terminal that is gone answers every write with EPIPE. Unhandled, that error would end the runner
606
+ // in the middle of its shutdown, before the route is released; the output is lost either way.
607
+ for (const stream of [process.stdout, process.stderr])
608
+ stream.on("error", () => {});
574
609
  }
575
610
 
576
- // Ctrl+C and the terminal going away, which is the operator leaving: the runner ends whatever the kill
577
- // achieved, and a port that outlived the child is a line on the way out. `/stop` is the other way in,
578
- // and it is the opposite - there somebody is waiting for the answer, so a refused kill is refused.
611
+ // Ctrl+C and the terminal going away (SIGHUP, or a console the heartbeat finds gone), which is the
612
+ // operator leaving: the runner ends whatever the kill achieved, and a port that outlived the child is
613
+ // a line on the way out. `/stop` is the other way in, and it is the opposite - there somebody is
614
+ // waiting for the answer, so a refused kill is refused.
579
615
  private async shutdown(code: number): Promise<void>
580
616
  {
581
617
  if (this.stopping) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "localgate",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Stable names for local dev servers: one port 80 multiplexed by Host, plus an API that can restart a dev server owned by your editor.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -24,7 +24,7 @@
24
24
  "engines": {
25
25
  "node": ">=24"
26
26
  },
27
- "packageManager": "pnpm@11.17.0",
27
+ "packageManager": "pnpm@12.8.1",
28
28
  "bin": {
29
29
  "localgate": "bin/localgate.mjs"
30
30
  },