localgate 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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
 
@@ -180,7 +183,7 @@ A project gets its name from `package.json`, and nothing else is needed to work
180
183
  |---|---|---|
181
184
  | `local` (default) | `myapp.localhost` | this machine |
182
185
  | `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 |
186
+ | `internet` | + `<public-prefix>-myapp.<your-domain>` | local machine, LAN and the configured tunnel |
184
187
 
185
188
  The name is the package name, with a scope dropped (`@org/web` becomes `web`), and it has to be a
186
189
  usable hostname label. When the package name is long or is not what you want to type, override it -
@@ -206,21 +209,24 @@ their own names without either name being in the repository:
206
209
  "label": "dev", // your machine, as a DNS label
207
210
  "baseDomain": "example.com", // a domain whose wildcard resolves to this LAN
208
211
  "lanIp": "192.0.2.10", // the address the proxy also listens on
212
+ "publicPrefix": "pub", // prefix owned by this machine on the public domain
209
213
  "autoRestart": false // see "When a dev server stops answering"
210
214
  }
211
215
  ```
212
216
 
213
- With that file present, `myapp` in mode `lan` also answers on `myapp.dev.example.com`. Browser-facing
217
+ With that file present, `myapp` in mode `lan` also answers on `myapp.dev.example.com`, while mode
218
+ `internet` additionally answers on `pub-myapp.example.com`. Browser-facing
214
219
  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.
220
+ `.localhost` to the name selected by the current mode on the way into the dev server. Public URLs use
221
+ HTTPS and never carry the proxy's internal LAN port. Server-side variables stay on `.localhost`.
218
222
 
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.
223
+ For reaching an app from outside the LAN, `localgate cloudflare-info` prints the exact prefixed DNS
224
+ record and tunnel ingress entry. It prints them and stops: localgate holds no API token and sends
225
+ nothing anywhere. In Atomix projects, use `axtoolsv2 expose <dir> off|network|internet`; AtomixToolsV2
226
+ owns the API calls, project state, and Localgate reload. It retains an existing managed CNAME when
227
+ leaving `internet` and removes only ingress, so the public hostname reaches the tunnel's 404 catch-all
228
+ without DNS recreation delay. Anyone holding an enabled public URL reaches the dev server, which is why
229
+ `internet` is a mode you switch back from.
224
230
 
225
231
  ## When a dev server stops answering
226
232
 
@@ -244,7 +250,7 @@ the names come back without touching a single dev server.
244
250
 
245
251
  ## Design rules
246
252
 
247
- - **Nothing machine-specific is committed.** The label, the domain and the LAN IP live in
253
+ - **Nothing machine-specific is committed.** The label, public prefix, domain and LAN IP live in
248
254
  `~/.localgate/config.json`; a repository carries at most a `package.json` key holding a mode
249
255
  (`local` / `lan` / `internet`) and an optional name. Absent key means `local`, which is names on
250
256
  `.localhost` only.
@@ -14,12 +14,13 @@ export class LocalgateBanner
14
14
 
15
15
  static render(route: LocalgateRoute, proxyPort: number): string
