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.
@@ -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,28 @@ export class LocalgateMachineConfig
65
65
  return `.${settings.label}.${settings.baseDomain}`;
66
66
  }
67
67
 
68
+ // The alias store validates names against the same rule, and two copies of a DNS-label regex is how
69
+ // one of them ends up accepting a name the proxy will never serve.
70
+ static isLabel(value: string): boolean
71
+ {
72
+ return LocalgateMachineConfig.labelPatternConst.test(value);
73
+ }
74
+
75
+ private static optionalLabel(parsed: Record<string, unknown>, key: string, filePath: string): string | null
76
+ {
77
+ const value = parsed[key];
78
+ if (value === undefined || value === null) return null;
79
+ return LocalgateMachineConfig.requireLabel(parsed, key, filePath);
80
+ }
81
+
82
+ private static requireLabel(parsed: Record<string, unknown>, key: string, filePath: string): string
83
+ {
84
+ const value = LocalgateMachineConfig.requireString(parsed, key, filePath);
85
+ if (!LocalgateMachineConfig.labelPatternConst.test(value))
86
+ throw new Error(`${filePath}: "${key}" must be a DNS label (lowercase letters, digits, hyphens), got "${value}"`);
87
+ return value;
88
+ }
89
+
68
90
  private static requireString(parsed: Record<string, unknown>, key: string, filePath: string): string
