localgate 0.4.0 → 0.6.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.
@@ -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
@@ -25,9 +24,11 @@ export class LocalgateEnvRewrite
25
24
 
26
25
  for (const [key, value] of Object.entries(result))
27
26
  {
28
- if (!value || !LocalgateEnvRewrite.isBrowserFacing(key)) continue;
27
+ if (!value) continue;
29
28
 
30
- const rewritten = LocalgateEnvRewrite.rewriteAuthority(value, mode, machine, proxyPort);
29
+ const rewritten = LocalgateEnvRewrite.isBrowserFacing(key)
30
+ ? LocalgateEnvRewrite.rewriteBrowserAuthority(value, mode, machine, proxyPort)
31
+ : LocalgateEnvRewrite.rewriteServerAuthority(value, proxyPort);
31
32
  if (rewritten) result[key] = rewritten;
32
33
  }
33
34
 
@@ -45,7 +46,7 @@ export class LocalgateEnvRewrite
45
46
  // keeps its exact original shape - notably no trailing slash appears on a bare origin, which app code
46
47
  // concatenates onto. A port already in the value is replaced rather than kept: behind a proxy that
47
48
  // multiplexes by name, a browser-facing URL has exactly one correct port.
48
- private static rewriteAuthority(value: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null,
49
+ private static rewriteBrowserAuthority(value: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null,
49
50
  proxyPort: number): string | null
50
51
  {
51
52
  let url: URL;
@@ -73,4 +74,25 @@ export class LocalgateEnvRewrite
73
74
  const withAuthority = value.replace(url.host, authority);
74
75
  return `${protocol}${withAuthority.slice(url.protocol.length)}`;
75
76
  }
77
+
78
+ private static rewriteServerAuthority(value: string, proxyPort: number): string | null
79
+ {
80
+ let url: URL;
81
+ try
82
+ {
83
+ url = new URL(value);
84
+ }
85
+ catch
86
+ {
87
+ return null;
88
+ }
89
+
90
+ if (!url.hostname.endsWith(LocalgateEnvRewrite.localSuffixConst)) return null;
91
+ const label = url.hostname.slice(0, -LocalgateEnvRewrite.localSuffixConst.length);
92
+ if (label.length == 0) return null;
93
+
94
+ const authority = LocalgateUrl.forName(url.hostname, proxyPort).replace("http://", "");
95
+ if (url.host == authority) return null;
96
+ return value.replace(url.host, authority);
97
+ }
76
98
  }
@@ -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
+ }
@@ -1,11 +1,20 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { connect } from "node:net";
3
+ import { win32 } from "node:path";
3
4
  import { promisify } from "node:util";
4
5
 
5
6
  export type LocalgateKillSpec =
6
7
  | { via: "command"; file: string; args: string[] }
7
8
  | { via: "signal"; target: number };
8
9
 
10
+ // What a kill actually achieved. `released` is the fact a caller may act on - the port is free - and the
11
+ // errors are the reason it is not, which the platform prints once and nowhere else.
12
+ export type LocalgateKillOutcome =
13
+ {
14
+ released: boolean;
15
+ errors: string[];
16
+ };
17
+
9
18
  // Killing a dev server is not one call on either platform, and for the same reason: `npm run dev` spawns
10
19
  // a shell that spawns the real server, so the process that holds the port is not the one whose pid we
11
20
  // recorded. Windows walks parent links with `taskkill /T`, POSIX signals the process group the child was
