localgate 0.4.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 +10 -4
- package/logic/cli/localgateBanner.ts +5 -4
- package/logic/cli/localgateCli.ts +123 -14
- package/logic/client/localgateProxyClient.ts +2 -0
- package/logic/config/localgateAliasStore.ts +147 -0
- package/logic/config/localgateConfigReport.ts +45 -0
- package/logic/config/localgateMachineConfig.ts +7 -0
- package/logic/config/localgateNames.ts +7 -0
- package/logic/proxy/localgateAliasRoute.ts +46 -0
- package/logic/proxy/localgateControlApi.ts +18 -0
- package/logic/proxy/localgateHealth.ts +46 -15
- package/logic/proxy/localgateProxy.ts +9 -0
- package/logic/proxy/localgateProxyHost.ts +13 -1
- package/logic/proxy/localgateRegistry.ts +3 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -151,7 +151,9 @@ without asking.
|
|
|
151
151
|
| `localgate restart [app]` | Restart a route's dev server. |
|
|
152
152
|
| `localgate stop [app]` | Stop a route's dev server. |
|
|
153
153
|
| `localgate logs [app] [--lines N]` | Tail a route's captured output. |
|
|
154
|
-
| `localgate alias <name> <port>` | Register a static route, e.g. a docker service. |
|
|
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. |
|
|
155
157
|
| `localgate cloudflare-info` | Print the DNS and ingress entries to paste. |
|
|
156
158
|
| `localgate prune` | Drop routes whose runner is gone. |
|
|
157
159
|
|
|
@@ -246,7 +248,8 @@ externally indistinguishable from a wedged one, and killing it would destroy the
|
|
|
246
248
|
standing in. Reporting always happens; only the restart is behind the switch.
|
|
247
249
|
|
|
248
250
|
If the proxy itself dies, every running app notices within ten seconds and re-registers its route, so
|
|
249
|
-
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.
|
|
250
253
|
|
|
251
254
|
## Design rules
|
|
252
255
|
|
|
@@ -254,8 +257,11 @@ the names come back without touching a single dev server.
|
|
|
254
257
|
`~/.localgate/config.json`; a repository carries at most a `package.json` key holding a mode
|
|
255
258
|
(`local` / `lan` / `internet`) and an optional name. Absent key means `local`, which is names on
|
|
256
259
|
`.localhost` only.
|
|
257
|
-
- **Nothing is persisted.** The route table is live state; after a reboot nothing
|
|
258
|
-
command.
|
|
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>`.
|
|
259
265
|
- **The proxy is not a service.** The first `run` or `alias` starts it, and it exits once the last route
|
|
260
266
|
disappears.
|
|
261
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
|
|
|
@@ -30,7 +31,7 @@ export class LocalgateBanner
|
|
|
30
31
|
// The short name a person types, which is the first label of the local name.
|
|
31
32
|
static appName(route: LocalgateRoute): string
|
|
32
33
|
{
|
|
33
|
-
return route.names[0]
|
|
34
|
+
return LocalgateNames.shortName(route.names[0]);
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
private static subtitle(route: LocalgateRoute): string
|
|
@@ -41,12 +42,12 @@ export class LocalgateBanner
|
|
|
41
42
|
throw new Error(`Unknown route kind: ${JSON.stringify(route.kind)}`);
|
|
42
43
|
}
|
|
43
44
|
|
|
44
|
-
// An alias has no process, so there is nothing to restart
|
|
45
|
-
//
|
|
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.
|
|
46
47
|
private static next(route: LocalgateRoute): [string, string]
|
|
47
48
|
{
|
|
48
49
|
if (route.kind == "app") return ["restart", "localgate restart"];
|
|
49
|
-
else if (route.kind == "alias") return ["
|
|
50
|
+
else if (route.kind == "alias") return ["remove", `localgate alias --remove ${LocalgateBanner.appName(route)}`];
|
|
50
51
|
else
|
|
51
52
|
throw new Error(`Unknown route kind: ${JSON.stringify(route.kind)}`);
|
|
52
53
|
}
|
|
@@ -1,9 +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";
|
|
5
6
|
import { LocalgateNames } from "../config/localgateNames.ts";
|
|
6
7
|
import { LocalgateProjectConfig } from "../config/localgateProjectConfig.ts";
|
|
8
|
+
import { LocalgateConfigReporter } from "../config/localgateConfigReport.ts";
|
|
9
|
+
import { LocalgateAliasRoute } from "../proxy/localgateAliasRoute.ts";
|
|
7
10
|
import { LocalgateProxyHost } from "../proxy/localgateProxyHost.ts";
|
|
8
11
|
import { LocalgateUrl } from "../proxy/localgateUrl.ts";
|
|
9
12
|
import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
|
|
@@ -36,6 +39,7 @@ export class LocalgateCli
|
|
|
36
39
|
else if (command == "stop") return LocalgateCli.control(rest, "stop");
|
|
37
40
|
else if (command == "logs") return LocalgateCli.logs(rest);
|
|
38
41
|
else if (command == "alias") return LocalgateCli.alias(rest);
|
|
42
|
+
else if (command == "config") return LocalgateCli.config(rest);
|
|
39
43
|
else if (command == "cloudflare-info") return LocalgateCli.cloudflareInfo();
|
|
40
44
|
else if (command == "prune") return LocalgateCli.prune();
|
|
41
45
|
else
|
|
@@ -59,6 +63,11 @@ export class LocalgateCli
|
|
|
59
63
|
if (routes.length == 0)
|
|
60
64
|
{
|
|
61
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
|
+
|
|
62
71
|
return 0;
|
|
63
72
|
}
|
|
64
73
|
|
|
@@ -76,6 +85,38 @@ export class LocalgateCli
|
|
|
76
85
|
return 0;
|
|
77
86
|
}
|
|
78
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
|
+
|
|
79
120
|
private static async status(args: string[]): Promise<number>
|
|
80
121
|
{
|
|
81
122
|
const asJson = args.includes("--json");
|
|
@@ -149,6 +190,8 @@ export class LocalgateCli
|
|
|
149
190
|
|
|
150
191
|
private static async alias(args: string[]): Promise<number>
|
|
151
192
|
{
|
|
193
|
+
if (args[0] == "--remove") return LocalgateCli.aliasRemove(args[1]);
|
|
194
|
+
|
|
152
195
|
const [name, portText] = args;
|
|
153
196
|
const port = Number.parseInt(portText ?? "", 10);
|
|
154
197
|
|
|
@@ -158,26 +201,30 @@ export class LocalgateCli
|
|
|
158
201
|
return 1;
|
|
159
202
|
}
|
|
160
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
|
+
|
|
161
213
|
const machine = LocalgateMachineConfig.load();
|
|
162
|
-
|
|
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
|
+
}
|
|
163
221
|
|
|
164
222
|
await LocalgateProxyClient.ensureRunning();
|
|
165
223
|
|
|
166
224
|
let route: LocalgateRoute;
|
|
167
225
|
try
|
|
168
226
|
{
|
|
169
|
-
route = await LocalgateProxyClient.register(
|
|
170
|
-
names,
|
|
171
|
-
port,
|
|
172
|
-
kind: "alias",
|
|
173
|
-
mode: machine ? "lan" : "local",
|
|
174
|
-
cwd: null,
|
|
175
|
-
command: null,
|
|
176
|
-
controlUrl: null,
|
|
177
|
-
runnerPid: null,
|
|
178
|
-
childPid: null,
|
|
179
|
-
debuggerAttached: false
|
|
180
|
-
});
|
|
227
|
+
route = await LocalgateProxyClient.register(LocalgateAliasRoute.registration(name, port, machine));
|
|
181
228
|
}
|
|
182
229
|
catch (error)
|
|
183
230
|
{
|
|
@@ -188,10 +235,69 @@ export class LocalgateCli
|
|
|
188
235
|
return 1;
|
|
189
236
|
}
|
|
190
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
|
+
|
|
191
251
|
process.stdout.write(LocalgateBanner.render(route, LocalgateProxyClient.proxyPort()));
|
|
192
252
|
return 0;
|
|
193
253
|
}
|
|
194
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
|
+
|
|
195
301
|
private static cloudflareInfo(): number
|
|
196
302
|
{
|
|
197
303
|
const machine = LocalgateMachineConfig.load();
|
|
@@ -289,7 +395,10 @@ export class LocalgateCli
|
|
|
289
395
|
" localgate restart [app] restart a route's dev server\n" +
|
|
290
396
|
" localgate stop [app] stop a route's dev server\n" +
|
|
291
397
|
" localgate logs [app] [--lines N] tail a route's captured output\n" +
|
|
292
|
-
" 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" +
|
|
293
402
|
" localgate cloudflare-info print the DNS and ingress entries to paste\n" +
|
|
294
403
|
" localgate prune drop routes whose runner is gone\n\n" +
|
|
295
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;
|
|
@@ -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
|
+
}
|
|
@@ -65,6 +65,13 @@ 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
|
+
|
|
68
75
|
private static optionalLabel(parsed: Record<string, unknown>, key: string, filePath: string): string | null
|
|
69
76
|
{
|
|
70
77
|
const value = parsed[key];
|
|
@@ -25,6 +25,13 @@ export class LocalgateNames
|
|
|
25
25
|
return `${label}.${machine.baseDomain}`;
|
|
26
26
|
}
|
|
27
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
|
+
|
|
28
35
|
static routeNames(projectName: string, mode: LocalgateMode, machine: LocalgateMachineSettings | null): string[]
|
|
29
36
|
{
|
|
30
37
|
const local = LocalgateNames.local(projectName);
|
|
@@ -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[] = [];
|
|
@@ -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
|
|
63
|
-
return [
|
|
65
|
+
const stalled = [
|
|
64
66
|
`localgate: ${route.names[0]} is not responding.`,
|
|
65
67
|
"",
|
|
66
|
-
`The
|
|
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
|
-
]
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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
|
|
@@ -127,6 +127,15 @@ export class LocalgateProxy
|
|
|
127
127
|
|
|
128
128
|
private forward(route: LocalgateRoute, request: IncomingMessage, response: ServerResponse): void
|
|
129
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
|
+
|
|
130
139
|
const headers = { ...request.headers };
|
|
131
140
|
LocalgateHeaderRewrite.apply(request.url ?? "/", headers, request.headers.host ?? "", route.names[0]!);
|
|
132
141
|
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
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";
|
|
@@ -34,6 +36,8 @@ export class LocalgateProxyHost
|
|
|
34
36
|
}
|
|
35
37
|
);
|
|
36
38
|
|
|
39
|
+
LocalgateProxyHost.restoreAliases(registry, machine);
|
|
40
|
+
|
|
37
41
|
await proxy.start();
|
|
38
42
|
process.stdout.write(`localgate proxy listening on 127.0.0.1:${port}`
|
|
39
43
|
+ `${machine?.lanIp ? ` and ${machine.lanIp}:${port}` : ""}\n`);
|
|
@@ -42,6 +46,14 @@ export class LocalgateProxyHost
|
|
|
42
46
|
process.on(signal, () => void proxy.stop().then(() => process.exit(0)));
|
|
43
47
|
}
|
|
44
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
|
+
|
|
45
57
|
private static async requestRestart(route: LocalgateRoute): Promise<void>
|
|
46
58
|
{
|
|
47
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";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "localgate",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.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",
|