16
16
  {
17
- const [local, shared] = route.names;
17
+ const [local, network, internet] = route.names;
18
18
  const [nextLabel, nextCommand] = LocalgateBanner.next(route);
19
19
 
20
20
  const lines = ["", ` localgate ${LocalgateBanner.appName(route)} · ${LocalgateBanner.subtitle(route)}`, ""];
21
21
 
22
- if (shared) lines.push(LocalgateBanner.row("shared", LocalgateUrl.forName(shared, proxyPort)));
22
+ if (internet) lines.push(LocalgateBanner.row("internet", `https://${internet}`));
23
+ if (network) lines.push(LocalgateBanner.row("network", LocalgateUrl.forName(network, proxyPort)));
23
24
  lines.push(LocalgateBanner.row("local", LocalgateUrl.forName(local, proxyPort)));
24
25
  lines.push("", LocalgateBanner.row("upstream", `127.0.0.1:${route.port}`), LocalgateBanner.row(nextLabel, nextCommand), "");
25
26
 
@@ -2,6 +2,7 @@ import { LocalgateProxyClient } from "../client/localgateProxyClient.ts";
2
2
  import { LocalgateBanner } from "./localgateBanner.ts";
3
3
  import { LocalgateCloudflareInfo } from "../cloudflare/localgateCloudflareInfo.ts";
4
4
  import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
5
+ import { LocalgateNames } from "../config/localgateNames.ts";
5
6
  import { LocalgateProjectConfig } from "../config/localgateProjectConfig.ts";
6
7
  import { LocalgateProxyHost } from "../proxy/localgateProxyHost.ts";
7
8
  import { LocalgateUrl } from "../proxy/localgateUrl.ts";
@@ -65,7 +66,7 @@ export class LocalgateCli
65
66
  const proxyPort = LocalgateProxyClient.proxyPort();
66
67
  for (const route of routes)
67
68
  {
68
- process.stdout.write(` ${route.names.map(name => LocalgateUrl.forName(name, proxyPort)).join("\n ")}\n`);
69
+ process.stdout.write(` ${LocalgateCli.routeUrls(route, proxyPort).join("\n ")}\n`);
69
70
  process.stdout.write(` -> 127.0.0.1:${route.port} [${route.state}] ${route.kind}`
70
71
  + `${route.debuggerAttached ? " debugger" : ""}\n`);
71
72
  if (route.cwd) process.stdout.write(` ${route.cwd}\n`);
@@ -95,7 +96,7 @@ export class LocalgateCli
95
96
  }
96
97
 
97
98
  process.stdout.write([
98
- `${route.names.map(name => LocalgateUrl.forName(name, LocalgateProxyClient.proxyPort())).join("\n")}`,
99
+ LocalgateCli.routeUrls(route, LocalgateProxyClient.proxyPort()).join("\n"),
99
100
  `port 127.0.0.1:${route.port}`,
100
101
  `state ${route.state}`,
101
102
  `mode ${route.mode}`,
@@ -158,10 +159,7 @@ export class LocalgateCli
158
159
  }
159
160
 
160
161
  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)}`);
162
+ const names = LocalgateNames.routeNames(name, machine ? "lan" : "local", machine);
165
163
 
166
164
  await LocalgateProxyClient.ensureRunning();
167
165
 
@@ -205,12 +203,19 @@ export class LocalgateCli
205
203
  }
206
204
 
207
205
  const project = LocalgateProjectConfig.load(process.cwd());
206
+ const publicName = LocalgateNames.publicName(project.name, machine);
207
+ if (!publicName)
208
+ {
209
+ process.stderr.write(`localgate: ${LocalgateMachineConfig.filePath()} has no publicPrefix\n`);
210
+ return 1;
211
+ }
212
+
208
213
  if (project.mode != "internet")
209
214
  process.stdout.write(`Note: this project's mode is "${project.mode}". Set it to "internet" `
210
215
  + "in package.json when you actually want the entries below to be live.\n\n");
211
216
 
212
217
  process.stdout.write(LocalgateCloudflareInfo.render(
213
- `${project.name}${LocalgateMachineConfig.externalSuffix(machine)}`,
218
+ publicName,
214
219
  machine.lanIp,
215
220
  LocalgateUrl.proxyPort(machine)
216
221
  ));
@@ -266,6 +271,13 @@ export class LocalgateCli
266
271
  return 1;
267
272
  }
268
273
 
274
+ private static routeUrls(route: LocalgateRoute, proxyPort: number): string[]
275
+ {
276
+ return route.names.map((name, index) => route.mode == "internet" && index == 2
277
+ ? `https://${name}`
278
+ : LocalgateUrl.forName(name, proxyPort));
279
+ }
280
+
269
281
  private static printUsage(): void