69
91
  {
70
92
  const value = parsed[key];
@@ -0,0 +1,59 @@
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
+ // The short name a person types, from any of the names a route answers to. Every layer needs it - the
29
+ // banner, the proxy's error pages, the CLI - and each one deriving it again is how they drift apart.
30
+ static shortName(hostname: string): string
31
+ {
32
+ return hostname.split(".")[0];
33
+ }
34
+
35
+ static routeNames(projectName: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null): string[]
36
+ {
37
+ const local = LocalgateNames.local(projectName);
38
+ if (mode == "local") return [local];
39
+ else if (mode == "lan") return machine ? [local, LocalgateNames.lan(projectName, machine)] : [local];
40
+ else if (mode == "internet")
41
+ {
42
+ if (!machine) return [local];
43
+ const publicName = LocalgateNames.publicName(projectName, machine);
44
+ return publicName ? [local, LocalgateNames.lan(projectName, machine), publicName] : [local, LocalgateNames.lan(projectName, machine)];
45
+ }
46
+ else
47
+ throw new Error(`unknown localgate mode: ${JSON.stringify(mode)}`);
48
+ }
49
+
50
+ static browserName(projectName: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null): string
51
+ {
52
+ if (mode == "local") return LocalgateNames.local(projectName);
53
+ else if (mode == "lan") return machine ? LocalgateNames.lan(projectName, machine) : LocalgateNames.local(projectName);
54
+ else if (mode == "internet")
55
+ return machine ? LocalgateNames.publicName(projectName, machine) ?? LocalgateNames.lan(projectName, machine) : LocalgateNames.local(projectName);
56
+ else
57
+ throw new Error(`unknown localgate mode: ${JSON.stringify(mode)}`);
58
+ }
59
+ }
@@ -0,0 +1,46 @@
1
+ import { LocalgateNames } from "../config/localgateNames.ts";
2
+ import type { LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
3
+ import type { LocalgatePersistedAlias } from "../config/localgateAliasStore.ts";
4
+ import type { LocalgateMode } from "../config/localgateProjectConfig.ts";
5
+ import type { LocalgateRegistry, LocalgateRouteRegistration } from "./localgateRegistry.ts";
6
+
7
+ // One builder for the registration an alias produces, shared by the `alias` command and by the proxy's
8
+ // boot restore. Two copies of this literal is how a restored alias ends up subtly different from the one
9
+ // the person registered - a missing name, a different mode - in the half of the flow nobody watches.
10
+ export class LocalgateAliasRoute
11
+ {
12
+ static registration(name: string, port: number, machine: LocalgateMachineSettings | null): LocalgateRouteRegistration
13
+ {
14
+ const mode: LocalgateMode = machine ? "lan" : "local";
15
+
16
+ return {
17
+ names: LocalgateNames.routeNames(name, mode, machine),
18
+ port,
19
+ kind: "alias",
20
+ mode,
21
+ cwd: null,
22
+ command: null,
23
+ controlUrl: null,
24
+ runnerPid: null,
25
+ childPid: null,
26
+ debuggerAttached: false
27
+ };
28
+ }
29
+
30
+ // Replays persisted intent into a fresh table. Kept out of the proxy host so the step that actually
31
+ // fixes a lost alias can be tested without binding a port.
32
+ static restore(registry: LocalgateRegistry, aliases: LocalgatePersistedAlias[],
33
+ machine: LocalgateMachineSettings | null, now: string): string[]
34
+ {
35
+ const restored: string[] = [];
36
+ for (const alias of aliases)
37
+ {
38
+ // The table is empty at boot, so nothing can collide; a name repeated in a hand-edited file
39
+ // replaces the earlier row, the same as re-running the alias command.
40
+ registry.register(LocalgateAliasRoute.registration(alias.name, alias.port, machine), now);
41
+ restored.push(`localgate: restored alias ${alias.name} -> 127.0.0.1:${alias.port}`);
42
+ }
43
+
44
+ return restored;
45
+ }
46
+ }
@@ -8,6 +8,8 @@ export class LocalgateControlApi
8
8
  {
9
9
  static readonly pathPrefixConst = "/__localgate/";
10
10
 
11
+ private static readonly maxPortConst = 65_535;
12
+
11
13
  // onChange lets the proxy re-evaluate whether it still has a reason to run, since the registry itself
12
14
  // is a plain table and emits nothing.
13
15
  constructor(private readonly registry: LocalgateRegistry, private readonly onChange: () => void) {}
@@ -34,6 +36,7 @@ export class LocalgateControlApi
34
36
  if (route == "routes" && method == "POST")
35
37
  {
36
38
  const registration = await LocalgateControlApi.readJson(request) as LocalgateRouteRegistration;
39
+ LocalgateControlApi.checkRegistration(registration);
37
40
  const created = this.registry.register(registration, new Date().toISOString());
38
41
  this.onChange();
39
42
  return LocalgateControlApi.sendJson(response, 201, { route: created });
@@ -72,6 +75,21 @@ export class LocalgateControlApi
72
75
  }
73
76
  }
74
77
 
78
+ // The body is JSON from another process, so it is checked here rather than trusted through the cast.
79
+ // A port outside the dialable range ends the proxy on the first request to that route, and a kind
80
+ // nothing branches on reaches the throwing `else` of every message that switches on it.
81
+ private static checkRegistration(registration: LocalgateRouteRegistration): void
82
+ {
83
+ if (!Array.isArray(registration.names) || registration.names.length == 0)
84
+ throw new Error("a route needs at least one name");
85
+
86
+ if (!Number.isInteger(registration.port) || registration.port < 1 || registration.port > LocalgateControlApi.maxPortConst)
87
+ throw new Error(`port ${JSON.stringify(registration.port)} is not a port a route can point at`);
88
+
89
+ if (registration.kind != "app" && registration.kind != "alias")
90
+ throw new Error(`unknown route kind: ${JSON.stringify(registration.kind)}`);
91
+ }
92
+
75
93
  private static async readJson(request: IncomingMessage): Promise<unknown>
76
94
  {
77
95
  const chunks: Buffer[] = [];
@@ -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
  }
@@ -1,3 +1,4 @@
1
+ import { LocalgateNames } from "../config/localgateNames.ts";
1
2
  import type { LocalgateRegistry, LocalgateRoute } from "./localgateRegistry.ts";
2
3
 
3
4
  export type LocalgateRestartRequest = (route: LocalgateRoute) => Promise<void>;
@@ -57,31 +58,61 @@ export class LocalgateHealth
57
58
  this.registry.update(route.id, { state: withinGrace ? "starting" : "dead" });
58
59
  }
59
60
 
61
+ // `localgate restart` refuses an alias, because there is no process localgate owns to restart, so the
62
+ // two kinds cannot share the closing advice.
60
63
  unresponsiveMessage(route: LocalgateRoute): string
