localgate 0.5.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.
- package/README.md +82 -16
- package/logic/cli/localgateBanner.ts +4 -4
- package/logic/cli/localgateCli.ts +36 -10
- package/logic/client/localgateProxyClient.ts +7 -1
- package/logic/config/localgateAliasStore.ts +58 -18
- package/logic/config/localgateNames.ts +12 -0
- package/logic/proxy/localgateHealth.ts +7 -0
- package/logic/proxy/localgatePortProbe.ts +42 -0
- package/logic/proxy/localgateProxy.ts +25 -1
- package/logic/proxy/localgateProxyHost.ts +39 -5
- package/logic/proxy/localgateRegistry.ts +17 -7
- package/logic/proxy/localgateStartPage.ts +491 -0
- package/logic/proxy/localgateUrl.ts +43 -0
- package/logic/run/localgateEnvRewrite.ts +28 -6
- package/logic/run/localgateNodeBootstrap.mjs +29 -0
- package/logic/run/localgateNodeOptions.ts +15 -0
- package/logic/run/localgateProcessTree.ts +122 -31
- package/logic/run/localgateRunner.ts +215 -124
- package/logic/run/localgateRunnerControl.ts +151 -0
- package/logic/run/localgateShellCommand.ts +51 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -49,7 +49,7 @@ request. Localgate only needs the public prefix to register the exact public nam
|
|
|
49
49
|
The table lives in the proxy's memory. There is no config file listing apps, no port assignment to keep
|
|
50
50
|
in sync, and nothing to clean up after a crash.
|
|
51
51
|
|
|
52
|
-
## How restart
|
|
52
|
+
## How restart and stop work
|
|
53
53
|
|
|
54
54
|
The runner sits in your editor's debug terminal and owns the dev server as its child. That is what lets
|
|
55
55
|
a restart keep the terminal and debugger while swapping the process underneath. The restart also
|
|
@@ -70,6 +70,18 @@ sequenceDiagram
|
|
|
70
70
|
Note over Cli,Dev: same route, same port, the browser keeps its URL
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
+
A restart reports success only once the runner has seen both halves of it: the old tree gone with its
|
|
74
|
+
port free, and a replacement child running. If the kill is refused or the port stays bound, the runner
|
|
75
|
+
answers `409` with what the kill said, `localgate restart` prints that and exits non-zero, and the old
|
|
76
|
+
process is left named rather than reported as replaced. See
|
|
77
|
+
[docs/architecture/restart-verification.md](docs/architecture/restart-verification.md).
|
|
78
|
+
|
|
79
|
+
`localgate stop` is decided the same way, on the same fact: the runner kills the tree first and answers
|
|
80
|
+
with what that achieved, so a stop the system refused prints the reason and exits non-zero instead of
|
|
81
|
+
`stopped`. A refused stop keeps its route and its runner, because the process behind that route is still
|
|
82
|
+
the one serving it. Ctrl+C is the other way round and ends the runner whatever the kill said. See
|
|
83
|
+
[docs/architecture/stop-verification.md](docs/architecture/stop-verification.md).
|
|
84
|
+
|
|
73
85
|
While the dev server is down the proxy answers with a readable page instead of a connection error.
|
|
74
86
|
Websocket upgrades are proxied, and on Next.js dev endpoints (`/_next/*`, `/__nextjs*`) the `Origin`
|
|
75
87
|
and `Referer` headers are mapped back to the route's `.localhost` name. The rewrite requires the header
|
|
@@ -119,7 +131,9 @@ The debugger attaches to the child as usual, and the terminal stays where it is
|
|
|
119
131
|
Press the editor's restart button and you start a *second* `localgate run` for the same project, which
|
|
120
132
|
used to fail twice over: the name moved to the new runner and left the old one unreachable, and the
|
|
121
133
|
dev server then refused the port because of its own lock. So the collision is settled before anything
|
|
122
|
-
is claimed - the new run finds its predecessor
|
|
134
|
+
is claimed - the new run finds its predecessor, prints what it is about to stop in the debug terminal
|
|
135
|
+
it was started from, and takes over without asking. A compound launch of several projects therefore
|
|
136
|
+
restarts all of them, with no terminal left waiting for an answer:
|
|
123
137
|
|
|
124
138
|
```
|
|
125
139
|
localgate myapp.localhost is already running
|
|
@@ -130,34 +144,79 @@ is claimed - the new run finds its predecessor and asks, in the debug terminal i
|
|
|
130
144
|
pids runner 45568, child 4544
|
|
131
145
|
debugger attached
|
|
132
146
|
|
|
133
|
-
|
|
147
|
+
localgate: stopping myapp.localhost (runner 45568)
|
|
134
148
|
```
|
|
135
149
|
|
|
136
|
-
|
|
150
|
+
The old one is stopped the good way: its own runner kills the child tree, releases the port and
|
|
137
151
|
deregisters itself, so its terminal ends cleanly and the new run takes the name. Killing by pid is
|
|
138
152
|
only the fallback for a runner that no longer answers.
|
|
139
153
|
|
|
140
|
-
A route whose runner is already gone is
|
|
141
|
-
holds the port - that is the orphan a framework lock trips over - so it is
|
|
142
|
-
|
|
154
|
+
A route whose runner is already gone is cleared too. Its dev server usually outlived it and still
|
|
155
|
+
holds the port - that is the orphan a framework lock trips over - so it is killed and the name reused.
|
|
156
|
+
|
|
157
|
+
The same takeover happens if the name is taken between finding it free and claiming it. The route
|
|
158
|
+
table lives in the proxy, so a proxy that has just started has an empty one, and the runners that were
|
|
159
|
+
already running refill it from their heartbeats a few seconds later - a window in which the check sees
|
|
160
|
+
a free name that is not free.
|
|
161
|
+
|
|
162
|
+
An alias is never taken over: `run` refuses the name and exits 1.
|
|
163
|
+
|
|
164
|
+
## The start page
|
|
165
|
+
|
|
166
|
+
`http://start.localhost` is every route in a browser. One card per app: click it anywhere and it opens.
|
|
167
|
+
It needs no setup - the proxy serves the page from itself, and the name is reserved, so no project or
|
|
168
|
+
alias can take it.
|
|
169
|
+
|
|
170
|
+