270
282
  {
271
283
  process.stdout.write(
@@ -72,9 +72,10 @@ export class LocalgateProxyClient
72
72
  await LocalgateProxyClient.send("DELETE", `/routes/${id}`);
73
73
  }
74
74
 
75
- static async patch(id: string, patch: Record<string, unknown>): Promise<void>
75
+ static async patch(id: string, patch: Record<string, unknown>): Promise<LocalgateRoute>
76
76
  {
77
- await LocalgateProxyClient.send("PATCH", `/routes/${id}`, patch);
77
+ const payload = await LocalgateProxyClient.send("PATCH", `/routes/${id}`, patch) as { route: LocalgateRoute };
78
+ return payload.route;
78
79
  }
79
80
 
80
81
  static async list(): Promise<LocalgateRoute[]>
@@ -7,6 +7,7 @@ export type LocalgateMachineSettings =
7
7
  label: string;
8
8
  baseDomain: string;
9
9
  lanIp: string;
10
+ publicPrefix: string | null;
10
11
  autoRestart: boolean;
11
12
  // null leaves the port to the platform default. Set it only when the machine has arranged for
12
13
  // something else - a capability that permits 80 on Linux, or another port because 8080 is taken.
@@ -38,14 +39,13 @@ export class LocalgateMachineConfig
38
39
 
39
40
  const parsed = JSON.parse(raw) as Record<string, unknown>;
40
41
 
41
- const label = LocalgateMachineConfig.requireString(parsed, "label", filePath);
42
- if (!LocalgateMachineConfig.labelPatternConst.test(label))
43
- throw new Error(`${filePath}: "label" must be a DNS label (lowercase letters, digits, hyphens), got "${label}"`);
42
+ const label = LocalgateMachineConfig.requireLabel(parsed, "label", filePath);
44
43
 
45
44
  return {
46
45
  label,
47
46
  baseDomain: LocalgateMachineConfig.requireString(parsed, "baseDomain", filePath),
48
47
  lanIp: LocalgateMachineConfig.requireString(parsed, "lanIp", filePath),
48
+ publicPrefix: LocalgateMachineConfig.optionalLabel(parsed, "publicPrefix", filePath),
49
49
  autoRestart: parsed.autoRestart === true,
50
50
  proxyPort: LocalgateMachineConfig.optionalPort(parsed, "proxyPort", filePath)
51
51
  };
@@ -65,6 +65,21 @@ export class LocalgateMachineConfig
65
65
  return `.${settings.label}.${settings.baseDomain}`;
66
66
  }
67
67
 
68
+ private static optionalLabel(parsed: Record<string, unknown>, key: string, filePath: string): string | null
69
+ {
70
+ const value = parsed[key];
71
+ if (value === undefined || value === null) return null;
72
+ return LocalgateMachineConfig.requireLabel(parsed, key, filePath);
73
+ }
74
+
75
+ private static requireLabel(parsed: Record<string, unknown>, key: string, filePath: string): string
76
+ {
77
+ const value = LocalgateMachineConfig.requireString(parsed, key, filePath);
78
+ if (!LocalgateMachineConfig.labelPatternConst.test(value))
79
+ throw new Error(`${filePath}: "${key}" must be a DNS label (lowercase letters, digits, hyphens), got "${value}"`);
80
+ return value;
81
+ }
82
+
68
83
  private static requireString(parsed: Record<string, unknown>, key: string, filePath: string): string
