localgate 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,8 +6,8 @@ Stable names for local dev servers.
6
6
  [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
7
7
 
8
8
  One reverse proxy multiplexes every dev server on the machine by `Host` header, so each app gets a name
9
- instead of a port: `myapp.localhost` locally, and optionally `myapp.<label>.<your-domain>` so a
10
- colleague on the LAN can open it too.
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.
11
11
 
12
12
  It also owns the dev process it starts, which is the part editors cannot give you: `localgate restart`
13
13
  restarts the server running inside your editor's debug terminal, without stealing the route or the
@@ -32,7 +32,8 @@ Every dev server binds an ephemeral loopback port and registers its name. The pr
32
32
  flowchart LR
33
33
  local["this PC"] -->|"local: myapp.localhost"| proxy
34
34
  lan["the LAN"] -->|"lan: myapp.dev.example.com"| proxy
35
- net["a tunnel"] -->|"internet: same name"| proxy
35
+ net["the internet"] -->|"internet: pub-myapp.example.com"| tunnel["shared tunnel"]
36
+ tunnel --> proxy
36
37
 
37
38
  proxy["localgate proxy"]
38
39
 
@@ -41,9 +42,9 @@ flowchart LR
41
42
  proxy --> alias["alias :8001"]
42
43
  ```
43
44
 
44
- The tunnel is not localgate's - it is whatever you already run, pointed at this machine's LAN address
45
- on the proxy's port. It keeps the `Host` header, so a request arriving through it is routed exactly
46
- like a LAN request and localgate needs to know nothing about it.
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.
47
48
 
48
49
  The table lives in the proxy's memory. There is no config file listing apps, no port assignment to keep
49
50
  in sync, and nothing to clean up after a crash.
@@ -51,7 +52,8 @@ in sync, and nothing to clean up after a crash.
51
52
  ## How restart works
52
53
 
53
54
  The runner sits in your editor's debug terminal and owns the dev server as its child. That is what lets
54
- a restart keep the terminal, the debugger and the route, and swap only the process underneath.
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.
55
57
 
56
58
  With no argument, `localgate restart` asks the proxy which route owns the current directory, and posts
57
59
  to that runner's own control endpoint, which listens on loopback and nowhere else.
@@ -70,8 +72,9 @@ sequenceDiagram
70
72
 
71
73
  While the dev server is down the proxy answers with a readable page instead of a connection error.
72
74
  Websocket upgrades are proxied, and on Next.js dev endpoints (`/_next/*`, `/__nextjs*`) the `Origin`
73
- and `Referer` headers are mapped back to `.localhost` - which is what hot module reload needs to work
74
- through a shared name, without an `allowedDevOrigins` entry in the project.
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.
75
78
 
76
79
  ## Install
77
80
 
@@ -148,7 +151,9 @@ without asking.
148
151
  | `localgate restart [app]` | Restart a route's dev server. |
149
152
  | `localgate stop [app]` | Stop a route's dev server. |
150
153
  | `localgate logs [app] [--lines N]` | Tail a route's captured output. |
151
- | `localgate alias <name> <port>` | Register a static route, e.g. a docker service. |
154
+ | `localgate alias <name> <port>` | Register a static route, e.g. a docker service. Remembered across proxy restarts. |
155
+ | `localgate alias --remove <name>` | Drop a static route and forget it. |
156
+ | `localgate config [dir] [--json]` | Machine and project config, the names it implies, and the alias file. |
152
157
  | `localgate cloudflare-info` | Print the DNS and ingress entries to paste. |
153
158
  | `localgate prune` | Drop routes whose runner is gone. |
154
159
 
@@ -180,7 +185,7 @@ A project gets its name from `package.json`, and nothing else is needed to work
180
185
  |---|---|---|
181
186
  | `local` (default) | `myapp.localhost` | this machine |
182
187
  | `lan` | + `myapp.<label>.<your-domain>` | any PC on the LAN that resolves your domain |
183
- | `internet` | the same shared name | wherever you point a tunnel at it |
188
+ | `internet` | + `<public-prefix>-myapp.<your-domain>` | local machine, LAN and the configured tunnel |
184
189
 
185
190
  The name is the package name, with a scope dropped (`@org/web` becomes `web`), and it has to be a
186
191
  usable hostname label. When the package name is long or is not what you want to type, override it -
@@ -206,21 +211,24 @@ their own names without either name being in the repository:
206
211
  "label": "dev", // your machine, as a DNS label
207
212
  "baseDomain": "example.com", // a domain whose wildcard resolves to this LAN
208
213
  "lanIp": "192.0.2.10", // the address the proxy also listens on
214
+ "publicPrefix": "pub", // prefix owned by this machine on the public domain
209
215
  "autoRestart": false // see "When a dev server stops answering"
210
216
  }
211
217
  ```
212
218
 
213
- With that file present, `myapp` in mode `lan` also answers on `myapp.dev.example.com`. Browser-facing
219
+ With that file present, `myapp` in mode `lan` also answers on `myapp.dev.example.com`, while mode
220
+ `internet` additionally answers on `pub-myapp.example.com`. Browser-facing
214
221
  environment variables (`NEXT_PUBLIC_*`, `*_PUBLIC_URL`, `AUTH_URL`, `NEXTAUTH_URL`) are rewritten from
215
- `.localhost` to that name on the way into the dev server, in memory - a remote browser resolves
216
- `.localhost` to itself, so those URLs have to carry the shared name, while server-side variables stay
217
- on `.localhost` where they are faster and need no DNS.
222
+ `.localhost` to the name selected by the current mode on the way into the dev server. Public URLs use
223
+ HTTPS and never carry the proxy's internal LAN port. Server-side variables stay on `.localhost`.
218
224
 
219
- For reaching an app from outside the LAN, `localgate cloudflare-info` prints the DNS record and the
220
- tunnel ingress entry to paste. It prints them and stops: localgate holds no API token and sends nothing
221
- anywhere. Worth knowing before you paste them: a specific DNS record wins over the wildcard, so from
222
- then on the name goes out to Cloudflare and back for everyone, the LAN included, and anyone holding the
223
- URL reaches the dev server. That is why `internet` is a mode you switch back from.
225
+ For reaching an app from outside the LAN, `localgate cloudflare-info` prints the exact prefixed DNS
226
+ record and tunnel ingress entry. It prints them and stops: localgate holds no API token and sends
227
+ nothing anywhere. In Atomix projects, use `axtoolsv2 expose <dir> off|network|internet`; AtomixToolsV2
228
+ owns the API calls, project state, and Localgate reload. It retains an existing managed CNAME when
229
+ leaving `internet` and removes only ingress, so the public hostname reaches the tunnel's 404 catch-all
230
+ without DNS recreation delay. Anyone holding an enabled public URL reaches the dev server, which is why
231
+ `internet` is a mode you switch back from.
224
232
 
225
233
  ## When a dev server stops answering
226
234
 
@@ -240,16 +248,20 @@ externally indistinguishable from a wedged one, and killing it would destroy the
240
248
  standing in. Reporting always happens; only the restart is behind the switch.
241
249
 
242
250
  If the proxy itself dies, every running app notices within ten seconds and re-registers its route, so
243
- the names come back without touching a single dev server.
251
+ the names come back without touching a single dev server. An alias has no process to notice, so the
252
+ starting proxy replays the aliases from `~/.localgate/aliases.json` instead.
244
253
 
245
254
  ## Design rules
246
255
 
247
- - **Nothing machine-specific is committed.** The label, the domain and the LAN IP live in
256
+ - **Nothing machine-specific is committed.** The label, public prefix, domain and LAN IP live in
248
257
  `~/.localgate/config.json`; a repository carries at most a `package.json` key holding a mode
249
258
  (`local` / `lan` / `internet`) and an optional name. Absent key means `local`, which is names on
250
259
  `.localhost` only.
251
- - **Nothing is persisted.** The route table is live state; after a reboot nothing runs until the first
252
- command. Aliases are part of that: `localgate alias` has to be re-run after the proxy exits.
260
+ - **Nothing is persisted except alias intent.** The route table is live state; after a reboot nothing
261
+ runs until the first command. The one exception is `localgate alias`: it records the name and the port
262
+ in `~/.localgate/aliases.json`, and a starting proxy serves those names again. An alias has no process
263
+ of its own, so a file is the only thing that can bring it back. Drop it with
264
+ `localgate alias --remove <name>`.
253
265
  - **The proxy is not a service.** The first `run` or `alias` starts it, and it exits once the last route
254
266
  disappears.
255
267
  - **No TLS, no tunnels of its own.** Plain http; put Cloudflare in front when something must be reachable
@@ -1,3 +1,4 @@
1
+ import { LocalgateNames } from "../config/localgateNames.ts";
1
2
  import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
2
3
  import { LocalgateUrl } from "../proxy/localgateUrl.ts";
3
4
 
@@ -14,12 +15,13 @@ export class LocalgateBanner
14
15
 
15
16
  static render(route: LocalgateRoute, proxyPort: number): string
16
17
  {
17
- const [local, shared] = route.names;
18
+ const [local, network, internet] = route.names;
18
19
  const [nextLabel, nextCommand] = LocalgateBanner.next(route);
19
20
 
20
21
  const lines = ["", ` localgate ${LocalgateBanner.appName(route)} · ${LocalgateBanner.subtitle(route)}`, ""];
21
22
 
22
- if (shared) lines.push(LocalgateBanner.row("shared", LocalgateUrl.forName(shared, proxyPort)));
23
+ if (internet) lines.push(LocalgateBanner.row("internet", `https://${internet}`));
24
+ if (network) lines.push(LocalgateBanner.row("network", LocalgateUrl.forName(network, proxyPort)));
23
25
  lines.push(LocalgateBanner.row("local", LocalgateUrl.forName(local, proxyPort)));
24
26
  lines.push("", LocalgateBanner.row("upstream", `127.0.0.1:${route.port}`), LocalgateBanner.row(nextLabel, nextCommand), "");
25
27
 
@@ -29,7 +31,7 @@ export class LocalgateBanner
29
31
  // The short name a person types, which is the first label of the local name.
30
32
  static appName(route: LocalgateRoute): string
31
33
  {
32
- return route.names[0].split(".")[0];
34
+ return LocalgateNames.shortName(route.names[0]);
33
35
  }
34
36
 
35
37
  private static subtitle(route: LocalgateRoute): string
@@ -40,12 +42,12 @@ export class LocalgateBanner
40
42
  throw new Error(`Unknown route kind: ${JSON.stringify(route.kind)}`);
41
43
  }
42
44
 
43
- // An alias has no process, so there is nothing to restart - what it needs instead is the line that puts
44
- // it back, because the route table is in memory and a proxy restart drops it.
45
+ // An alias has no process, so there is nothing to restart. It used to need the line that put it back
46
+ // after a proxy restart; now that its intent is remembered, the line it needs is the way out.
45
47
  private static next(route: LocalgateRoute): [string, string]
46
48
  {
47
49
  if (route.kind == "app") return ["restart", "localgate restart"];
48
- else if (route.kind == "alias") return ["re-add", `localgate alias ${LocalgateBanner.appName(route)} ${route.port}`];
50
+ else if (route.kind == "alias") return ["remove", `localgate alias --remove ${LocalgateBanner.appName(route)}`];
49
51
  else
50
52
  throw new Error(`Unknown route kind: ${JSON.stringify(route.kind)}`);
51
53
  }
@@ -1,8 +1,12 @@
1
1
  import { LocalgateProxyClient } from "../client/localgateProxyClient.ts";
2
2
  import { LocalgateBanner } from "./localgateBanner.ts";
3
3
  import { LocalgateCloudflareInfo } from "../cloudflare/localgateCloudflareInfo.ts";
4
+ import { LocalgateAliasStore } from "../config/localgateAliasStore.ts";
4
5
  import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
6
+ import { LocalgateNames } from "../config/localgateNames.ts";
5
7
  import { LocalgateProjectConfig } from "../config/localgateProjectConfig.ts";
8
+ import { LocalgateConfigReporter } from "../config/localgateConfigReport.ts";
9
+ import { LocalgateAliasRoute } from "../proxy/localgateAliasRoute.ts";
6
10
  import { LocalgateProxyHost } from "../proxy/localgateProxyHost.ts";
7
11
  import { LocalgateUrl } from "../proxy/localgateUrl.ts";
8
12
  import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
@@ -35,6 +39,7 @@ export class LocalgateCli
35
39
  else if (command == "stop") return LocalgateCli.control(rest, "stop");
36
40
  else if (command == "logs") return LocalgateCli.logs(rest);
37
41
  else if (command == "alias") return LocalgateCli.alias(rest);
42
+ else if (command == "config") return LocalgateCli.config(rest);
38
43
  else if (command == "cloudflare-info") return LocalgateCli.cloudflareInfo();
39
44
  else if (command == "prune") return LocalgateCli.prune();
40
45
  else
@@ -58,6 +63,11 @@ export class LocalgateCli
58
63
  if (routes.length == 0)
59
64
  {
60
65
  process.stdout.write("No routes. Nothing is running, and the proxy is not needed until something is.\n");
66
+
67
+ const dormant = LocalgateAliasStore.load().length;
68
+ if (dormant > 0)
69
+ process.stdout.write(`${dormant} alias(es) will answer again when the proxy next starts.\n`);
70
+
61
71
  return 0;
62
72
  }
63
73
 
@@ -65,7 +75,7 @@ export class LocalgateCli
65
75
  const proxyPort = LocalgateProxyClient.proxyPort();
66
76
  for (const route of routes)
67
77
  {
68
- process.stdout.write(` ${route.names.map(name => LocalgateUrl.forName(name, proxyPort)).join("\n ")}\n`);
78
+ process.stdout.write(` ${LocalgateCli.routeUrls(route, proxyPort).join("\n ")}\n`);
69
79
  process.stdout.write(` -> 127.0.0.1:${route.port} [${route.state}] ${route.kind}`
70
80
  + `${route.debuggerAttached ? " debugger" : ""}\n`);
71
81
  if (route.cwd) process.stdout.write(` ${route.cwd}\n`);
@@ -75,6 +85,38 @@ export class LocalgateCli
75
85
  return 0;
76
86
  }
77
87
 
88
+ // Read-only: what this machine and this project are configured as, and the names that follow from it.
89
+ // Other tools ask for this instead of parsing ~/.localgate/config.json and re-deriving the names, which
90
+ // is how two copies of the same rules start to drift.
91
+ private static config(args: string[]): number
92
+ {
93
+ const asJson = args.includes("--json");
94
+ const directory = args.find(argument => !argument.startsWith("--")) ?? process.cwd();
95
+ const report = LocalgateConfigReporter.build(directory);
96
+
97
+ if (asJson)
98
+ {
99
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
100
+ return 0;
101
+ }
102
+
103
+ process.stdout.write([
104
+ `machine config ${report.machineFilePath}${report.machine ? "" : " (missing - this machine serves .localhost only)"}`,
105
+ `label ${report.machine?.label ?? "-"}`,
106
+ `base domain ${report.machine?.baseDomain ?? "-"}`,
107
+ `lan ip ${report.machine?.lanIp ?? "-"}`,
108
+ `public prefix ${report.machine?.publicPrefix ?? "-"}`,
109
+ `proxy port ${report.proxyPort}`,
110
+ `project ${report.project ? `${report.project.name} (${report.project.mode})` : "-"}`,
111
+ `local name ${report.names?.local ?? "-"}`,
112
+ `lan name ${report.names?.lan ?? "-"}`,
113
+ `public name ${report.names?.public ?? "-"}`,
114
+ `aliases ${report.aliases.filePath} (${report.aliases.count})`,
115
+ ""
116
+ ].join("\n"));
117
+ return 0;
118
+ }
119
+
78
120
  private static async status(args: string[]): Promise<number>
79
121
  {
80
122
  const asJson = args.includes("--json");
@@ -95,7 +137,7 @@ export class LocalgateCli
95
137
  }
96
138
 
97
139
  process.stdout.write([
98
- `${route.names.map(name => LocalgateUrl.forName(name, LocalgateProxyClient.proxyPort())).join("\n")}`,
140
+ LocalgateCli.routeUrls(route, LocalgateProxyClient.proxyPort()).join("\n"),
99
141
  `port 127.0.0.1:${route.port}`,
100
142
  `state ${route.state}`,
101
143
  `mode ${route.mode}`,
@@ -148,6 +190,8 @@ export class LocalgateCli
148
190
 
149
191
  private static async alias(args: string[]): Promise<number>
150
192
  {
193
+ if (args[0] == "--remove") return LocalgateCli.aliasRemove(args[1]);
194
+
151
195
  const [name, portText] = args;
152
196
  const port = Number.parseInt(portText ?? "", 10);
153
197
 
@@ -157,29 +201,30 @@ export class LocalgateCli
157
201
  return 1;
158
202
  }
159
203
 
204
+ // The store applies exactly these two rules when it reads the file back, so anything refused here
205
+ // would otherwise register, print a banner, and be dropped without a word at the next proxy boot.
206
+ if (!LocalgateMachineConfig.isLabel(name) || !LocalgateAliasStore.isPort(port))
207
+ {
208
+ process.stderr.write(`localgate: ${name} ${portText} cannot be an alias. The name must be a DNS `
209
+ + "label (lowercase letters, digits, hyphens) and the port a number from 1 to 65535.\n");
210
+ return 1;
211
+ }
212
+
160
213
  const machine = LocalgateMachineConfig.load();
161
- const names = [`${name}.localhost`];
162
- // An alias gets the shared name too when the machine has one: a browser on another PC loads media
163
- // from these services by absolute URL, so they have to answer on the name that resolves there.
164
- if (machine) names.push(`${name}${LocalgateMachineConfig.externalSuffix(machine)}`);
214
+
215
+ if (port == LocalgateUrl.proxyPort(machine))
216
+ {
217
+ process.stderr.write(`localgate: port ${port} is localgate's own port, so the alias would only `
218
+ + "send requests back to the proxy. Point it at the port the service listens on.\n");
219
+ return 1;
220
+ }
165
221
 
166
222
  await LocalgateProxyClient.ensureRunning();
167
223
 
168
224
  let route: LocalgateRoute;
169
225
  try
170
226
  {
171
- route = await LocalgateProxyClient.register({
172
- names,
173
- port,
174
- kind: "alias",
175
- mode: machine ? "lan" : "local",
176
- cwd: null,
177
- command: null,
178
- controlUrl: null,
179
- runnerPid: null,
180
- childPid: null,
181
- debuggerAttached: false
182
- });
227
+ route = await LocalgateProxyClient.register(LocalgateAliasRoute.registration(name, port, machine));
183
228
  }
184
229
  catch (error)
185
230
  {
@@ -190,10 +235,69 @@ export class LocalgateCli
190
235
  return 1;
191
236
  }
192
237
 
238
+ // Only once the proxy took the name: a refused registration must not leave an entry that the next
239
+ // proxy boot would restore. A disk failure here is worth saying out loud rather than throwing over
240
+ // the banner, because the alias is already live and useful - it just will not come back.
241
+ try
242
+ {
243
+ LocalgateAliasStore.add({ name, port });
244
+ }
245
+ catch (error)
246
+ {
247
+ process.stderr.write(`localgate: ${name} is live, but ${LocalgateAliasStore.filePath()} could not `
248
+ + `be written, so it will not survive a proxy restart: ${String(error)}\n`);
249
+ }
250
+
193
251
  process.stdout.write(LocalgateBanner.render(route, LocalgateProxyClient.proxyPort()));
194
252
  return 0;
195
253
  }
196
254
 
255
+ // Removal has to work with the proxy down, because an alias outliving the proxy is the whole point of
256
+ // persisting it. With nothing listening, dropping the file entry IS the removal: the only other reader
257
+ // of the file is the next proxy boot.
258
+ private static async aliasRemove(argument: string | undefined): Promise<number>
259
+ {
260
+ if (!argument)
261
+ {
262
+ process.stderr.write("localgate: usage is localgate alias --remove <name>\n");
263
+ return 1;
264
+ }
265
+
266
+ // The store knows an alias by the short name it was registered under, while a route answers to its
267
+ // full hostnames too - and those are the names a person reads in `localgate list`. Reduce once, so
268
+ // the route and the file cannot end up disagreeing about what was removed.
269
+ const name = LocalgateNames.shortName(argument);
270
+ const route = await LocalgateProxyClient.resolve({ name });
271
+
272
+ // An app that took an alias's name evicts the route but not the intent, so the entry has to go even
273
+ // here - otherwise the alias comes back at the next proxy boot and nothing can stop it.
274
+ if (route && route.kind != "alias")
275
+ {
276
+ const forgotten = LocalgateAliasStore.remove(name);
277
+ if (forgotten)
278
+ {
279
+ process.stdout.write(`localgate: ${name} is a running dev server, so its route stays. `
280
+ + "The persisted alias of that name was removed.\n");
281
+ return 0;
282
+ }
283
+
284
+ process.stderr.write(`localgate: ${name} is a running dev server, not an alias\n`);
285
+ return 1;
286
+ }
287
+
288
+ if (route) await LocalgateProxyClient.deregister(route.id);
289
+ const dropped = LocalgateAliasStore.remove(name);
290
+
291
+ if (!route && !dropped)
292
+ {
293
+ process.stderr.write(`localgate: no alias named ${name}\n`);
294
+ return 1;
295
+ }
296
+
297
+ process.stdout.write(`localgate: alias ${name} removed\n`);
298
+ return 0;
299
+ }
300
+
197
301
  private static cloudflareInfo(): number
198
302
  {
199
303
  const machine = LocalgateMachineConfig.load();
@@ -205,12 +309,19 @@ export class LocalgateCli
205
309
  }
206
310
 
207
311
  const project = LocalgateProjectConfig.load(process.cwd());
312
+ const publicName = LocalgateNames.publicName(project.name, machine);
313
+ if (!publicName)
314
+ {
315
+ process.stderr.write(`localgate: ${LocalgateMachineConfig.filePath()} has no publicPrefix\n`);
316
+ return 1;
317
+ }
318
+
208
319
  if (project.mode != "internet")
209
320
  process.stdout.write(`Note: this project's mode is "${project.mode}". Set it to "internet" `
210
321
  + "in package.json when you actually want the entries below to be live.\n\n");
211
322
 
212
323
  process.stdout.write(LocalgateCloudflareInfo.render(
213
- `${project.name}${LocalgateMachineConfig.externalSuffix(machine)}`,
324
+ publicName,
214
325
  machine.lanIp,
215
326
  LocalgateUrl.proxyPort(machine)
216
327
  ));
@@ -266,6 +377,13 @@ export class LocalgateCli
266
377
  return 1;
267
378
  }
268
379
 
380
+ private static routeUrls(route: LocalgateRoute, proxyPort: number): string[]
381
+ {
382
+ return route.names.map((name, index) => route.mode == "internet" && index == 2
383
+ ? `https://${name}`
384
+ : LocalgateUrl.forName(name, proxyPort));
385
+ }
386
+
269
387
  private static printUsage(): void
270
388
  {
271
389
  process.stdout.write(
@@ -277,7 +395,10 @@ export class LocalgateCli
277
395
  " localgate restart [app] restart a route's dev server\n" +
278
396
  " localgate stop [app] stop a route's dev server\n" +
279
397
  " localgate logs [app] [--lines N] tail a route's captured output\n" +
280
- " localgate alias <name> <port> register a static route (e.g. a docker service)\n" +
398
+ " localgate alias <name> <port> register a static route (e.g. a docker service); it is\n" +
399
+ " remembered and comes back when the proxy restarts\n" +
400
+ " localgate alias --remove <name> drop a static route and forget it\n" +
401
+ " localgate config [dir] [--json] machine + project config and the names it implies\n" +
281
402
  " localgate cloudflare-info print the DNS and ingress entries to paste\n" +
282
403
  " localgate prune drop routes whose runner is gone\n\n" +
283
404
  "[app] is optional: with no argument a command acts on the route owning the current directory.\n"
@@ -8,6 +8,8 @@ import type { LocalgateRoute, LocalgateRouteRegistration } from "../proxy/localg
8
8
 
9
9
  // Every process other than the proxy reaches the route table through here. The table has no file, so
10
10
  // this client is the only way in - and it is loopback-only, which is what keeps the LAN out of it.
11
+ // Alias intent is the one exception: `localgate alias --remove` edits ~/.localgate/aliases.json itself
12
+ // when the proxy is down, because there is nothing to ask.
11
13
  export class LocalgateProxyClient
12
14
  {
13
15
  private static readonly startTimeoutMsConst = 15_000;
@@ -72,9 +74,10 @@ export class LocalgateProxyClient
72
74
  await LocalgateProxyClient.send("DELETE", `/routes/${id}`);
73
75
  }
74
76
 
75
- static async patch(id: string, patch: Record<string, unknown>): Promise<void>
77
+ static async patch(id: string, patch: Record<string, unknown>): Promise<LocalgateRoute>
76
78
  {
77
- await LocalgateProxyClient.send("PATCH", `/routes/${id}`, patch);
79
+ const payload = await LocalgateProxyClient.send("PATCH", `/routes/${id}`, patch) as { route: LocalgateRoute };
80
+ return payload.route;
78
81
  }
79
82
 
80
83
  static async list(): Promise<LocalgateRoute[]>
@@ -0,0 +1,147 @@
1
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { LocalgateMachineConfig } from "./localgateMachineConfig.ts";
5
+
6
+ export type LocalgatePersistedAlias =
7
+ {
8
+ name: string;
9
+ port: number;
10
+ };
11
+
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.
17
+ export class LocalgateAliasStore
18
+ {
19
+ private static readonly maxPortConst = 65_535;
20
+ private static readonly directoryModeConst = 0o700;
21
+ private static readonly fileModeConst = 0o600;
22
+
23
+ static filePath(): string
24
+ {
25
+ return join(homedir(), ".localgate", "aliases.json");
26
+ }
27
+
28
+ // The one port rule for an alias, so the command that writes an entry and the loader that reads it back
29
+ // cannot disagree about what is storable.
30
+ static isPort(value: number): boolean
31
+ {
32
+ return Number.isInteger(value) && value >= 1 && value <= LocalgateAliasStore.maxPortConst;
33
+ }
34
+
35
+ // Never throws. A hand-edited or half-written file must not take down a proxy boot that every dev
36
+ // server on the machine depends on, so a bad entry is dropped and the rest still load.
37
+ static load(filePath: string = LocalgateAliasStore.filePath()): LocalgatePersistedAlias[]
38
+ {
39
+ let raw: string;
40
+ try
41
+ {
42
+ raw = readFileSync(filePath, "utf8");
43
+ }
44
+ catch (error)
45
+ {
46
+ // A machine that never registered an alias is the ordinary case and says nothing. Anything else -
47
+ // 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")
49
+ process.stderr.write(`localgate: ${filePath} could not be read, continuing without its aliases: ${String(error)}\n`);
50
+ return [];
51
+ }
52
+
53
+ let parsed: unknown;
54
+ try
55
+ {
56
+ parsed = JSON.parse(raw);
57
+ }
58
+ catch
59
+ {
60
+ // Left on disk on purpose: the next add or remove rewrites it, and until then the person can
61
+ // still see what they typed.
62
+ process.stderr.write(`localgate: ${filePath} is not valid JSON, ignoring the aliases in it\n`);
63
+ return [];
64
+ }
65
+
66
+ const entries = (parsed as { aliases?: unknown } | null)?.aliases;
67
+ if (!Array.isArray(entries))
68
+ {
69
+ process.stderr.write(`localgate: ${filePath} has no alias list, ignoring it\n`);
70
+ return [];
71
+ }
72
+
73
+ const aliases: LocalgatePersistedAlias[] = [];
74
+ for (const entry of entries)
75
+ {
76
+ const alias = LocalgateAliasStore.validated(entry, filePath);
77
+ if (alias) aliases.push(alias);
78
+ }
79
+
80
+ return aliases;
81
+ }
82
+
83
+ // Upsert by name, because re-running `localgate alias myapp 8002` moves an existing alias to a new
84
+ // port the same way the registry replaces the live route.
85
+ static add(alias: LocalgatePersistedAlias, filePath: string = LocalgateAliasStore.filePath()): void
86
+ {
87
+ const aliases = LocalgateAliasStore.load(filePath).filter(existing => existing.name != alias.name);
88
+ aliases.push(alias);
89
+ LocalgateAliasStore.write(aliases, filePath);
90
+ }
91
+
92
+ static remove(name: string, filePath: string = LocalgateAliasStore.filePath()): boolean
93
+ {
94
+ const aliases = LocalgateAliasStore.load(filePath);
95
+ const kept = aliases.filter(alias => alias.name != name);
96
+ if (kept.length == aliases.length) return false;
97
+
98
+ LocalgateAliasStore.write(kept, filePath);
99
+ return true;
100
+ }
101
+
102
+ // Throws on a disk failure, unlike `load`: a caller that cannot write has to decide what to tell the
103
+ // user, and a silently dropped write is an alias that goes missing at the next boot.
104
+ private static write(aliases: LocalgatePersistedAlias[], filePath: string): void
105
+ {
106
+ // The file lists this machine's internal services, so it stays readable by its owner alone.
107
+ mkdirSync(dirname(filePath), { recursive: true, mode: LocalgateAliasStore.directoryModeConst });
108
+
109
+ // Write beside the file, flush it, then rename over the target. Losing every alias to a crash
110
+ // halfway through a write is the failure this file exists to prevent, and without the flush the
111
+ // rename can still publish an empty file after a power cut.
112
+ const temporary = `${filePath}.tmp`;
113
+ const handle = openSync(temporary, "w", LocalgateAliasStore.fileModeConst);
114
+ try
115
+ {
116
+ writeSync(handle, `${JSON.stringify({ aliases }, null, 2)}\n`);
117
+ fsyncSync(handle);
118
+ }
119
+ finally
120
+ {
121
+ closeSync(handle);
122
+ }
123
+
124
+ renameSync(temporary, filePath);
125
+ }
126
+
127
+ private static validated(entry: unknown, filePath: string): LocalgatePersistedAlias | null
128
+ {
129
+ const candidate = entry as { name?: unknown; port?: unknown } | null;
130
+ const name = candidate?.name;
131
+ const port = candidate?.port;
132
+
133
+ if (typeof name != "string" || !LocalgateMachineConfig.isLabel(name))
134
+ {
135
+ process.stderr.write(`localgate: ${filePath} holds an alias whose name is not a DNS label, skipping it\n`);
136
+ return null;
137
+ }
138
+
139
+ if (typeof port != "number" || !LocalgateAliasStore.isPort(port))
140
+ {
141
+ process.stderr.write(`localgate: ${filePath} holds alias ${name} without a usable port, skipping it\n`);
142
+ return null;
143
+ }
144
+
145
+ return { name, port };
146
+ }
147
+ }
@@ -0,0 +1,45 @@
1
+ import { LocalgateAliasStore } from "./localgateAliasStore.ts";
2
+ import { LocalgateMachineConfig, type LocalgateMachineSettings } from "./localgateMachineConfig.ts";
3
+ import { LocalgateNames } from "./localgateNames.ts";
4
+ import { LocalgateProjectConfig, type LocalgateMode } from "./localgateProjectConfig.ts";
5
+ import { LocalgateUrl } from "../proxy/localgateUrl.ts";
6
+
7
+ export type LocalgateConfigReport =
8
+ {
9
+ machineFilePath: string;
10
+ machine: LocalgateMachineSettings | null;
11
+ proxyPort: number;
12
+ project: { name: string; mode: LocalgateMode; packageDirectory: string } | null;
13
+ names: { local: string; lan: string | null; public: string | null } | null;
14
+ aliases: { filePath: string; count: number };
15
+ };
16
+
17
+ // Localgate owns the naming and machine-config rules, so anything that needs them can read them from
18
+ // here instead of parsing ~/.localgate/config.json and re-deriving the names. Read-only by design:
19
+ // this reports what is configured, it never writes.
20
+ export class LocalgateConfigReporter
21
+ {
22
+ static build(directory: string | null): LocalgateConfigReport
23
+ {
24
+ const machine = LocalgateMachineConfig.load();
25
+ const report: LocalgateConfigReport = {
26
+ machineFilePath: LocalgateMachineConfig.filePath(),
27
+ machine,
28
+ proxyPort: LocalgateUrl.proxyPort(machine),
29
+ project: null,
30
+ names: null,
31
+ aliases: { filePath: LocalgateAliasStore.filePath(), count: LocalgateAliasStore.load().length }
32
+ };
33
+
34
+ if (directory === null) return report;
35
+
36
+ const project = LocalgateProjectConfig.load(directory);
37
+ report.project = { name: project.name, mode: project.mode, packageDirectory: project.packageDirectory };
38
+ report.names = {
39
+ local: LocalgateNames.local(project.name),
40
+ lan: machine ? LocalgateNames.lan(project.name, machine) : null,
41
+ public: machine ? LocalgateNames.publicName(project.name, machine) : null
42
+ };
43
+ return report;
44
+ }
45
+ }