|
|
171
|
+
|
|
172
|
+
The card opens the address that works from where you opened the page, and the route's other addresses -
|
|
173
|
+
the shared name, the public one - are chips next to it. The line at the bottom is the upstream port, the
|
|
174
|
+
command and the directory. The page refreshes itself every few seconds, so a dev server that has just
|
|
175
|
+
started appears without a reload, and a state changes while you watch.
|
|
176
|
+
|
|
177
|
+
The badge is measured, not remembered: the page opens a connection to each route's port as it renders,
|
|
178
|
+
so a route nobody has visited says **running** rather than sitting at "starting", and a route with
|
|
179
|
+
nothing behind it says **not running** and dims. A wedged app - one that accepts connections but answers
|
|
180
|
+
nothing - still reads **not responding**, because only forwarded traffic can tell you that.
|
|
181
|
+
|
|
182
|
+
A `stop` chip ends a dev server: the first click turns that card into a question, the second asks the
|
|
183
|
+
runner to kill the child tree and exit, exactly as `localgate stop` does. It is on the loopback page
|
|
184
|
+
only, and it takes a same-origin POST, so no other site the browser has open can reach it.
|
|
185
|
+
|
|
186
|
+
An alias has no runner, so it gets that button only once you say how to stop what it points at:
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
localgate alias wagtail 8003 --stop "docker stop wagtail"
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
The command lives in `~/.localgate/aliases.json`, which is machine-local and never committed, and the
|
|
193
|
+
question names it before it runs. Without one, an alias card has no stop button - localgate will not
|
|
194
|
+
guess how to end a process it did not start.
|
|
195
|
+
|
|
196
|
+
With a machine config it also answers on `start.<label>.<your-domain>`, which is the address to send a
|
|
197
|
+
colleague - and that answer is narrower than the local one. A route in mode `local` is absent from it,
|
|
198
|
+
its name included, and the routes that remain show only the addresses that work off this machine,
|
|
199
|
+
without the upstream port, the command or the directory. Details in
|
|
200
|
+
[docs/architecture/start-page.md](docs/architecture/start-page.md).
|
|
143
201
|
|
|
144
202
|
## Commands
|
|
145
203
|
|
|
146
204
|
| Command | What it does |
|
|
147
205
|
|---|---|
|
|
148
|
-
| `localgate run [--force] <cmd...>` | Run a dev server behind its name.
|
|
206
|
+
| `localgate run [--force] <cmd...>` | Run a dev server behind its name. One already running for the project is stopped first; without a terminal, only with `--force`. |
|
|
149
207
|
| `localgate list [--json]` | Show active routes. |
|
|
150
208
|
| `localgate status [app] [--json]` | State of one route, with a tail of its output in `--json`. |
|
|
151
209
|
| `localgate restart [app]` | Restart a route's dev server. |
|
|
152
210
|
| `localgate stop [app]` | Stop a route's dev server. |
|
|
153
211
|
| `localgate logs [app] [--lines N]` | Tail a route's captured output. |
|
|
154
|
-
| `localgate alias <name> <port
|
|
212
|
+
| `localgate alias <name> <port> [--stop "<cmd>"]` | Register a static route, e.g. a docker service. Remembered across proxy restarts. `--stop` records what ends it, which gives it a stop button on the start page. |
|
|
155
213
|
| `localgate alias --remove <name>` | Drop a static route and forget it. |
|
|
156
214
|
| `localgate config [dir] [--json]` | Machine and project config, the names it implies, and the alias file. |
|
|
157
215
|
| `localgate cloudflare-info` | Print the DNS and ingress entries to paste. |
|
|
158
216
|
| `localgate prune` | Drop routes whose runner is gone. |
|
|
159
217
|
|
|
160
|
-
With no `[app]` argument, a command acts on the route owning the current directory.
|
|
218
|
+
With no `[app]` argument, a command acts on the route owning the current directory. `start` is not a
|
|
219
|
+
name a project or an alias can use: it belongs to the start page above.
|
|
161
220
|
|
|
162
221
|
## Working with a coding agent
|
|
163
222
|
|
|
@@ -173,9 +232,10 @@ localgate list --json # everything running on the machine
|
|
|
173
232
|
`status --json` includes the last lines the dev server printed, so an agent can check whether its
|
|
174
233
|
change compiled without owning the terminal it compiled in.
|
|
175
234
|
|
|
176
|
-
The takeover
|
|
177
|
-
|
|
178
|
-
|
|
235
|
+
The takeover above is the one place this matters for safety. **With no terminal - an agent, a CI job -
|
|
236
|
+
`localgate run` prints what is already running and exits 1 instead of taking it over.** It never ends
|
|
237
|
+
the developer's session by accident; `localgate run --force` takes over deliberately. To pick up a
|
|
238
|
+
change, use `localgate restart`, which keeps the runner, the terminal and the debugger.
|
|
179
239
|
|
|
180
240
|
## Names, and who can reach them
|
|
181
241
|
|
|
@@ -221,6 +281,8 @@ With that file present, `myapp` in mode `lan` also answers on `myapp.dev.example
|
|
|
221
281
|
environment variables (`NEXT_PUBLIC_*`, `*_PUBLIC_URL`, `AUTH_URL`, `NEXTAUTH_URL`) are rewritten from
|
|
222
282
|
`.localhost` to the name selected by the current mode on the way into the dev server. Public URLs use
|
|
223
283
|
HTTPS and never carry the proxy's internal LAN port. Server-side variables stay on `.localhost`.
|
|
284
|
+
Node children get a lookup hook for that reserved suffix, so Fetch and the standard HTTP clients reach
|
|
285
|
+
the local proxy even when the operating system resolver does not expand nested localhost names.
|
|
224
286
|
|
|
225
287
|
For reaching an app from outside the LAN, `localgate cloudflare-info` prints the exact prefixed DNS
|
|
226
288
|
record and tunnel ingress entry. It prints them and stops: localgate holds no API token and sends
|
|
@@ -278,6 +340,10 @@ machine that resolved it", so the LAN listener never answers one, whatever `Host
|
|
|
278
340
|
carries and whether it is a plain request or a websocket upgrade. An app in the default `local` mode
|
|
279
341
|
has no other name, which is what keeps it on this machine.
|
|
280
342
|
|
|
343
|
+
The start page follows the same rule rather than working around it: on the LAN it lists only what that
|
|
344
|
+
listener would serve. An app in mode `local` does not appear on it at all - not its name, its port, its
|
|
345
|
+
command or its directory.
|
|
346
|
+
|
|
281
347
|
Those dev servers are the real exposure: in `lan` mode anyone on the network reaches them with no
|
|
282
348
|
authentication, and in `internet` mode anyone holding the URL does. Use `lan` on networks you trust, and
|
|
283
349
|
switch back from `internet` when you are done. There is no TLS - it is plain http by design.
|
|
@@ -297,9 +363,9 @@ build step.
|
|
|
297
363
|
Early. Windows, Linux and macOS: the kill that makes `restart` reliable goes through `taskkill /T` on
|
|
298
364
|
Windows and the child's process group elsewhere, and the port-holder lookup is PowerShell or `lsof`.
|
|
299
365
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
366
|
+
Browsers and Node processes started through Localgate resolve `*.localhost` to loopback. Other
|
|
367
|
+
command-line programs still use the operating system resolver, so on a system that does not expand
|
|
368
|
+
nested localhost names they need an explicit resolver option or a hosts entry.
|
|
303
369
|
|
|
304
370
|
Bug reports and ideas are welcome - see [CONTRIBUTING.md](CONTRIBUTING.md), and
|
|
305
371
|
[SECURITY.md](SECURITY.md) for anything security-related. Licensed under
|
|
@@ -15,14 +15,14 @@ export class LocalgateBanner
|
|
|
15
15
|
|
|
16
16
|
static render(route: LocalgateRoute, proxyPort: number): string
|
|
17
17
|
{
|
|
18
|
-
const [local, network, internet] = route.names;
|
|
19
18
|
const [nextLabel, nextCommand] = LocalgateBanner.next(route);
|
|
20
19
|
|
|
21
20
|
const lines = ["", ` localgate ${LocalgateBanner.appName(route)} · ${LocalgateBanner.subtitle(route)}`, ""];
|
|
22
21
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
22
|
+
// Widest reach first, because the address a person came here for is the one that leaves the machine.
|
|
23
|
+
for (const address of LocalgateUrl.routeAddresses(route, proxyPort).reverse())
|
|
24
|
+
lines.push(LocalgateBanner.row(address.label, address.url));
|
|
25
|
+
|
|
26
26
|
lines.push("", LocalgateBanner.row("upstream", `127.0.0.1:${route.port}`), LocalgateBanner.row(nextLabel, nextCommand), "");
|
|
27
27
|
|
|
28
28
|
return `${lines.join("\n")}\n`;
|
|
@@ -8,10 +8,12 @@ import { LocalgateProjectConfig } from "../config/localgateProjectConfig.ts";
|
|
|
8
8
|
import { LocalgateConfigReporter } from "../config/localgateConfigReport.ts";
|
|
9
9
|
import { LocalgateAliasRoute } from "../proxy/localgateAliasRoute.ts";
|
|
10
10
|
import { LocalgateProxyHost } from "../proxy/localgateProxyHost.ts";
|
|
11
|
+
import { LocalgateStartPage } from "../proxy/localgateStartPage.ts";
|
|
11
12
|
import { LocalgateUrl } from "../proxy/localgateUrl.ts";
|
|
12
13
|
import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
|
|
13
14
|
import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
|
|
14
15
|
import { LocalgateRunner } from "../run/localgateRunner.ts";
|
|
16
|
+
import { LocalgateRunnerControl } from "../run/localgateRunnerControl.ts";
|
|
15
17
|
|
|
16
18
|
export class LocalgateCli
|
|
17
19
|
{
|
|
@@ -82,6 +84,9 @@ export class LocalgateCli
|
|
|
82
84
|
process.stdout.write("\n");
|
|
83
85
|
}
|
|
84
86
|
|
|
87
|
+
// Only with a route in hand, because the page is served by the proxy and the proxy is not running
|
|
88
|
+
// when nothing is registered - naming it above would send the reader to a refused connection.
|
|
89
|
+
process.stdout.write(`All of this in a browser: ${LocalgateStartPage.localUrl(proxyPort)}\n`);
|
|
85
90
|
return 0;
|
|
86
91
|
}
|
|
87
92
|
|
|
@@ -166,7 +171,8 @@ export class LocalgateCli
|
|
|
166
171
|
const response = await fetch(`${route.controlUrl}/${action}`, { method: "POST" });
|
|
167
172
|
if (!response.ok)
|
|
168
173
|
{
|
|
169
|
-
|
|
174
|
+
const detail = LocalgateRunnerControl.refusalDetail(await response.text().catch(() => ""));
|
|
175
|
+
process.stderr.write(`localgate: ${action} failed, the runner answered ${response.status}${detail}\n`);
|
|
170
176
|
return 1;
|
|
171
177
|
}
|
|
172
178
|
|
|
@@ -192,12 +198,30 @@ export class LocalgateCli
|
|
|
192
198
|
{
|
|
193
199
|
if (args[0] == "--remove") return LocalgateCli.aliasRemove(args[1]);
|
|
194
200
|
|
|
195
|
-
|
|
201
|
+
// Everything after --stop is the command, kept out of the positional pair so a name and a port can
|
|
202
|
+
// still be read the way they always were.
|
|
203
|
+
const stopIndex = args.indexOf("--stop");
|
|
204
|
+
const stop = stopIndex >= 0 ? args.slice(stopIndex + 1).join(" ").trim() : null;
|
|
205
|
+
const [name, portText] = stopIndex >= 0 ? args.slice(0, stopIndex) : args;
|
|
196
206
|
const port = Number.parseInt(portText ?? "", 10);
|
|
197
207
|
|
|
198
208
|
if (!name || !Number.isFinite(port))
|
|
199
209
|
{
|
|
200
|
-
process.stderr.write("localgate: usage is localgate alias <name> <port>\n");
|
|
210
|
+
process.stderr.write("localgate: usage is localgate alias <name> <port> [--stop \"<command>\"]\n");
|
|
211
|
+
return 1;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (stop !== null && stop.length == 0)
|
|
215
|
+
{
|
|
216
|
+
process.stderr.write("localgate: --stop needs the command that stops the service, "
|
|
217
|
+
+ "for example --stop \"docker stop myservice\"\n");
|
|
218
|
+
return 1;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (LocalgateNames.isReserved(name))
|
|
222
|
+
{
|
|
223
|
+
process.stderr.write(`localgate: "${LocalgateNames.startNameConst}" is reserved for the start page, `
|
|
224
|
+
+ "which lists every route. Pick another name for the alias.\n");
|
|
201
225
|
return 1;
|
|
202
226
|
}
|
|
203
227
|
|
|
@@ -240,7 +264,7 @@ export class LocalgateCli
|
|
|
240
264
|
// the banner, because the alias is already live and useful - it just will not come back.
|
|
241
265
|
try
|
|
242
266
|
{
|
|
243
|
-
LocalgateAliasStore.add({ name, port });
|
|
267
|
+
LocalgateAliasStore.add({ name, port, stop });
|
|
244
268
|
}
|
|
245
269
|
catch (error)
|
|
246
270
|
{
|
|
@@ -379,17 +403,16 @@ export class LocalgateCli
|
|
|
379
403
|
|
|
380
404
|
private static routeUrls(route: LocalgateRoute, proxyPort: number): string[]
|
|
381
405
|
{
|
|
382
|
-
return
|
|
383
|
-
? `https://${name}`
|
|
384
|
-
: LocalgateUrl.forName(name, proxyPort));
|
|
406
|
+
return LocalgateUrl.routeAddresses(route, proxyPort).map(address => address.url);
|
|
385
407
|
}
|
|
386
408
|
|
|
387
409
|
private static printUsage(): void
|
|
388
410
|
{
|
|
389
411
|
process.stdout.write(
|
|
390
412
|
"localgate - stable names for local dev servers\n\n" +
|
|
391
|
-
" localgate run [--force] <cmd...> run a dev server behind its name\n" +
|
|
392
|
-
"
|
|
413
|
+
" localgate run [--force] <cmd...> run a dev server behind its name; one already\n" +
|
|
414
|
+
" running for the project is stopped first\n" +
|
|
415
|
+
" --force is needed for that without a terminal\n" +
|
|
393
416
|
" localgate list [--json] show active routes\n" +
|
|
394
417
|
" localgate status [app] [--json] state of one route (defaults to this directory)\n" +
|
|
395
418
|
" localgate restart [app] restart a route's dev server\n" +
|
|
@@ -397,11 +420,14 @@ export class LocalgateCli
|
|
|
397
420
|
" localgate logs [app] [--lines N] tail a route's captured output\n" +
|
|
398
421
|
" localgate alias <name> <port> register a static route (e.g. a docker service); it is\n" +
|
|
399
422
|
" remembered and comes back when the proxy restarts\n" +
|
|
423
|
+
" [--stop \"<command>\"] what stops that service, e.g. \"docker stop myservice\";\n" +
|
|
424
|
+
" it gives the alias a stop button on the start page\n" +
|
|
400
425
|
" localgate alias --remove <name> drop a static route and forget it\n" +
|
|
401
426
|
" localgate config [dir] [--json] machine + project config and the names it implies\n" +
|
|
402
427
|
" localgate cloudflare-info print the DNS and ingress entries to paste\n" +
|
|
403
428
|
" localgate prune drop routes whose runner is gone\n\n" +
|
|
404
|
-
"[app] is optional: with no argument a command acts on the route owning the current directory.\n"
|
|
429
|
+
"[app] is optional: with no argument a command acts on the route owning the current directory.\n" +
|
|
430
|
+
`Every route, with its addresses, is also a page: ${LocalgateStartPage.localUrl(LocalgateProxyClient.proxyPort())}\n`
|
|
405
431
|
);
|
|
406
432
|
}
|
|
407
433
|
}
|
|
@@ -134,8 +134,14 @@ export class LocalgateProxyClient
|
|
|
134
134
|
throw new LocalgateRouteConflictError(payload.existing);
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
// The proxy refuses a registration with a sentence saying why - a reserved name, a port outside the
|
|
138
|
+
// dialable range - and a bare status code throws that sentence away in the one place a person reads
|
|
139
|
+
// it, which is the terminal the run was started from.
|
|
137
140
|
if (!response.ok)
|
|
138
|
-
|
|
141
|
+
{
|
|
142
|
+
const reason = await response.json().then(payload => (payload as { error?: string }).error).catch(() => undefined);
|
|
143
|
+
throw new Error(reason ?? `localgate proxy answered ${response.status} for ${method} ${path}`);
|
|
144
|
+
}
|
|
139
145
|
|
|
140
146
|
return response.json();
|
|
141
147
|
}
|
|
@@ -7,13 +7,22 @@ export type LocalgatePersistedAlias =
|
|
|
7
7
|
{
|
|
8
8
|
name: string;
|
|
9
9
|
port: number;
|
|
10
|
+
// What ends whatever answers on that port, when the machine knows. An alias names a process localgate
|
|
11
|
+
// did not start - a container, a service - so there is nobody to ask; this line is the answer the
|
|
12
|
+
// machine's owner wrote down, and it is what lets an alias have a stop button at all.
|
|
13
|
+
stop: string | null;
|
|
10
14
|
};
|
|
11
15
|
|
|
12
|
-
// Records alias INTENT - the short name
|
|
13
|
-
// process behind it, so a runner heartbeat cannot bring it back
|
|
14
|
-
// only possible owner of record. Names and mode are deliberately
|
|
15
|
-
// time is what keeps a changed machine label or domain from
|
|
16
|
-
//
|
|
16
|
+
// Records alias INTENT - the short name, the port, and optionally the command that stops what listens
|
|
17
|
+
// there. An alias is the one route with no process behind it, so a runner heartbeat cannot bring it back
|
|
18
|
+
// after a proxy restart and a file is its only possible owner of record. Names and mode are deliberately
|
|
19
|
+
// not stored: re-deriving them at restore time is what keeps a changed machine label or domain from
|
|
20
|
+
// resurrecting hostnames nobody uses any more.
|
|
21
|
+
//
|
|
22
|
+
// The CLI alias command is the only writer. The proxy reads it at boot to restore the routes, and the
|
|
23
|
+
// start page reads the stop commands as it renders, so an alias that gains one needs no proxy restart.
|
|
24
|
+
// A stop command is trusted because this file is the only way in: it never crosses the control API,
|
|
25
|
+
// where a form POST from a browser could plant one.
|
|
17
26
|
export class LocalgateAliasStore
|
|
18
27
|
{
|
|
19
28
|
private static readonly maxPortConst = 65_535;
|
|
@@ -35,6 +44,22 @@ export class LocalgateAliasStore
|
|
|
35
44
|
// Never throws. A hand-edited or half-written file must not take down a proxy boot that every dev
|
|
36
45
|
// server on the machine depends on, so a bad entry is dropped and the rest still load.
|
|
37
46
|
static load(filePath: string = LocalgateAliasStore.filePath()): LocalgatePersistedAlias[]
|
|
47
|
+
{
|
|
48
|
+
return LocalgateAliasStore.read(filePath, true);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// The stop commands alone, by alias name, and without a word to stderr: the page asks for these on
|
|
52
|
+
// every render, and a file the boot already complained about must not complain again every five
|
|
53
|
+
// seconds.
|
|
54
|
+
static stopCommands(filePath: string = LocalgateAliasStore.filePath()): Map<string, string>
|
|
55
|
+
{
|
|
56
|
+
const commands = new Map<string, string>();
|
|
57
|
+
for (const alias of LocalgateAliasStore.read(filePath, false))
|
|
58
|
+
if (alias.stop) commands.set(alias.name, alias.stop);
|
|
59
|
+
return commands;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private static read(filePath: string, report: boolean): LocalgatePersistedAlias[]
|
|
38
63
|
{
|
|
39
64
|
let raw: string;
|
|
40
65
|
try
|
|
@@ -45,7 +70,7 @@ export class LocalgateAliasStore
|
|
|
45
70
|
{
|
|
46
71
|
// A machine that never registered an alias is the ordinary case and says nothing. Anything else -
|
|
47
72
|
// no permission, a directory in the way - is worth a line, because it loses aliases that exist.
|
|
48
|
-
if ((error as NodeJS.ErrnoException).code != "ENOENT")
|
|
73
|
+
if (report && (error as NodeJS.ErrnoException).code != "ENOENT")
|
|
49
74
|
process.stderr.write(`localgate: ${filePath} could not be read, continuing without its aliases: ${String(error)}\n`);
|
|
50
75
|
return [];
|
|
51
76
|
}
|
|
@@ -59,21 +84,21 @@ export class LocalgateAliasStore
|
|
|
59
84
|
{
|
|
60
85
|
// Left on disk on purpose: the next add or remove rewrites it, and until then the person can
|
|
61
86
|
// still see what they typed.
|
|
62
|
-
process.stderr.write(`localgate: ${filePath} is not valid JSON, ignoring the aliases in it\n`);
|
|
87
|
+
if (report) process.stderr.write(`localgate: ${filePath} is not valid JSON, ignoring the aliases in it\n`);
|
|
63
88
|
return [];
|
|
64
89
|
}
|
|
65
90
|
|
|
66
91
|
const entries = (parsed as { aliases?: unknown } | null)?.aliases;
|
|
67
92
|
if (!Array.isArray(entries))
|
|
68
93
|
{
|
|
69
|
-
process.stderr.write(`localgate: ${filePath} has no alias list, ignoring it\n`);
|
|
94
|
+
if (report) process.stderr.write(`localgate: ${filePath} has no alias list, ignoring it\n`);
|
|
70
95
|
return [];
|
|
71
96
|
}
|
|
72
97
|
|
|
73
98
|
const aliases: LocalgatePersistedAlias[] = [];
|
|
74
99
|
for (const entry of entries)
|
|
75
100
|
{
|
|
76
|
-
const alias = LocalgateAliasStore.validated(entry, filePath);
|
|
101
|
+
const alias = LocalgateAliasStore.validated(entry, filePath, report);
|
|
77
102
|
if (alias) aliases.push(alias);
|
|
78
103
|
}
|
|
79
104
|
|
|
@@ -84,9 +109,14 @@ export class LocalgateAliasStore
|
|
|
84
109
|
// port the same way the registry replaces the live route.
|
|
85
110
|
static add(alias: LocalgatePersistedAlias, filePath: string = LocalgateAliasStore.filePath()): void
|
|
86
111
|
{
|
|
87
|
-
const aliases = LocalgateAliasStore.load(filePath)
|
|
88
|
-
aliases.
|
|
89
|
-
|
|
112
|
+
const aliases = LocalgateAliasStore.load(filePath);
|
|
113
|
+
const previous = aliases.find(existing => existing.name == alias.name);
|
|
114
|
+
|
|
115
|
+
// Re-running `localgate alias myapp 8002` moves the port, and it must not silently drop a stop
|
|
116
|
+
// command written for that name. Passing one replaces it.
|
|
117
|
+
const kept = aliases.filter(existing => existing.name != alias.name);
|
|
118
|
+
kept.push({ ...alias, stop: alias.stop ?? previous?.stop ?? null });
|
|
119
|
+
LocalgateAliasStore.write(kept, filePath);
|
|
90
120
|
}
|
|
91
121
|
|
|
92
122
|
static remove(name: string, filePath: string = LocalgateAliasStore.filePath()): boolean
|
|
@@ -113,7 +143,9 @@ export class LocalgateAliasStore
|
|
|
113
143
|
const handle = openSync(temporary, "w", LocalgateAliasStore.fileModeConst);
|
|
114
144
|
try
|
|
115
145
|
{
|
|
116
|
-
|
|
146
|
+
// An absent command is absent from the file rather than written as a null: people edit this file.
|
|
147
|
+
const written = aliases.map(alias => alias.stop ? alias : { name: alias.name, port: alias.port });
|
|
148
|
+
writeSync(handle, `${JSON.stringify({ aliases: written }, null, 2)}\n`);
|
|
117
149
|
fsyncSync(handle);
|
|
118
150
|
}
|
|
119
151
|
finally
|
|
@@ -124,24 +156,32 @@ export class LocalgateAliasStore
|
|
|
124
156
|
renameSync(temporary, filePath);
|
|
125
157
|
}
|
|
126
158
|
|
|
127
|
-
private static validated(entry: unknown, filePath: string): LocalgatePersistedAlias | null
|
|
159
|
+
private static validated(entry: unknown, filePath: string, report: boolean): LocalgatePersistedAlias | null
|
|
128
160
|
{
|
|
129
|
-
const candidate = entry as { name?: unknown; port?: unknown } | null;
|
|
161
|
+
const candidate = entry as { name?: unknown; port?: unknown; stop?: unknown } | null;
|
|
130
162
|
const name = candidate?.name;
|
|
131
163
|
const port = candidate?.port;
|
|
132
164
|
|
|
133
165
|
if (typeof name != "string" || !LocalgateMachineConfig.isLabel(name))
|
|
134
166
|
{
|
|
135
|
-
process.stderr.write(`localgate: ${filePath} holds an alias whose name is not a DNS label, skipping it\n`);
|
|
167
|
+
if (report) process.stderr.write(`localgate: ${filePath} holds an alias whose name is not a DNS label, skipping it\n`);
|
|
136
168
|
return null;
|
|
137
169
|
}
|
|
138
170
|
|
|
139
171
|
if (typeof port != "number" || !LocalgateAliasStore.isPort(port))
|
|
140
172
|
{
|
|
141
|
-
process.stderr.write(`localgate: ${filePath} holds alias ${name} without a usable port, skipping it\n`);
|
|
173
|
+
if (report) process.stderr.write(`localgate: ${filePath} holds alias ${name} without a usable port, skipping it\n`);
|
|
142
174
|
return null;
|
|
143
175
|
}
|
|
144
176
|
|
|
145
|
-
|
|
177
|
+
// A malformed stop command costs the button, not the alias: the name and the port are what make the
|
|
178
|
+
// route, and dropping those over a mistyped extra field would take a service off the machine.
|
|
179
|
+
const stop = typeof candidate?.stop == "string" && candidate.stop.trim().length > 0 ? candidate.stop : null;
|
|
180
|
+
// A written `null` says "none", which is exactly what this returns, so only a value that tried to be
|
|
181
|
+
// a command and failed is worth a word.
|
|
182
|
+
if (candidate?.stop != null && !stop && report)
|
|
183
|
+
process.stderr.write(`localgate: ${filePath} holds alias ${name} with an unusable "stop" command, ignoring that field\n`);
|
|
184
|
+
|
|
185
|
+
return { name, port, stop };
|
|
146
186
|
}
|
|
147
187
|
}
|
|
@@ -3,6 +3,11 @@ import type { LocalgateMode } from "./localgateProjectConfig.ts";
|
|
|
3
3
|
|
|
4
4
|
export class LocalgateNames
|
|
5
5
|
{
|
|
6
|
+
// The start page answers on this label instead of a route, on `.localhost` and on the machine's own
|
|
7
|
+
// domain. It is resolved before the route table, so a project or alias holding the same name would be
|
|
8
|
+
// registered, listed and never reached - refused at registration instead.
|
|
9
|
+
static readonly startNameConst = "start";
|
|
10
|
+
|
|
6
11
|
private static readonly dnsLabelMaxLengthConst = 63;
|
|
7
12
|
|
|
8
13
|
static local(projectName: string): string
|
|
@@ -32,6 +37,13 @@ export class LocalgateNames
|
|
|
32
37
|
return hostname.split(".")[0];
|
|
33
38
|
}
|
|
34
39
|
|
|
40
|
+
// Takes the short name as well as any hostname built from it, because the name arrives as both: a
|
|
41
|
+
// project name from package.json, an alias argument, and a full hostname from `localgate list`.
|
|
42
|
+
static isReserved(name: string): boolean
|
|
43
|
+
{
|
|
44
|
+
return LocalgateNames.shortName(name) == LocalgateNames.startNameConst;
|
|
45
|
+
}
|
|
46
|
+
|
|
35
47
|
static routeNames(projectName: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null): string[]
|
|
36
48
|
{
|
|
37
49
|
const local = LocalgateNames.local(projectName);
|
|
@@ -32,6 +32,13 @@ export class LocalgateHealth
|
|
|
32
32
|
return LocalgateHealth.requestTimeoutMsConst;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
// How long a refused connection still reads as "not bound yet" rather than "gone". Shared with the
|
|
36
|
+
// start page, which has to draw the same line when its own probe finds nothing on the port.
|
|
37
|
+
static startupGraceMs(): number
|
|
38
|
+
{
|
|
39
|
+
return LocalgateHealth.startupGraceMsConst;
|
|
40
|
+
}
|
|
41
|
+
|
|
35
42
|
noteSuccess(route: LocalgateRoute): void
|
|
36
43
|
{
|
|
37
44
|
this.failures.delete(route.id);
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { connect } from "node:net";
|
|
2
|
+
import type { LocalgateRoute } from "./localgateRegistry.ts";
|
|
3
|
+
|
|
4
|
+
// Whether anything is listening on a route's port, right now.
|
|
5
|
+
//
|
|
6
|
+
// The proxy's own health is learned from forwarded traffic, which costs nothing but says nothing at all
|
|
7
|
+
// about a route nobody has opened: a dev server that has been up for an hour and an alias whose
|
|
8
|
+
// container is down both sit at "starting" until someone visits them. A connection to loopback answers
|
|
9
|
+
// that question directly and costs a millisecond, so the start page asks it rather than repeating a
|
|
10
|
+
// guess back to the reader.
|
|
11
|
+
export class LocalgatePortProbe
|
|
12
|
+
{
|
|
13
|
+
// Loopback either accepts or refuses at once. The timeout is for the case in between - a port being
|
|
14
|
+
// dropped by a firewall rule - where the page must not wait on it.
|
|
15
|
+
private static readonly timeoutMsConst = 400;
|
|
16
|
+
|
|
17
|
+
static listening(port: number, timeoutMs: number = LocalgatePortProbe.timeoutMsConst): Promise<boolean>
|
|
18
|
+
{
|
|
19
|
+
return new Promise<boolean>(resolve =>
|
|
20
|
+
{
|
|
21
|
+
const socket = connect({ host: "127.0.0.1", port });
|
|
22
|
+
const settle = (answer: boolean) =>
|
|
23
|
+
{
|
|
24
|
+
socket.destroy();
|
|
25
|
+
resolve(answer);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
socket.setTimeout(timeoutMs, () => settle(false));
|
|
29
|
+
socket.once("connect", () => settle(true));
|
|
30
|
+
socket.once("error", () => settle(false));
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// All of them at once, keyed by route id: a page that probed eight ports one after another would
|
|
35
|
+
// answer eight timeouts later in the worst case. It takes the two fields it dials with rather than the
|
|
36
|
+
// whole route, because that is all a port probe can honestly need.
|
|
37
|
+
static async listeningRoutes(routes: Pick<LocalgateRoute, "id" | "port">[]): Promise<Map<string, boolean>>
|
|
38
|
+
{
|
|
39
|
+
const answers = await Promise.all(routes.map(route => LocalgatePortProbe.listening(route.port)));
|
|
40
|
+
return new Map(routes.map((route, index) => [route.id, answers[index]!]));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -4,6 +4,7 @@ import { LocalgateControlApi } from "./localgateControlApi.ts";
|
|
|
4
4
|
import { LocalgateHeaderRewrite } from "./localgateHeaderRewrite.ts";
|
|
5
5
|
import { LocalgateHealth } from "./localgateHealth.ts";
|
|
6
6
|
import type { LocalgateReach, LocalgateRegistry, LocalgateRoute } from "./localgateRegistry.ts";
|
|
7
|
+
import { LocalgateStartPage } from "./localgateStartPage.ts";
|
|
7
8
|
|
|
8
9
|
export type LocalgateProxyOptions =
|
|
9
10
|
{
|
|
@@ -27,6 +28,7 @@ export class LocalgateProxy
|
|
|
27
28
|
private readonly registry: LocalgateRegistry,
|
|
28
29
|
private readonly health: LocalgateHealth,
|
|
29
30
|
private readonly controlApi: LocalgateControlApi,
|
|
31
|
+
private readonly startPage: LocalgateStartPage,
|
|
30
32
|
private readonly options: LocalgateProxyOptions
|
|
31
33
|
) {}
|
|
32
34
|
|
|
@@ -115,6 +117,11 @@ export class LocalgateProxy
|
|
|
115
117
|
if (loopback && LocalgateControlApi.handles(requestUrl))
|
|
116
118
|
return this.controlApi.handle(request, response);
|
|
117
119
|
|
|
120
|
+
// Before the table, not after it: the start page has no route, and a route that took its name would
|
|
121
|
+
// shadow the page rather than the other way round. The registry refuses that name for this reason.
|
|
122
|
+
if (this.startPage.handles(request.headers.host ?? "", reachedFrom))
|
|
123
|
+
return this.startPage.handle(request, response, reachedFrom);
|
|
124
|
+
|
|
118
125
|
const route = this.registry.byHostname(request.headers.host ?? "", reachedFrom);
|
|
119
126
|
if (!route)
|
|
120
127
|
{
|
|
@@ -165,8 +172,20 @@ export class LocalgateProxy
|
|
|
165
172
|
upstreamResponse.pipe(response);
|
|
166
173
|
});
|
|
167
174
|
|
|
175
|
+
// pipe() only unpipes when the browser goes away, it never ends the source. Without this an SSE
|
|
176
|
+
// stream or a long poll stays open on the dev server after a refresh, and the handler there never
|
|
177
|
+
// sees its request aborted. The same close covers a browser that leaves mid-upload or mid-wait.
|
|
178
|
+
response.once("close", () =>
|
|
179
|
+
{
|
|
180
|
+
if (!response.writableFinished) upstream.destroy();
|
|
181
|
+
});
|
|
182
|
+
|
|
168
183
|
upstream.once("error", (error: NodeJS.ErrnoException) =>
|
|
169
184
|
{
|
|
185
|
+
// The browser left and the close above tore the request down. That reset says nothing about the
|
|
186
|
+
// dev server, so it must not move the route to starting or dead.
|
|
187
|
+
if (response.destroyed) return;
|
|
188
|
+
|
|
170
189
|
if (response.headersSent)
|
|
171
190
|
{
|
|
172
191
|
response.destroy();
|
|
@@ -237,6 +256,9 @@ export class LocalgateProxy
|
|
|
237
256
|
});
|
|
238
257
|
|
|
239
258
|
upstream.once("error", () => clientSocket.destroy());
|
|
259
|
+
// A browser that leaves before the dev server answers the handshake would otherwise leave the
|
|
260
|
+
// upgrade request, and the socket it later yields, open on the dev server with nobody to pipe to.
|
|
261
|
+
clientSocket.once("close", () => upstream.destroy());
|
|
240
262
|
upstream.end();
|
|
241
263
|
}
|
|
242
264
|
|
|
@@ -267,7 +289,9 @@ export class LocalgateProxy
|
|
|
267
289
|
lines.push(` ${route.names.join(" ")} -> 127.0.0.1:${route.port} [${route.state}]`);
|
|
268
290
|
}
|
|
269
291
|
|
|
270
|
-
|
|
292
|
+
// The port this request arrived on, not the configured one: the two differ when the proxy was asked
|
|
293
|
+
// for an ephemeral port, and a hint pointing at a port nothing listens on is worse than no hint.
|
|
294
|
+
lines.push("", `Every route, with its addresses: ${LocalgateStartPage.localUrl(this.boundPorts()[0]!)}`, "");
|
|
271
295
|
return lines.join("\n");
|
|
272
296
|
}
|
|
273
297
|
|