69
84
  {
70
85
  const value = parsed[key];
@@ -0,0 +1,52 @@
1
+ import type { LocalgateMachineSettings } from "./localgateMachineConfig.ts";
2
+ import type { LocalgateMode } from "./localgateProjectConfig.ts";
3
+
4
+ export class LocalgateNames
5
+ {
6
+ private static readonly dnsLabelMaxLengthConst = 63;
7
+
8
+ static local(projectName: string): string
9
+ {
10
+ return `${projectName}.localhost`;
11
+ }
12
+
13
+ static lan(projectName: string, machine: LocalgateMachineSettings): string
14
+ {
15
+ return `${projectName}.${machine.label}.${machine.baseDomain}`;
16
+ }
17
+
18
+ static publicName(projectName: string, machine: LocalgateMachineSettings): string | null
19
+ {
20
+ if (!machine.publicPrefix) return null;
21
+
22
+ const label = `${machine.publicPrefix}-${projectName}`;
23
+ if (label.length > LocalgateNames.dnsLabelMaxLengthConst)
24
+ throw new Error(`public hostname label "${label}" is longer than ${LocalgateNames.dnsLabelMaxLengthConst} characters`);
25
+ return `${label}.${machine.baseDomain}`;
26
+ }
27
+
28
+ static routeNames(projectName: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null): string[]
29
+ {
30
+ const local = LocalgateNames.local(projectName);
31
+ if (mode == "local") return [local];
32
+ else if (mode == "lan") return machine ? [local, LocalgateNames.lan(projectName, machine)] : [local];
33
+ else if (mode == "internet")
34
+ {
35
+ if (!machine) return [local];
36
+ const publicName = LocalgateNames.publicName(projectName, machine);
37
+ return publicName ? [local, LocalgateNames.lan(projectName, machine), publicName] : [local, LocalgateNames.lan(projectName, machine)];
38
+ }
39
+ else
40
+ throw new Error(`unknown localgate mode: ${JSON.stringify(mode)}`);
41
+ }
42
+
43
+ static browserName(projectName: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null): string
44
+ {
45
+ if (mode == "local") return LocalgateNames.local(projectName);
46
+ else if (mode == "lan") return machine ? LocalgateNames.lan(projectName, machine) : LocalgateNames.local(projectName);
47
+ else if (mode == "internet")
48
+ return machine ? LocalgateNames.publicName(projectName, machine) ?? LocalgateNames.lan(projectName, machine) : LocalgateNames.local(projectName);
49
+ else
50
+ throw new Error(`unknown localgate mode: ${JSON.stringify(mode)}`);
51
+ }
52
+ }
@@ -2,12 +2,11 @@ import type { IncomingHttpHeaders } from "node:http";
2
2
 
3
3
  // Next.js blocks cross-origin requests to its dev endpoints unless the origin is allow-listed, and it
4
4
  // allows `**.localhost` unconditionally. It inspects Origin (and Referer for no-cors requests), never
5
- // Host, and only on `/_next/*` and `/__nextjs*`. Mapping the external suffix back to `.localhost` on
6
- // exactly those requests keeps HMR and dev assets working from a shared name, with no
5
+ // Host, and only on `/_next/*` and `/__nextjs*`. Mapping the name used for this request back to the
6
+ // route's canonical `.localhost` name keeps HMR and dev assets working from LAN and public names, with no
7
7
  // `allowedDevOrigins` entry in any project - which is what keeps our domain out of every repository.
8
8
  export class LocalgateHeaderRewrite
9
9
  {
10
- private static readonly localSuffixConst = ".localhost";
11
10
  private static readonly internalPrefixesConst = ["/_next", "/__nextjs"];
12
11
 
13
12
  static isInternalPath(requestUrl: string): boolean
@@ -16,21 +15,24 @@ export class LocalgateHeaderRewrite
16
15
  return LocalgateHeaderRewrite.internalPrefixesConst.some(prefix => path.startsWith(prefix));
17
16
  }
18
17
 
19
- static apply(requestUrl: string, headers: IncomingHttpHeaders, externalSuffix: string | null): void
18
+ static apply(requestUrl: string, headers: IncomingHttpHeaders, requestHost: string, canonicalName: string): void
20
19
  {
21
- if (!externalSuffix || !LocalgateHeaderRewrite.isInternalPath(requestUrl)) return;
20
+ if (!LocalgateHeaderRewrite.isInternalPath(requestUrl)) return;
21
+
22
+ const requestHostname = LocalgateHeaderRewrite.hostnameOf(requestHost);
23
+ if (!requestHostname) return;
22
24
 
23
25
  for (const name of ["origin", "referer"] as const)
24
26
  {
25
27
  const value = headers[name];
26
28
  if (typeof value != "string") continue;
27
29
 
28
- const rewritten = LocalgateHeaderRewrite.toLocalName(value, externalSuffix);
30
+ const rewritten = LocalgateHeaderRewrite.toCanonicalName(value, requestHostname, canonicalName);
29
31
  if (rewritten) headers[name] = rewritten;
30
32
  }
31
33
  }
32
34
 
33
- private static toLocalName(value: string, externalSuffix: string): string | null
35
+ private static toCanonicalName(value: string, requestHostname: string, canonicalName: string): string | null
34
36
  {
35
37
  let url: URL;
36
38
  try
@@ -42,11 +44,25 @@ export class LocalgateHeaderRewrite
42
44
  return null;
43
45
  }
44
46
 
45
- if (!url.hostname.endsWith(externalSuffix)) return null;
47
+ if (url.hostname.toLowerCase() != requestHostname) return null;
46
48
 
47
- const label = url.hostname.slice(0, -externalSuffix.length);
48
- if (label.length == 0) return null;
49
+ const authorityStart = value.indexOf("://") + 3;
50
+ if (authorityStart < 3) return null;
51
+ const suffixOffset = value.slice(authorityStart).search(/[/?#]/);
52
+ const authorityEnd = suffixOffset < 0 ? value.length : authorityStart + suffixOffset;
53
+ const authority = `${canonicalName}${url.port ? `:${url.port}` : ""}`;
54
+ return `${value.slice(0, authorityStart)}${authority}${value.slice(authorityEnd)}`;
55
+ }
49
56
 
50
- return value.replace(url.hostname, `${label}${LocalgateHeaderRewrite.localSuffixConst}`);
57
+ private static hostnameOf(host: string): string | null
58
+ {
59
+ try
60
+ {
61
+ return new URL(`http://${host}`).hostname.toLowerCase();
62
+ }
63
+ catch
64
+ {
65
+ return null;
66
+ }
51
67
  }
52
68
  }
@@ -10,7 +10,6 @@ export type LocalgateProxyOptions =
10
10
  port: number;
11
11
  // null keeps the proxy on loopback only, which is what a machine with no localgate config gets.
12
12
  lanIp: string | null;
13
- externalSuffix: string | null;
14
13
  gracePeriodMs: number;
15
14
  onIdle: () => void;
16
15
  };