@@ -15,57 +24,85 @@ export class LocalgateProcessTree
15
24
  {
16
25
  private static readonly pollIntervalMsConst = 100;
17
26
  private static readonly connectTimeoutMsConst = 500;
27
+ private static readonly commandTimeoutMsConst = 5_000;
18
28
 
19
29
  // Pure so both branches are testable from either OS: what runs is a decision, and only the execution
20
30
  // below is platform-bound.
21
- static killSpec(pid: number, platform: NodeJS.Platform = process.platform): LocalgateKillSpec
31
+ static killSpec(pid: number, platform: NodeJS.Platform = process.platform,
32
+ systemRoot = process.env.SystemRoot): LocalgateKillSpec
22
33
  {
23
- if (platform == "win32") return { via: "command", file: "taskkill", args: ["/T", "/F", "/PID", String(pid)] };
34
+ if (platform == "win32") return {
35
+ via: "command", file: LocalgateProcessTree.windowsTool("taskkill.exe", systemRoot),
36
+ args: ["/T", "/F", "/PID", String(pid)]
37
+ };
24
38
 
25
39
  // The negative pid is the process group. The child is spawned detached precisely so that it leads
26
40
  // one, which is what reaches the shell's children instead of only the shell.
27
41
  return { via: "signal", target: -pid };
28
42
  }
29
43
 
30
- static portHolderCommand(port: number, platform: NodeJS.Platform = process.platform): { file: string; args: string[] }
44
+ static portHolderCommand(port: number, platform: NodeJS.Platform = process.platform,
45
+ systemRoot = process.env.SystemRoot): { file: string; args: string[] }
31
46
  {
32
47
  if (platform == "win32")
33
48
  return {
34
- file: "powershell",
49
+ file: LocalgateProcessTree.windowsTool("WindowsPowerShell\\v1.0\\powershell.exe", systemRoot),
35
50
  args: [
36
51
  "-NoProfile",
52
+ "-NonInteractive",
37
53
  "-Command",
38
- `(Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1).OwningProcess`
54
+ `$ErrorActionPreference = 'Stop'; (Get-NetTCPConnection -ErrorAction Stop | `
55
+ + `Where-Object { $_.LocalPort -eq ${port} -and $_.State -eq 'Listen' } | Select-Object -First 1).OwningProcess`
39
56
  ]
40
57
  };
41
58
 
42
59
  return { file: "lsof", args: ["-ti", `tcp:${port}`, "-sTCP:LISTEN"] };
43
60
  }
44
61
 
45
- static async killTree(pid: number, port: number, timeoutMs = 10_000): Promise<void>
62
+ static async killTree(pid: number, port: number, timeoutMs = 10_000): Promise<LocalgateKillOutcome>
46
63
  {
47
- await LocalgateProcessTree.killPid(pid);
64
+ const errors: string[] = [];
65
+ const killed = await LocalgateProcessTree.killPid(pid, timeoutMs);
66
+ if (killed !== null) errors.push(killed);
48
67
 
49
- if (await LocalgateProcessTree.waitForPortRelease(port, timeoutMs)) return;
68
+ if (await LocalgateProcessTree.waitForPortRelease(port, timeoutMs)) return { released: true, errors };
50
69
 
51
- const holder = await LocalgateProcessTree.findPortHolder(port);
70
+ const holder = await LocalgateProcessTree.findPortHolder(port, errors, timeoutMs);
52
71
  if (holder !== null && holder != pid)
53
72
  {
54
- await LocalgateProcessTree.killPid(holder);
55
- await LocalgateProcessTree.waitForPortRelease(port, timeoutMs);
73
+ const holderKilled = await LocalgateProcessTree.killPid(holder, timeoutMs);
74
+ if (holderKilled !== null) errors.push(holderKilled);
75
+ if (await LocalgateProcessTree.waitForPortRelease(port, timeoutMs)) return { released: true, errors };
56
76
  }
77
+
78
+ // The wait ran out rather than the port being sampled once, so this last look only catches a release
79
+ // that happened between the deadline and now. Everything else is a process that is still serving.
80
+ return { released: !await LocalgateProcessTree.isPortListening(port), errors };
57
81
  }
58
82
 
59
83
  // For a process nobody owns any more. The recorded pid belongs to something that already exited and
60
84
  // both platforms reuse pid numbers, so killing it blind can take out an unrelated tree; whoever
61
85
  // actually holds the port is the only target that is still known to be the right one.
62
- static async killPortHolder(port: number, timeoutMs = 10_000): Promise<boolean>
86
+ static async killPortHolder(port: number, timeoutMs = 10_000): Promise<LocalgateKillOutcome>
63
87
  {
64
- const holder = await LocalgateProcessTree.findPortHolder(port);
65
- if (holder === null) return !await LocalgateProcessTree.isPortListening(port);
88
+ const errors: string[] = [];
89
+ const holder = await LocalgateProcessTree.findPortHolder(port, errors, timeoutMs);
90
+ if (holder === null) return { released: !await LocalgateProcessTree.isPortListening(port), errors };
91
+
92
+ const killed = await LocalgateProcessTree.killPid(holder, timeoutMs);
93
+ if (killed !== null) errors.push(killed);
94
+ return {
95
+ released: await LocalgateProcessTree.waitForPortRelease(port, timeoutMs),
96
+ errors
97
+ };
98
+ }
66
99
 
67
- await LocalgateProcessTree.killPid(holder);
68
- return LocalgateProcessTree.waitForPortRelease(port, timeoutMs);
100
+ // Appended to a caller's own "still held" line, which on its own cannot say which kill was refused or
101
+ // what it printed. Empty when nothing failed, which is the case where the process outlived a kill that
102
+ // the platform accepted.
103
+ static describeErrors(outcome: LocalgateKillOutcome): string
104
+ {
105
+ return outcome.errors.length > 0 ? ` (${outcome.errors.join("; ")})` : "";
69
106
  }
70
107
 
71
108
  static async waitForPortRelease(port: number, timeoutMs: number): Promise<boolean>
@@ -97,45 +134,57 @@ export class LocalgateProcessTree
97
134
  });
