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
| 1 | import type { ManagedPolicyDocument } from "@t3tools/contracts"; |
| 2 | import { assert, it } from "@effect/vitest"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Fiber from "effect/Fiber"; |
| 5 | import * as PlatformError from "effect/PlatformError"; |
| 6 | import * as Sink from "effect/Sink"; |
| 7 | import * as Stream from "effect/Stream"; |
| 8 | import * as TestClock from "effect/testing/TestClock"; |
| 9 | import { ChildProcessSpawner } from "effect/process"; |
| 10 | |
| 11 | import * as NetService from "@t3tools/shared/Net"; |
| 12 | |
| 13 | import * as EnvironmentAuthPolicy from "../auth/EnvironmentAuthPolicy.ts"; |
| 14 | import * as ManagedLimits from "./managedLimits.ts"; |
| 15 | import * as ManagedPolicy from "./ManagedPolicy.ts"; |
| 16 | |
| 17 | const policy = (limits?: ManagedPolicyDocument["limits"]) => ({ |
| 18 | document: { |
| 19 | schemaVersion: 1 as const, |
| 20 | organization: "Example Corp", |
| 21 | ...(limits === undefined ? {} : { limits }), |
| 22 | }, |
| 23 | }); |
| 24 | |
| 25 | const desktopAndLocal = policy({ clients: ["desktop", "local-browser"] }); |
| 26 | |
| 27 | it.effect("refuses to listen on a non-loopback host when remote clients are not allowed", () => |
| 28 | Effect.gen(function* () { |
| 29 | const error = yield* ManagedLimits.checkServerReachability(desktopAndLocal, { |
| 30 | authPolicy: "remote-reachable", |
| 31 | host: "0.0.0.0", |
| 32 | tailscaleServeEnabled: false, |
| 33 | }).pipe(Effect.flip); |
| 34 | assert.equal( |
| 35 | error.message, |
| 36 | "Example Corp's policy does not allow remote clients, so the server cannot listen on 0.0.0.0.", |
| 37 | ); |
| 38 | }), |
| 39 | ); |
| 40 | |
| 41 | it.effect("binds only the loopback address it approved when remote clients are not allowed", () => |
| 42 | Effect.gen(function* () { |
| 43 | const bind = ( |
| 44 | host: string | undefined, |
| 45 | policy: { readonly document: ManagedPolicyDocument | undefined } = desktopAndLocal, |
| 46 | ) => |
| 47 | ManagedLimits.checkServerReachability(policy, { |
| 48 | authPolicy: EnvironmentAuthPolicy.resolveServerAuthPolicy({ mode: "web", host }), |
| 49 | host, |
| 50 | tailscaleServeEnabled: false, |
| 51 | }); |
| 52 | // Node listens on every interface for an empty host, and a name resolves through DNS. |
| 53 | for (const host of ["", "127.office.example", "127.0.0.1e0", "0.0.0.0"]) { |
| 54 | const error = yield* bind(host).pipe(Effect.flip); |
| 55 | assert.include(error.message, "does not allow remote clients", host); |
| 56 | } |
| 57 | for (const [host, address] of [ |
| 58 | [undefined, "127.0.0.1"], |
| 59 | ["localhost", "127.0.0.1"], |
| 60 | ["127.0.0.2", "127.0.0.2"], |
| 61 | ["[::1]", "::1"], |
| 62 | ] as const) { |
| 63 | assert.equal(yield* bind(host), address); |
| 64 | } |
| 65 | const service = yield* ManagedLimits.checkServerReachability(desktopAndLocal, { |
| 66 | authPolicy: "remote-reachable", |
| 67 | host: "0.0.0.0", |
| 68 | tailscaleServeEnabled: false, |
| 69 | privateNetworkOnly: true, |
| 70 | }).pipe(Effect.flip); |
| 71 | assert.include(service.message, "set T3CODE_HOST=127.0.0.1 in its service.env"); |
| 72 | assert.equal(yield* bind("localhost", { document: undefined }), "localhost"); |
| 73 | assert.equal(yield* bind(undefined, { document: undefined }), "127.0.0.1"); |
| 74 | }), |
| 75 | ); |
| 76 | |
| 77 | it.effect("refuses Tailscale Serve when remote clients are not allowed", () => |
| 78 | Effect.gen(function* () { |
| 79 | const error = yield* ManagedLimits.checkServerReachability(desktopAndLocal, { |
| 80 | authPolicy: "loopback-browser", |
| 81 | host: undefined, |
| 82 | tailscaleServeEnabled: true, |
| 83 | }).pipe(Effect.flip); |
| 84 | assert.include(error.message, "Tailscale Serve"); |
| 85 | }), |
| 86 | ); |
| 87 | |
| 88 | it.effect("refuses an auth policy the clients list leaves out", () => |
| 89 | Effect.gen(function* () { |
| 90 | const error = yield* ManagedLimits.checkServerReachability(policy({ clients: ["desktop"] }), { |
| 91 | authPolicy: "loopback-browser", |
| 92 | host: undefined, |
| 93 | tailscaleServeEnabled: false, |
| 94 | }).pipe(Effect.flip); |
| 95 | assert.equal(error.message, "Example Corp's policy does not allow browsers on this machine."); |
| 96 | }), |
| 97 | ); |
| 98 | |
| 99 | it.effect("refuses unsafe-no-auth under any policy file, even one without limits", () => |
| 100 | Effect.gen(function* () { |
| 101 | const error = yield* ManagedLimits.checkServerReachability(policy(), { |
| 102 | authPolicy: "unsafe-no-auth", |
| 103 | host: undefined, |
| 104 | tailscaleServeEnabled: false, |
| 105 | }).pipe(Effect.flip); |
| 106 | assert.include(error.message, "without authentication"); |
| 107 | assert.isTrue(ManagedLimits.allowsAuthPolicy({ document: undefined }, "unsafe-no-auth")); |
| 108 | }), |
| 109 | ); |
| 110 | |
| 111 | it.effect("allows the clients the policy lists", () => |
| 112 | ManagedLimits.checkServerReachability(policy({ clients: ["remote"] }), { |
| 113 | authPolicy: "remote-reachable", |
| 114 | host: "0.0.0.0", |
| 115 | tailscaleServeEnabled: true, |
| 116 | }), |
| 117 | ); |
| 118 | |
| 119 | it.effect("tells clients Connect is off when the policy leaves out remote clients", () => |
| 120 | Effect.gen(function* () { |
| 121 | const managed = yield* ManagedPolicy.fromDocument("/test/policy.json", { |
| 122 | ...desktopAndLocal.document, |
| 123 | }); |
| 124 | assert.deepEqual(managed.summary?.limits, { |
| 125 | clients: ["desktop", "local-browser"], |
| 126 | connect: false, |
| 127 | }); |
| 128 | assert.isTrue(ManagedLimits.allowsConnect(policy({ clients: ["remote"] }))); |
| 129 | assert.isFalse(ManagedLimits.allowsConnect(policy({ connect: false }))); |
| 130 | }), |
| 131 | ); |
| 132 | |
| 133 | it.effect( |
| 134 | "turns off only the Tailscale Serve routes that forward here, and refuses to start if one stays", |
| 135 | () => { |
| 136 | type Web = Record<string, Record<string, string>>; |
| 137 | interface Answers { |
| 138 | /** Serve handlers by host:port, then mount, to proxy target. */ |
| 139 | readonly web?: Web; |
| 140 | /** TCP forwards by port. */ |
| 141 | readonly tcp?: Record<string, string>; |
| 142 | /** The name `off` acts on: the machine's current one. */ |
| 143 | readonly currentName?: string; |
| 144 | readonly status?: { |
| 145 | readonly stdout: string; |
| 146 | readonly exitCode: number; |
| 147 | readonly stderr?: string; |
| 148 | }; |
| 149 | readonly offExitCode?: number; |
| 150 | /** `serve status` never answers, as on a Mac where Tailscale was never set up. */ |
| 151 | readonly statusHangs?: boolean; |
| 152 | /** `off` exits as told but leaves the config alone. */ |
| 153 | readonly offIgnored?: boolean; |
| 154 | } |
| 155 | // Acts as the real CLI: `serve status --json` prints the config; `serve --https=<port> off` |
| 156 | // drops every handler on that port of the current name unless `--set-path` names one |
| 157 | // (serve_v2.go removeWebServe), and `serve --tcp=<port> off` drops that port's forward. |
| 158 | const close = (answers: Answers, offCalls: Array<ReadonlyArray<string>> = []) => { |
| 159 | const web: Web = answers.web ?? { |
| 160 | "box.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" }, |
| 161 | }; |
| 162 | const tcp = answers.tcp ?? {}; |
| 163 | const currentName = answers.currentName ?? "box.tailnet.ts.net"; |
| 164 | return ManagedLimits.closeTailscaleServeTo(desktopAndLocal, { |
| 165 | host: "127.0.0.1", |
| 166 | port: 3773, |
| 167 | }).pipe( |
| 168 | Effect.provideService( |
| 169 | ChildProcessSpawner.ChildProcessSpawner, |
| 170 | ChildProcessSpawner.make((command) => { |
| 171 | const { args } = command as unknown as { readonly args: ReadonlyArray<string> }; |
| 172 | // `tailscale status --json` names the machine; `tailscale serve status --json` routes. |
| 173 | if (args[0] === "status") { |
| 174 | return Effect.succeed( |
| 175 | ChildProcessSpawner.makeHandle({ |
| 176 | pid: ChildProcessSpawner.ProcessId(1), |
| 177 | exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), |
| 178 | isRunning: Effect.succeed(false), |
| 179 | kill: () => Effect.void, |
| 180 | unref: Effect.succeed(Effect.void), |
| 181 | stdin: Sink.drain, |
| 182 | stdout: Stream.make( |
| 183 | new TextEncoder().encode( |
| 184 | JSON.stringify({ Self: { DNSName: `${currentName}.` } }), |
| 185 | ), |
| 186 | ), |
| 187 | stderr: Stream.empty, |
| 188 | all: Stream.empty, |
| 189 | getInputFd: () => Sink.drain, |
| 190 | getOutputFd: () => Stream.empty, |
| 191 | }), |
| 192 | ); |
| 193 | } |
| 194 | const isStatus = args.includes("status"); |
| 195 | if (!isStatus) { |
| 196 | offCalls.push(args); |
| 197 | const port = args.find((arg) => arg.startsWith("--https="))?.slice(8); |
| 198 | const tcpPort = args.find((arg) => arg.startsWith("--tcp="))?.slice(6); |
| 199 | const mount = args.find((arg) => arg.startsWith("--set-path="))?.slice(11); |
| 200 | const site = web[`${currentName}:${port}`]; |
| 201 | if (answers.offIgnored !== true) { |
| 202 | if (tcpPort !== undefined) delete tcp[tcpPort]; |
| 203 | for (const handler of Object.keys(site ?? {})) { |
| 204 | if (mount === undefined || mount === handler) delete site![handler]; |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | const status = answers.status ?? { |
| 209 | stdout: JSON.stringify({ |
| 210 | TCP: Object.fromEntries( |
| 211 | Object.entries(tcp).map(([port, forward]) => [port, { TCPForward: forward }]), |
| 212 | ), |
| 213 | Web: Object.fromEntries( |
| 214 | Object.entries(web).map(([hostPort, handlers]) => [ |
| 215 | hostPort, |
| 216 | { |
| 217 | Handlers: Object.fromEntries( |
| 218 | Object.entries(handlers).map(([mount, proxy]) => [mount, { Proxy: proxy }]), |
| 219 | ), |
| 220 | }, |
| 221 | ]), |
| 222 | ), |
| 223 | }), |
| 224 | exitCode: 0, |
| 225 | }; |
| 226 | const text = (value: string | undefined) => |
| 227 | value === undefined ? Stream.empty : Stream.make(new TextEncoder().encode(value)); |
| 228 | return Effect.succeed( |
| 229 | ChildProcessSpawner.makeHandle({ |
| 230 | pid: ChildProcessSpawner.ProcessId(1), |
| 231 | exitCode: |
| 232 | isStatus && answers.statusHangs === true |
| 233 | ? Effect.never |
| 234 | : Effect.succeed( |
| 235 | ChildProcessSpawner.ExitCode( |
| 236 | isStatus ? status.exitCode : (answers.offExitCode ?? 0), |
| 237 | ), |
| 238 | ), |
| 239 | isRunning: Effect.succeed(false), |
| 240 | kill: () => Effect.void, |
| 241 | unref: Effect.succeed(Effect.void), |
| 242 | stdin: Sink.drain, |
| 243 | stdout: isStatus ? text(status.stdout) : Stream.empty, |
| 244 | stderr: isStatus ? text(status.stderr) : Stream.empty, |
| 245 | all: Stream.empty, |
| 246 | getInputFd: () => Sink.drain, |
| 247 | getOutputFd: () => Stream.empty, |
| 248 | }), |
| 249 | ); |
| 250 | }), |
| 251 | ), |
| 252 | ); |
| 253 | }; |
| 254 | const portFree = { ...NetService.make(), canListenOnHost: () => Effect.succeed(true) }; |
| 255 | const portHeld = { ...portFree, canListenOnHost: () => Effect.succeed(false) }; |
| 256 | return Effect.gen(function* () { |
| 257 | // A route that shares the port with this server's stays, as does one to another loopback |
| 258 | // address on the same port; a TCP forward here goes too. |
| 259 | for (const mount of ["/t3", "/"]) { |
| 260 | const web: Web = { |
| 261 | "box.tailnet.ts.net:443": { |
| 262 | [mount]: "http://127.0.0.1:3773", |
| 263 | "/dashboard": "http://127.0.0.1:9000", |
| 264 | "/other": "http://127.0.0.2:3773", |
| 265 | }, |
| 266 | }; |
| 267 | const tcp: Record<string, string> = { "7000": "127.0.0.1:3773" }; |
| 268 | const offCalls: Array<ReadonlyArray<string>> = []; |
| 269 | yield* close({ web, tcp }, offCalls); |
| 270 | assert.deepEqual(web, { |
| 271 | "box.tailnet.ts.net:443": { |
| 272 | "/dashboard": "http://127.0.0.1:9000", |
| 273 | "/other": "http://127.0.0.2:3773", |
| 274 | }, |
| 275 | }); |
| 276 | assert.deepEqual(tcp, {}); |
| 277 | assert.deepEqual(offCalls, [ |
| 278 | ["serve", "--tcp=7000", "off"], |
| 279 | ["serve", "--https=443", `--set-path=${mount}`, "off"], |
| 280 | ]); |
| 281 | } |
| 282 | // `off` acts on the current name: a route under a former one is left, with how to clear it, |
| 283 | // while one under the current name goes even if a former name has routes too. |
| 284 | const renamed: Web = { |
| 285 | "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" }, |
| 286 | "new.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" }, |
| 287 | }; |
| 288 | const renamedOffCalls: Array<ReadonlyArray<string>> = []; |
| 289 | const former = yield* close( |
| 290 | { web: renamed, currentName: "new.tailnet.ts.net" }, |
| 291 | renamedOffCalls, |
| 292 | ).pipe(Effect.flip); |
| 293 | assert.deepEqual(renamedOffCalls, []); |
| 294 | assert.deepEqual(renamed["new.tailnet.ts.net:443"], { "/": "http://127.0.0.1:9000" }); |
| 295 | assert.include( |
| 296 | former.message, |
| 297 | 'under old.tailnet.ts.net, a former name of this machine, which "tailscale serve ... off" cannot reach; run "tailscale serve reset"', |
| 298 | ); |
| 299 | const current: Web = { |
| 300 | "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" }, |
| 301 | "new.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" }, |
| 302 | }; |
| 303 | yield* close({ web: current, currentName: "new.tailnet.ts.net" }); |
| 304 | assert.deepEqual(current, { |
| 305 | "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" }, |
| 306 | "new.tailnet.ts.net:443": {}, |
| 307 | }); |
| 308 | // A `localhost` target might reach another service on the other loopback, so it stays. |
| 309 | const localhostOffCalls: Array<ReadonlyArray<string>> = []; |
| 310 | const localhost = yield* close( |
| 311 | { web: { "box.tailnet.ts.net:443": { "/": "http://localhost:3773" } } }, |
| 312 | localhostOffCalls, |
| 313 | ).pipe(Effect.flip); |
| 314 | assert.deepEqual(localhostOffCalls, []); |
| 315 | assert.include(localhost.message, "its target localhost might be another service"); |
| 316 | // Only a fresh read confirms the route is gone, whatever `off` exits with. |
| 317 | for (const answers of [{ offIgnored: true }, { offIgnored: true, offExitCode: 1 }]) { |
| 318 | const stuck = yield* close(answers).pipe(Effect.flip); |
| 319 | assert.include( |
| 320 | stuck.message, |
| 321 | 'Tailscale Serve forwards port 443 at / here; turn it off with "tailscale serve --https=443 --set-path=/ off"', |
| 322 | ); |
| 323 | } |
| 324 | // Routes the server must not remove itself: a Service's, and a foreground command's. |
| 325 | const owners = { |
| 326 | stdout: JSON.stringify({ |
| 327 | Foreground: { |
| 328 | session1: { |
| 329 | Web: { "box:443": { Handlers: { "/": { Proxy: "http://127.0.0.1:3773" } } } }, |
| 330 | }, |
| 331 | }, |
| 332 | Services: { |
| 333 | "svc:t3": { |
| 334 | Web: { "t3:443": { Handlers: { "/t3": { Proxy: "http://127.0.0.1:3773" } } } }, |
| 335 | }, |
| 336 | }, |
| 337 | }), |
| 338 | exitCode: 0, |
| 339 | }; |
| 340 | const ownedOffCalls: Array<ReadonlyArray<string>> = []; |
| 341 | const owned = yield* close({ status: owners }, ownedOffCalls).pipe(Effect.flip); |
| 342 | assert.deepEqual(ownedOffCalls, []); |
| 343 | assert.include(owned.message, 'stop the "tailscale serve" command that runs it'); |
| 344 | assert.include( |
| 345 | owned.message, |
| 346 | '"tailscale serve --service=svc:t3 --https=443 --set-path=/t3 off"', |
| 347 | ); |
| 348 | // An answer that cannot be read might hide a mapping, so the server does not start. |
| 349 | const dialFailure = (reason: string) => |
| 350 | `Failed to connect to local Tailscale daemon for /localapi/v0/serve-config; not running? Error: dial unix /var/run/tailscale/tailscaled.sock: connect: ${reason}`; |
| 351 | for (const status of [ |
| 352 | { stdout: "", exitCode: 1, stderr: "something unexpected" }, |
| 353 | { stdout: "not json", exitCode: 0 }, |
| 354 | { stdout: "", exitCode: 1, stderr: "Access denied: serve config denied" }, |
| 355 | { stdout: "", exitCode: 1, stderr: dialFailure("permission denied") }, |
| 356 | ]) { |
| 357 | const unread = yield* close({ status }).pipe(Effect.flip); |
| 358 | assert.include(unread.message, "does not start until Tailscale Serve can be checked"); |
| 359 | } |
| 360 | // A Tailscale that never answers is not read as nothing to close, and the refusal says why. |
| 361 | const hung = yield* close({ statusHangs: true }).pipe(Effect.flip, Effect.forkChild); |
| 362 | yield* TestClock.adjust("10 seconds"); |
| 363 | assert.include((yield* Fiber.join(hung)).message, "Tailscale did not answer"); |
| 364 | // Tailscale down, logged out, or not installed forwards nothing now. |
| 365 | for (const stderr of [ |
| 366 | dialFailure("connection refused"), |
| 367 | "NeedsLogin: not logged in", |
| 368 | String.raw`Get "http://local-tailscaled.sock/localapi/v0/serve-config": open \\.\pipe\ProtectedPrefix\Administrators\Tailscale\tailscaled: The system cannot find the file specified.`, |
| 369 | ]) { |
| 370 | yield* close({ status: { stdout: "", exitCode: 1, stderr } }); |
| 371 | } |
| 372 | const spawnFailing = (tag: "NotFound" | "PermissionDenied") => |
| 373 | ManagedLimits.closeTailscaleServeTo(desktopAndLocal, { |
| 374 | host: "127.0.0.1", |
| 375 | port: 3773, |
| 376 | }).pipe( |
| 377 | Effect.provideService( |
| 378 | ChildProcessSpawner.ChildProcessSpawner, |
| 379 | ChildProcessSpawner.make(() => |
| 380 | Effect.fail( |
| 381 | PlatformError.systemError({ _tag: tag, module: "ChildProcess", method: "spawn" }), |
| 382 | ), |
| 383 | ), |
| 384 | ), |
| 385 | ); |
| 386 | yield* spawnFailing("NotFound"); |
| 387 | // Node throws this instead when PATH ends in a file. |
| 388 | yield* ManagedLimits.closeTailscaleServeTo(desktopAndLocal, { |
| 389 | host: "127.0.0.1", |
| 390 | port: 3773, |
| 391 | }).pipe( |
| 392 | Effect.provideService( |
| 393 | ChildProcessSpawner.ChildProcessSpawner, |
| 394 | ChildProcessSpawner.make(() => |
| 395 | Effect.die(Object.assign(new Error("spawn tailscale ENOTDIR"), { code: "ENOTDIR" })), |
| 396 | ), |
| 397 | ), |
| 398 | ); |
| 399 | // A CLI that is there but will not run might still front a daemon with a mapping. |
| 400 | yield* spawnFailing("PermissionDenied").pipe(Effect.flip); |
| 401 | // Another app holds the port: its route is not ours, and it could let go before the bind. |
| 402 | const heldOffCalls: Array<ReadonlyArray<string>> = []; |
| 403 | const held = yield* close({}, heldOffCalls).pipe( |
| 404 | Effect.provideService(NetService.NetService, portHeld), |
| 405 | Effect.flip, |
| 406 | ); |
| 407 | assert.deepEqual(heldOffCalls, []); |
| 408 | assert.include(held.message, "while it cannot bind 127.0.0.1:3773"); |
| 409 | }).pipe(Effect.provideService(NetService.NetService, portFree)); |
| 410 | }, |
| 411 | ); |