@@ -129,7 +128,7 @@ export class LocalgateProxy
129
128
  private forward(route: LocalgateRoute, request: IncomingMessage, response: ServerResponse): void
130
129
  {
131
130
  const headers = { ...request.headers };
132
- LocalgateHeaderRewrite.apply(request.url ?? "/", headers, this.options.externalSuffix);
131
+ LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
133
132
 
134
133
  const upstream = httpRequest({
135
134
  host: "127.0.0.1",
@@ -193,7 +192,7 @@ export class LocalgateProxy
193
192
  }
194
193
 
195
194
  const headers = { ...request.headers };
196
- LocalgateHeaderRewrite.apply(request.url ?? "/", headers, this.options.externalSuffix);
195
+ LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
197
196
 
198
197
  const upstream = httpRequest({
199
198
  host: "127.0.0.1",
@@ -25,7 +25,6 @@ export class LocalgateProxyHost
25
25
  {
26
26
  port,
27
27
  lanIp: machine?.lanIp ?? null,
28
- externalSuffix: machine ? LocalgateMachineConfig.externalSuffix(machine) : null,
29
28
  gracePeriodMs: LocalgateProxyHost.gracePeriodMsConst,
30
29
  onIdle: () =>
31
30
  {
@@ -164,10 +164,22 @@ export class LocalgateRegistry
164
164
  return best;
165
165
  }
166
166
 
167
- update(id: string, patch: Partial<Pick<LocalgateRoute, "state" | "lastResponseAt" | "childPid" | "debuggerAttached">>): LocalgateRoute
167
+ update(id: string, patch: Partial<Pick<LocalgateRoute,
168
+ "names" | "mode" | "state" | "lastResponseAt" | "childPid" | "debuggerAttached">>): LocalgateRoute
168
169
  {
169
170
  const route = this.routes.get(id);
170
171
  if (!route) throw new Error(`unknown route ${id}`);
172
+
173
+ if (patch.names)
174
+ {
175
+ if (patch.names.length == 0) throw new Error("a route needs at least one name");
176
+ for (const name of patch.names)
177
+ {
178
+ const existing = this.findByName(name);
179
+ if (existing && existing.id != id) throw new LocalgateRouteConflictError(existing);
180
+ }
181
+ }
182
+
171
183
  Object.assign(route, patch);
172
184
  return route;
173
185
  }
@@ -1,3 +1,6 @@
1
+ import type { LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
2
+ import { LocalgateNames } from "../config/localgateNames.ts";
3
+ import type { LocalgateMode } from "../config/localgateProjectConfig.ts";
1
4
  import { LocalgateUrl } from "../proxy/localgateUrl.ts";
2
5
 
3
6
  // Keeps repositories machine-agnostic: a committed env file says `.localhost` everywhere, and what this
@@ -15,7 +18,8 @@ export class LocalgateEnvRewrite
15
18
  private static readonly localSuffixConst = ".localhost";
16
19
  private static readonly browserFacingNamesConst = ["AUTH_URL", "NEXTAUTH_URL"];
17
20
 
18
- static apply(env: NodeJS.ProcessEnv, externalSuffix: string | null, proxyPort: number): NodeJS.ProcessEnv
21
+ static apply(env: NodeJS.ProcessEnv, mode: LocalgateMode, machine: LocalgateMachineSettings | null,
22
+ proxyPort: number): NodeJS.ProcessEnv
19
23
  {
20
24
  const result: NodeJS.ProcessEnv = { ...env };
21
25
 
@@ -23,7 +27,7 @@ export class LocalgateEnvRewrite
23
27
  {
24
28
  if (!value || !LocalgateEnvRewrite.isBrowserFacing(key)) continue;
25
29
 
26
- const rewritten = LocalgateEnvRewrite.rewriteAuthority(value, externalSuffix, proxyPort);
30
+ const rewritten = LocalgateEnvRewrite.rewriteAuthority(value, mode, machine, proxyPort);
27
31
  if (rewritten) result[key] = rewritten;
28
32
  }
29
33
 
@@ -41,7 +45,8 @@ export class LocalgateEnvRewrite
41
45
  // keeps its exact original shape - notably no trailing slash appears on a bare origin, which app code
42
46
  // concatenates onto. A port already in the value is replaced rather than kept: behind a proxy that
43
47
  // multiplexes by name, a browser-facing URL has exactly one correct port.
44
- private static rewriteAuthority(value: string, externalSuffix: string | null, proxyPort: number): string | null
48
+ private static rewriteAuthority(value: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null,
49
+ proxyPort: number): string | null
45
50
  {
46
51
  let url: URL;
47
52
  try
@@ -58,9 +63,14 @@ export class LocalgateEnvRewrite
58
63
  const label = url.hostname.slice(0, -LocalgateEnvRewrite.localSuffixConst.length);
59
64
  if (label.length == 0) return null;
60
65
 
61
- const name = `${label}${externalSuffix ?? LocalgateEnvRewrite.localSuffixConst}`;
62
- const authority = LocalgateUrl.forName(name, proxyPort).replace("http://", "");
66
+ const name = LocalgateNames.browserName(label, mode, machine);
67
+ const publiclyExposed = mode == "internet" && machine?.publicPrefix;
68
+ const browserPort = publiclyExposed ? 80 : proxyPort;
69
+ const authority = LocalgateUrl.forName(name, browserPort).replace("http://", "");
70
+ const protocol = publiclyExposed && (url.protocol == "http:" || url.protocol == "https:") ? "https:" : url.protocol;
63
71
 
64
- return url.host == authority ? null : value.replace(url.host, authority);
72
+ if (url.host == authority && url.protocol == protocol) return null;
73
+ const withAuthority = value.replace(url.host, authority);
74
+ return `${protocol}${withAuthority.slice(url.protocol.length)}`;
65
75
  }
66
76
  }
@@ -6,13 +6,21 @@ import { join } from "node:path";
6
6
  import { createInterface } from "node:readline/promises";
7
7
  import { LocalgateBanner } from "../cli/localgateBanner.ts";
8
8
  import { LocalgateProxyClient } from "../client/localgateProxyClient.ts";
9
- import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
9
+ import { LocalgateMachineConfig, type LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
10
+ import { LocalgateNames } from "../config/localgateNames.ts";
10
11
  import { LocalgateProjectConfig, type LocalgateProjectSettings } from "../config/localgateProjectConfig.ts";
11
12
  import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
12
13
  import { LocalgateUrl } from "../proxy/localgateUrl.ts";
13
14
  import { LocalgateEnvRewrite } from "./localgateEnvRewrite.ts";
14
15
  import { LocalgateProcessTree } from "./localgateProcessTree.ts";
15
16
 
17
+ type LocalgateRunnerRuntime =
18
+ {
19
+ project: LocalgateProjectSettings;
20
+ machine: LocalgateMachineSettings | null;
21
+ names: string[];
22
+ };
23
+
16
24
  // Runs inside the editor's debug terminal and owns the dev process, which is the part an editor cannot
17
25
  // give away: the terminal keeps the debugger attached, while `localgate restart` swaps the child
18
26
  // underneath without touching the terminal, the route or the port.
@@ -25,6 +33,7 @@ export class LocalgateRunner
25
33
  private child: ChildProcess | null = null;
26
34
  private controlServer: Server | null = null;
27
35
  private route: LocalgateRoute | null = null;
36
+ private runtime: LocalgateRunnerRuntime | null = null;
28
37
  private readonly logs: string[] = [];
29
38
  private stopping = false;
30
39
  private restarting = false;
@@ -97,6 +106,11 @@ export class LocalgateRunner
97
106
  return command.map(part => /[\s"]/.test(part) ? `"${part.replace(/"/g, '\\"')}"` : part).join(" ");
98
107
  }
99
108
 
109
+ static routeRegistrationMatches(route: LocalgateRoute, registered: LocalgateRoute | null, runnerPid: number): boolean
110
+ {
111
+ return registered?.runnerPid == runnerPid && registered.controlUrl == route.controlUrl;
112
+ }
113
+
100
114
  static async freePort(): Promise<number>
101
115
  {
102
116
  return new Promise<number>((resolve, reject) =>
@@ -122,27 +136,21 @@ export class LocalgateRunner
122
136
  {
123
137
  if (this.command.length == 0) throw new Error("localgate run needs a command, for example: localgate run npm run dev");
124
138
 
125
- const project = LocalgateProjectConfig.load(this.directory);
139
+ const runtime = this.loadRuntime();
126
140
 
127
- const blocked = await this.clearPredecessor(project);
141
+ const blocked = await this.clearPredecessor(runtime.project);
128
142
  if (blocked != 0) return blocked;
129
143
 
130
- const machine = LocalgateMachineConfig.load();
131
- const external = machine && project.mode != "local" ? LocalgateMachineConfig.externalSuffix(machine) : null;
132
-
133
- const names = [`${project.name}.localhost`];
134
- if (external) names.push(`${project.name}${external}`);
135
-
136
144
  const port = await LocalgateRunner.freePort();
137
145
  const controlUrl = await this.startControlServer();
138
146
 
139
147
  await LocalgateProxyClient.ensureRunning();
140
148
  const route = await LocalgateProxyClient.register({
141
- names,
149
+ names: runtime.names,
142
150
  port,
143
151
  kind: "app",
144
- mode: project.mode,
145
- cwd: project.packageDirectory,
152
+ mode: runtime.project.mode,
153
+ cwd: runtime.project.packageDirectory,
146
154
  command: this.command.join(" "),
147
155
  controlUrl,
148
156
  runnerPid: process.pid,
@@ -150,13 +158,14 @@ export class LocalgateRunner
150
158
  debuggerAttached: LocalgateRunner.debuggerAttached()
151
159
  });
152
160
  this.route = route;
161
+ this.runtime = runtime;
153
162
 
154
163
  process.stdout.write(LocalgateBanner.render(route, LocalgateProxyClient.proxyPort()));
155
164
 
156
165
  this.installSignalHandlers();
157
166
  const heartbeat = this.startHeartbeat();
158
167
 
159
- const finished = this.spawnChild(port, project.packageDirectory, external);
168
+ const finished = this.spawnChild(port);
160
169
  await finished;
161
170
 
162
171
  clearInterval(heartbeat);
@@ -295,12 +304,16 @@ export class LocalgateRunner
295
304
  throw new Error(`${route.names[0]} still holds 127.0.0.1:${route.port} - stop it by hand`);
296
305
  }
297
306
 
298
- private spawnChild(port: number, packageDirectory: string, external: string | null): Promise<void>
307
+ private spawnChild(port: number): Promise<void>
299
308
  {
300
- const scripts = LocalgateRunner.readScripts(packageDirectory);
309
+ const runtime = this.runtime;
310
+ if (!runtime) throw new Error("localgate runtime is not configured");
311
+
312
+ const scripts = LocalgateRunner.readScripts(runtime.project.packageDirectory);
301
313
  const command = LocalgateRunner.withPortFlag(this.command, scripts, port);
302
314
 
303
- const env = LocalgateEnvRewrite.apply(process.env, external, LocalgateProxyClient.proxyPort());
315
+ const env = LocalgateEnvRewrite.apply(process.env, runtime.project.mode, runtime.machine,
316
+ LocalgateProxyClient.proxyPort());
304
317
  env.PORT = String(port);
305
318
 
306
319
  // One command string rather than a command plus an args array: `npm run dev` on Windows is a .cmd,
@@ -320,7 +333,10 @@ export class LocalgateRunner
320
333
  });
321
334
 
322
335
  this.child = child;
323
- if (this.route) void LocalgateProxyClient.patch(this.route.id, { childPid: child.pid ?? null }).catch(() => {});
336
+ if (this.route)
337
+ void LocalgateProxyClient.patch(this.route.id, { childPid: child.pid ?? null })
338
+ .then(route => { this.route = route; })
339
+ .catch(() => {});
324
340
 
325
341
  child.stdout?.on("data", chunk => this.absorb(chunk as Buffer, process.stdout));
326
342
  child.stderr?.on("data", chunk => this.absorb(chunk as Buffer, process.stderr));
@@ -334,7 +350,7 @@ export class LocalgateRunner
334
350
  if (this.restarting)
335
351
  {
336
352
  this.restarting = false;
337
- resolve(this.spawnChild(port, packageDirectory, external));
353
+ resolve(this.spawnChild(port));
338
354
  return;
339
355
  }
340
356
 
@@ -349,6 +365,12 @@ export class LocalgateRunner
349
365
  const child = this.child;
350
366
  if (!child?.pid || !this.route) throw new Error("nothing to restart");
351
367
 
368
+ const runtime = this.loadRuntime();
369
+ this.route = await LocalgateProxyClient.patch(this.route.id, {
370
+ names: runtime.names,
371
+ mode: runtime.project.mode
372
+ });
373
+ this.runtime = runtime;
352
374
  this.restarting = true;
353
375
  await LocalgateProcessTree.killTree(child.pid, this.route.port);
354
376
  }
@@ -422,8 +444,9 @@ export class LocalgateRunner
422
444
  });
423
445
  }
424
446
 
425
- // The proxy holds the route table in memory, so if it dies the route dies with it. Re-registering on a
426
- // failed ping keeps a running dev server reachable without the developer noticing anything happened.
447
+ // The proxy holds the route table in memory, so if it dies the route dies with it. Another runner may
448
+ // start the proxy before this heartbeat, so a successful ping is not enough: this runner verifies that
449
+ // its own route is present and re-registers when it is missing.
427
450
  private startHeartbeat(): NodeJS.Timeout
428
451
  {
429
452
  const timer = setInterval(() =>
@@ -431,7 +454,13 @@ export class LocalgateRunner
431
454
  void (async () =>
432
455
  {
433
456
  if (this.stopping || !this.route) return;
434
- if (await LocalgateProxyClient.ping()) return;
457
+
458
+ const registered = await LocalgateProxyClient.resolve({ name: this.route.names[0] }).catch(() => null);
459
+ if (LocalgateRunner.routeRegistrationMatches(this.route, registered, process.pid))
460
+ {
461
+ this.route = registered;
462
+ return;
463
+ }
435
464
 
436
465
  try
437
466
  {
@@ -486,6 +515,7 @@ export class LocalgateRunner
486
515
  {
487
516
  await LocalgateProxyClient.deregister(this.route.id).catch(() => {});
488
517
  this.route = null;
518
+ this.runtime = null;
489
519
  }
490
520
 
491
521
  if (this.controlServer)
@@ -508,4 +538,11 @@ export class LocalgateRunner
508
538
  return {};
509
539
  }
510
540
  }
541
+
542
+ private loadRuntime(): LocalgateRunnerRuntime
543
+ {
544
+ const project = LocalgateProjectConfig.load(this.directory);
545
+ const machine = LocalgateMachineConfig.load();
546
+ return { project, machine, names: LocalgateNames.routeNames(project.name, project.mode, machine) };
547
+ }
511
548
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "localgate",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Stable names for local dev servers: one port 80 multiplexed by Host, plus an API that can restart a dev server owned by your editor.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",