61
64
  {
62
- const target = route.cwd ?? route.names[0];
63
- return [
65
+ const stalled = [
64
66
  `localgate: ${route.names[0]} is not responding.`,
65
67
  "",
66
- `The dev server accepted the connection but did not answer ${LocalgateHealth.failuresBeforeUnresponsiveConst} requests in a row`,
68
+ `The server accepted the connection but did not answer ${LocalgateHealth.failuresBeforeUnresponsiveConst} requests in a row`,
67
69
  `(${LocalgateHealth.requestTimeoutMsConst / 1000} s each). It is wedged, or it is paused in a debugger.`,
68
- "",
69
- "Restart it with:",
70
- ` localgate restart ${route.names[0].split(".")[0]}`,
71
- ` (or run localgate restart in ${target})`,
72
70
  ""
73
- ].join("\n");
71
+ ];
72
+
73
+ if (route.kind == "app")
74
+ return [
75
+ ...stalled,
76
+ "Restart it with:",
77
+ ` localgate restart ${LocalgateNames.shortName(route.names[0])}`,
78
+ ` (or run localgate restart in ${route.cwd ?? route.names[0]})`,
79
+ ""
80
+ ].join("\n");
81
+ else if (route.kind == "alias")
82
+ return [
83
+ ...stalled,
84
+ `The alias points at 127.0.0.1:${route.port}, a process localgate does not own, so restart it`,
85
+ "yourself. Drop the alias with:",
86
+ ` localgate alias --remove ${LocalgateNames.shortName(route.names[0])}`,
87
+ ""
88
+ ].join("\n");
89
+ else
90
+ throw new Error(`Unknown route kind: ${JSON.stringify(route.kind)}`);
74
91
  }
75
92
 
93
+ // An alias points at a process localgate does not own, so neither half of the app advice applies to it:
94
+ // there is no editor to start it from, and `prune` deliberately leaves aliases alone.
76
95
  deadMessage(route: LocalgateRoute): string
77
96
  {
78
- return [
79
- `localgate: nothing is listening for ${route.names[0]}.`,
80
- "",
81
- "The route is registered but its dev server is gone. Start it again from your editor,",
82
- "or run localgate prune to drop the route.",
83
- ""
84
- ].join("\n");
97
+ if (route.kind == "app")
98
+ return [
99
+ `localgate: nothing is listening for ${route.names[0]}.`,
100
+ "",
101
+ "The route is registered but its dev server is gone. Start it again from your editor,",
102
+ "or run localgate prune to drop the route.",
103
+ ""
104
+ ].join("\n");
105
+ else if (route.kind == "alias")
106
+ return [
107
+ `localgate: nothing is listening for ${route.names[0]}.`,
108
+ "",
109
+ `The alias points at 127.0.0.1:${route.port} and nothing answers there. Start whatever should`,
110
+ "listen on that port, or drop the alias with:",
111
+ ` localgate alias --remove ${LocalgateNames.shortName(route.names[0])}`,
112
+ ""
113
+ ].join("\n");
114
+ else
115
+ throw new Error(`Unknown route kind: ${JSON.stringify(route.kind)}`);
85
116
  }
86
117
 
87
118
  startingMessage(route: LocalgateRoute): string
@@ -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
  };
@@ -128,8 +127,17 @@ export class LocalgateProxy
128
127
 
129
128
  private forward(route: LocalgateRoute, request: IncomingMessage, response: ServerResponse): void
