localgate 0.2.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/LICENSE +202 -0
- package/README.md +287 -0
- package/bin/localgate.mjs +9 -0
- package/logic/cli/localgateBanner.ts +56 -0
- package/logic/cli/localgateCli.ts +283 -0
- package/logic/client/localgateProxyClient.ts +122 -0
- package/logic/cloudflare/localgateCloudflareInfo.ts +29 -0
- package/logic/config/localgateMachineConfig.ts +62 -0
- package/logic/config/localgateProjectConfig.ts +97 -0
- package/logic/proxy/localgateControlApi.ts +89 -0
- package/logic/proxy/localgateHeaderRewrite.ts +52 -0
- package/logic/proxy/localgateHealth.ts +121 -0
- package/logic/proxy/localgateProxy.ts +271 -0
- package/logic/proxy/localgateProxyHost.ts +52 -0
- package/logic/proxy/localgateRegistry.ts +205 -0
- package/logic/run/localgateEnvRewrite.ts +56 -0
- package/logic/run/localgateProcessTree.ts +115 -0
- package/logic/run/localgateRunner.ts +503 -0
- package/package.json +56 -0
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { LocalgateProxyClient } from "../client/localgateProxyClient.ts";
|
|
2
|
+
import { LocalgateBanner } from "./localgateBanner.ts";
|
|
3
|
+
import { LocalgateCloudflareInfo } from "../cloudflare/localgateCloudflareInfo.ts";
|
|
4
|
+
import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
|
|
5
|
+
import { LocalgateProjectConfig } from "../config/localgateProjectConfig.ts";
|
|
6
|
+
import { LocalgateProxyHost } from "../proxy/localgateProxyHost.ts";
|
|
7
|
+
import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
|
|
8
|
+
import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
|
|
9
|
+
import { LocalgateRunner } from "../run/localgateRunner.ts";
|
|
10
|
+
|
|
11
|
+
export class LocalgateCli
|
|
12
|
+
{
|
|
13
|
+
static async main(args: string[]): Promise<number>
|
|
14
|
+
{
|
|
15
|
+
const command = args[0];
|
|
16
|
+
const rest = args.slice(1);
|
|
17
|
+
|
|
18
|
+
if (command === undefined || command == "help" || command == "--help" || command == "-h")
|
|
19
|
+
{
|
|
20
|
+
LocalgateCli.printUsage();
|
|
21
|
+
return 0;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (command == "run")
|
|
25
|
+
{
|
|
26
|
+
const { force, command: childCommand } = LocalgateRunner.parseOptions(rest);
|
|
27
|
+
return new LocalgateRunner(childCommand, process.cwd(), force).run();
|
|
28
|
+
}
|
|
29
|
+
// Internal: how a runner brings the resident half up. Not in the usage text on purpose.
|
|
30
|
+
else if (command == "__proxy") { await LocalgateProxyHost.run(); return 0; }
|
|
31
|
+
else if (command == "list") return LocalgateCli.list(rest.includes("--json"));
|
|
32
|
+
else if (command == "status") return LocalgateCli.status(rest);
|
|
33
|
+
else if (command == "restart") return LocalgateCli.control(rest, "restart");
|
|
34
|
+
else if (command == "stop") return LocalgateCli.control(rest, "stop");
|
|
35
|
+
else if (command == "logs") return LocalgateCli.logs(rest);
|
|
36
|
+
else if (command == "alias") return LocalgateCli.alias(rest);
|
|
37
|
+
else if (command == "cloudflare-info") return LocalgateCli.cloudflareInfo();
|
|
38
|
+
else if (command == "prune") return LocalgateCli.prune();
|
|
39
|
+
else
|
|
40
|
+
{
|
|
41
|
+
process.stderr.write(`localgate: unknown command "${command}"\n\n`);
|
|
42
|
+
LocalgateCli.printUsage();
|
|
43
|
+
return 1;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private static async list(asJson: boolean): Promise<number>
|
|
48
|
+
{
|
|
49
|
+
const routes = await LocalgateProxyClient.list();
|
|
50
|
+
|
|
51
|
+
if (asJson)
|
|
52
|
+
{
|
|
53
|
+
process.stdout.write(`${JSON.stringify({ routes }, null, 2)}\n`);
|
|
54
|
+
return 0;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (routes.length == 0)
|
|
58
|
+
{
|
|
59
|
+
process.stdout.write("No routes. Nothing is running, and the proxy is not needed until something is.\n");
|
|
60
|
+
return 0;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
process.stdout.write("Active routes:\n\n");
|
|
64
|
+
for (const route of routes)
|
|
65
|
+
{
|
|
66
|
+
process.stdout.write(` ${route.names.map(name => `http://${name}`).join("\n ")}\n`);
|
|
67
|
+
process.stdout.write(` -> 127.0.0.1:${route.port} [${route.state}] ${route.kind}`
|
|
68
|
+
+ `${route.debuggerAttached ? " debugger" : ""}\n`);
|
|
69
|
+
if (route.cwd) process.stdout.write(` ${route.cwd}\n`);
|
|
70
|
+
process.stdout.write("\n");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return 0;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
private static async status(args: string[]): Promise<number>
|
|
77
|
+
{
|
|
78
|
+
const asJson = args.includes("--json");
|
|
79
|
+
const route = await LocalgateCli.resolve(args.find(argument => !argument.startsWith("--")));
|
|
80
|
+
|
|
81
|
+
if (!route)
|
|
82
|
+
{
|
|
83
|
+
const message = { running: false, reason: "no route for this directory or name" };
|
|
84
|
+
process.stdout.write(asJson ? `${JSON.stringify(message, null, 2)}\n` : `${message.reason}\n`);
|
|
85
|
+
return 1;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (asJson)
|
|
89
|
+
{
|
|
90
|
+
const logs = await LocalgateCli.fetchLogs(route, 20);
|
|
91
|
+
process.stdout.write(`${JSON.stringify({ ...route, logTail: logs }, null, 2)}\n`);
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
process.stdout.write([
|
|
96
|
+
`${route.names.map(name => `http://${name}`).join("\n")}`,
|
|
97
|
+
`port 127.0.0.1:${route.port}`,
|
|
98
|
+
`state ${route.state}`,
|
|
99
|
+
`mode ${route.mode}`,
|
|
100
|
+
`command ${route.command ?? "-"}`,
|
|
101
|
+
`directory ${route.cwd ?? "-"}`,
|
|
102
|
+
`pids runner ${route.runnerPid ?? "-"}, child ${route.childPid ?? "-"}`,
|
|
103
|
+
`debugger ${route.debuggerAttached ? "attached" : "no"}`,
|
|
104
|
+
`started ${route.startedAt}`,
|
|
105
|
+
""
|
|
106
|
+
].join("\n"));
|
|
107
|
+
|
|
108
|
+
return 0;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private static async control(args: string[], action: "restart" | "stop"): Promise<number>
|
|
112
|
+
{
|
|
113
|
+
const route = await LocalgateCli.resolve(args.find(argument => !argument.startsWith("--")));
|
|
114
|
+
if (!route) return LocalgateCli.reportUnresolved();
|
|
115
|
+
|
|
116
|
+
if (!route.controlUrl)
|
|
117
|
+
{
|
|
118
|
+
process.stderr.write(`localgate: ${route.names[0]} is an alias, there is no process to ${action}\n`);
|
|
119
|
+
return 1;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const response = await fetch(`${route.controlUrl}/${action}`, { method: "POST" });
|
|
123
|
+
if (!response.ok)
|
|
124
|
+
{
|
|
125
|
+
process.stderr.write(`localgate: ${action} failed, the runner answered ${response.status}\n`);
|
|
126
|
+
return 1;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
process.stdout.write(`localgate: ${route.names[0]} ${action == "restart" ? "restarted" : "stopped"}\n`);
|
|
130
|
+
return 0;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
private static async logs(args: string[]): Promise<number>
|
|
134
|
+
{
|
|
135
|
+
const linesIndex = args.indexOf("--lines");
|
|
136
|
+
const lines = linesIndex >= 0 ? Number.parseInt(args[linesIndex + 1] ?? "80", 10) : 80;
|
|
137
|
+
const route = await LocalgateCli.resolve(args.find((argument, index) =>
|
|
138
|
+
!argument.startsWith("--") && index != linesIndex + 1));
|
|
139
|
+
|
|
140
|
+
if (!route) return LocalgateCli.reportUnresolved();
|
|
141
|
+
|
|
142
|
+
const collected = await LocalgateCli.fetchLogs(route, lines);
|
|
143
|
+
process.stdout.write(collected.length > 0 ? `${collected.join("\n")}\n` : "no output captured yet\n");
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private static async alias(args: string[]): Promise<number>
|
|
148
|
+
{
|
|
149
|
+
const [name, portText] = args;
|
|
150
|
+
const port = Number.parseInt(portText ?? "", 10);
|
|
151
|
+
|
|
152
|
+
if (!name || !Number.isFinite(port))
|
|
153
|
+
{
|
|
154
|
+
process.stderr.write("localgate: usage is localgate alias <name> <port>\n");
|
|
155
|
+
return 1;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const machine = LocalgateMachineConfig.load();
|
|
159
|
+
const names = [`${name}.localhost`];
|
|
160
|
+
// An alias gets the shared name too when the machine has one: a browser on another PC loads media
|
|
161
|
+
// from these services by absolute URL, so they have to answer on the name that resolves there.
|
|
162
|
+
if (machine) names.push(`${name}${LocalgateMachineConfig.externalSuffix(machine)}`);
|
|
163
|
+
|
|
164
|
+
await LocalgateProxyClient.ensureRunning();
|
|
165
|
+
|
|
166
|
+
let route: LocalgateRoute;
|
|
167
|
+
try
|
|
168
|
+
{
|
|
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
|
+
});
|
|
181
|
+
}
|
|
182
|
+
catch (error)
|
|
183
|
+
{
|
|
184
|
+
if (!(error instanceof LocalgateRouteConflictError)) throw error;
|
|
185
|
+
|
|
186
|
+
process.stderr.write(`localgate: ${name} is the name of a running dev server `
|
|
187
|
+
+ `(${error.existing.command ?? "?"} in ${error.existing.cwd ?? "?"}), so an alias cannot take it.\n`);
|
|
188
|
+
return 1;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
process.stdout.write(LocalgateBanner.render(route));
|
|
192
|
+
return 0;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private static cloudflareInfo(): number
|
|
196
|
+
{
|
|
197
|
+
const machine = LocalgateMachineConfig.load();
|
|
198
|
+
if (!machine)
|
|
199
|
+
{
|
|
200
|
+
process.stderr.write(`localgate: no machine config at ${LocalgateMachineConfig.filePath()}, `
|
|
201
|
+
+ "so this machine serves .localhost only\n");
|
|
202
|
+
return 1;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const project = LocalgateProjectConfig.load(process.cwd());
|
|
206
|
+
if (project.mode != "internet")
|
|
207
|
+
process.stdout.write(`Note: this project's mode is "${project.mode}". Set it to "internet" `
|
|
208
|
+
+ "in package.json when you actually want the entries below to be live.\n\n");
|
|
209
|
+
|
|
210
|
+
process.stdout.write(LocalgateCloudflareInfo.render(
|
|
211
|
+
`${project.name}${LocalgateMachineConfig.externalSuffix(machine)}`,
|
|
212
|
+
machine.lanIp
|
|
213
|
+
));
|
|
214
|
+
|
|
215
|
+
return 0;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private static async prune(): Promise<number>
|
|
219
|
+
{
|
|
220
|
+
const routes = await LocalgateProxyClient.list();
|
|
221
|
+
let dropped = 0;
|
|
222
|
+
|
|
223
|
+
for (const route of routes)
|
|
224
|
+
{
|
|
225
|
+
if (!route.controlUrl) continue;
|
|
226
|
+
|
|
227
|
+
const alive = await fetch(`${route.controlUrl}/ping`, { signal: AbortSignal.timeout(1_000) })
|
|
228
|
+
.then(response => response.ok)
|
|
229
|
+
.catch(() => false);
|
|
230
|
+
|
|
231
|
+
if (alive) continue;
|
|
232
|
+
|
|
233
|
+
await LocalgateProxyClient.deregister(route.id);
|
|
234
|
+
process.stdout.write(`dropped ${route.names[0]} (its runner is gone)\n`);
|
|
235
|
+
dropped++;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (dropped == 0) process.stdout.write("nothing to prune\n");
|
|
239
|
+
return 0;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private static async fetchLogs(route: LocalgateRoute, lines: number): Promise<string[]>
|
|
243
|
+
{
|
|
244
|
+
if (!route.controlUrl) return [];
|
|
245
|
+
|
|
246
|
+
return fetch(`${route.controlUrl}/logs?lines=${lines}`, { signal: AbortSignal.timeout(2_000) })
|
|
247
|
+
.then(response => response.json() as Promise<{ lines: string[] }>)
|
|
248
|
+
.then(payload => payload.lines)
|
|
249
|
+
.catch(() => []);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
private static resolve(selector: string | undefined): Promise<LocalgateRoute | null>
|
|
253
|
+
{
|
|
254
|
+
return selector
|
|
255
|
+
? LocalgateProxyClient.resolve({ name: selector })
|
|
256
|
+
: LocalgateProxyClient.resolve({ directory: process.cwd() });
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
private static reportUnresolved(): number
|
|
260
|
+
{
|
|
261
|
+
process.stderr.write("localgate: no route for this directory or name. "
|
|
262
|
+
+ "Start the dev server from your editor, or pass the app name.\n");
|
|
263
|
+
return 1;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
private static printUsage(): void
|
|
267
|
+
{
|
|
268
|
+
process.stdout.write(
|
|
269
|
+
"localgate - stable names for local dev servers\n\n" +
|
|
270
|
+
" localgate run [--force] <cmd...> run a dev server behind its name\n" +
|
|
271
|
+
" --force takes over a running one without asking\n" +
|
|
272
|
+
" localgate list [--json] show active routes\n" +
|
|
273
|
+
" localgate status [app] [--json] state of one route (defaults to this directory)\n" +
|
|
274
|
+
" localgate restart [app] restart a route's dev server\n" +
|
|
275
|
+
" localgate stop [app] stop a route's dev server\n" +
|
|
276
|
+
" localgate logs [app] [--lines N] tail a route's captured output\n" +
|
|
277
|
+
" localgate alias <name> <port> register a static route (e.g. a docker service)\n" +
|
|
278
|
+
" localgate cloudflare-info print the DNS and ingress entries to paste\n" +
|
|
279
|
+
" localgate prune drop routes whose runner is gone\n\n" +
|
|
280
|
+
"[app] is optional: with no argument a command acts on the route owning the current directory.\n"
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { LocalgateProxyHost } from "../proxy/localgateProxyHost.ts";
|
|
5
|
+
import { LocalgateRouteConflictError } from "../proxy/localgateRegistry.ts";
|
|
6
|
+
import type { LocalgateRoute, LocalgateRouteRegistration } from "../proxy/localgateRegistry.ts";
|
|
7
|
+
|
|
8
|
+
// Every process other than the proxy reaches the route table through here. The table has no file, so
|
|
9
|
+
// this client is the only way in - and it is loopback-only, which is what keeps the LAN out of it.
|
|
10
|
+
export class LocalgateProxyClient
|
|
11
|
+
{
|
|
12
|
+
private static readonly baseUrlConst = `http://127.0.0.1:${LocalgateProxyHost.portConst}/__localgate`;
|
|
13
|
+
private static readonly startTimeoutMsConst = 15_000;
|
|
14
|
+
|
|
15
|
+
static async ping(): Promise<boolean>
|
|
16
|
+
{
|
|
17
|
+
try
|
|
18
|
+
{
|
|
19
|
+
const response = await fetch(`${LocalgateProxyClient.baseUrlConst}/ping`, {
|
|
20
|
+
signal: AbortSignal.timeout(1_000)
|
|
21
|
+
});
|
|
22
|
+
return response.ok;
|
|
23
|
+
}
|
|
24
|
+
catch
|
|
25
|
+
{
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
static async ensureRunning(): Promise<void>
|
|
31
|
+
{
|
|
32
|
+
if (await LocalgateProxyClient.ping()) return;
|
|
33
|
+
|
|
34
|
+
LocalgateProxyClient.spawnDetached();
|
|
35
|
+
|
|
36
|
+
const deadline = Date.now() + LocalgateProxyClient.startTimeoutMsConst;
|
|
37
|
+
for (;;)
|
|
38
|
+
{
|
|
39
|
+
await new Promise(resolve => setTimeout(resolve, 150));
|
|
40
|
+
if (await LocalgateProxyClient.ping()) return;
|
|
41
|
+
if (Date.now() >= deadline)
|
|
42
|
+
throw new Error(`localgate proxy did not come up on port ${LocalgateProxyHost.portConst} within `
|
|
43
|
+
+ `${LocalgateProxyClient.startTimeoutMsConst / 1000} s (is something else holding the port?)`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
static async register(registration: LocalgateRouteRegistration): Promise<LocalgateRoute>
|
|
48
|
+
{
|
|
49
|
+
const payload = await LocalgateProxyClient.send("POST", "/routes", registration) as { route: LocalgateRoute };
|
|
50
|
+
return payload.route;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
static async deregister(id: string): Promise<void>
|
|
54
|
+
{
|
|
55
|
+
await LocalgateProxyClient.send("DELETE", `/routes/${id}`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
static async patch(id: string, patch: Record<string, unknown>): Promise<void>
|
|
59
|
+
{
|
|
60
|
+
await LocalgateProxyClient.send("PATCH", `/routes/${id}`, patch);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
static async list(): Promise<LocalgateRoute[]>
|
|
64
|
+
{
|
|
65
|
+
if (!await LocalgateProxyClient.ping()) return [];
|
|
66
|
+
const payload = await LocalgateProxyClient.send("GET", "/routes") as { routes: LocalgateRoute[] };
|
|
67
|
+
return payload.routes;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
static async resolve(selector: { name?: string; directory?: string }): Promise<LocalgateRoute | null>
|
|
71
|
+
{
|
|
72
|
+
if (!await LocalgateProxyClient.ping()) return null;
|
|
73
|
+
|
|
74
|
+
const query = selector.name
|
|
75
|
+
? `name=${encodeURIComponent(selector.name)}`
|
|
76
|
+
: `cwd=${encodeURIComponent(selector.directory ?? "")}`;
|
|
77
|
+
|
|
78
|
+
const response = await fetch(`${LocalgateProxyClient.baseUrlConst}/resolve?${query}`);
|
|
79
|
+
if (!response.ok) return null;
|
|
80
|
+
return ((await response.json()) as { route: LocalgateRoute | null }).route;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Two levels of spawn on Windows, deliberately: `cmd` exits immediately, so the proxy's recorded
|
|
84
|
+
// parent is already gone and the tree kill VSCode performs when a terminal closes cannot reach it.
|
|
85
|
+
// Otherwise closing one project's terminal would take the routing of every other project with it.
|
|
86
|
+
private static spawnDetached(): void
|
|
87
|
+
{
|
|
88
|
+
const entry = join(fileURLToPath(new URL("../../", import.meta.url)), "bin", "localgate.mjs");
|
|
89
|
+
|
|
90
|
+
const child = process.platform == "win32"
|
|
91
|
+
? spawn("cmd", ["/c", "start", "\"\"", "/b", process.execPath, entry, "__proxy"],
|
|
92
|
+
{ detached: true, stdio: "ignore", windowsHide: true })
|
|
93
|
+
: spawn(process.execPath, [entry, "__proxy"], { detached: true, stdio: "ignore" });
|
|
94
|
+
|
|
95
|
+
child.unref();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private static async send(method: string, path: string, body?: unknown): Promise<unknown>
|
|
99
|
+
{
|
|
100
|
+
const init: RequestInit = { method };
|
|
101
|
+
if (body !== undefined)
|
|
102
|
+
{
|
|
103
|
+
init.headers = { "content-type": "application/json" };
|
|
104
|
+
init.body = JSON.stringify(body);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const response = await fetch(`${LocalgateProxyClient.baseUrlConst}${path}`, init);
|
|
108
|
+
|
|
109
|
+
// A collision travels as its own type so the runner can name the process that holds the name,
|
|
110
|
+
// rather than reporting a bare status code.
|
|
111
|
+
if (response.status == 409)
|
|
112
|
+
{
|
|
113
|
+
const payload = await response.json() as { existing: LocalgateRoute };
|
|
114
|
+
throw new LocalgateRouteConflictError(payload.existing);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (!response.ok)
|
|
118
|
+
throw new Error(`localgate proxy answered ${response.status} for ${method} ${path}`);
|
|
119
|
+
|
|
120
|
+
return response.json();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Prints, never applies. Exposing a dev server to the internet is two entries in systems localgate has
|
|
2
|
+
// no business holding credentials for, so it hands you the exact text and stops there.
|
|
3
|
+
export class LocalgateCloudflareInfo
|
|
4
|
+
{
|
|
5
|
+
static render(hostname: string, lanIp: string): string
|
|
6
|
+
{
|
|
7
|
+
return [
|
|
8
|
+
`To reach http://${hostname} from outside the LAN, add these two entries.`,
|
|
9
|
+
"",
|
|
10
|
+
"1. Cloudflare DNS, proxied (a specific record wins over the wildcard):",
|
|
11
|
+
"",
|
|
12
|
+
` ${hostname} CNAME <tunnel-id>.cfargotunnel.com`,
|
|
13
|
+
"",
|
|
14
|
+
"2. Ingress list of the shared cloudflared container:",
|
|
15
|
+
"",
|
|
16
|
+
` - hostname: ${hostname}`,
|
|
17
|
+
` service: http://${lanIp}:80`,
|
|
18
|
+
"",
|
|
19
|
+
"cloudflared keeps the Host header, so the proxy routes it like any LAN request.",
|
|
20
|
+
"",
|
|
21
|
+
"Two things worth knowing before you paste this:",
|
|
22
|
+
` - the direct LAN path for ${hostname} disappears; visitors go out to Cloudflare and back`,
|
|
23
|
+
" - anyone holding the URL reaches this dev server, so switch the mode back to lan afterwards",
|
|
24
|
+
"",
|
|
25
|
+
"localgate sent nothing to Cloudflare and holds no API token.",
|
|
26
|
+
""
|
|
27
|
+
].join("\n");
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
export type LocalgateMachineSettings =
|
|
6
|
+
{
|
|
7
|
+
label: string;
|
|
8
|
+
baseDomain: string;
|
|
9
|
+
lanIp: string;
|
|
10
|
+
autoRestart: boolean;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export class LocalgateMachineConfig
|
|
14
|
+
{
|
|
15
|
+
private static readonly labelPatternConst = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
|
|
16
|
+
|
|
17
|
+
static filePath(): string
|
|
18
|
+
{
|
|
19
|
+
return join(homedir(), ".localgate", "config.json");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// null means there is no machine config, which is a complete answer: every project stays on
|
|
23
|
+
// `.localhost` and no external name exists anywhere. A fresh checkout behaves this way.
|
|
24
|
+
static load(filePath: string = LocalgateMachineConfig.filePath()): LocalgateMachineSettings | null
|
|
25
|
+
{
|
|
26
|
+
let raw: string;
|
|
27
|
+
try
|
|
28
|
+
{
|
|
29
|
+
raw = readFileSync(filePath, "utf8");
|
|
30
|
+
}
|
|
31
|
+
catch
|
|
32
|
+
{
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const parsed = JSON.parse(raw) as Record<string, unknown>;
|
|
37
|
+
|
|
38
|
+
const label = LocalgateMachineConfig.requireString(parsed, "label", filePath);
|
|
39
|
+
if (!LocalgateMachineConfig.labelPatternConst.test(label))
|
|
40
|
+
throw new Error(`${filePath}: "label" must be a DNS label (lowercase letters, digits, hyphens), got "${label}"`);
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
label,
|
|
44
|
+
baseDomain: LocalgateMachineConfig.requireString(parsed, "baseDomain", filePath),
|
|
45
|
+
lanIp: LocalgateMachineConfig.requireString(parsed, "lanIp", filePath),
|
|
46
|
+
autoRestart: parsed.autoRestart === true
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
static externalSuffix(settings: LocalgateMachineSettings): string
|
|
51
|
+
{
|
|
52
|
+
return `.${settings.label}.${settings.baseDomain}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private static requireString(parsed: Record<string, unknown>, key: string, filePath: string): string
|
|
56
|
+
{
|
|
57
|
+
const value = parsed[key];
|
|
58
|
+
if (typeof value != "string" || value.length == 0)
|
|
59
|
+
throw new Error(`${filePath}: "${key}" must be a non-empty string`);
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, basename } from "node:path";
|
|
3
|
+
|
|
4
|
+
export type LocalgateMode = "local" | "lan" | "internet";
|
|
5
|
+
|
|
6
|
+
export type LocalgateProjectSettings =
|
|
7
|
+
{
|
|
8
|
+
name: string;
|
|
9
|
+
mode: LocalgateMode;
|
|
10
|
+
packageDirectory: string;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export class LocalgateProjectConfig
|
|
14
|
+
{
|
|
15
|
+
private static readonly namePatternConst = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
|
|
16
|
+
|
|
17
|
+
static load(startDirectory: string): LocalgateProjectSettings
|
|
18
|
+
{
|
|
19
|
+
const packageDirectory = LocalgateProjectConfig.findPackageDirectory(startDirectory);
|
|
20
|
+
if (!packageDirectory)
|
|
21
|
+
return { name: LocalgateProjectConfig.nameFromDirectory(startDirectory), mode: "local", packageDirectory: startDirectory };
|
|
22
|
+
|
|
23
|
+
const parsed = JSON.parse(readFileSync(join(packageDirectory, "package.json"), "utf8")) as Record<string, unknown>;
|
|
24
|
+
const key = parsed.localgate;
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
name: LocalgateProjectConfig.resolveName(key, parsed.name, packageDirectory),
|
|
28
|
+
mode: LocalgateProjectConfig.resolveMode(key, packageDirectory),
|
|
29
|
+
packageDirectory
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
static findPackageDirectory(startDirectory: string): string | null
|
|
34
|
+
{
|
|
35
|
+
let directory = startDirectory;
|
|
36
|
+
for (;;)
|
|
37
|
+
{
|
|
38
|
+
try
|
|
39
|
+
{
|
|
40
|
+
readFileSync(join(directory, "package.json"), "utf8");
|
|
41
|
+
return directory;
|
|
42
|
+
}
|
|
43
|
+
catch
|
|
44
|
+
{
|
|
45
|
+
const parent = dirname(directory);
|
|
46
|
+
if (parent == directory) return null;
|
|
47
|
+
directory = parent;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// A missing key means mode `local`: names on `.localhost` only, no rewriting, no external name. That
|
|
53
|
+
// is why a project that must leave no trace of our infrastructure needs no configuration at all.
|
|
54
|
+
private static resolveMode(key: unknown, packageDirectory: string): LocalgateMode
|
|
55
|
+
{
|
|
56
|
+
if (key === undefined || key === null) return "local";
|
|
57
|
+
if (typeof key != "object" || Array.isArray(key))
|
|
58
|
+
throw new Error(`${packageDirectory}/package.json: "localgate" must be an object, got ${JSON.stringify(key)}`);
|
|
59
|
+
|
|
60
|
+
const mode = (key as Record<string, unknown>).mode;
|
|
61
|
+
if (mode === undefined) return "local";
|
|
62
|
+
if (mode == "local") return "local";
|
|
63
|
+
else if (mode == "lan") return "lan";
|
|
64
|
+
else if (mode == "internet") return "internet";
|
|
65
|
+
else
|
|
66
|
+
throw new Error(`${packageDirectory}/package.json: "localgate.mode" must be local, lan or internet, got ${JSON.stringify(mode)}`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private static resolveName(key: unknown, packageName: unknown, packageDirectory: string): string
|
|
70
|
+
{
|
|
71
|
+
const override = typeof key == "object" && key !== null ? (key as Record<string, unknown>).name : undefined;
|
|
72
|
+
if (typeof override == "string" && override.length > 0)
|
|
73
|
+
return LocalgateProjectConfig.requireHostnameLabel(override, `${packageDirectory}/package.json: "localgate.name"`);
|
|
74
|
+
|
|
75
|
+
if (typeof packageName == "string" && packageName.length > 0)
|
|
76
|
+
{
|
|
77
|
+
// A scoped name (@org/web) is not a usable hostname label, so the scope is dropped the way
|
|
78
|
+
// portless dropped it: the package's own short name is what a person types into the browser.
|
|
79
|
+
const short = packageName.startsWith("@") ? packageName.slice(packageName.indexOf("/") + 1) : packageName;
|
|
80
|
+
return LocalgateProjectConfig.requireHostnameLabel(short, `${packageDirectory}/package.json: "name"`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return LocalgateProjectConfig.nameFromDirectory(packageDirectory);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
private static nameFromDirectory(directory: string): string
|
|
87
|
+
{
|
|
88
|
+
return basename(directory).toLowerCase();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private static requireHostnameLabel(value: string, source: string): string
|
|
92
|
+
{
|
|
93
|
+
if (!LocalgateProjectConfig.namePatternConst.test(value))
|
|
94
|
+
throw new Error(`${source} is not usable as a hostname label (lowercase letters, digits, hyphens): "${value}"`);
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { LocalgateRouteConflictError } from "./localgateRegistry.ts";
|
|
3
|
+
import type { LocalgateRegistry, LocalgateRouteRegistration } from "./localgateRegistry.ts";
|
|
4
|
+
|
|
5
|
+
// The registry lives in the proxy's memory, so runners and the CLI reach it over this API. It is served
|
|
6
|
+
// only on the loopback listener: nothing on the LAN can register, restart or even enumerate routes.
|
|
7
|
+
export class LocalgateControlApi
|
|
8
|
+
{
|
|
9
|
+
static readonly pathPrefixConst = "/__localgate/";
|
|
10
|
+
|
|
11
|
+
// onChange lets the proxy re-evaluate whether it still has a reason to run, since the registry itself
|
|
12
|
+
// is a plain table and emits nothing.
|
|
13
|
+
constructor(private readonly registry: LocalgateRegistry, private readonly onChange: () => void) {}
|
|
14
|
+
|
|
15
|
+
static handles(requestUrl: string): boolean
|
|
16
|
+
{
|
|
17
|
+
return requestUrl.startsWith(LocalgateControlApi.pathPrefixConst);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async handle(request: IncomingMessage, response: ServerResponse): Promise<void>
|
|
21
|
+
{
|
|
22
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
23
|
+
const route = url.pathname.slice(LocalgateControlApi.pathPrefixConst.length);
|
|
24
|
+
const method = request.method ?? "GET";
|
|
25
|
+
|
|
26
|
+
try
|
|
27
|
+
{
|
|
28
|
+
if (route == "ping" && method == "GET")
|
|
29
|
+
return LocalgateControlApi.sendJson(response, 200, { ok: true });
|
|
30
|
+
|
|
31
|
+
if (route == "routes" && method == "GET")
|
|
32
|
+
return LocalgateControlApi.sendJson(response, 200, { routes: this.registry.all() });
|
|
33
|
+
|
|
34
|
+
if (route == "routes" && method == "POST")
|
|
35
|
+
{
|
|
36
|
+
const registration = await LocalgateControlApi.readJson(request) as LocalgateRouteRegistration;
|
|
37
|
+
const created = this.registry.register(registration, new Date().toISOString());
|
|
38
|
+
this.onChange();
|
|
39
|
+
return LocalgateControlApi.sendJson(response, 201, { route: created });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (route == "resolve" && method == "GET")
|
|
43
|
+
{
|
|
44
|
+
const name = url.searchParams.get("name");
|
|
45
|
+
const directory = url.searchParams.get("cwd");
|
|
46
|
+
const found = name ? this.registry.byName(name) : directory ? this.registry.byDirectory(directory) : null;
|
|
47
|
+
return LocalgateControlApi.sendJson(response, found ? 200 : 404, { route: found });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (route.startsWith("routes/") && method == "DELETE")
|
|
51
|
+
{
|
|
52
|
+
const removed = this.registry.remove(route.slice("routes/".length));
|
|
53
|
+
this.onChange();
|
|
54
|
+
return LocalgateControlApi.sendJson(response, removed ? 200 : 404, { removed });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (route.startsWith("routes/") && method == "PATCH")
|
|
58
|
+
{
|
|
59
|
+
const patch = await LocalgateControlApi.readJson(request) as Record<string, unknown>;
|
|
60
|
+
const updated = this.registry.update(route.slice("routes/".length), patch);
|
|
61
|
+
return LocalgateControlApi.sendJson(response, 200, { route: updated });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return LocalgateControlApi.sendJson(response, 404, { error: `unknown control route ${method} ${url.pathname}` });
|
|
65
|
+
}
|
|
66
|
+
catch (error)
|
|
67
|
+
{
|
|
68
|
+
if (error instanceof LocalgateRouteConflictError)
|
|
69
|
+
return LocalgateControlApi.sendJson(response, 409, { error: error.message, existing: error.existing });
|
|
70
|
+
|
|
71
|
+
return LocalgateControlApi.sendJson(response, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
private static async readJson(request: IncomingMessage): Promise<unknown>
|
|
76
|
+
{
|
|
77
|
+
const chunks: Buffer[] = [];
|
|
78
|
+
for await (const chunk of request) chunks.push(chunk as Buffer);
|
|
79
|
+
const body = Buffer.concat(chunks).toString("utf8");
|
|
80
|
+
return body.length > 0 ? JSON.parse(body) : {};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private static sendJson(response: ServerResponse, status: number, payload: unknown): void
|
|
84
|
+
{
|
|
85
|
+
const body = JSON.stringify(payload);
|
|
86
|
+
response.writeHead(status, { "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(body) });
|
|
87
|
+
response.end(body);
|
|
88
|
+
}
|
|
89
|
+
}
|