@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 239 lines 10.3 KB
Raw
1 /**
2 * managedLimits - what `limits.clients` and `limits.connect` in the managed policy allow, and the
3 * one error every refusal uses so each transport can show the administrator's organization.
4 *
5 * @module managedLimits
6 */
7 import type {
8 ManagedPolicyClient,
9 ManagedPolicyDocument,
10 ServerAuthPolicy,
11 } from "@t3tools/contracts";
12 import {
13 disableTailscaleServe,
14 disableTailscaleServeTcp,
15 readTailscaleServeRoutesTo,
16 tailscaleServeOffArgs,
17 readTailscaleStatus,
18 type TailscaleServeRoute,
19 type TailscaleStderrDiagnostic,
20 } from "@t3tools/tailscale";
21 import * as Effect from "effect/Effect";
22 import * as PlatformError from "effect/PlatformError";
23 import * as Schema from "effect/Schema";
24
25 import * as NetService from "@t3tools/shared/Net";
26
27 import { loopbackBindAddress } from "../auth/utils.ts";
28
29 type PolicyDocument = { readonly document: ManagedPolicyDocument | undefined };
30
31 export class ManagedPolicyRefusedError extends Schema.TaggedError<ManagedPolicyRefusedError>()(
32 "ManagedPolicyRefusedError",
33 {
34 organization: Schema.String,
35 /** What the policy does not allow, for example "T3 Connect". */
36 action: Schema.String,
37 /** What that means for this request, for example "so the server cannot listen on 0.0.0.0". */
38 detail: Schema.optionalKey(Schema.String),
39 },
40 ) {
41 override get message(): string {
42 return `${this.organization}'s policy does not allow ${this.action}${
43 this.detail === undefined ? "" : `, ${this.detail}`
44 }.`;
45 }
46 }
47
48 const CLIENT_AUTH_POLICY: Record<ManagedPolicyClient, ServerAuthPolicy> = {
49 desktop: "desktop-managed-local",
50 "local-browser": "loopback-browser",
51 remote: "remote-reachable",
52 };
53
54 const AUTH_POLICY_ACTION: Record<ServerAuthPolicy, string> = {
55 "desktop-managed-local": "the desktop app",
56 "loopback-browser": "browsers on this machine",
57 "remote-reachable": "remote clients",
58 "unsafe-no-auth": "running without authentication",
59 };
60
61 /** Whether the server may run with `authPolicy`. Any policy file rules out `unsafe-no-auth`. */
62 export function allowsAuthPolicy(policy: PolicyDocument, authPolicy: ServerAuthPolicy): boolean {
63 if (policy.document === undefined) return true;
64 if (authPolicy === "unsafe-no-auth") return false;
65 const clients = policy.document.limits?.clients;
66 return (
67 clients === undefined || clients.some((client) => CLIENT_AUTH_POLICY[client] === authPolicy)
68 );
69 }
70
71 /** Whether anything off this machine may pair, by LAN, Tailscale, or a minted link. */
72 export const allowsRemoteClients = (policy: PolicyDocument) =>
73 allowsAuthPolicy(policy, "remote-reachable");
74
75 /** T3 Connect is a way for remote clients in, so a policy without `remote` turns it off too. */
76 export const allowsConnect = (policy: PolicyDocument) =>
77 policy.document?.limits?.connect !== false && allowsRemoteClients(policy);
78
79 const refuse = (policy: PolicyDocument, action: string, detail?: string) =>
80 new ManagedPolicyRefusedError({
81 organization: policy.document?.organization ?? "Your organization",
82 action,
83 ...(detail === undefined ? {} : { detail }),
84 });
85
86 export const refuseConnect = (policy: PolicyDocument) => refuse(policy, "T3 Connect");
87
88 // Node throws ENOTDIR, outside the spawner's error mapping, when PATH ends in a file.
89 const isMissingCli = (cause: unknown) =>
90 (PlatformError.isPlatformError(cause) && cause.reason._tag === "NotFound") ||
91 (cause instanceof Error && "code" in cause && cause.code === "ENOTDIR");
92
93 const NOTHING_FORWARDED: ReadonlyArray<TailscaleServeRoute> = [];
94
95 /** Tailscale answers that leave nothing forwarding here right now. */
96 const NOTHING_TO_CLOSE: ReadonlySet<TailscaleStderrDiagnostic | undefined> = new Set([
97 "not-running",
98 "not-logged-in",
99 ]);
100
101 /**
102 * Turns off the Tailscale Serve routes that forward to the server at `target`, such as one
103 * `t3 pair --tailscale` left from before the policy, and keeps every other route. Runs before the
104 * server binds, and fails unless a fresh read shows no route here, since `off` can exit 0 and
105 * leave it. Without the CLI, or with Tailscale down or logged out, nothing forwards.
106 */
107 export const closeTailscaleServeTo = Effect.fn("managedLimits.closeTailscaleServeTo")(function* (
108 policy: PolicyDocument,
109 target: { readonly host: string; readonly port: number },
110 ) {
111 if (allowsRemoteClients(policy)) return;
112 // Another app holds the port, so its routes are not ours to remove. It could let go before the
113 // bind, which would then take over those routes, so the server does not start.
114 if (!(yield* (yield* NetService.NetService).canListenOnHost(target.port, target.host))) {
115 return yield* refuseRemoteClients(
116 policy,
117 `so the server does not start while it cannot bind ${target.host}:${target.port}; if another app holds that port, the server would take over its Tailscale Serve routes`,
118 );
119 }
120 const readRoutes = readTailscaleServeRoutesTo(target).pipe(
121 Effect.catchTags({
122 // Only a CLI that is not there; one that will not run might still front a daemon.
123 TailscaleCommandSpawnError: (error) =>
124 isMissingCli(error.cause) ? Effect.succeed(NOTHING_FORWARDED) : Effect.fail(error),
125 TailscaleCommandExitError: (error) =>
126 NOTHING_TO_CLOSE.has(error.stderrDiagnostic)
127 ? Effect.succeed(NOTHING_FORWARDED)
128 : Effect.fail(error),
129 }),
130 // Tailscale errors carry only labelled diagnostics, never raw stderr, so they are safe to log.
131 Effect.tapError((cause) =>
132 Effect.logWarning("Tailscale Serve could not be checked", { cause }),
133 ),
134 Effect.mapError((error) =>
135 refuseRemoteClients(
136 policy,
137 error._tag === "TailscaleCommandTimeoutError"
138 ? // Seen on a Mac where Tailscale is installed but was never set up.
139 "so the server does not start until Tailscale Serve can be checked, and Tailscale did not answer; open Tailscale and finish setting it up, or remove it"
140 : "so the server does not start until Tailscale Serve can be checked",
141 ),
142 ),
143 );
144 const found = yield* readRoutes;
145 if (found.length === 0) return;
146 // `off` acts on the machine's current name, so a web route under a former name stays.
147 const currentName = found.some((route) => route.mount !== undefined && route.owner === undefined)
148 ? yield* readTailscaleStatus.pipe(
149 Effect.map((status) => status.magicDnsName?.toLowerCase() ?? null),
150 Effect.orElseSucceed(() => null),
151 )
152 : null;
153 const formerName = (route: TailscaleServeRoute) =>
154 route.owner === undefined &&
155 route.host !== undefined &&
156 currentName !== null &&
157 route.host.toLowerCase() !== currentName;
158 // A Service is shared across the tailnet, and a foreground route lives as long as its command.
159 const removable = (route: TailscaleServeRoute) =>
160 route.owner === undefined &&
161 route.ambiguous === undefined &&
162 (route.mount === undefined || (currentName !== null && !formerName(route)));
163 for (const route of found.filter(removable)) {
164 yield* (
165 route.mount === undefined
166 ? disableTailscaleServeTcp(route.servePort)
167 : disableTailscaleServe(route)
168 ).pipe(
169 Effect.catch((cause) =>
170 Effect.logWarning("Tailscale Serve route could not be turned off", { ...route, cause }),
171 ),
172 );
173 }
174 const left = yield* readRoutes;
175 if (left.length > 0) {
176 const describe = (route: TailscaleServeRoute) => {
177 const where = `port ${route.servePort}${route.mount === undefined ? "" : ` at ${route.mount}`} here`;
178 const off = tailscaleServeOffArgs(route);
179 if (off === undefined) return `${where}; stop the "tailscale serve" command that runs it`;
180 if (formerName(route)) {
181 return `${where} under ${route.host}, a former name of this machine, which "tailscale serve ... off" cannot reach; run "tailscale serve reset" and set up your other routes again`;
182 }
183 const command = `"tailscale ${off.join(" ")}"`;
184 // Without the current name, `off` might act on another name's route at this path.
185 if (currentName === null && route.owner === undefined && route.host !== undefined) {
186 return `${where} under ${route.host}; if that is this machine's current name, turn it off with ${command}`;
187 }
188 return route.ambiguous !== undefined
189 ? `${where}, and its target ${route.ambiguous} might be another service on this port; check it, then turn it off with ${command}`
190 : `${where}; turn it off with ${command}`;
191 };
192 return yield* refuseRemoteClients(
193 policy,
194 `so the server does not start while Tailscale Serve forwards ${left.map(describe).join(", and ")}`,
195 );
196 }
197 yield* Effect.logInfo("Turned off Tailscale Serve the managed policy does not allow", {
198 routes: found,
199 });
200 });
201
202 export const refuseRemoteClients = (policy: PolicyDocument, detail?: string) =>
203 refuse(policy, AUTH_POLICY_ACTION["remote-reachable"], detail);
204
205 /**
206 * Fails when the server would accept clients the policy leaves out; otherwise returns the address
207 * to bind. Runs before the server binds, so a refused configuration never listens, not even
208 * briefly. Without `remote` that address is the loopback literal the check approved, never a name.
209 */
210 export const checkServerReachability = Effect.fn("managedLimits.checkServerReachability")(
211 function* (
212 policy: PolicyDocument,
213 input: {
214 readonly authPolicy: ServerAuthPolicy;
215 readonly host: string | undefined;
216 readonly tailscaleServeEnabled: boolean;
217 /** The background service chose `host` to reach private networks; the user did not. */
218 readonly privateNetworkOnly?: boolean | undefined;
219 },
220 ) {
221 const cannotListen = () =>
222 refuseRemoteClients(
223 policy,
224 input.privateNetworkOnly === true
225 ? "so the background service cannot listen on private networks; set T3CODE_HOST=127.0.0.1 in its service.env"
226 : `so the server cannot listen on ${input.host === "" ? "every interface" : (input.host ?? "this host")}`,
227 );
228 if (!allowsAuthPolicy(policy, input.authPolicy)) {
229 return yield* input.authPolicy === "remote-reachable"
230 ? cannotListen()
231 : refuse(policy, AUTH_POLICY_ACTION[input.authPolicy]);
232 }
233 if (allowsRemoteClients(policy)) return input.host ?? "127.0.0.1";
234 if (input.tailscaleServeEnabled) {
235 return yield* refuseRemoteClients(policy, "so Tailscale Serve cannot be turned on");
236 }
237 return loopbackBindAddress(input.host) ?? (yield* cannotListen());
238 },
239 );