localgate 0.2.0 → 0.4.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 +43 -30
- package/logic/cli/localgateBanner.ts +9 -7
- package/logic/cli/localgateCli.ts +24 -9
- package/logic/client/localgateProxyClient.ts +26 -8
- package/logic/cloudflare/localgateCloudflareInfo.ts +2 -2
- package/logic/config/localgateMachineConfig.ts +32 -4
- package/logic/config/localgateNames.ts +52 -0
- package/logic/proxy/localgateHeaderRewrite.ts +27 -11
- package/logic/proxy/localgateProxy.ts +2 -3
- package/logic/proxy/localgateProxyHost.ts +5 -5
- package/logic/proxy/localgateRegistry.ts +13 -1
- package/logic/proxy/localgateUrl.ts +25 -0
- package/logic/run/localgateEnvRewrite.ts +33 -13
- package/logic/run/localgateProcessTree.ts +67 -24
- package/logic/run/localgateRunner.ts +68 -23
- package/package.json +2 -5
package/README.md
CHANGED
|
@@ -5,12 +5,9 @@ Stable names for local dev servers.
|
|
|
5
5
|
[](https://github.com/ludekvodicka/LocalGate/actions/workflows/ci.yml)
|
|
6
6
|
[](LICENSE)
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
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, optionally `myapp.<label>.<your-domain>` on the LAN,
|
|
10
|
+
and optionally `<public-prefix>-myapp.<your-domain>` through a tunnel.
|
|
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,24 +26,25 @@ 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
|
|
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
|
|
36
33
|
local["this PC"] -->|"local: myapp.localhost"| proxy
|
|
37
34
|
lan["the LAN"] -->|"lan: myapp.dev.example.com"| proxy
|
|
38
|
-
net["
|
|
35
|
+
net["the internet"] -->|"internet: pub-myapp.example.com"| tunnel["shared tunnel"]
|
|
36
|
+
tunnel --> proxy
|
|
39
37
|
|
|
40
|
-
proxy["localgate
|
|
38
|
+
proxy["localgate proxy"]
|
|
41
39
|
|
|
42
40
|
proxy --> app1["myapp :41000"]
|
|
43
41
|
proxy --> app2["docs :41001"]
|
|
44
42
|
proxy --> alias["alias :8001"]
|
|
45
43
|
```
|
|
46
44
|
|
|
47
|
-
The tunnel is not localgate's
|
|
48
|
-
on port
|
|
49
|
-
request
|
|
45
|
+
The tunnel is not localgate's. It is whatever you already run, pointed at this machine's LAN address
|
|
46
|
+
on the proxy's port. It keeps the `Host` header, so a request arriving through it is routed like a LAN
|
|
47
|
+
request. Localgate only needs the public prefix to register the exact public name.
|
|
50
48
|
|
|
51
49
|
The table lives in the proxy's memory. There is no config file listing apps, no port assignment to keep
|
|
52
50
|
in sync, and nothing to clean up after a crash.
|
|
@@ -54,7 +52,8 @@ in sync, and nothing to clean up after a crash.
|
|
|
54
52
|
## How restart works
|
|
55
53
|
|
|
56
54
|
The runner sits in your editor's debug terminal and owns the dev server as its child. That is what lets
|
|
57
|
-
a restart keep the terminal
|
|
55
|
+
a restart keep the terminal and debugger while swapping the process underneath. The restart also
|
|
56
|
+
reloads `package.json` and the machine config, then updates the route names before the new child starts.
|
|
58
57
|
|
|
59
58
|
With no argument, `localgate restart` asks the proxy which route owns the current directory, and posts
|
|
60
59
|
to that runner's own control endpoint, which listens on loopback and nowhere else.
|
|
@@ -73,17 +72,25 @@ sequenceDiagram
|
|
|
73
72
|
|
|
74
73
|
While the dev server is down the proxy answers with a readable page instead of a connection error.
|
|
75
74
|
Websocket upgrades are proxied, and on Next.js dev endpoints (`/_next/*`, `/__nextjs*`) the `Origin`
|
|
76
|
-
and `Referer` headers are mapped back to `.localhost`
|
|
77
|
-
|
|
75
|
+
and `Referer` headers are mapped back to the route's `.localhost` name. The rewrite requires the header
|
|
76
|
+
hostname to equal the incoming `Host`, so it works for LAN and public names without accepting a foreign
|
|
77
|
+
origin or requiring an `allowedDevOrigins` entry in the project.
|
|
78
78
|
|
|
79
79
|
## Install
|
|
80
80
|
|
|
81
|
-
|
|
81
|
+
Node 24+.
|
|
82
82
|
|
|
83
83
|
```bash
|
|
84
84
|
npm install -g localgate
|
|
85
85
|
```
|
|
86
86
|
|
|
87
|
+
On Windows the proxy binds port 80, so a name stands alone: `http://myapp.localhost`. On Linux and
|
|
88
|
+
macOS everything below 1024 belongs to root, and a tool that starts itself on demand has no business
|
|
89
|
+
asking for that, so it binds **8080** and the port rides along: `http://myapp.localhost:8080`. Every
|
|
90
|
+
URL localgate prints already carries it. To have 80 there too, give the node binary the capability
|
|
91
|
+
(`sudo setcap cap_net_bind_service=+ep $(which node)` on Linux) and set `"proxyPort": 80` in
|
|
92
|
+
`~/.localgate/config.json`.
|
|
93
|
+
|
|
87
94
|
Or from a clone, which is also how you develop on it:
|
|
88
95
|
|
|
89
96
|
```bash
|
|
@@ -176,7 +183,7 @@ A project gets its name from `package.json`, and nothing else is needed to work
|
|
|
176
183
|
|---|---|---|
|
|
177
184
|
| `local` (default) | `myapp.localhost` | this machine |
|
|
178
185
|
| `lan` | + `myapp.<label>.<your-domain>` | any PC on the LAN that resolves your domain |
|
|
179
|
-
| `internet` |
|
|
186
|
+
| `internet` | + `<public-prefix>-myapp.<your-domain>` | local machine, LAN and the configured tunnel |
|
|
180
187
|
|
|
181
188
|
The name is the package name, with a scope dropped (`@org/web` becomes `web`), and it has to be a
|
|
182
189
|
usable hostname label. When the package name is long or is not what you want to type, override it -
|
|
@@ -202,21 +209,24 @@ their own names without either name being in the repository:
|
|
|
202
209
|
"label": "dev", // your machine, as a DNS label
|
|
203
210
|
"baseDomain": "example.com", // a domain whose wildcard resolves to this LAN
|
|
204
211
|
"lanIp": "192.0.2.10", // the address the proxy also listens on
|
|
212
|
+
"publicPrefix": "pub", // prefix owned by this machine on the public domain
|
|
205
213
|
"autoRestart": false // see "When a dev server stops answering"
|
|
206
214
|
}
|
|
207
215
|
```
|
|
208
216
|
|
|
209
|
-
With that file present, `myapp` in mode `lan` also answers on `myapp.dev.example.com
|
|
217
|
+
With that file present, `myapp` in mode `lan` also answers on `myapp.dev.example.com`, while mode
|
|
218
|
+
`internet` additionally answers on `pub-myapp.example.com`. Browser-facing
|
|
210
219
|
environment variables (`NEXT_PUBLIC_*`, `*_PUBLIC_URL`, `AUTH_URL`, `NEXTAUTH_URL`) are rewritten from
|
|
211
|
-
`.localhost` to
|
|
212
|
-
|
|
213
|
-
on `.localhost` where they are faster and need no DNS.
|
|
220
|
+
`.localhost` to the name selected by the current mode on the way into the dev server. Public URLs use
|
|
221
|
+
HTTPS and never carry the proxy's internal LAN port. Server-side variables stay on `.localhost`.
|
|
214
222
|
|
|
215
|
-
For reaching an app from outside the LAN, `localgate cloudflare-info` prints the
|
|
216
|
-
tunnel ingress entry
|
|
217
|
-
anywhere.
|
|
218
|
-
|
|
219
|
-
|
|
223
|
+
For reaching an app from outside the LAN, `localgate cloudflare-info` prints the exact prefixed DNS
|
|
224
|
+
record and tunnel ingress entry. It prints them and stops: localgate holds no API token and sends
|
|
225
|
+
nothing anywhere. In Atomix projects, use `axtoolsv2 expose <dir> off|network|internet`; AtomixToolsV2
|
|
226
|
+
owns the API calls, project state, and Localgate reload. It retains an existing managed CNAME when
|
|
227
|
+
leaving `internet` and removes only ingress, so the public hostname reaches the tunnel's 404 catch-all
|
|
228
|
+
without DNS recreation delay. Anyone holding an enabled public URL reaches the dev server, which is why
|
|
229
|
+
`internet` is a mode you switch back from.
|
|
220
230
|
|
|
221
231
|
## When a dev server stops answering
|
|
222
232
|
|
|
@@ -240,7 +250,7 @@ the names come back without touching a single dev server.
|
|
|
240
250
|
|
|
241
251
|
## Design rules
|
|
242
252
|
|
|
243
|
-
- **Nothing machine-specific is committed.** The label,
|
|
253
|
+
- **Nothing machine-specific is committed.** The label, public prefix, domain and LAN IP live in
|
|
244
254
|
`~/.localgate/config.json`; a repository carries at most a `package.json` key holding a mode
|
|
245
255
|
(`local` / `lan` / `internet`) and an optional name. Absent key means `local`, which is names on
|
|
246
256
|
`.localhost` only.
|
|
@@ -278,9 +288,12 @@ build step.
|
|
|
278
288
|
|
|
279
289
|
## Status
|
|
280
290
|
|
|
281
|
-
Early, and
|
|
282
|
-
|
|
283
|
-
|
|
291
|
+
Early. Windows, Linux and macOS: the kill that makes `restart` reliable goes through `taskkill /T` on
|
|
292
|
+
Windows and the child's process group elsewhere, and the port-holder lookup is PowerShell or `lsof`.
|
|
293
|
+
|
|
294
|
+
One rough edge on macOS: browsers resolve `*.localhost` to loopback by RFC 6761, but the system
|
|
295
|
+
resolver does not, so `curl http://myapp.localhost:8080` and server-to-server calls by name need an
|
|
296
|
+
`/etc/hosts` entry there. Browsers are fine.
|
|
284
297
|
|
|
285
298
|
Bug reports and ideas are welcome - see [CONTRIBUTING.md](CONTRIBUTING.md), and
|
|
286
299
|
[SECURITY.md](SECURITY.md) for anything security-related. Licensed under
|
|
@@ -1,25 +1,27 @@
|
|
|
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
|
|
8
|
-
// decided here rather than passed in, because 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
|
-
const [local,
|
|
17
|
+
const [local, network, internet] = 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 (
|
|
22
|
-
lines.push(LocalgateBanner.row("
|
|
22
|
+
if (internet) lines.push(LocalgateBanner.row("internet", `https://${internet}`));
|
|
23
|
+
if (network) lines.push(LocalgateBanner.row("network", LocalgateUrl.forName(network, proxyPort)));
|
|
24
|
+
lines.push(LocalgateBanner.row("local", LocalgateUrl.forName(local, proxyPort)));
|
|
23
25
|
lines.push("", LocalgateBanner.row("upstream", `127.0.0.1:${route.port}`), LocalgateBanner.row(nextLabel, nextCommand), "");
|
|
24
26
|
|
|
25
27
|
return `${lines.join("\n")}\n`;
|
|
@@ -2,8 +2,10 @@ import { LocalgateProxyClient } from "../client/localgateProxyClient.ts";
|
|
|
2
2
|
import { LocalgateBanner } from "./localgateBanner.ts";
|
|
3
3
|
import { LocalgateCloudflareInfo } from "../cloudflare/localgateCloudflareInfo.ts";
|
|
4
4
|
import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
|
|
5
|
+
import { LocalgateNames } from "../config/localgateNames.ts";
|
|
5
6
|
import { LocalgateProjectConfig } from "../config/localgateProjectConfig.ts";
|
|
6
7
|
import { LocalgateProxyHost } from "../proxy/localgateProxyHost.ts";
|
|
8
|
+
import { LocalgateUrl } from "../proxy/localgateUrl.ts";
|
|
7
9
|
import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
|
|
8
10
|
import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
|
|
9
11
|
import { LocalgateRunner } from "../run/localgateRunner.ts";
|
|
@@ -61,9 +63,10 @@ export class LocalgateCli
|
|
|
61
63
|
}
|
|
62
64
|
|
|
63
65
|
process.stdout.write("Active routes:\n\n");
|
|
66
|
+
const proxyPort = LocalgateProxyClient.proxyPort();
|
|
64
67
|
for (const route of routes)
|
|
65
68
|
{
|
|
66
|
-
process.stdout.write(` ${
|
|
69
|
+
process.stdout.write(` ${LocalgateCli.routeUrls(route, proxyPort).join("\n ")}\n`);
|
|
67
70
|
process.stdout.write(` -> 127.0.0.1:${route.port} [${route.state}] ${route.kind}`
|
|
68
71
|
+ `${route.debuggerAttached ? " debugger" : ""}\n`);
|
|
69
72
|
if (route.cwd) process.stdout.write(` ${route.cwd}\n`);
|
|
@@ -93,7 +96,7 @@ export class LocalgateCli
|
|
|
93
96
|
}
|
|
94
97
|
|
|
95
98
|
process.stdout.write([
|
|
96
|
-
|
|
99
|
+
LocalgateCli.routeUrls(route, LocalgateProxyClient.proxyPort()).join("\n"),
|
|
97
100
|
`port 127.0.0.1:${route.port}`,
|
|
98
101
|
`state ${route.state}`,
|
|
99
102
|
`mode ${route.mode}`,
|
|
@@ -156,10 +159,7 @@ export class LocalgateCli
|
|
|
156
159
|
}
|
|
157
160
|
|
|
158
161
|
const machine = LocalgateMachineConfig.load();
|
|
159
|
-
const names =
|
|
160
|
-
// An alias gets the shared name too when the machine has one: a browser on another PC loads media
|
|
161
|
-
// from these services by absolute URL, so they have to answer on the name that resolves there.
|
|
162
|
-
if (machine) names.push(`${name}${LocalgateMachineConfig.externalSuffix(machine)}`);
|
|
162
|
+
const names = LocalgateNames.routeNames(name, machine ? "lan" : "local", machine);
|
|
163
163
|
|
|
164
164
|
await LocalgateProxyClient.ensureRunning();
|
|
165
165
|
|
|
@@ -188,7 +188,7 @@ export class LocalgateCli
|
|
|
188
188
|
return 1;
|
|
189
189
|
}
|
|
190
190
|
|
|
191
|
-
process.stdout.write(LocalgateBanner.render(route));
|
|
191
|
+
process.stdout.write(LocalgateBanner.render(route, LocalgateProxyClient.proxyPort()));
|
|
192
192
|
return 0;
|
|
193
193
|
}
|
|
194
194
|
|
|
@@ -203,13 +203,21 @@ export class LocalgateCli
|
|
|
203
203
|
}
|
|
204
204
|
|
|
205
205
|
const project = LocalgateProjectConfig.load(process.cwd());
|
|
206
|
+
const publicName = LocalgateNames.publicName(project.name, machine);
|
|
207
|
+
if (!publicName)
|
|
208
|
+
{
|
|
209
|
+
process.stderr.write(`localgate: ${LocalgateMachineConfig.filePath()} has no publicPrefix\n`);
|
|
210
|
+
return 1;
|
|
211
|
+
}
|
|
212
|
+
|
|
206
213
|
if (project.mode != "internet")
|
|
207
214
|
process.stdout.write(`Note: this project's mode is "${project.mode}". Set it to "internet" `
|
|
208
215
|
+ "in package.json when you actually want the entries below to be live.\n\n");
|
|
209
216
|
|
|
210
217
|
process.stdout.write(LocalgateCloudflareInfo.render(
|
|
211
|
-
|
|
212
|
-
machine.lanIp
|
|
218
|
+
publicName,
|
|
219
|
+
machine.lanIp,
|
|
220
|
+
LocalgateUrl.proxyPort(machine)
|
|
213
221
|
));
|
|
214
222
|
|
|
215
223
|
return 0;
|
|
@@ -263,6 +271,13 @@ export class LocalgateCli
|
|
|
263
271
|
return 1;
|
|
264
272
|
}
|
|
265
273
|
|
|
274
|
+
private static routeUrls(route: LocalgateRoute, proxyPort: number): string[]
|
|
275
|
+
{
|
|
276
|
+
return route.names.map((name, index) => route.mode == "internet" && index == 2
|
|
277
|
+
? `https://${name}`
|
|
278
|
+
: LocalgateUrl.forName(name, proxyPort));
|
|
279
|
+
}
|
|
280
|
+
|
|
266
281
|
private static printUsage(): void
|
|
267
282
|
{
|
|
268
283
|
process.stdout.write(
|
|
@@ -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 {
|
|
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.
|
|
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 ${
|
|
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
|
}
|
|
@@ -55,9 +72,10 @@ export class LocalgateProxyClient
|
|
|
55
72
|
await LocalgateProxyClient.send("DELETE", `/routes/${id}`);
|
|
56
73
|
}
|
|
57
74
|
|
|
58
|
-
static async patch(id: string, patch: Record<string, unknown>): Promise<
|
|
75
|
+
static async patch(id: string, patch: Record<string, unknown>): Promise<LocalgateRoute>
|
|
59
76
|
{
|
|
60
|
-
await LocalgateProxyClient.send("PATCH", `/routes/${id}`, patch);
|
|
77
|
+
const payload = await LocalgateProxyClient.send("PATCH", `/routes/${id}`, patch) as { route: LocalgateRoute };
|
|
78
|
+
return payload.route;
|
|
61
79
|
}
|
|
62
80
|
|
|
63
81
|
static async list(): Promise<LocalgateRoute[]>
|
|
@@ -75,7 +93,7 @@ export class LocalgateProxyClient
|
|
|
75
93
|
? `name=${encodeURIComponent(selector.name)}`
|
|
76
94
|
: `cwd=${encodeURIComponent(selector.directory ?? "")}`;
|
|
77
95
|
|
|
78
|
-
const response = await fetch(`${LocalgateProxyClient.
|
|
96
|
+
const response = await fetch(`${LocalgateProxyClient.baseUrl()}/resolve?${query}`);
|
|
79
97
|
if (!response.ok) return null;
|
|
80
98
|
return ((await response.json()) as { route: LocalgateRoute | null }).route;
|
|
81
99
|
}
|
|
@@ -104,7 +122,7 @@ export class LocalgateProxyClient
|
|
|
104
122
|
init.body = JSON.stringify(body);
|
|
105
123
|
}
|
|
106
124
|
|
|
107
|
-
const response = await fetch(`${LocalgateProxyClient.
|
|
125
|
+
const response = await fetch(`${LocalgateProxyClient.baseUrl()}${path}`, init);
|
|
108
126
|
|
|
109
127
|
// A collision travels as its own type so the runner can name the process that holds the name,
|
|
110
128
|
// 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}
|
|
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
|
"",
|
|
@@ -7,7 +7,11 @@ export type LocalgateMachineSettings =
|
|
|
7
7
|
label: string;
|
|
8
8
|
baseDomain: string;
|
|
9
9
|
lanIp: string;
|
|
10
|
+
publicPrefix: string | null;
|
|
10
11
|
autoRestart: boolean;
|
|
12
|
+
// null leaves the port to the platform default. Set it only when the machine has arranged for
|
|
13
|
+
// something else - a capability that permits 80 on Linux, or another port because 8080 is taken.
|
|
14
|
+
proxyPort: number | null;
|
|
11
15
|
};
|
|
12
16
|
|
|
13
17
|
export class LocalgateMachineConfig
|
|
@@ -35,23 +39,47 @@ export class LocalgateMachineConfig
|
|
|
35
39
|
|
|
36
40
|
const parsed = JSON.parse(raw) as Record<string, unknown>;
|
|
37
41
|
|
|
38
|
-
const label = LocalgateMachineConfig.
|
|
39
|
-
if (!LocalgateMachineConfig.labelPatternConst.test(label))
|
|
40
|
-
throw new Error(`${filePath}: "label" must be a DNS label (lowercase letters, digits, hyphens), got "${label}"`);
|
|
42
|
+
const label = LocalgateMachineConfig.requireLabel(parsed, "label", filePath);
|
|
41
43
|
|
|
42
44
|
return {
|
|
43
45
|
label,
|
|
44
46
|
baseDomain: LocalgateMachineConfig.requireString(parsed, "baseDomain", filePath),
|
|
45
47
|
lanIp: LocalgateMachineConfig.requireString(parsed, "lanIp", filePath),
|
|
46
|
-
|
|
48
|
+
publicPrefix: LocalgateMachineConfig.optionalLabel(parsed, "publicPrefix", filePath),
|
|
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}`;
|
|
53
66
|
}
|
|
54
67
|
|
|
68
|
+
private static optionalLabel(parsed: Record<string, unknown>, key: string, filePath: string): string | null
|
|
69
|
+
{
|
|
70
|
+
const value = parsed[key];
|
|
71
|
+
if (value === undefined || value === null) return null;
|
|
72
|
+
return LocalgateMachineConfig.requireLabel(parsed, key, filePath);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
private static requireLabel(parsed: Record<string, unknown>, key: string, filePath: string): string
|
|
76
|
+
{
|
|
77
|
+
const value = LocalgateMachineConfig.requireString(parsed, key, filePath);
|
|
78
|
+
if (!LocalgateMachineConfig.labelPatternConst.test(value))
|
|
79
|
+
throw new Error(`${filePath}: "${key}" must be a DNS label (lowercase letters, digits, hyphens), got "${value}"`);
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
|
|
55
83
|
private static requireString(parsed: Record<string, unknown>, key: string, filePath: string): string
|
|
56
84
|
{
|
|
57
85
|
const value = parsed[key];
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { LocalgateMachineSettings } from "./localgateMachineConfig.ts";
|
|
2
|
+
import type { LocalgateMode } from "./localgateProjectConfig.ts";
|
|
3
|
+
|
|
4
|
+
export class LocalgateNames
|
|
5
|
+
{
|
|
6
|
+
private static readonly dnsLabelMaxLengthConst = 63;
|
|
7
|
+
|
|
8
|
+
static local(projectName: string): string
|
|
9
|
+
{
|
|
10
|
+
return `${projectName}.localhost`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
static lan(projectName: string, machine: LocalgateMachineSettings): string
|
|
14
|
+
{
|
|
15
|
+
return `${projectName}.${machine.label}.${machine.baseDomain}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
static publicName(projectName: string, machine: LocalgateMachineSettings): string | null
|
|
19
|
+
{
|
|
20
|
+
if (!machine.publicPrefix) return null;
|
|
21
|
+
|
|
22
|
+
const label = `${machine.publicPrefix}-${projectName}`;
|
|
23
|
+
if (label.length > LocalgateNames.dnsLabelMaxLengthConst)
|
|
24
|
+
throw new Error(`public hostname label "${label}" is longer than ${LocalgateNames.dnsLabelMaxLengthConst} characters`);
|
|
25
|
+
return `${label}.${machine.baseDomain}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
static routeNames(projectName: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null): string[]
|
|
29
|
+
{
|
|
30
|
+
const local = LocalgateNames.local(projectName);
|
|
31
|
+
if (mode == "local") return [local];
|
|
32
|
+
else if (mode == "lan") return machine ? [local, LocalgateNames.lan(projectName, machine)] : [local];
|
|
33
|
+
else if (mode == "internet")
|
|
34
|
+
{
|
|
35
|
+
if (!machine) return [local];
|
|
36
|
+
const publicName = LocalgateNames.publicName(projectName, machine);
|
|
37
|
+
return publicName ? [local, LocalgateNames.lan(projectName, machine), publicName] : [local, LocalgateNames.lan(projectName, machine)];
|
|
38
|
+
}
|
|
39
|
+
else
|
|
40
|
+
throw new Error(`unknown localgate mode: ${JSON.stringify(mode)}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
static browserName(projectName: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null): string
|
|
44
|
+
{
|
|
45
|
+
if (mode == "local") return LocalgateNames.local(projectName);
|
|
46
|
+
else if (mode == "lan") return machine ? LocalgateNames.lan(projectName, machine) : LocalgateNames.local(projectName);
|
|
47
|
+
else if (mode == "internet")
|
|
48
|
+
return machine ? LocalgateNames.publicName(projectName, machine) ?? LocalgateNames.lan(projectName, machine) : LocalgateNames.local(projectName);
|
|
49
|
+
else
|
|
50
|
+
throw new Error(`unknown localgate mode: ${JSON.stringify(mode)}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -2,12 +2,11 @@ import type { IncomingHttpHeaders } from "node:http";
|
|
|
2
2
|
|
|
3
3
|
// Next.js blocks cross-origin requests to its dev endpoints unless the origin is allow-listed, and it
|
|
4
4
|
// allows `**.localhost` unconditionally. It inspects Origin (and Referer for no-cors requests), never
|
|
5
|
-
// Host, and only on `/_next/*` and `/__nextjs*`. Mapping the
|
|
6
|
-
//
|
|
5
|
+
// Host, and only on `/_next/*` and `/__nextjs*`. Mapping the name used for this request back to the
|
|
6
|
+
// route's canonical `.localhost` name keeps HMR and dev assets working from LAN and public names, with no
|
|
7
7
|
// `allowedDevOrigins` entry in any project - which is what keeps our domain out of every repository.
|
|
8
8
|
export class LocalgateHeaderRewrite
|
|
9
9
|
{
|
|
10
|
-
private static readonly localSuffixConst = ".localhost";
|
|
11
10
|
private static readonly internalPrefixesConst = ["/_next", "/__nextjs"];
|
|
12
11
|
|
|
13
12
|
static isInternalPath(requestUrl: string): boolean
|
|
@@ -16,21 +15,24 @@ export class LocalgateHeaderRewrite
|
|
|
16
15
|
return LocalgateHeaderRewrite.internalPrefixesConst.some(prefix => path.startsWith(prefix));
|
|
17
16
|
}
|
|
18
17
|
|
|
19
|
-
static apply(requestUrl: string, headers: IncomingHttpHeaders,
|
|
18
|
+
static apply(requestUrl: string, headers: IncomingHttpHeaders, requestHost: string, canonicalName: string): void
|
|
20
19
|
{
|
|
21
|
-
if (!
|
|
20
|
+
if (!LocalgateHeaderRewrite.isInternalPath(requestUrl)) return;
|
|
21
|
+
|
|
22
|
+
const requestHostname = LocalgateHeaderRewrite.hostnameOf(requestHost);
|
|
23
|
+
if (!requestHostname) return;
|
|
22
24
|
|
|
23
25
|
for (const name of ["origin", "referer"] as const)
|
|
24
26
|
{
|
|
25
27
|
const value = headers[name];
|
|
26
28
|
if (typeof value != "string") continue;
|
|
27
29
|
|
|
28
|
-
const rewritten = LocalgateHeaderRewrite.
|
|
30
|
+
const rewritten = LocalgateHeaderRewrite.toCanonicalName(value, requestHostname, canonicalName);
|
|
29
31
|
if (rewritten) headers[name] = rewritten;
|
|
30
32
|
}
|
|
31
33
|
}
|
|
32
34
|
|
|
33
|
-
private static
|
|
35
|
+
private static toCanonicalName(value: string, requestHostname: string, canonicalName: string): string | null
|
|
34
36
|
{
|
|
35
37
|
let url: URL;
|
|
36
38
|
try
|
|
@@ -42,11 +44,25 @@ export class LocalgateHeaderRewrite
|
|
|
42
44
|
return null;
|
|
43
45
|
}
|
|
44
46
|
|
|
45
|
-
if (
|
|
47
|
+
if (url.hostname.toLowerCase() != requestHostname) return null;
|
|
46
48
|
|
|
47
|
-
const
|
|
48
|
-
if (
|
|
49
|
+
const authorityStart = value.indexOf("://") + 3;
|
|
50
|
+
if (authorityStart < 3) return null;
|
|
51
|
+
const suffixOffset = value.slice(authorityStart).search(/[/?#]/);
|
|
52
|
+
const authorityEnd = suffixOffset < 0 ? value.length : authorityStart + suffixOffset;
|
|
53
|
+
const authority = `${canonicalName}${url.port ? `:${url.port}` : ""}`;
|
|
54
|
+
return `${value.slice(0, authorityStart)}${authority}${value.slice(authorityEnd)}`;
|
|
55
|
+
}
|
|
49
56
|
|
|
50
|
-
|
|
57
|
+
private static hostnameOf(host: string): string | null
|
|
58
|
+
{
|
|
59
|
+
try
|
|
60
|
+
{
|
|
61
|
+
return new URL(`http://${host}`).hostname.toLowerCase();
|
|
62
|
+
}
|
|
63
|
+
catch
|
|
64
|
+
{
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
51
67
|
}
|
|
52
68
|
}
|
|
@@ -10,7 +10,6 @@ export type LocalgateProxyOptions =
|
|
|
10
10
|
port: number;
|
|
11
11
|
// null keeps the proxy on loopback only, which is what a machine with no localgate config gets.
|
|
12
12
|
lanIp: string | null;
|
|
13
|
-
externalSuffix: string | null;
|
|
14
13
|
gracePeriodMs: number;
|
|
15
14
|
onIdle: () => void;
|
|
16
15
|
};
|
|
@@ -129,7 +128,7 @@ export class LocalgateProxy
|
|
|
129
128
|
private forward(route: LocalgateRoute, request: IncomingMessage, response: ServerResponse): void
|
|
130
129
|
{
|
|
131
130
|
const headers = { ...request.headers };
|
|
132
|
-
LocalgateHeaderRewrite.apply(request.url ?? "/", headers,
|
|
131
|
+
LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
|
|
133
132
|
|
|
134
133
|
const upstream = httpRequest({
|
|
135
134
|
host: "127.0.0.1",
|
|
@@ -193,7 +192,7 @@ export class LocalgateProxy
|
|
|
193
192
|
}
|
|
194
193
|
|
|
195
194
|
const headers = { ...request.headers };
|
|
196
|
-
LocalgateHeaderRewrite.apply(request.url ?? "/", headers,
|
|
195
|
+
LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
|
|
197
196
|
|
|
198
197
|
const upstream = httpRequest({
|
|
199
198
|
host: "127.0.0.1",
|
|
@@ -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,9 +23,8 @@ export class LocalgateProxyHost
|
|
|
22
23
|
health,
|
|
23
24
|
new LocalgateControlApi(registry, () => proxy.checkIdle()),
|
|
24
25
|
{
|
|
25
|
-
port
|
|
26
|
+
port,
|
|
26
27
|
lanIp: machine?.lanIp ?? null,
|
|
27
|
-
externalSuffix: machine ? LocalgateMachineConfig.externalSuffix(machine) : null,
|
|
28
28
|
gracePeriodMs: LocalgateProxyHost.gracePeriodMsConst,
|
|
29
29
|
onIdle: () =>
|
|
30
30
|
{
|
|
@@ -35,8 +35,8 @@ export class LocalgateProxyHost
|
|
|
35
35
|
);
|
|
36
36
|
|
|
37
37
|
await proxy.start();
|
|
38
|
-
process.stdout.write(`localgate proxy listening on 127.0.0.1:${
|
|
39
|
-
+ `${machine?.lanIp ? ` and ${machine.lanIp}:${
|
|
38
|
+
process.stdout.write(`localgate proxy listening on 127.0.0.1:${port}`
|
|
39
|
+
+ `${machine?.lanIp ? ` and ${machine.lanIp}:${port}` : ""}\n`);
|
|
40
40
|
|
|
41
41
|
for (const signal of ["SIGINT", "SIGTERM"] as const)
|
|
42
42
|
process.on(signal, () => void proxy.stop().then(() => process.exit(0)));
|
|
@@ -164,10 +164,22 @@ export class LocalgateRegistry
|
|
|
164
164
|
return best;
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
-
update(id: string, patch: Partial<Pick<LocalgateRoute,
|
|
167
|
+
update(id: string, patch: Partial<Pick<LocalgateRoute,
|
|
168
|
+
"names" | "mode" | "state" | "lastResponseAt" | "childPid" | "debuggerAttached">>): LocalgateRoute
|
|
168
169
|
{
|
|
169
170
|
const route = this.routes.get(id);
|
|
170
171
|
if (!route) throw new Error(`unknown route ${id}`);
|
|
172
|
+
|
|
173
|
+
if (patch.names)
|
|
174
|
+
{
|
|
175
|
+
if (patch.names.length == 0) throw new Error("a route needs at least one name");
|
|
176
|
+
for (const name of patch.names)
|
|
177
|
+
{
|
|
178
|
+
const existing = this.findByName(name);
|
|
179
|
+
if (existing && existing.id != id) throw new LocalgateRouteConflictError(existing);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
171
183
|
Object.assign(route, patch);
|
|
172
184
|
return route;
|
|
173
185
|
}
|
|
@@ -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,33 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import type { LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
|
|
2
|
+
import { LocalgateNames } from "../config/localgateNames.ts";
|
|
3
|
+
import type { LocalgateMode } from "../config/localgateProjectConfig.ts";
|
|
4
|
+
import { LocalgateUrl } from "../proxy/localgateUrl.ts";
|
|
5
|
+
|
|
6
|
+
// Keeps repositories machine-agnostic: a committed env file says `.localhost` everywhere, and what this
|
|
7
|
+
// machine actually answers on is substituted here, in memory, on the way into the child process.
|
|
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.
|
|
12
|
+
//
|
|
13
|
+
// The job is "point this at the proxy", not "swap the suffix". That distinction is what the port makes:
|
|
14
|
+
// where the proxy cannot have 80 the value needs `:8080` even in mode local, where no suffix exists and
|
|
15
|
+
// nothing used to be rewritten at all.
|
|
6
16
|
export class LocalgateEnvRewrite
|
|
7
17
|
{
|
|
8
18
|
private static readonly localSuffixConst = ".localhost";
|
|
9
19
|
private static readonly browserFacingNamesConst = ["AUTH_URL", "NEXTAUTH_URL"];
|
|
10
20
|
|
|
11
|
-
static apply(env: NodeJS.ProcessEnv,
|
|
21
|
+
static apply(env: NodeJS.ProcessEnv, mode: LocalgateMode, machine: LocalgateMachineSettings | null,
|
|
22
|
+
proxyPort: number): NodeJS.ProcessEnv
|
|
12
23
|
{
|
|
13
24
|
const result: NodeJS.ProcessEnv = { ...env };
|
|
14
|
-
if (!externalSuffix) return result;
|
|
15
25
|
|
|
16
26
|
for (const [key, value] of Object.entries(result))
|
|
17
27
|
{
|
|
18
28
|
if (!value || !LocalgateEnvRewrite.isBrowserFacing(key)) continue;
|
|
19
29
|
|
|
20
|
-
const rewritten = LocalgateEnvRewrite.
|
|
30
|
+
const rewritten = LocalgateEnvRewrite.rewriteAuthority(value, mode, machine, proxyPort);
|
|
21
31
|
if (rewritten) result[key] = rewritten;
|
|
22
32
|
}
|
|
23
33
|
|
|
@@ -31,10 +41,12 @@ export class LocalgateEnvRewrite
|
|
|
31
41
|
|| LocalgateEnvRewrite.browserFacingNamesConst.includes(key);
|
|
32
42
|
}
|
|
33
43
|
|
|
34
|
-
// Substitutes
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
|
|
44
|
+
// Substitutes the authority only, and by string replacement rather than URL.toString(), so a value
|
|
45
|
+
// keeps its exact original shape - notably no trailing slash appears on a bare origin, which app code
|
|
46
|
+
// concatenates onto. A port already in the value is replaced rather than kept: behind a proxy that
|
|
47
|
+
// multiplexes by name, a browser-facing URL has exactly one correct port.
|
|
48
|
+
private static rewriteAuthority(value: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null,
|
|
49
|
+
proxyPort: number): string | null
|
|
38
50
|
{
|
|
39
51
|
let url: URL;
|
|
40
52
|
try
|
|
@@ -51,6 +63,14 @@ export class LocalgateEnvRewrite
|
|
|
51
63
|
const label = url.hostname.slice(0, -LocalgateEnvRewrite.localSuffixConst.length);
|
|
52
64
|
if (label.length == 0) return null;
|
|
53
65
|
|
|
54
|
-
|
|
66
|
+
const name = LocalgateNames.browserName(label, mode, machine);
|
|
67
|
+
const publiclyExposed = mode == "internet" && machine?.publicPrefix;
|
|
68
|
+
const browserPort = publiclyExposed ? 80 : proxyPort;
|
|
69
|
+
const authority = LocalgateUrl.forName(name, browserPort).replace("http://", "");
|
|
70
|
+
const protocol = publiclyExposed && (url.protocol == "http:" || url.protocol == "https:") ? "https:" : url.protocol;
|
|
71
|
+
|
|
72
|
+
if (url.host == authority && url.protocol == protocol) return null;
|
|
73
|
+
const withAuthority = value.replace(url.host, authority);
|
|
74
|
+
return `${protocol}${withAuthority.slice(url.protocol.length)}`;
|
|
55
75
|
}
|
|
56
76
|
}
|
|
@@ -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
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
//
|
|
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
|
-
//
|
|
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
|
-
|
|
102
|
+
const { file, args } = LocalgateProcessTree.portHolderCommand(port);
|
|
73
103
|
|
|
74
104
|
try
|
|
75
105
|
{
|
|
76
|
-
const { stdout } = await promisify(execFile)(
|
|
77
|
-
|
|
78
|
-
|
|
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
|
-
|
|
120
|
+
const spec = LocalgateProcessTree.killSpec(pid);
|
|
121
|
+
|
|
122
|
+
if (spec.via == "command")
|
|
94
123
|
{
|
|
95
124
|
try
|
|
96
125
|
{
|
|
97
|
-
await promisify(execFile)(
|
|
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
|
-
|
|
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
|
}
|
|
@@ -6,12 +6,21 @@ import { join } from "node:path";
|
|
|
6
6
|
import { createInterface } from "node:readline/promises";
|
|
7
7
|
import { LocalgateBanner } from "../cli/localgateBanner.ts";
|
|
8
8
|
import { LocalgateProxyClient } from "../client/localgateProxyClient.ts";
|
|
9
|
-
import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
|
|
9
|
+
import { LocalgateMachineConfig, type LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
|
|
10
|
+
import { LocalgateNames } from "../config/localgateNames.ts";
|
|
10
11
|
import { LocalgateProjectConfig, type LocalgateProjectSettings } from "../config/localgateProjectConfig.ts";
|
|
11
12
|
import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
|
|
13
|
+
import { LocalgateUrl } from "../proxy/localgateUrl.ts";
|
|
12
14
|
import { LocalgateEnvRewrite } from "./localgateEnvRewrite.ts";
|
|
13
15
|
import { LocalgateProcessTree } from "./localgateProcessTree.ts";
|
|
14
16
|
|
|
17
|
+
type LocalgateRunnerRuntime =
|
|
18
|
+
{
|
|
19
|
+
project: LocalgateProjectSettings;
|
|
20
|
+
machine: LocalgateMachineSettings | null;
|
|
21
|
+
names: string[];
|
|
22
|
+
};
|
|
23
|
+
|
|
15
24
|
// Runs inside the editor's debug terminal and owns the dev process, which is the part an editor cannot
|
|
16
25
|
// give away: the terminal keeps the debugger attached, while `localgate restart` swaps the child
|
|
17
26
|
// underneath without touching the terminal, the route or the port.
|
|
@@ -24,6 +33,7 @@ export class LocalgateRunner
|
|
|
24
33
|
private child: ChildProcess | null = null;
|
|
25
34
|
private controlServer: Server | null = null;
|
|
26
35
|
private route: LocalgateRoute | null = null;
|
|
36
|
+
private runtime: LocalgateRunnerRuntime | null = null;
|
|
27
37
|
private readonly logs: string[] = [];
|
|
28
38
|
private stopping = false;
|
|
29
39
|
private restarting = false;
|
|
@@ -96,6 +106,11 @@ export class LocalgateRunner
|
|
|
96
106
|
return command.map(part => /[\s"]/.test(part) ? `"${part.replace(/"/g, '\\"')}"` : part).join(" ");
|
|
97
107
|
}
|
|
98
108
|
|
|
109
|
+
static routeRegistrationMatches(route: LocalgateRoute, registered: LocalgateRoute | null, runnerPid: number): boolean
|
|
110
|
+
{
|
|
111
|
+
return registered?.runnerPid == runnerPid && registered.controlUrl == route.controlUrl;
|
|
112
|
+
}
|
|
113
|
+
|
|
99
114
|
static async freePort(): Promise<number>
|
|
100
115
|
{
|
|
101
116
|
return new Promise<number>((resolve, reject) =>
|
|
@@ -121,27 +136,21 @@ export class LocalgateRunner
|
|
|
121
136
|
{
|
|
122
137
|
if (this.command.length == 0) throw new Error("localgate run needs a command, for example: localgate run npm run dev");
|
|
123
138
|
|
|
124
|
-
const
|
|
139
|
+
const runtime = this.loadRuntime();
|
|
125
140
|
|
|
126
|
-
const blocked = await this.clearPredecessor(project);
|
|
141
|
+
const blocked = await this.clearPredecessor(runtime.project);
|
|
127
142
|
if (blocked != 0) return blocked;
|
|
128
143
|
|
|
129
|
-
const machine = LocalgateMachineConfig.load();
|
|
130
|
-
const external = machine && project.mode != "local" ? LocalgateMachineConfig.externalSuffix(machine) : null;
|
|
131
|
-
|
|
132
|
-
const names = [`${project.name}.localhost`];
|
|
133
|
-
if (external) names.push(`${project.name}${external}`);
|
|
134
|
-
|
|
135
144
|
const port = await LocalgateRunner.freePort();
|
|
136
145
|
const controlUrl = await this.startControlServer();
|
|
137
146
|
|
|
138
147
|
await LocalgateProxyClient.ensureRunning();
|
|
139
148
|
const route = await LocalgateProxyClient.register({
|
|
140
|
-
names,
|
|
149
|
+
names: runtime.names,
|
|
141
150
|
port,
|
|
142
151
|
kind: "app",
|
|
143
|
-
mode: project.mode,
|
|
144
|
-
cwd: project.packageDirectory,
|
|
152
|
+
mode: runtime.project.mode,
|
|
153
|
+
cwd: runtime.project.packageDirectory,
|
|
145
154
|
command: this.command.join(" "),
|
|
146
155
|
controlUrl,
|
|
147
156
|
runnerPid: process.pid,
|
|
@@ -149,13 +158,14 @@ export class LocalgateRunner
|
|
|
149
158
|
debuggerAttached: LocalgateRunner.debuggerAttached()
|
|
150
159
|
});
|
|
151
160
|
this.route = route;
|
|
161
|
+
this.runtime = runtime;
|
|
152
162
|
|
|
153
|
-
process.stdout.write(LocalgateBanner.render(route));
|
|
163
|
+
process.stdout.write(LocalgateBanner.render(route, LocalgateProxyClient.proxyPort()));
|
|
154
164
|
|
|
155
165
|
this.installSignalHandlers();
|
|
156
166
|
const heartbeat = this.startHeartbeat();
|
|
157
167
|
|
|
158
|
-
const finished = this.spawnChild(port
|
|
168
|
+
const finished = this.spawnChild(port);
|
|
159
169
|
await finished;
|
|
160
170
|
|
|
161
171
|
clearInterval(heartbeat);
|
|
@@ -205,7 +215,8 @@ export class LocalgateRunner
|
|
|
205
215
|
|
|
206
216
|
if (!await LocalgateRunner.askTakeover())
|
|
207
217
|
{
|
|
208
|
-
process.stdout.write(
|
|
218
|
+
process.stdout.write("localgate: left it running. Reach it at "
|
|
219
|
+
+ `${LocalgateUrl.forName(existing.names[0], LocalgateProxyClient.proxyPort())}\n`);
|
|
209
220
|
return 1;
|
|
210
221
|
}
|
|
211
222
|
}
|
|
@@ -293,26 +304,39 @@ export class LocalgateRunner
|
|
|
293
304
|
throw new Error(`${route.names[0]} still holds 127.0.0.1:${route.port} - stop it by hand`);
|
|
294
305
|
}
|
|
295
306
|
|
|
296
|
-
private spawnChild(port: number
|
|
307
|
+
private spawnChild(port: number): Promise<void>
|
|
297
308
|
{
|
|
298
|
-
const
|
|
309
|
+
const runtime = this.runtime;
|
|
310
|
+
if (!runtime) throw new Error("localgate runtime is not configured");
|
|
311
|
+
|
|
312
|
+
const scripts = LocalgateRunner.readScripts(runtime.project.packageDirectory);
|
|
299
313
|
const command = LocalgateRunner.withPortFlag(this.command, scripts, port);
|
|
300
314
|
|
|
301
|
-
const env = LocalgateEnvRewrite.apply(process.env,
|
|
315
|
+
const env = LocalgateEnvRewrite.apply(process.env, runtime.project.mode, runtime.machine,
|
|
316
|
+
LocalgateProxyClient.proxyPort());
|
|
302
317
|
env.PORT = String(port);
|
|
303
318
|
|
|
304
319
|
// One command string rather than a command plus an args array: `npm run dev` on Windows is a .cmd,
|
|
305
320
|
// which node refuses to spawn without a shell, and passing an args array alongside `shell: true`
|
|
306
321
|
// triggers DEP0190 because the shell concatenates them anyway. Quoting here makes that explicit.
|
|
322
|
+
//
|
|
323
|
+
// `detached` off Windows makes the child lead its own process group, which is the only way to reach
|
|
324
|
+
// the dev server the shell spawns underneath it: signalling the shell alone leaves the server
|
|
325
|
+
// running and holding the port. On Windows the same flag would hand the child its own console
|
|
326
|
+
// instead, and `taskkill /T` already walks the tree, so it stays off there.
|
|
307
327
|
const child = spawn(LocalgateRunner.shellCommand(command), {
|
|
308
328
|
cwd: this.directory,
|
|
309
329
|
env,
|
|
310
330
|
shell: true,
|
|
331
|
+
detached: process.platform != "win32",
|
|
311
332
|
stdio: ["inherit", "pipe", "pipe"]
|
|
312
333
|
});
|
|
313
334
|
|
|
314
335
|
this.child = child;
|
|
315
|
-
if (this.route)
|
|
336
|
+
if (this.route)
|
|
337
|
+
void LocalgateProxyClient.patch(this.route.id, { childPid: child.pid ?? null })
|
|
338
|
+
.then(route => { this.route = route; })
|
|
339
|
+
.catch(() => {});
|
|
316
340
|
|
|
317
341
|
child.stdout?.on("data", chunk => this.absorb(chunk as Buffer, process.stdout));
|
|
318
342
|
child.stderr?.on("data", chunk => this.absorb(chunk as Buffer, process.stderr));
|
|
@@ -326,7 +350,7 @@ export class LocalgateRunner
|
|
|
326
350
|
if (this.restarting)
|
|
327
351
|
{
|
|
328
352
|
this.restarting = false;
|
|
329
|
-
resolve(this.spawnChild(port
|
|
353
|
+
resolve(this.spawnChild(port));
|
|
330
354
|
return;
|
|
331
355
|
}
|
|
332
356
|
|
|
@@ -341,6 +365,12 @@ export class LocalgateRunner
|
|
|
341
365
|
const child = this.child;
|
|
342
366
|
if (!child?.pid || !this.route) throw new Error("nothing to restart");
|
|
343
367
|
|
|
368
|
+
const runtime = this.loadRuntime();
|
|
369
|
+
this.route = await LocalgateProxyClient.patch(this.route.id, {
|
|
370
|
+
names: runtime.names,
|
|
371
|
+
mode: runtime.project.mode
|
|
372
|
+
});
|
|
373
|
+
this.runtime = runtime;
|
|
344
374
|
this.restarting = true;
|
|
345
375
|
await LocalgateProcessTree.killTree(child.pid, this.route.port);
|
|
346
376
|
}
|
|
@@ -414,8 +444,9 @@ export class LocalgateRunner
|
|
|
414
444
|
});
|
|
415
445
|
}
|
|
416
446
|
|
|
417
|
-
// The proxy holds the route table in memory, so if it dies the route dies with it.
|
|
418
|
-
//
|
|
447
|
+
// The proxy holds the route table in memory, so if it dies the route dies with it. Another runner may
|
|
448
|
+
// start the proxy before this heartbeat, so a successful ping is not enough: this runner verifies that
|
|
449
|
+
// its own route is present and re-registers when it is missing.
|
|
419
450
|
private startHeartbeat(): NodeJS.Timeout
|
|
420
451
|
{
|
|
421
452
|
const timer = setInterval(() =>
|
|
@@ -423,7 +454,13 @@ export class LocalgateRunner
|
|
|
423
454
|
void (async () =>
|
|
424
455
|
{
|
|
425
456
|
if (this.stopping || !this.route) return;
|
|
426
|
-
|
|
457
|
+
|
|
458
|
+
const registered = await LocalgateProxyClient.resolve({ name: this.route.names[0] }).catch(() => null);
|
|
459
|
+
if (LocalgateRunner.routeRegistrationMatches(this.route, registered, process.pid))
|
|
460
|
+
{
|
|
461
|
+
this.route = registered;
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
427
464
|
|
|
428
465
|
try
|
|
429
466
|
{
|
|
@@ -478,6 +515,7 @@ export class LocalgateRunner
|
|
|
478
515
|
{
|
|
479
516
|
await LocalgateProxyClient.deregister(this.route.id).catch(() => {});
|
|
480
517
|
this.route = null;
|
|
518
|
+
this.runtime = null;
|
|
481
519
|
}
|
|
482
520
|
|
|
483
521
|
if (this.controlServer)
|
|
@@ -500,4 +538,11 @@ export class LocalgateRunner
|
|
|
500
538
|
return {};
|
|
501
539
|
}
|
|
502
540
|
}
|
|
541
|
+
|
|
542
|
+
private loadRuntime(): LocalgateRunnerRuntime
|
|
543
|
+
{
|
|
544
|
+
const project = LocalgateProjectConfig.load(this.directory);
|
|
545
|
+
const machine = LocalgateMachineConfig.load();
|
|
546
|
+
return { project, machine, names: LocalgateNames.routeNames(project.name, project.mode, machine) };
|
|
547
|
+
}
|
|
503
548
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "localgate",
|
|
3
|
-
"version": "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.
|
|
3
|
+
"version": "0.4.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"
|