130
129
  {
130
+ // A route pointing at the proxy's own port turns every listener into a bridge to the loopback one:
131
+ // the request comes back in as loopback, so a LAN caller reaches the control API, and any other path
132
+ // loops until the machine runs out of sockets. Refused here rather than at each registration point,
133
+ // because this is the one place every route is dialled from.
134
+ if (this.boundPorts().includes(route.port))
135
+ return LocalgateProxy.sendText(response, 502, `localgate: ${route.names[0]} points at localgate's own `
136
+ + `port ${route.port}, which would only send the request back here. Point it at the port the `
137
+ + "service actually listens on.\n");
138
+
131
139
  const headers = { ...request.headers };
132
- LocalgateHeaderRewrite.apply(request.url ?? "/", headers, this.options.externalSuffix);
140
+ LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
133
141
 
134
142
  const upstream = httpRequest({
135
143
  host: "127.0.0.1",
@@ -193,7 +201,7 @@ export class LocalgateProxy
193
201
  }
194
202
 
195
203
  const headers = { ...request.headers };
196
- LocalgateHeaderRewrite.apply(request.url ?? "/", headers, this.options.externalSuffix);
204
+ LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
197
205
 
198
206
  const upstream = httpRequest({
199
207
  host: "127.0.0.1",
@@ -1,4 +1,6 @@
1
- import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
1
+ import { LocalgateAliasStore } from "../config/localgateAliasStore.ts";
2
+ import { LocalgateMachineConfig, type LocalgateMachineSettings } from "../config/localgateMachineConfig.ts";
3
+ import { LocalgateAliasRoute } from "./localgateAliasRoute.ts";
2
4
  import { LocalgateUrl } from "./localgateUrl.ts";
3
5
  import { LocalgateControlApi } from "./localgateControlApi.ts";
4
6
  import { LocalgateHealth } from "./localgateHealth.ts";
@@ -25,7 +27,6 @@ export class LocalgateProxyHost
25
27
  {
26
28
  port,
27
29
  lanIp: machine?.lanIp ?? null,
28
- externalSuffix: machine ? LocalgateMachineConfig.externalSuffix(machine) : null,
29
30
  gracePeriodMs: LocalgateProxyHost.gracePeriodMsConst,
30
31
  onIdle: () =>
31
32
  {
@@ -35,6 +36,8 @@ export class LocalgateProxyHost
35
36
  }
36
37
  );
37
38
 
39
+ LocalgateProxyHost.restoreAliases(registry, machine);
40
+
38
41
  await proxy.start();
39
42
  process.stdout.write(`localgate proxy listening on 127.0.0.1:${port}`
40
43
  + `${machine?.lanIp ? ` and ${machine.lanIp}:${port}` : ""}\n`);
@@ -43,6 +46,14 @@ export class LocalgateProxyHost
43
46
  process.on(signal, () => void proxy.stop().then(() => process.exit(0)));
44
47
  }
45
48
 
49
+ // Runs before `start()`, whose last step is the idle check: routes registered by then keep the fresh
50
+ // proxy from scheduling its own exit, exactly as a live alias does.
51
+ private static restoreAliases(registry: LocalgateRegistry, machine: LocalgateMachineSettings | null): void
52
+ {
53
+ const restored = LocalgateAliasRoute.restore(registry, LocalgateAliasStore.load(), machine, new Date().toISOString());
54
+ for (const line of restored) process.stdout.write(`${line}\n`);
55
+ }
56
+
46
57
  private static async requestRestart(route: LocalgateRoute): Promise<void>
47
58
  {
48
59
  if (!route.controlUrl) throw new Error(`route ${route.names[0]} has no control endpoint`);
@@ -55,7 +55,9 @@ export class LocalgateRouteConflictError extends Error
55
55
 
56
56
  // The table lives in the proxy process and nowhere else: no state file, so there is no lock to take
57
57
  // and no stale row to prune after a crash. Runners and the CLI reach it over the proxy's loopback
58
- // control API, and a route disappears when its owner stops answering.
58
+ // control API, and a route disappears when its owner stops answering. Aliases are the one exception,
59
+ // and only outside this class: they have no owner to re-register them, so their INTENT is kept in
60
+ // ~/.localgate/aliases.json and replayed by the proxy host at boot. The table itself still has no file.
59
61
  export class LocalgateRegistry
60
62
  {
61
63
  private static readonly localSuffixConst = ".localhost";
@@ -164,10 +166,22 @@ export class LocalgateRegistry
164
166
  return best;
165
167
  }
166
168
 
167
- update(id: string, patch: Partial<Pick<LocalgateRoute, "state" | "lastResponseAt" | "childPid" | "debuggerAttached">>): LocalgateRoute
169
+ update(id: string, patch: Partial<Pick<LocalgateRoute,
170
+ "names" | "mode" | "state" | "lastResponseAt" | "childPid" | "debuggerAttached">>): LocalgateRoute
168
171
  {
169
172
  const route = this.routes.get(id);
170
173
  if (!route) throw new Error(`unknown route ${id}`);
174
+
175
+ if (patch.names)
176
+ {
177
+ if (patch.names.length == 0) throw new Error("a route needs at least one name");
178
+ for (const name of patch.names)
179
+ {
180
+ const existing = this.findByName(name);
181
+ if (existing && existing.id != id) throw new LocalgateRouteConflictError(existing);
182
+ }
183
+ }
184
+
171
185
  Object.assign(route, patch);
172
186
  return route;
173
187
  }
@@ -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
  }