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.
@@ -0,0 +1,205 @@
1
+ import { isAbsolute, relative, resolve, sep } from "node:path";
2
+ import type { LocalgateMode } from "../config/localgateProjectConfig.ts";
3
+
4
+ export type LocalgateRouteKind = "app" | "alias";
5
+
6
+ // Which listener a lookup is answering for. The proxy binds loopback always and the LAN address when
7
+ // the machine has one, and the two do not serve the same names.
8
+ export type LocalgateReach = "loopback" | "lan";
9
+
10
+ export type LocalgateRouteState = "starting" | "healthy" | "unresponsive" | "dead";
11
+
12
+ export type LocalgateRoute =
13
+ {
14
+ id: string;
15
+ // The local name first, the external one second when the mode grants it. Both point at one port.
16
+ names: string[];
17
+ port: number;
18
+ kind: LocalgateRouteKind;
19
+ mode: LocalgateMode;
20
+ cwd: string | null;
21
+ command: string | null;
22
+ controlUrl: string | null;
23
+ runnerPid: number | null;
24
+ childPid: number | null;
25
+ debuggerAttached: boolean;
26
+ startedAt: string;
27
+ state: LocalgateRouteState;
28
+ lastResponseAt: string | null;
29
+ };
30
+
31
+ export type LocalgateRouteRegistration =
32
+ {
33
+ names: string[];
34
+ port: number;
35
+ kind: LocalgateRouteKind;
36
+ mode: LocalgateMode;
37
+ cwd: string | null;
38
+ command: string | null;
39
+ controlUrl: string | null;
40
+ runnerPid: number | null;
41
+ childPid: number | null;
42
+ debuggerAttached: boolean;
43
+ };
44
+
45
+ // A name is already owned by a live runner. Its own kind so the control API can answer 409 and the
46
+ // caller can tell a collision apart from a malformed registration.
47
+ export class LocalgateRouteConflictError extends Error
48
+ {
49
+ constructor(readonly existing: LocalgateRoute)
50
+ {
51
+ super(`${existing.names[0]} is already registered by runner ${existing.runnerPid ?? "?"}`);
52
+ this.name = "LocalgateRouteConflictError";
53
+ }
54
+ }
55
+
56
+ // The table lives in the proxy process and nowhere else: no state file, so there is no lock to take
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.
59
+ export class LocalgateRegistry
60
+ {
61
+ private static readonly localSuffixConst = ".localhost";
62
+
63
+ private readonly routes = new Map<string, LocalgateRoute>();
64
+ private nextId = 1;
65
+
66
+ register(registration: LocalgateRouteRegistration, now: string): LocalgateRoute
67
+ {
68
+ if (registration.names.length == 0)
69
+ throw new Error("a route needs at least one name");
70
+
71
+ // Taking a name away from a live runner used to be silent, which left that runner holding its port
72
+ // with no route pointing at it - unreachable, and invisible to stop/restart/status. A runner may
73
+ // still re-register its own names, which is how the heartbeat recovers from a proxy restart.
74
+ for (const name of registration.names)
75
+ {
76
+ const existing = this.findByName(name);
77
+ if (!existing) continue;
78
+ if (existing.controlUrl && existing.runnerPid != registration.runnerPid)
79
+ throw new LocalgateRouteConflictError(existing);
80
+ this.routes.delete(existing.id);
81
+ }
82
+
83
+ const route: LocalgateRoute = {
84
+ ...registration,
85
+ id: `r${this.nextId++}`,
86
+ startedAt: now,
87
+ state: "starting",
88
+ lastResponseAt: null
89
+ };
90
+ this.routes.set(route.id, route);
91
+ return route;
92
+ }
93
+
94
+ remove(id: string): boolean
95
+ {
96
+ return this.routes.delete(id);
97
+ }
98
+
99
+ all(): LocalgateRoute[]
100
+ {
101
+ return [...this.routes.values()];
102
+ }
103
+
104
+ isEmpty(): boolean
105
+ {
106
+ return this.routes.size == 0;
107
+ }
108
+
109
+ byId(id: string): LocalgateRoute | null
110
+ {
111
+ return this.routes.get(id) ?? null;
112
+ }
113
+
114
+ // Exact name first, then a parent-domain match, so a request to `app.dev.example.com` still finds a
115
+ // route registered as `app.dev.example.com` while a stray subdomain of it resolves to the same app.
116
+ // The reach is not optional: a lookup that did not say where the request came from is how a
117
+ // `.localhost` name ends up answered on the LAN.
118
+ byHostname(hostHeader: string, reachedFrom: LocalgateReach): LocalgateRoute | null
119
+ {
120
+ const host = LocalgateRegistry.hostnameOf(hostHeader);
121
+ if (!host) return null;
122
+
123
+ for (const route of this.routes.values())
124
+ for (const name of route.names)
125
+ if (name == host && LocalgateRegistry.answers(name, reachedFrom)) return route;
126
+
127
+ for (const route of this.routes.values())
128
+ for (const name of route.names)
129
+ if (host.endsWith(`.${name}`) && LocalgateRegistry.answers(name, reachedFrom)) return route;
130
+
131
+ return null;
132
+ }
133
+
134
+ byName(name: string): LocalgateRoute | null
135
+ {
136
+ for (const route of this.routes.values())
137
+ if (route.names.some(candidate => candidate == name || candidate.startsWith(`${name}.`)))
138
+ return route;
139
+ return null;
140
+ }
141
+
142
+ // The working directory is the anchor an agent has: whichever route owns this directory or one of
143
+ // its ancestors is the one the caller means. The deepest match wins when projects are nested.
144
+ byDirectory(directory: string): LocalgateRoute | null
145
+ {
146
+ const target = resolve(directory);
147
+ let best: LocalgateRoute | null = null;
148
+ let bestDepth = -1;
149
+
150
+ for (const route of this.routes.values())
151
+ {
152
+ if (!route.cwd) continue;
153
+ const routeDirectory = resolve(route.cwd);
154
+ if (!LocalgateRegistry.contains(routeDirectory, target)) continue;
155
+
156
+ const depth = routeDirectory.split(sep).length;
157
+ if (depth > bestDepth)
158
+ {
159
+ best = route;
160
+ bestDepth = depth;
161
+ }
162
+ }
163
+
164
+ return best;
165
+ }
166
+
167
+ update(id: string, patch: Partial<Pick<LocalgateRoute, "state" | "lastResponseAt" | "childPid" | "debuggerAttached">>): LocalgateRoute
168
+ {
169
+ const route = this.routes.get(id);
170
+ if (!route) throw new Error(`unknown route ${id}`);
171
+ Object.assign(route, patch);
172
+ return route;
173
+ }
174
+
175
+ private findByName(name: string): LocalgateRoute | null
176
+ {
177
+ for (const route of this.routes.values())
178
+ if (route.names.includes(name)) return route;
179
+ return null;
180
+ }
181
+
182
+ private static hostnameOf(hostHeader: string): string | null
183
+ {
184
+ const host = hostHeader.trim().toLowerCase().split(":")[0];
185
+ return host ? host : null;
186
+ }
187
+
188
+ // `.localhost` resolves to the loopback address of whoever looked it up, so off this machine it
189
+ // names somebody else's computer. Serving it on the LAN listener would hand out every route,
190
+ // including the local-mode ones whose whole point is that they never leave the machine.
191
+ private static answers(name: string, reachedFrom: LocalgateReach): boolean
192
+ {
193
+ return reachedFrom == "loopback" || !name.endsWith(LocalgateRegistry.localSuffixConst);
194
+ }
195
+
196
+ // `relative` between two drives has no relative form, so it returns the target unchanged - an
197
+ // absolute path, which does not start with `..` and would read as "inside the parent". Without the
198
+ // absolute check every route on one drive contains every directory on another.
199
+ private static contains(parent: string, child: string): boolean
200
+ {
201
+ if (parent == child) return true;
202
+ const difference = relative(parent, child);
203
+ return difference.length > 0 && !difference.startsWith("..") && !isAbsolute(difference);
204
+ }
205
+ }
@@ -0,0 +1,56 @@
1
+ // Keeps repositories machine-agnostic: a committed env file says `.localhost` everywhere, and the
2
+ // machine's own suffix is substituted here, in memory, on the way into the child process. Only the
3
+ // variables a browser reads are rewritten - a remote viewer's browser resolves `.localhost` to its own
4
+ // machine, so those URLs must carry the shared name. Server-side variables stay on `.localhost`, which
5
+ // is faster and works with no DNS at all.
6
+ export class LocalgateEnvRewrite
7
+ {
8
+ private static readonly localSuffixConst = ".localhost";
9
+ private static readonly browserFacingNamesConst = ["AUTH_URL", "NEXTAUTH_URL"];
10
+
11
+ static apply(env: NodeJS.ProcessEnv, externalSuffix: string | null): NodeJS.ProcessEnv
12
+ {
13
+ const result: NodeJS.ProcessEnv = { ...env };
14
+ if (!externalSuffix) return result;
15
+
16
+ for (const [key, value] of Object.entries(result))
17
+ {
18
+ if (!value || !LocalgateEnvRewrite.isBrowserFacing(key)) continue;
19
+
20
+ const rewritten = LocalgateEnvRewrite.rewriteHostname(value, externalSuffix);
21
+ if (rewritten) result[key] = rewritten;
22
+ }
23
+
24
+ return result;
25
+ }
26
+
27
+ static isBrowserFacing(key: string): boolean
28
+ {
29
+ return key.startsWith("NEXT_PUBLIC_")
30
+ || key.endsWith("_PUBLIC_URL")
31
+ || LocalgateEnvRewrite.browserFacingNamesConst.includes(key);
32
+ }
33
+
34
+ // Substitutes inside the authority component only, and by string replacement rather than
35
+ // URL.toString(), so a value keeps its exact original shape - notably no trailing slash appears on a
36
+ // bare origin, which app code concatenates onto.
37
+ private static rewriteHostname(value: string, externalSuffix: string): string | null
38
+ {
39
+ let url: URL;
40
+ try
41
+ {
42
+ url = new URL(value);
43
+ }
44
+ catch
45
+ {
46
+ return null;
47
+ }
48
+
49
+ if (!url.hostname.endsWith(LocalgateEnvRewrite.localSuffixConst)) return null;
50
+
51
+ const label = url.hostname.slice(0, -LocalgateEnvRewrite.localSuffixConst.length);
52
+ if (label.length == 0) return null;
53
+
54
+ return value.replace(url.hostname, `${label}${externalSuffix}`);
55
+ }
56
+ }
@@ -0,0 +1,115 @@
1
+ import { execFile } from "node:child_process";
2
+ import { connect } from "node:net";
3
+ import { promisify } from "node:util";
4
+
5
+ // Killing a dev server on Windows is not one call. `taskkill /T` walks parent links, so when the
6
+ // intermediate shell npm spawned has already exited, the real server is an orphan the tree walk cannot
7
+ // see - it survives and keeps the port. That is the failure `portless prune` exists to clean up after.
8
+ // So: kill the tree, wait for the port to actually come free, and if it does not, find whoever still
9
+ // holds it and kill that process directly.
10
+ export class LocalgateProcessTree
11
+ {
12
+ private static readonly pollIntervalMsConst = 100;
13
+ private static readonly connectTimeoutMsConst = 500;
14
+
15
+ static async killTree(pid: number, port: number, timeoutMs = 10_000): Promise<void>
16
+ {
17
+ await LocalgateProcessTree.killPid(pid);
18
+
19
+ if (await LocalgateProcessTree.waitForPortRelease(port, timeoutMs)) return;
20
+
21
+ const holder = await LocalgateProcessTree.findPortHolder(port);
22
+ if (holder !== null && holder != pid)
23
+ {
24
+ await LocalgateProcessTree.killPid(holder);
25
+ await LocalgateProcessTree.waitForPortRelease(port, timeoutMs);
26
+ }
27
+ }
28
+
29
+ // For a process nobody owns any more. The recorded pid belongs to something that already exited and
30
+ // Windows reuses pid numbers, so killing it blind can take out an unrelated tree; whoever actually
31
+ // holds the port is the only target that is still known to be the right one.
32
+ static async killPortHolder(port: number, timeoutMs = 10_000): Promise<boolean>
33
+ {
34
+ const holder = await LocalgateProcessTree.findPortHolder(port);
35
+ if (holder === null) return !await LocalgateProcessTree.isPortListening(port);
36
+
37
+ await LocalgateProcessTree.killPid(holder);
38
+ return LocalgateProcessTree.waitForPortRelease(port, timeoutMs);
39
+ }
40
+
41
+ static async waitForPortRelease(port: number, timeoutMs: number): Promise<boolean>
42
+ {
43
+ const deadline = Date.now() + timeoutMs;
44
+ for (;;)
45
+ {
46
+ if (!await LocalgateProcessTree.isPortListening(port)) return true;
47
+ if (Date.now() >= deadline) return false;
48
+ await new Promise(resolve => setTimeout(resolve, LocalgateProcessTree.pollIntervalMsConst));
49
+ }
50
+ }
51
+
52
+ static isPortListening(port: number): Promise<boolean>
53
+ {
54
+ return new Promise<boolean>(resolve =>
55
+ {
56
+ const socket = connect({ host: "127.0.0.1", port });
57
+ const settle = (listening: boolean) =>
58
+ {
59
+ socket.destroy();
60
+ resolve(listening);
61
+ };
62
+
63
+ socket.setTimeout(LocalgateProcessTree.connectTimeoutMsConst);
64
+ socket.once("connect", () => settle(true));
65
+ socket.once("timeout", () => settle(false));
66
+ socket.once("error", () => settle(false));
67
+ });
68
+ }
69
+
70
+ static async findPortHolder(port: number): Promise<number | null>
71
+ {
72
+ if (process.platform != "win32") return null;
73
+
74
+ try
75
+ {
76
+ const { stdout } = await promisify(execFile)("powershell", [
77
+ "-NoProfile",
78
+ "-Command",
79
+ `(Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1).OwningProcess`
80
+ ]);
81
+
82
+ const pid = Number.parseInt(stdout.trim(), 10);
83
+ return Number.isFinite(pid) && pid > 0 ? pid : null;
84
+ }
85
+ catch
86
+ {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ private static async killPid(pid: number): Promise<void>
92
+ {
93
+ if (process.platform == "win32")
94
+ {
95
+ try
96
+ {
97
+ await promisify(execFile)("taskkill", ["/T", "/F", "/PID", String(pid)]);
98
+ }
99
+ catch
100
+ {
101
+ // Already gone, or gone between the check and the call: both mean there is nothing to kill.
102
+ }
103
+ return;
104
+ }
105
+
106
+ try
107
+ {
108
+ process.kill(pid, "SIGKILL");
109
+ }
110
+ catch
111
+ {
112
+ // Same as above.
113
+ }
114
+ }
115
+ }