localgate 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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 works
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 and asks, in the debug terminal it was started from:
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
- Stop it and take over? [Y/n]
147
+ localgate: stopping myapp.localhost (runner 45568)
134
148
  ```
135
149
 
136
- Yes stops the old one the good way: its own runner kills the child tree, releases the port and
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 not a question. Its dev server usually outlived it and still
141
- holds the port - that is the orphan a framework lock trips over - so it is cleared and the name reused
142
- without asking.
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
+ ![the localgate start page: a card per route with its name, state, addresses and upstream port](docs/media/localgate-start-page.png)
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. `--force` takes over a running one without asking. |
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>` | Register a static route, e.g. a docker service. Remembered across proxy restarts. |
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 question above is the one place this matters for safety. **With no terminal to ask in -
177
- an agent, a CI job - `localgate run` prints what is already running and exits 1 instead of asking.**
178
- It never kills the developer's session by accident; `localgate run --force` takes over deliberately.
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
 
@@ -218,9 +278,23 @@ their own names without either name being in the repository:
218
278
 
219
279
  With that file present, `myapp` in mode `lan` also answers on `myapp.dev.example.com`, while mode
220
280
  `internet` additionally answers on `pub-myapp.example.com`. Browser-facing
221
- environment variables (`NEXT_PUBLIC_*`, `*_PUBLIC_URL`, `AUTH_URL`, `NEXTAUTH_URL`) are rewritten from
281
+ environment variables (`NEXT_PUBLIC_*`, `*_PUBLIC_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.
286
+
287
+ For Auth.js applications that serve several origins, omit `AUTH_URL` and `NEXTAUTH_URL` from the
288
+ application's development env files and launch environment, and configure `trustHost: true` or
289
+ `AUTH_TRUST_HOST=true`. Authentication can then follow each request's origin. Localgate sets
290
+ `X-Forwarded-Host` to the routed `Host`, including its port, and defaults `X-Forwarded-Proto` to `http`,
291
+ preserving a tunnel's single `http` or `https` value. Each origin keeps its own session cookie.
292
+
293
+ Localgate does not delete auth settings, set trust flags or intercept env-file loading. Explicit auth
294
+ URLs keep their configured hostname; as with other server URLs, a `.localhost` value receives the
295
+ proxy port. This replaces the earlier behavior that rewrote auth URLs to the LAN or public hostname.
296
+ Custom auth paths, cookie prefixes and older NextAuth server helpers remain application configuration.
297
+ See [docs/architecture/auth-origin.md](docs/architecture/auth-origin.md) for compatibility and restart steps.
224
298
 
225
299
  For reaching an app from outside the LAN, `localgate cloudflare-info` prints the exact prefixed DNS
226
300
  record and tunnel ingress entry. It prints them and stops: localgate holds no API token and sends
@@ -278,6 +352,10 @@ machine that resolved it", so the LAN listener never answers one, whatever `Host
278
352
  carries and whether it is a plain request or a websocket upgrade. An app in the default `local` mode
279
353
  has no other name, which is what keeps it on this machine.
280
354
 
355
+ The start page follows the same rule rather than working around it: on the LAN it lists only what that
356
+ listener would serve. An app in mode `local` does not appear on it at all - not its name, its port, its
357
+ command or its directory.
358
+
281
359
  Those dev servers are the real exposure: in `lan` mode anyone on the network reaches them with no
282
360
  authentication, and in `internet` mode anyone holding the URL does. Use `lan` on networks you trust, and
283
361
  switch back from `internet` when you are done. There is no TLS - it is plain http by design.
@@ -297,9 +375,9 @@ build step.
297
375
  Early. Windows, Linux and macOS: the kill that makes `restart` reliable goes through `taskkill /T` on
298
376
  Windows and the child's process group elsewhere, and the port-holder lookup is PowerShell or `lsof`.
299
377
 
300
- One rough edge on macOS: browsers resolve `*.localhost` to loopback by RFC 6761, but the system
301
- resolver does not, so `curl http://myapp.localhost:8080` and server-to-server calls by name need an
302
- `/etc/hosts` entry there. Browsers are fine.
378
+ Browsers and Node processes started through Localgate resolve `*.localhost` to loopback. Other
379
+ command-line programs still use the operating system resolver, so on a system that does not expand
380
+ nested localhost names they need an explicit resolver option or a hosts entry.
303
381
 
304
382
  Bug reports and ideas are welcome - see [CONTRIBUTING.md](CONTRIBUTING.md), and
305
383
  [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
- if (internet) lines.push(LocalgateBanner.row("internet", `https://${internet}`));
24
- if (network) lines.push(LocalgateBanner.row("network", LocalgateUrl.forName(network, proxyPort)));
25
- lines.push(LocalgateBanner.row("local", LocalgateUrl.forName(local, proxyPort)));
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
- process.stderr.write(`localgate: ${action} failed, the runner answered ${response.status}\n`);
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
- const [name, portText] = args;
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 route.names.map((name, index) => route.mode == "internet" && index == 2
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
- " --force takes over a running one without asking\n" +
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
- throw new Error(`localgate proxy answered ${response.status} for ${method} ${path}`);
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 and the port, nothing else. An alias is the one route with no
13
- // process behind it, so a runner heartbeat cannot bring it back after a proxy restart and a file is its
14
- // only possible owner of record. Names and mode are deliberately not stored: re-deriving them at restore
15
- // time is what keeps a changed machine label or domain from resurrecting hostnames nobody uses any more.
16
- // The CLI alias command is the only writer; the proxy reads this once at boot and never writes it.
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).filter(existing => existing.name != alias.name);
88
- aliases.push(alias);
89
- LocalgateAliasStore.write(aliases, filePath);
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
- writeSync(handle, `${JSON.stringify({ aliases }, null, 2)}\n`);
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
- return { name, port };
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);
@@ -17,6 +17,12 @@ export class LocalgateHeaderRewrite
17
17
 
18
18
  static apply(requestUrl: string, headers: IncomingHttpHeaders, requestHost: string, canonicalName: string): void
19
19
  {
20
+ // Routing has already validated Host. Auth libraries prefer forwarded headers, so an unrelated
21
+ // forwarded host must not override it. A TLS-terminating tunnel supplies the original protocol.
22
+ headers["x-forwarded-host"] = requestHost;
23
+ if (headers["x-forwarded-proto"] != "http" && headers["x-forwarded-proto"] != "https")
24
+ headers["x-forwarded-proto"] = "http";
25
+
20
26
  if (!LocalgateHeaderRewrite.isInternalPath(requestUrl)) return;
21
27
 
22
28
  const requestHostname = LocalgateHeaderRewrite.hostnameOf(requestHost);
@@ -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
+ }