98
135
  }
99
136
 
100
- static async findPortHolder(port: number): Promise<number | null>
137
+ static async findPortHolder(port: number, errors: string[] = [],
138
+ timeoutMs = LocalgateProcessTree.commandTimeoutMsConst): Promise<number | null>
101
139
  {
102
- const { file, args } = LocalgateProcessTree.portHolderCommand(port);
103
-
104
140
  try
105
141
  {
106
- const { stdout } = await promisify(execFile)(file, args);
142
+ const { file, args } = LocalgateProcessTree.portHolderCommand(port);
143
+ const { stdout } = await LocalgateProcessTree.runCommand(file, args, timeoutMs);
107
144
  // lsof prints one pid per line and can name several; the listener is the first.
108
145
  const pid = Number.parseInt(stdout.trim().split(/\r?\n/)[0] ?? "", 10);
109
146
  return Number.isFinite(pid) && pid > 0 ? pid : null;
110
147
  }
111
- catch
148
+ catch (error)
112
149
  {
113
- // No holder, or no lsof on this machine. Both mean the same to every caller: nothing to kill here.
150
+ errors.push(`port lookup ${port}: ${LocalgateProcessTree.describeFailure(error)}`);
114
151
  return null;
115
152
  }
116
153
  }
117
154
 
118
- private static async killPid(pid: number): Promise<void>
155
+ // Returns what the kill said when it failed, and null when it was accepted. A process that was already
156
+ // gone and a `taskkill` that was refused look the same from here, so the decision is left to the port:
157
+ // this only makes sure the reason survives as far as the caller that has to report it.
158
+ private static async killPid(pid: number, timeoutMs: number): Promise<string | null>
119
159
  {
120
- const spec = LocalgateProcessTree.killSpec(pid);
160
+ let spec: LocalgateKillSpec;
161
+ try
162
+ {
163
+ spec = LocalgateProcessTree.killSpec(pid);
164
+ }
165
+ catch (error)
166
+ {
167
+ return `kill ${pid}: ${LocalgateProcessTree.describeFailure(error)}`;
168
+ }
121
169
 
122
170
  if (spec.via == "command")
123
171
  {
124
172
  try
125
173
  {
126
- await promisify(execFile)(spec.file, spec.args);
174
+ await LocalgateProcessTree.runCommand(spec.file, spec.args, timeoutMs);
175
+ return null;
127
176
  }
128
- catch
177
+ catch (error)
129
178
  {
130
- // Already gone, or gone between the check and the call: both mean there is nothing to kill.
179
+ return LocalgateProcessTree.describeFailure(error);
131
180
  }
132
- return;
133
181
  }
134
182
  else if (spec.via == "signal")
135
183
  {
136
184
  try
137
185
  {
138
186
  process.kill(spec.target, "SIGKILL");
187
+ return null;
139
188
  }
140
189
  catch
141
190
  {
@@ -144,15 +193,57 @@ export class LocalgateProcessTree
144
193
  try
145
194
  {
146
195
  process.kill(Math.abs(spec.target), "SIGKILL");
196
+ return null;
147
197
  }
148
- catch
198
+ catch (error)
149
199
  {
150
- // Same as above.
200
+ return `kill ${Math.abs(spec.target)}: ${LocalgateProcessTree.describeFailure(error)}`;
151
201
  }
152
202
  }
153
- return;
154
203
  }
155
204
  else
156
205
  throw new Error(`Unknown kill spec: ${JSON.stringify(spec)}`);
157
206
  }
