localgate 0.2.0 → 0.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.
package/README.md CHANGED
@@ -5,12 +5,9 @@ Stable names for local dev servers.
5
5
  [![CI](https://github.com/ludekvodicka/LocalGate/actions/workflows/ci.yml/badge.svg)](https://github.com/ludekvodicka/LocalGate/actions/workflows/ci.yml)
6
6
  [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
7
7
 
8
- > **Windows only today.** The process-tree kill behind `restart` is written for Windows, and the
9
- > port-80 bind assumes it. See [Status](#status).
10
-
11
- One reverse proxy on port 80 multiplexes every dev server on the machine by `Host` header, so each app
12
- gets a name instead of a port: `myapp.localhost` locally, and optionally `myapp.<label>.<your-domain>`
13
- so a colleague on the LAN can open it too.
8
+ One reverse proxy multiplexes every dev server on the machine by `Host` header, so each app gets a name
9
+ instead of a port: `myapp.localhost` locally, and optionally `myapp.<label>.<your-domain>` so a
10
+ colleague on the LAN can open it too.
14
11
 
15
12
  It also owns the dev process it starts, which is the part editors cannot give you: `localgate restart`
16
13
  restarts the server running inside your editor's debug terminal, without stealing the route or the
@@ -29,7 +26,7 @@ localgate status --json # machine-readable state
29
26
  ## How it routes
30
27
 
31
28
  Every dev server binds an ephemeral loopback port and registers its name. The proxy routes by the
32
- `Host` header, so nothing else has to listen on 80.
29
+ `Host` header, so it is the only thing that has to listen on a fixed port.
33
30
 
34
31
  ```mermaid
35
32
  flowchart LR
@@ -37,7 +34,7 @@ flowchart LR
37
34
  lan["the LAN"] -->|"lan: myapp.dev.example.com"| proxy
38
35
  net["a tunnel"] -->|"internet: same name"| proxy
39
36
 
40
- proxy["localgate :80"]
37
+ proxy["localgate proxy"]
41
38
 
42
39
  proxy --> app1["myapp :41000"]
43
40
  proxy --> app2["docs :41001"]
@@ -45,8 +42,8 @@ flowchart LR
45
42
  ```
46
43
 
47
44
  The tunnel is not localgate's - it is whatever you already run, pointed at this machine's LAN address
48
- on port 80. It keeps the `Host` header, so a request arriving through it is routed exactly like a LAN
49
- request and localgate needs to know nothing about it.
45
+ on the proxy's port. It keeps the `Host` header, so a request arriving through it is routed exactly
46
+ like a LAN request and localgate needs to know nothing about it.
50
47
 
51
48
  The table lives in the proxy's memory. There is no config file listing apps, no port assignment to keep
52
49
  in sync, and nothing to clean up after a crash.
@@ -78,12 +75,19 @@ through a shared name, without an `allowedDevOrigins` entry in the project.
78
75
 
79
76
  ## Install
80
77
 
81
- Windows and Node 24+.
78
+ Node 24+.
82
79
 
83
80
  ```bash
84
81
  npm install -g localgate
85
82
  ```
86
83
 
84
+ On Windows the proxy binds port 80, so a name stands alone: `http://myapp.localhost`. On Linux and
85
+ macOS everything below 1024 belongs to root, and a tool that starts itself on demand has no business
86
+ asking for that, so it binds **8080** and the port rides along: `http://myapp.localhost:8080`. Every
87
+ URL localgate prints already carries it. To have 80 there too, give the node binary the capability
88
+ (`sudo setcap cap_net_bind_service=+ep $(which node)` on Linux) and set `"proxyPort": 80` in
89
+ `~/.localgate/config.json`.
90
+
87
91
  Or from a clone, which is also how you develop on it:
88
92
 
89
93
  ```bash
@@ -278,9 +282,12 @@ build step.
278
282
 
279
283
  ## Status
280
284
 
281
- Early, and Windows-only for now: the process-tree kill that makes `restart`
282
- reliable is implemented with `taskkill`, and the port-80 bind assumes Windows' lack of privileged-port
283
- restrictions. The rest is plain Node and portable.
285
+ Early. Windows, Linux and macOS: the kill that makes `restart` reliable goes through `taskkill /T` on
286
+ Windows and the child's process group elsewhere, and the port-holder lookup is PowerShell or `lsof`.
287
+
288
+ One rough edge on macOS: browsers resolve `*.localhost` to loopback by RFC 6761, but the system
289
+ resolver does not, so `curl http://myapp.localhost:8080` and server-to-server calls by name need an
290
+ `/etc/hosts` entry there. Browsers are fine.
284
291
 
285
292
  Bug reports and ideas are welcome - see [CONTRIBUTING.md](CONTRIBUTING.md), and
286
293
  [SECURITY.md](SECURITY.md) for anything security-related. Licensed under
@@ -1,25 +1,26 @@
1
1
  import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
2
+ import { LocalgateUrl } from "../proxy/localgateUrl.ts";
2
3
 
3
4
  // What a command prints once a name answers. `run` and `alias` share it because to the person reading the
4
5
  // terminal they are the same event, and the one-line variant `alias` used to print is how a shared name
5
6
  // goes unnoticed - the script that registered one then wrote its own `.localhost` block instead.
6
7
  //
7
- // The route is the ONLY input. The title, the column alignment and even which command to type next are
8
- // decided here rather than passed in, because a caller that hand-builds a padded string is a caller that
9
- // can drift out of format again.
8
+ // The route and the port the proxy answers on are the ONLY inputs. The title, the column alignment and
9
+ // even which command to type next are decided here rather than passed in, because a caller that
10
+ // hand-builds a padded string is a caller that can drift out of format again.
10
11
  export class LocalgateBanner
11
12
  {
12
13
  private static readonly labelWidthConst = 11;
13
14
 
14
- static render(route: LocalgateRoute): string
15
+ static render(route: LocalgateRoute, proxyPort: number): string
15
16
  {
16
17
  const [local, shared] = route.names;
17
18
  const [nextLabel, nextCommand] = LocalgateBanner.next(route);
18
19
 
19
20
  const lines = ["", ` localgate ${LocalgateBanner.appName(route)} · ${LocalgateBanner.subtitle(route)}`, ""];
20
21
 
21
- if (shared) lines.push(LocalgateBanner.row("shared", `http://${shared}`));
22
- lines.push(LocalgateBanner.row("local", `http://${local}`));
22
+ if (shared) lines.push(LocalgateBanner.row("shared", LocalgateUrl.forName(shared, proxyPort)));
23
+ lines.push(LocalgateBanner.row("local", LocalgateUrl.forName(local, proxyPort)));
23
24
  lines.push("", LocalgateBanner.row("upstream", `127.0.0.1:${route.port}`), LocalgateBanner.row(nextLabel, nextCommand), "");
24
25
 
25
26
  return `${lines.join("\n")}\n`;
@@ -4,6 +4,7 @@ import { LocalgateCloudflareInfo } from "../cloudflare/localgateCloudflareInfo.t
4
4
  import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
5
5
  import { LocalgateProjectConfig } from "../config/localgateProjectConfig.ts";
6
6
  import { LocalgateProxyHost } from "../proxy/localgateProxyHost.ts";
7
+ import { LocalgateUrl } from "../proxy/localgateUrl.ts";
7
8
  import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
8
9
  import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
9
10
  import { LocalgateRunner } from "../run/localgateRunner.ts";
@@ -61,9 +62,10 @@ export class LocalgateCli
61
62
  }
62
63
 
63
64
  process.stdout.write("Active routes:\n\n");
65
+ const proxyPort = LocalgateProxyClient.proxyPort();
64
66
  for (const route of routes)
65
67
  {
66
- process.stdout.write(` ${route.names.map(name => `http://${name}`).join("\n ")}\n`);
68
+ process.stdout.write(` ${route.names.map(name => LocalgateUrl.forName(name, proxyPort)).join("\n ")}\n`);
67
69
  process.stdout.write(` -> 127.0.0.1:${route.port} [${route.state}] ${route.kind}`
68
70
  + `${route.debuggerAttached ? " debugger" : ""}\n`);
69
71
  if (route.cwd) process.stdout.write(` ${route.cwd}\n`);
@@ -93,7 +95,7 @@ export class LocalgateCli
93
95
  }
94
96
 
95
97
  process.stdout.write([
96
- `${route.names.map(name => `http://${name}`).join("\n")}`,
98
+ `${route.names.map(name => LocalgateUrl.forName(name, LocalgateProxyClient.proxyPort())).join("\n")}`,
97
99
  `port 127.0.0.1:${route.port}`,
98
100
  `state ${route.state}`,
99
101
  `mode ${route.mode}`,
@@ -188,7 +190,7 @@ export class LocalgateCli
188
190
  return 1;
189
191
  }
190
192
 
191
- process.stdout.write(LocalgateBanner.render(route));
193
+ process.stdout.write(LocalgateBanner.render(route, LocalgateProxyClient.proxyPort()));
192
194
  return 0;
193
195
  }
194
196
 
@@ -209,7 +211,8 @@ export class LocalgateCli
209
211
 
210
212
  process.stdout.write(LocalgateCloudflareInfo.render(
211
213
  `${project.name}${LocalgateMachineConfig.externalSuffix(machine)}`,
212
- machine.lanIp
214
+ machine.lanIp,
215
+ LocalgateUrl.proxyPort(machine)
213
216
  ));
214
217
 
215
218
  return 0;
@@ -1,7 +1,8 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { join } from "node:path";
4
- import { LocalgateProxyHost } from "../proxy/localgateProxyHost.ts";
4
+ import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
5
+ import { LocalgateUrl } from "../proxy/localgateUrl.ts";
5
6
  import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
6
7
  import type { LocalgateRoute, LocalgateRouteRegistration } from "../proxy/localgateRegistry.ts";
7
8
 
@@ -9,14 +10,30 @@ import type { LocalgateRoute, LocalgateRouteRegistration } from "../proxy/localg
9
10
  // this client is the only way in - and it is loopback-only, which is what keeps the LAN out of it.
10
11
  export class LocalgateProxyClient
11
12
  {
12
- private static readonly baseUrlConst = `http://127.0.0.1:${LocalgateProxyHost.portConst}/__localgate`;
13
13
  private static readonly startTimeoutMsConst = 15_000;
14
14
 
15
+ // Resolved once per process rather than per call: it reads the machine config from disk, and a
16
+ // long-lived runner asks for this on every heartbeat. Public because everything that prints a URL
17
+ // needs the same answer, and asking the one component that already talks to the proxy beats every
18
+ // caller loading the config for itself.
19
+ private static port: number | null = null;
20
+
21
+ static proxyPort(): number
22
+ {
23
+ LocalgateProxyClient.port ??= LocalgateUrl.proxyPort(LocalgateMachineConfig.load());
24
+ return LocalgateProxyClient.port;
25
+ }
26
+
27
+ private static baseUrl(): string
28
+ {
29
+ return `http://127.0.0.1:${LocalgateProxyClient.proxyPort()}/__localgate`;
30
+ }
31
+
15
32
  static async ping(): Promise<boolean>
16
33
  {
17
34
  try
18
35
  {
19
- const response = await fetch(`${LocalgateProxyClient.baseUrlConst}/ping`, {
36
+ const response = await fetch(`${LocalgateProxyClient.baseUrl()}/ping`, {
20
37
  signal: AbortSignal.timeout(1_000)
21
38
  });
22
39
  return response.ok;
@@ -39,7 +56,7 @@ export class LocalgateProxyClient
39
56
  await new Promise(resolve => setTimeout(resolve, 150));
40
57
  if (await LocalgateProxyClient.ping()) return;
41
58
  if (Date.now() >= deadline)
42
- throw new Error(`localgate proxy did not come up on port ${LocalgateProxyHost.portConst} within `
59
+ throw new Error(`localgate proxy did not come up on port ${LocalgateProxyClient.proxyPort()} within `
43
60
  + `${LocalgateProxyClient.startTimeoutMsConst / 1000} s (is something else holding the port?)`);
44
61
  }
45
62
  }
@@ -75,7 +92,7 @@ export class LocalgateProxyClient
75
92
  ? `name=${encodeURIComponent(selector.name)}`
76
93
  : `cwd=${encodeURIComponent(selector.directory ?? "")}`;
77
94
 
78
- const response = await fetch(`${LocalgateProxyClient.baseUrlConst}/resolve?${query}`);
95
+ const response = await fetch(`${LocalgateProxyClient.baseUrl()}/resolve?${query}`);
79
96
  if (!response.ok) return null;
80
97
  return ((await response.json()) as { route: LocalgateRoute | null }).route;
81
98
  }
@@ -104,7 +121,7 @@ export class LocalgateProxyClient
104
121
  init.body = JSON.stringify(body);
105
122
  }
106
123
 
107
- const response = await fetch(`${LocalgateProxyClient.baseUrlConst}${path}`, init);
124
+ const response = await fetch(`${LocalgateProxyClient.baseUrl()}${path}`, init);
108
125
 
109
126
  // A collision travels as its own type so the runner can name the process that holds the name,
110
127
  // rather than reporting a bare status code.
@@ -2,7 +2,7 @@
2
2
  // no business holding credentials for, so it hands you the exact text and stops there.
3
3
  export class LocalgateCloudflareInfo
4
4
  {
5
- static render(hostname: string, lanIp: string): string
5
+ static render(hostname: string, lanIp: string, proxyPort: number): string
6
6
  {
7
7
  return [
8
8
  `To reach http://${hostname} from outside the LAN, add these two entries.`,
@@ -14,7 +14,7 @@ export class LocalgateCloudflareInfo
14
14
  "2. Ingress list of the shared cloudflared container:",
15
15
  "",
16
16
  ` - hostname: ${hostname}`,
17
- ` service: http://${lanIp}:80`,
17
+ ` service: http://${lanIp}:${proxyPort}`,
18
18
  "",
19
19
  "cloudflared keeps the Host header, so the proxy routes it like any LAN request.",
20
20
  "",
@@ -8,6 +8,9 @@ export type LocalgateMachineSettings =
8
8
  baseDomain: string;
9
9
  lanIp: string;
10
10
  autoRestart: boolean;
11
+ // null leaves the port to the platform default. Set it only when the machine has arranged for
12
+ // something else - a capability that permits 80 on Linux, or another port because 8080 is taken.
13
+ proxyPort: number | null;
11
14
  };
12
15
 
13
16
  export class LocalgateMachineConfig
@@ -43,10 +46,20 @@ export class LocalgateMachineConfig
43
46
  label,
44
47
  baseDomain: LocalgateMachineConfig.requireString(parsed, "baseDomain", filePath),
45
48
  lanIp: LocalgateMachineConfig.requireString(parsed, "lanIp", filePath),
46
- autoRestart: parsed.autoRestart === true
49
+ autoRestart: parsed.autoRestart === true,
50
+ proxyPort: LocalgateMachineConfig.optionalPort(parsed, "proxyPort", filePath)
47
51
  };
48
52
  }
49
53
 
54
+ private static optionalPort(parsed: Record<string, unknown>, key: string, filePath: string): number | null
55
+ {
56
+ const value = parsed[key];
57
+ if (value === undefined || value === null) return null;
58
+ if (typeof value != "number" || !Number.isInteger(value) || value < 1 || value > 65_535)
59
+ throw new Error(`${filePath}: "${key}" must be a port number between 1 and 65535`);
60
+ return value;
61
+ }
62
+
50
63
  static externalSuffix(settings: LocalgateMachineSettings): string
51
64
  {
52
65
  return `.${settings.label}.${settings.baseDomain}`;
@@ -1,4 +1,5 @@
1
1
  import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
2
+ import { LocalgateUrl } from "./localgateUrl.ts";
2
3
  import { LocalgateControlApi } from "./localgateControlApi.ts";
3
4
  import { LocalgateHealth } from "./localgateHealth.ts";
4
5
  import { LocalgateProxy } from "./localgateProxy.ts";
@@ -8,12 +9,12 @@ import { LocalgateRegistry, type LocalgateRoute } from "./localgateRegistry.ts";
8
9
  // once the last route disappears, so nothing is installed and nothing runs when no dev server does.
9
10
  export class LocalgateProxyHost
10
11
  {
11
- static readonly portConst = 80;
12
12
  private static readonly gracePeriodMsConst = 20_000;
13
13
 
14
14
  static async run(): Promise<void>
15
15
  {
16
16
  const machine = LocalgateMachineConfig.load();
17
+ const port = LocalgateUrl.proxyPort(machine);
17
18
  const registry = new LocalgateRegistry();
18
19
  const health = new LocalgateHealth(registry, machine?.autoRestart === true, LocalgateProxyHost.requestRestart);
19
20
 
@@ -22,7 +23,7 @@ export class LocalgateProxyHost
22
23
  health,
23
24
  new LocalgateControlApi(registry, () => proxy.checkIdle()),
24
25
  {
25
- port: LocalgateProxyHost.portConst,
26
+ port,
26
27
  lanIp: machine?.lanIp ?? null,
27
28
  externalSuffix: machine ? LocalgateMachineConfig.externalSuffix(machine) : null,
28
29
  gracePeriodMs: LocalgateProxyHost.gracePeriodMsConst,
@@ -35,8 +36,8 @@ export class LocalgateProxyHost
35
36
  );
36
37
 
37
38
  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`);
39
+ process.stdout.write(`localgate proxy listening on 127.0.0.1:${port}`
40
+ + `${machine?.lanIp ? ` and ${machine.lanIp}:${port}` : ""}\n`);
40
41
 
41
42
  for (const signal of ["SIGINT", "SIGTERM"] as const)
42
43
  process.on(signal, () => void proxy.stop().then(() => process.exit(0)));
@@ -0,0 +1,25 @@
1
+ import type { LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
2
+
3
+ // Where the proxy listens, and how a route's name is written down for a person to paste. One place,
4
+ // because the two have to agree: every URL localgate prints is a name plus this port, and every
5
+ // client that talks to the control API has to find the same listener without being told.
6
+ export class LocalgateUrl
7
+ {
8
+ // Windows lets a normal user bind 80, so the name stands alone and the port never appears. Linux and
9
+ // macOS reserve everything below 1024 for root, and a dev tool that starts itself on demand has no
10
+ // business asking for that, so the port moves into the URL instead.
11
+ private static readonly windowsPortConst = 80;
12
+ private static readonly elsewherePortConst = 8080;
13
+ private static readonly defaultHttpPortConst = 80;
14
+
15
+ static proxyPort(settings: LocalgateMachineSettings | null, platform: NodeJS.Platform = process.platform): number
16
+ {
17
+ if (settings?.proxyPort != null) return settings.proxyPort;
18
+ return platform == "win32" ? LocalgateUrl.windowsPortConst : LocalgateUrl.elsewherePortConst;
19
+ }
20
+
21
+ static forName(name: string, port: number): string
22
+ {
23
+ return port == LocalgateUrl.defaultHttpPortConst ? `http://${name}` : `http://${name}:${port}`;
24
+ }
25
+ }
@@ -1,23 +1,29 @@
1
- // Keeps repositories machine-agnostic: a committed env file says `.localhost` everywhere, and the
2
- // machine's own suffix is substituted here, in memory, on the way into the child process. Only the
3
- // variables a browser reads are rewritten - a remote viewer's browser resolves `.localhost` to its own
4
- // machine, so those URLs must carry the shared name. Server-side variables stay on `.localhost`, which
5
- // is faster and works with no DNS at all.
1
+ import { LocalgateUrl } from "../proxy/localgateUrl.ts";
2
+
3
+ // Keeps repositories machine-agnostic: a committed env file says `.localhost` everywhere, and what this
4
+ // machine actually answers on is substituted here, in memory, on the way into the child process.
5
+ //
6
+ // Only the variables a browser reads are rewritten. A remote viewer's browser resolves `.localhost` to
7
+ // its own machine, so those URLs must carry the shared name; server-side variables stay on `.localhost`,
8
+ // which is faster and works with no DNS at all.
9
+ //
10
+ // The job is "point this at the proxy", not "swap the suffix". That distinction is what the port makes:
11
+ // where the proxy cannot have 80 the value needs `:8080` even in mode local, where no suffix exists and
12
+ // nothing used to be rewritten at all.
6
13
  export class LocalgateEnvRewrite
7
14
  {
8
15
  private static readonly localSuffixConst = ".localhost";
9
16
  private static readonly browserFacingNamesConst = ["AUTH_URL", "NEXTAUTH_URL"];
10
17
 
11
- static apply(env: NodeJS.ProcessEnv, externalSuffix: string | null): NodeJS.ProcessEnv
18
+ static apply(env: NodeJS.ProcessEnv, externalSuffix: string | null, proxyPort: number): NodeJS.ProcessEnv
12
19
  {
13
20
  const result: NodeJS.ProcessEnv = { ...env };
14
- if (!externalSuffix) return result;
15
21
 
16
22
  for (const [key, value] of Object.entries(result))
17
23
  {
18
24
  if (!value || !LocalgateEnvRewrite.isBrowserFacing(key)) continue;
19
25
 
20
- const rewritten = LocalgateEnvRewrite.rewriteHostname(value, externalSuffix);
26
+ const rewritten = LocalgateEnvRewrite.rewriteAuthority(value, externalSuffix, proxyPort);
21
27
  if (rewritten) result[key] = rewritten;
22
28
  }
23
29
 
@@ -31,10 +37,11 @@ export class LocalgateEnvRewrite
31
37
  || LocalgateEnvRewrite.browserFacingNamesConst.includes(key);
32
38
  }
33
39
 
34
- // Substitutes inside the authority component only, and by string replacement rather than
35
- // URL.toString(), so a value keeps its exact original shape - notably no trailing slash appears on a
36
- // bare origin, which app code concatenates onto.
37
- private static rewriteHostname(value: string, externalSuffix: string): string | null
40
+ // Substitutes the authority only, and by string replacement rather than URL.toString(), so a value
41
+ // keeps its exact original shape - notably no trailing slash appears on a bare origin, which app code
42
+ // concatenates onto. A port already in the value is replaced rather than kept: behind a proxy that
43
+ // multiplexes by name, a browser-facing URL has exactly one correct port.
44
+ private static rewriteAuthority(value: string, externalSuffix: string | null, proxyPort: number): string | null
38
45
  {
39
46
  let url: URL;
40
47
  try
@@ -51,6 +58,9 @@ export class LocalgateEnvRewrite
51
58
  const label = url.hostname.slice(0, -LocalgateEnvRewrite.localSuffixConst.length);
52
59
  if (label.length == 0) return null;
53
60
 
54
- return value.replace(url.hostname, `${label}${externalSuffix}`);
61
+ const name = `${label}${externalSuffix ?? LocalgateEnvRewrite.localSuffixConst}`;
62
+ const authority = LocalgateUrl.forName(name, proxyPort).replace("http://", "");
63
+
64
+ return url.host == authority ? null : value.replace(url.host, authority);
55
65
  }
56
66
  }
@@ -2,16 +2,46 @@ import { execFile } from "node:child_process";
2
2
  import { connect } from "node:net";
3
3
  import { promisify } from "node:util";
4
4
 
5
- // Killing a dev server on Windows is not one call. `taskkill /T` walks parent links, so when the
6
- // intermediate shell npm spawned has already exited, the real server is an orphan the tree walk cannot
7
- // see - it survives and keeps the port. That is the failure `portless prune` exists to clean up after.
8
- // So: kill the tree, wait for the port to actually come free, and if it does not, find whoever still
9
- // holds it and kill that process directly.
5
+ export type LocalgateKillSpec =
6
+ | { via: "command"; file: string; args: string[] }
7
+ | { via: "signal"; target: number };
8
+
9
+ // Killing a dev server is not one call on either platform, and for the same reason: `npm run dev` spawns
10
+ // a shell that spawns the real server, so the process that holds the port is not the one whose pid we
11
+ // recorded. Windows walks parent links with `taskkill /T`, POSIX signals the process group the child was
12
+ // made the leader of. Both miss an orphan whose parent already exited, so the port is checked afterwards
13
+ // and whoever still holds it is killed directly.
10
14
  export class LocalgateProcessTree
11
15
  {
12
16
  private static readonly pollIntervalMsConst = 100;
13
17
  private static readonly connectTimeoutMsConst = 500;
14
18
 
19
+ // Pure so both branches are testable from either OS: what runs is a decision, and only the execution
20
+ // below is platform-bound.
21
+ static killSpec(pid: number, platform: NodeJS.Platform = process.platform): LocalgateKillSpec
22
+ {
23
+ if (platform == "win32") return { via: "command", file: "taskkill", args: ["/T", "/F", "/PID", String(pid)] };
24
+
25
+ // The negative pid is the process group. The child is spawned detached precisely so that it leads
26
+ // one, which is what reaches the shell's children instead of only the shell.
27
+ return { via: "signal", target: -pid };
28
+ }
29
+
30
+ static portHolderCommand(port: number, platform: NodeJS.Platform = process.platform): { file: string; args: string[] }
31
+ {
32
+ if (platform == "win32")
33
+ return {
34
+ file: "powershell",
35
+ args: [
36
+ "-NoProfile",
37
+ "-Command",
38
+ `(Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1).OwningProcess`
39
+ ]
40
+ };
41
+
42
+ return { file: "lsof", args: ["-ti", `tcp:${port}`, "-sTCP:LISTEN"] };
43
+ }
44
+
15
45
  static async killTree(pid: number, port: number, timeoutMs = 10_000): Promise<void>
16
46
  {
17
47
  await LocalgateProcessTree.killPid(pid);
@@ -27,8 +57,8 @@ export class LocalgateProcessTree
27
57
  }
28
58
 
29
59
  // For a process nobody owns any more. The recorded pid belongs to something that already exited and
30
- // Windows reuses pid numbers, so killing it blind can take out an unrelated tree; whoever actually
31
- // holds the port is the only target that is still known to be the right one.
60
+ // both platforms reuse pid numbers, so killing it blind can take out an unrelated tree; whoever
61
+ // actually holds the port is the only target that is still known to be the right one.
32
62
  static async killPortHolder(port: number, timeoutMs = 10_000): Promise<boolean>
33
63
  {
34
64
  const holder = await LocalgateProcessTree.findPortHolder(port);
@@ -69,32 +99,31 @@ export class LocalgateProcessTree
69
99
 
70
100
  static async findPortHolder(port: number): Promise<number | null>
71
101
  {
72
- if (process.platform != "win32") return null;
102
+ const { file, args } = LocalgateProcessTree.portHolderCommand(port);
73
103
 
74
104
  try
75
105
  {
76
- const { stdout } = await promisify(execFile)("powershell", [
77
- "-NoProfile",
78
- "-Command",
79
- `(Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1).OwningProcess`
80
- ]);
81
-
82
- const pid = Number.parseInt(stdout.trim(), 10);
106
+ const { stdout } = await promisify(execFile)(file, args);
107
+ // lsof prints one pid per line and can name several; the listener is the first.
108
+ const pid = Number.parseInt(stdout.trim().split(/\r?\n/)[0] ?? "", 10);
83
109
  return Number.isFinite(pid) && pid > 0 ? pid : null;
84
110
  }
85
111
  catch
86
112
  {
113
+ // No holder, or no lsof on this machine. Both mean the same to every caller: nothing to kill here.
87
114
  return null;
88
115
  }
89
116
  }
90
117
 
91
118
  private static async killPid(pid: number): Promise<void>
92
119
  {
93
- if (process.platform == "win32")
120
+ const spec = LocalgateProcessTree.killSpec(pid);
121
+
122
+ if (spec.via == "command")
94
123
  {
95
124
  try
96
125
  {
97
- await promisify(execFile)("taskkill", ["/T", "/F", "/PID", String(pid)]);
126
+ await promisify(execFile)(spec.file, spec.args);
98
127
  }
99
128
  catch
100
129
  {
@@ -102,14 +131,28 @@ export class LocalgateProcessTree
102
131
  }
103
132
  return;
104
133
  }
105
-
106
- try
107
- {
108
- process.kill(pid, "SIGKILL");
109
- }
110
- catch
134
+ else if (spec.via == "signal")
111
135
  {
112
- // Same as above.
136
+ try
137
+ {
138
+ process.kill(spec.target, "SIGKILL");
139
+ }
140
+ catch
141
+ {
142
+ // A child that was never detached leads no group, so the group signal finds nothing. Falling
143
+ // back to the pid itself still ends the process we were asked to end.
144
+ try
145
+ {
146
+ process.kill(Math.abs(spec.target), "SIGKILL");
147
+ }
148
+ catch
149
+ {
150
+ // Same as above.
151
+ }
152
+ }
153
+ return;
113
154
  }
155
+ else
156
+ throw new Error(`Unknown kill spec: ${JSON.stringify(spec)}`);
114
157
  }
115
158
  }
@@ -9,6 +9,7 @@ import { LocalgateProxyClient } from "../client/localgateProxyClient.ts";
9
9
  import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
10
10
  import { LocalgateProjectConfig, type LocalgateProjectSettings } from "../config/localgateProjectConfig.ts";
11
11
  import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
12
+ import { LocalgateUrl } from "../proxy/localgateUrl.ts";
12
13
  import { LocalgateEnvRewrite } from "./localgateEnvRewrite.ts";
13
14
  import { LocalgateProcessTree } from "./localgateProcessTree.ts";
14
15
 
@@ -150,7 +151,7 @@ export class LocalgateRunner
150
151
  });
151
152
  this.route = route;
152
153
 
153
- process.stdout.write(LocalgateBanner.render(route));
154
+ process.stdout.write(LocalgateBanner.render(route, LocalgateProxyClient.proxyPort()));
154
155
 
155
156
  this.installSignalHandlers();
156
157
  const heartbeat = this.startHeartbeat();
@@ -205,7 +206,8 @@ export class LocalgateRunner
205
206
 
206
207
  if (!await LocalgateRunner.askTakeover())
207
208
  {
208
- process.stdout.write(`localgate: left it running. Reach it at http://${existing.names[0]}\n`);
209
+ process.stdout.write("localgate: left it running. Reach it at "
210
+ + `${LocalgateUrl.forName(existing.names[0], LocalgateProxyClient.proxyPort())}\n`);
209
211
  return 1;
210
212
  }
211
213
  }
@@ -298,16 +300,22 @@ export class LocalgateRunner
298
300
  const scripts = LocalgateRunner.readScripts(packageDirectory);
299
301
  const command = LocalgateRunner.withPortFlag(this.command, scripts, port);
300
302
 
301
- const env = LocalgateEnvRewrite.apply(process.env, external);
303
+ const env = LocalgateEnvRewrite.apply(process.env, external, LocalgateProxyClient.proxyPort());
302
304
  env.PORT = String(port);
303
305
 
304
306
  // One command string rather than a command plus an args array: `npm run dev` on Windows is a .cmd,
305
307
  // which node refuses to spawn without a shell, and passing an args array alongside `shell: true`
306
308
  // triggers DEP0190 because the shell concatenates them anyway. Quoting here makes that explicit.
309
+ //
310
+ // `detached` off Windows makes the child lead its own process group, which is the only way to reach
311
+ // the dev server the shell spawns underneath it: signalling the shell alone leaves the server
312
+ // running and holding the port. On Windows the same flag would hand the child its own console
313
+ // instead, and `taskkill /T` already walks the tree, so it stays off there.
307
314
  const child = spawn(LocalgateRunner.shellCommand(command), {
308
315
  cwd: this.directory,
309
316
  env,
310
317
  shell: true,
318
+ detached: process.platform != "win32",
311
319
  stdio: ["inherit", "pipe", "pipe"]
312
320
  });
313
321
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "localgate",
3
- "version": "0.2.0",
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. Windows only today.",
3
+ "version": "0.3.0",
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",
7
7
  "author": "ludekvodicka",
@@ -24,9 +24,6 @@
24
24
  "engines": {
25
25
  "node": ">=24"
26
26
  },
27
- "os": [
28
- "win32"
29
- ],
30
27
  "packageManager": "pnpm@11.17.0",
31
28
  "bin": {
32
29
  "localgate": "bin/localgate.mjs"