207
+
208
+ // A runner can inherit a project-local PATH. Use the system tools without a shell, and include the
209
+ // selected path in failures instead of dumping an environment that can contain credentials.
210
+ private static windowsTool(relativePath: string, systemRoot: string | undefined): string
211
+ {
212
+ if (!systemRoot || !win32.isAbsolute(systemRoot))
213
+ throw new Error("SystemRoot must be an absolute Windows directory to resolve process tools");
214
+ return win32.join(systemRoot, "System32", relativePath);
215
+ }
216
+
217
+ private static async runCommand(file: string, args: string[], timeoutMs: number): Promise<{ stdout: string; stderr: string }>
218
+ {
219
+ const timeout = Math.max(1, Math.min(timeoutMs, LocalgateProcessTree.commandTimeoutMsConst));
220
+ try
221
+ {
222
+ return await promisify(execFile)(file, args, { timeout, killSignal: "SIGKILL", windowsHide: true, shell: false });
223
+ }
224
+ catch (error)
225
+ {
226
+ throw new Error(`${file} ${JSON.stringify(args)} [shell=false timeout=${timeout}ms]: `
227
+ + LocalgateProcessTree.describeFailure(error));
228
+ }
229
+ }
230
+
231
+ private static describeFailure(error: unknown): string
232
+ {
233
+ if (typeof error != "object" || error === null) return String(error);
234
+
235
+ const detail: { stdout?: unknown; stderr?: unknown; message?: unknown;
236
+ code?: unknown; signal?: unknown; killed?: unknown } = error;
237
+ const stdout = typeof detail.stdout == "string" ? detail.stdout.trim() : "";
238
+ const stderr = typeof detail.stderr == "string" ? detail.stderr.trim() : "";
239
+ const message = typeof detail.message == "string" ? detail.message.trim() : "";
240
+ const parts: string[] = [];
241
+ if (detail.code !== undefined) parts.push(`code=${String(detail.code)}`);
242
+ if (detail.signal !== undefined) parts.push(`signal=${String(detail.signal)}`);
243
+ if (detail.killed !== undefined) parts.push(`killed=${String(detail.killed)}`);
244
+ if (stdout) parts.push(`stdout=${stdout}`);
245
+ if (stderr) parts.push(`stderr=${stderr}`);
246
+ if (!stdout && !stderr) parts.push(message || String(error));
247
+ return parts.join("; ").replace(/\s+/g, " ");
248
+ }
158
249
  }