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 { |
| 2 | AuthRelayReadScope, |
| 3 | AuthRelayWriteScope, |
| 4 | type EnvironmentConnectReachability, |
| 5 | formatConnectReachable, |
| 6 | type RelayClientInstallProgressEvent, |
| 7 | type RelayClientInstallProgressStage, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import { RelayOkResponse } from "@t3tools/contracts/relay"; |
| 10 | import * as RelayClient from "@t3tools/shared/relayClient"; |
| 11 | import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; |
| 12 | import * as Cause from "effect/Cause"; |
| 13 | import * as Clock from "effect/Clock"; |
| 14 | import * as Config from "effect/Config"; |
| 15 | import * as Console from "effect/Console"; |
| 16 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 17 | import * as Duration from "effect/Duration"; |
| 18 | import * as Effect from "effect/Effect"; |
| 19 | import * as Exit from "effect/Exit"; |
| 20 | import * as FileSystem from "effect/FileSystem"; |
| 21 | import * as Layer from "effect/Layer"; |
| 22 | import * as Option from "effect/Option"; |
| 23 | import * as Path from "effect/Path"; |
| 24 | import * as References from "effect/References"; |
| 25 | import * as Schema from "effect/Schema"; |
| 26 | import { Command, Flag, GlobalFlag, Prompt } from "effect/cli"; |
| 27 | import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; |
| 28 | |
| 29 | import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; |
| 30 | import * as ManagedLimits from "../policy/managedLimits.ts"; |
| 31 | import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; |
| 32 | import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; |
| 33 | import * as BootService from "../cloud/bootService.ts"; |
| 34 | import * as CliState from "../cloud/CliState.ts"; |
| 35 | import * as CliTokenManager from "../cloud/CliTokenManager.ts"; |
| 36 | import { formatReachabilityFailure } from "../cloud/ConnectReachability.ts"; |
| 37 | import { filterRelayResponse } from "../cloud/relayResponse.ts"; |
| 38 | import { |
| 39 | CLOUD_ENDPOINT_RUNTIME_CONFIG, |
| 40 | CLOUD_LINK_REVOKED, |
| 41 | CLOUD_LINKED_USER_ID, |
| 42 | isAgentActivityPublishingEnabledValue, |
| 43 | PUBLISH_AGENT_ACTIVITY_SECRET, |
| 44 | RELAY_ENVIRONMENT_CREDENTIAL_SECRET, |
| 45 | RELAY_URL_SECRET, |
| 46 | } from "../cloud/config.ts"; |
| 47 | import { relayUrlConfig } from "../cloud/publicConfig.ts"; |
| 48 | import * as RelayTracing from "../cloud/relayTracing.ts"; |
| 49 | import * as ServerConfig from "../config.ts"; |
| 50 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 51 | import * as ExternalLauncher from "../process/externalLauncher.ts"; |
| 52 | import { |
| 53 | isProcessAlive, |
| 54 | readLiveServerRuntimeState, |
| 55 | readPersistedServerRuntimeState, |
| 56 | } from "../serverRuntimeState.ts"; |
| 57 | import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; |
| 58 | import * as RunningServer from "./runningServer.ts"; |
| 59 | import { resolveHostCliHint } from "./invocation.ts"; |
| 60 | import * as CliService from "./service.ts"; |
| 61 | |
| 62 | const jsonFlag = Flag.Boolean("json").pipe( |
| 63 | Flag.withDescription("Emit JSON instead of human-readable output."), |
| 64 | Flag.withDefault(false), |
| 65 | ); |
| 66 | |
| 67 | const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError); |
| 68 | |
| 69 | export const headlessFlag = Flag.Boolean("headless").pipe( |
| 70 | Flag.withDescription( |
| 71 | "Sign in with a URL and code on any device. Automatic without a terminal or over SSH.", |
| 72 | ), |
| 73 | Flag.withDefault(false), |
| 74 | ); |
| 75 | |
| 76 | /** |
| 77 | * Inside an SSH session there is no local browser to complete the loopback |
| 78 | * OAuth callback, so the device authorization grant is the only flow that |
| 79 | * can work. |
| 80 | */ |
| 81 | const headlessSessionConfig = Config.all({ |
| 82 | sshConnection: Config.String("SSH_CONNECTION").pipe(Config.option), |
| 83 | sshTty: Config.String("SSH_TTY").pipe(Config.option), |
| 84 | }).pipe( |
| 85 | Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)), |
| 86 | ); |
| 87 | |
| 88 | const showDeviceAuthorizationPrompt = (prompt: CliTokenManager.DeviceAuthorizationPrompt) => |
| 89 | Console.log(formatDeviceAuthorizationPrompt(prompt)); |
| 90 | |
| 91 | function formatDeviceAuthorizationPrompt( |
| 92 | prompt: CliTokenManager.DeviceAuthorizationPrompt, |
| 93 | ): string { |
| 94 | const minutes = Math.max(1, Math.round(Duration.toMinutes(prompt.expiresIn))); |
| 95 | return [ |
| 96 | "Sign in to T3 Connect. Open on any device:", |
| 97 | ` ${prompt.verificationUriComplete ?? prompt.verificationUri}`, |
| 98 | `Code: ${prompt.userCode}`, |
| 99 | `Waiting for approval. Expires in ${minutes} min. Ctrl+C cancels.`, |
| 100 | ].join("\n"); |
| 101 | } |
| 102 | |
| 103 | const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: { |
| 104 | readonly headless: boolean; |
| 105 | }) { |
| 106 | const tokens = yield* CliTokenManager.CloudCliTokenManager; |
| 107 | // Without a terminal, no key press can open a browser, so sign in with a code. |
| 108 | const useOutOfBandOAuth = |
| 109 | options.headless || |
| 110 | (yield* headlessSessionConfig) || |
| 111 | !(process.stdin.isTTY && process.stdout.isTTY); |
| 112 | if (!useOutOfBandOAuth) { |
| 113 | const authorization = yield* tokens.get; |
| 114 | if (authorization._tag === "Authorized") { |
| 115 | return authorization.token.identity ?? null; |
| 116 | } |
| 117 | } |
| 118 | const existing = yield* tokens.getExisting.pipe( |
| 119 | Effect.catchTags({ |
| 120 | CloudCliCredentialRefreshError: () => |
| 121 | Console.log("T3 Connect sign-in expired. Sign in again.").pipe(Effect.as(Option.none())), |
| 122 | }), |
| 123 | ); |
| 124 | if (Option.isSome(existing)) { |
| 125 | return existing.value.identity ?? null; |
| 126 | } |
| 127 | const { token, identity } = yield* CliTokenManager.deviceAuthorizationLogin( |
| 128 | showDeviceAuthorizationPrompt, |
| 129 | ).pipe( |
| 130 | Effect.mapError((cause) => |
| 131 | isCloudCliTokenManagerError(cause) |
| 132 | ? cause |
| 133 | : new CliTokenManager.CloudCliAuthorizationError({ cause }), |
| 134 | ), |
| 135 | ); |
| 136 | yield* tokens.store(token); |
| 137 | return identity; |
| 138 | }); |
| 139 | |
| 140 | function bytesToString(value: Uint8Array): string { |
| 141 | return new TextDecoder().decode(value); |
| 142 | } |
| 143 | |
| 144 | function stringToBytes(value: string): Uint8Array { |
| 145 | return new TextEncoder().encode(value); |
| 146 | } |
| 147 | |
| 148 | interface CloudCliStatus { |
| 149 | readonly desired: boolean; |
| 150 | readonly authenticated: boolean; |
| 151 | readonly linked: boolean; |
| 152 | readonly revoked: boolean; |
| 153 | readonly cloudUserId: string | null; |
| 154 | readonly relayUrl: string | null; |
| 155 | readonly publishAgentActivity: boolean; |
| 156 | readonly relayClient: RelayClient.RelayClientStatus; |
| 157 | readonly linkMode: CliState.CliDesiredLinkMode; |
| 158 | /** `null` when no server answered the live check, or none ran because no tunnel is wanted. */ |
| 159 | readonly reachability: EnvironmentConnectReachability | null; |
| 160 | } |
| 161 | |
| 162 | function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> { |
| 163 | switch (executable.status) { |
| 164 | case "available": { |
| 165 | const source = |
| 166 | executable.source === "path" |
| 167 | ? "PATH" |
| 168 | : executable.source === "managed" |
| 169 | ? "managed install" |
| 170 | : "configured override"; |
| 171 | return [ |
| 172 | ` Relay client: available via ${source}`, |
| 173 | ` Path: ${executable.executablePath}`, |
| 174 | ` Version: ${executable.version}`, |
| 175 | ]; |
| 176 | } |
| 177 | case "missing": |
| 178 | return [" Relay client: not installed"]; |
| 179 | case "unsupported": |
| 180 | return [ |
| 181 | ` Relay client: unsupported on ${executable.platform}-${executable.arch}`, |
| 182 | ` Managed version: ${executable.version}`, |
| 183 | ]; |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | function formatCloudStatus( |
| 188 | status: CloudCliStatus, |
| 189 | commands: { readonly link: string; readonly serviceStatus: string }, |
| 190 | options?: { readonly json?: boolean }, |
| 191 | ): string { |
| 192 | if (options?.json) { |
| 193 | return JSON.stringify(status, null, 2); |
| 194 | } |
| 195 | |
| 196 | const provisioned = status.revoked |
| 197 | ? "removed from T3 Connect" |
| 198 | : status.linked |
| 199 | ? "provisioned" |
| 200 | : status.desired && status.authenticated |
| 201 | ? "pending server startup" |
| 202 | : "not provisioned"; |
| 203 | const publishOnly = status.desired && status.linkMode === "publish_only"; |
| 204 | // An app-made link needs no CLI credential once provisioned. |
| 205 | const nextStep = |
| 206 | status.desired && status.linked && !status.revoked |
| 207 | ? undefined |
| 208 | : !status.authenticated |
| 209 | ? `Run \`${commands.link}\` to authorize and enable T3 Connect.` |
| 210 | : status.revoked |
| 211 | ? `Run \`${commands.link}\` to link this environment again.` |
| 212 | : !status.desired |
| 213 | ? `Run \`${commands.link}\` to enable T3 Connect.` |
| 214 | : publishOnly |
| 215 | ? "Start T3 to provision the environment link." |
| 216 | : "Start T3 to provision the environment link and launch its managed tunnel."; |
| 217 | |
| 218 | return [ |
| 219 | "T3 Connect", |
| 220 | ` Exposure: ${publishOnly ? "publish-only" : status.desired ? "enabled" : "disabled"}`, |
| 221 | ` Authorization: ${status.authenticated ? "stored credential" : "missing"}`, |
| 222 | ` Environment link: ${provisioned}`, |
| 223 | ` Relay: ${status.relayUrl ?? "not provisioned"}`, |
| 224 | ` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`, |
| 225 | ...formatRelayClientStatus(status.relayClient), |
| 226 | ...(!status.desired |
| 227 | ? [] |
| 228 | : publishOnly |
| 229 | ? [ |
| 230 | "", |
| 231 | "This link only publishes agent activity. Remote access through T3 Connect is off, so other devices need their own route to this machine, such as LAN or Tailscale.", |
| 232 | ] |
| 233 | : status.reachability === null |
| 234 | ? [ |
| 235 | "", |
| 236 | `No running server answered, so reachability was not checked. Check the background service with \`${commands.serviceStatus}\`.`, |
| 237 | ] |
| 238 | : status.reachability.status === "reachable" |
| 239 | ? [ |
| 240 | "", |
| 241 | `✓ Other devices can reach this machine · ${formatConnectReachable(status.reachability)}`, |
| 242 | ] |
| 243 | : ["", formatReachabilityFailure(status.reachability)]), |
| 244 | ...(nextStep ? ["", `Next: ${nextStep}`] : []), |
| 245 | ].join("\n"); |
| 246 | } |
| 247 | |
| 248 | const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5); |
| 249 | |
| 250 | const confirmRelayClientInstall = (version: string) => |
| 251 | Prompt.run( |
| 252 | Prompt.Confirm({ |
| 253 | message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`, |
| 254 | initial: false, |
| 255 | }), |
| 256 | ); |
| 257 | |
| 258 | function relayClientInstallProgressMessage(stage: RelayClientInstallProgressStage): string { |
| 259 | switch (stage) { |
| 260 | case "checking": |
| 261 | return "Checking existing installation"; |
| 262 | case "waiting_for_lock": |
| 263 | return "Waiting for installation lock"; |
| 264 | case "downloading": |
| 265 | return "Downloading"; |
| 266 | case "verifying": |
| 267 | return "Verifying download"; |
| 268 | case "installing": |
| 269 | return "Installing"; |
| 270 | case "validating": |
| 271 | return "Validating executable"; |
| 272 | case "activating": |
| 273 | return "Activating installation"; |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | const reportRelayClientInstallProgress = (event: RelayClientInstallProgressEvent) => |
| 278 | event.type === "progress" |
| 279 | ? Console.log(`Relay client: ${relayClientInstallProgressMessage(event.stage)}...`) |
| 280 | : Effect.void; |
| 281 | |
| 282 | export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_client_for_link")( |
| 283 | function* <ConfirmError, ConfirmContext>( |
| 284 | relayClient: RelayClient.RelayClient["Service"], |
| 285 | confirmInstall: (version: string) => Effect.Effect<boolean, ConfirmError, ConfirmContext>, |
| 286 | reportProgress: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>, |
| 287 | ) { |
| 288 | const executable = yield* relayClient.resolve; |
| 289 | if (executable.status === "available") { |
| 290 | return Option.some(executable); |
| 291 | } |
| 292 | if (executable.status === "unsupported") { |
| 293 | return Option.some(yield* relayClient.installWithProgress(reportProgress)); |
| 294 | } |
| 295 | if (!(yield* confirmInstall(executable.version))) { |
| 296 | return Option.none(); |
| 297 | } |
| 298 | return Option.some(yield* relayClient.installWithProgress(reportProgress)); |
| 299 | }, |
| 300 | ); |
| 301 | |
| 302 | type LiveCloudActionResult = |
| 303 | | { readonly status: "not-running" } |
| 304 | | { readonly status: "server-gone" } |
| 305 | | { readonly status: "succeeded" } |
| 306 | | { readonly status: "failed"; readonly cause: Cause.Cause<unknown> }; |
| 307 | |
| 308 | const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () { |
| 309 | const config = yield* ServerConfig.ServerConfig; |
| 310 | const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath); |
| 311 | if (Option.isNone(runtimeState)) { |
| 312 | return { status: "not-running" } satisfies LiveCloudActionResult; |
| 313 | } |
| 314 | // A killed server leaves its record behind, and another process may own its port by now. |
| 315 | if (!isProcessAlive(runtimeState.value.pid)) { |
| 316 | return { status: "server-gone" } satisfies LiveCloudActionResult; |
| 317 | } |
| 318 | |
| 319 | const result = yield* Effect.exit( |
| 320 | RunningServer.serverClient(runtimeState.value.origin, [AuthRelayWriteScope]).pipe( |
| 321 | Effect.flatMap((client) => client.connect.unlink({ headers: {} })), |
| 322 | Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT), |
| 323 | Effect.scoped, |
| 324 | ), |
| 325 | ); |
| 326 | return Exit.isSuccess(result) |
| 327 | ? ({ status: "succeeded" } satisfies LiveCloudActionResult) |
| 328 | : ({ status: "failed", cause: result.cause } satisfies LiveCloudActionResult); |
| 329 | }); |
| 330 | |
| 331 | // One check probes the endpoint, the tunnel edge, and Tailscale, each with its own timeout. |
| 332 | const CLOUD_CLI_REACHABILITY_TIMEOUT = Duration.seconds(30); |
| 333 | const CLOUD_CLI_REACHABILITY_WAIT = Duration.seconds(60); |
| 334 | const CLOUD_CLI_REACHABILITY_RETRY = Duration.seconds(5); |
| 335 | |
| 336 | /** Asks the running server to check T3 Connect now. `null` when no server answers. */ |
| 337 | const checkLiveReachability = Effect.fn("cloud.cli.check_live_reachability")(function* () { |
| 338 | const config = yield* ServerConfig.ServerConfig; |
| 339 | const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath); |
| 340 | if (Option.isNone(runtimeState)) return null; |
| 341 | return yield* RunningServer.serverClient(runtimeState.value.origin, [AuthRelayReadScope]).pipe( |
| 342 | Effect.flatMap((client) => client.connect.checkReachability({ headers: {} })), |
| 343 | Effect.timeout(CLOUD_CLI_REACHABILITY_TIMEOUT), |
| 344 | Effect.scoped, |
| 345 | Effect.orElseSucceed(() => null), |
| 346 | ); |
| 347 | }); |
| 348 | |
| 349 | function formatAlertBox(text: string): string { |
| 350 | const lines = text.split("\n"); |
| 351 | const width = Math.max(...lines.map((line) => line.length)); |
| 352 | const color = process.stdout.isTTY === true && !process.env.NO_COLOR; |
| 353 | const red = (line: string) => (color ? `\x1b[1;31m${line}\x1b[0m` : line); |
| 354 | return [ |
| 355 | `┌${"─".repeat(width + 2)}┐`, |
| 356 | ...lines.map((line) => `│ ${line.padEnd(width)} │`), |
| 357 | `└${"─".repeat(width + 2)}┘`, |
| 358 | ] |
| 359 | .map(red) |
| 360 | .join("\n"); |
| 361 | } |
| 362 | |
| 363 | /** |
| 364 | * Waits for the server that `t3 connect` just started to prove other devices |
| 365 | * can reach it, so a broken tunnel fails setup instead of looking green. |
| 366 | */ |
| 367 | export const waitForReachability = Effect.fn("cloud.cli.wait_for_reachability")(function* () { |
| 368 | yield* Console.log("Checking T3 Connect..."); |
| 369 | const deadline = |
| 370 | (yield* Clock.currentTimeMillis) + Duration.toMillis(CLOUD_CLI_REACHABILITY_WAIT); |
| 371 | let last: EnvironmentConnectReachability | null = null; |
| 372 | while (true) { |
| 373 | last = (yield* checkLiveReachability()) ?? last; |
| 374 | if (last?.status === "reachable") { |
| 375 | yield* Console.log("✓ T3 Connect is reachable."); |
| 376 | return; |
| 377 | } |
| 378 | if ((yield* Clock.currentTimeMillis) >= deadline) break; |
| 379 | yield* Effect.sleep(CLOUD_CLI_REACHABILITY_RETRY); |
| 380 | } |
| 381 | yield* Console.error( |
| 382 | formatAlertBox( |
| 383 | last === null |
| 384 | ? "✕ Could not check T3 Connect\n The T3 server on this machine did not answer.\n Fix: run `t3 service status`, then `t3 connect status`." |
| 385 | : formatReachabilityFailure(last), |
| 386 | ), |
| 387 | ); |
| 388 | yield* Effect.sync(() => { |
| 389 | process.exitCode = 1; |
| 390 | }); |
| 391 | }); |
| 392 | |
| 393 | type RelayUnlinkResult = |
| 394 | | { readonly status: "not-authenticated" } |
| 395 | | { readonly status: "revoked" } |
| 396 | | { readonly status: "not-linked" }; |
| 397 | |
| 398 | type CloudDisconnectOperation = "live-server-unlink" | "relay-environment-unlink"; |
| 399 | |
| 400 | const logCloudDisconnectFailure = ( |
| 401 | operation: CloudDisconnectOperation, |
| 402 | clearAuthorization: boolean, |
| 403 | cause: Cause.Cause<unknown>, |
| 404 | ) => |
| 405 | Effect.logWarning("T3 Connect disconnect operation failed.").pipe( |
| 406 | Effect.annotateLogs({ |
| 407 | operation, |
| 408 | clearAuthorization, |
| 409 | cause: Cause.pretty(cause), |
| 410 | }), |
| 411 | ); |
| 412 | |
| 413 | const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () { |
| 414 | const tokens = yield* CliTokenManager.CloudCliTokenManager; |
| 415 | const token = yield* tokens.getExisting; |
| 416 | if (Option.isNone(token)) { |
| 417 | return { status: "not-authenticated" } satisfies RelayUnlinkResult; |
| 418 | } |
| 419 | |
| 420 | const environment = yield* ServerEnvironment.ServerEnvironmentIdentity; |
| 421 | const environmentId = yield* environment.getEnvironmentId; |
| 422 | const relayUrl = yield* relayUrlConfig; |
| 423 | const httpClient = yield* HttpClient.HttpClient; |
| 424 | const response = yield* HttpClientRequest.delete( |
| 425 | `${relayUrl}/v1/client/environment-links/${encodeURIComponent(environmentId)}`, |
| 426 | ).pipe( |
| 427 | HttpClientRequest.bearerToken(token.value.accessToken), |
| 428 | httpClient.execute, |
| 429 | Effect.flatMap(filterRelayResponse), |
| 430 | Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)), |
| 431 | withRelayClientTracing, |
| 432 | ); |
| 433 | return response.ok |
| 434 | ? ({ status: "revoked" } satisfies RelayUnlinkResult) |
| 435 | : ({ status: "not-linked" } satisfies RelayUnlinkResult); |
| 436 | }); |
| 437 | |
| 438 | /** |
| 439 | * Prints the local disconnect outcome, then whether the relay record was revoked. |
| 440 | * A missing CLI login or a failed relay DELETE leaves that record registered, so |
| 441 | * those outcomes warn to deregister it from the T3 Connect account page. |
| 442 | */ |
| 443 | const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")( |
| 444 | function* (input: { |
| 445 | readonly clearAuthorization: boolean; |
| 446 | readonly liveResult: LiveCloudActionResult; |
| 447 | readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>; |
| 448 | }) { |
| 449 | if (input.liveResult.status === "failed") { |
| 450 | yield* logCloudDisconnectFailure( |
| 451 | "live-server-unlink", |
| 452 | input.clearAuthorization, |
| 453 | input.liveResult.cause, |
| 454 | ); |
| 455 | yield* Console.warn( |
| 456 | "T3 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.", |
| 457 | ); |
| 458 | } else { |
| 459 | yield* Console.log("T3 Connect is disabled locally."); |
| 460 | // A killed server cannot stop the connector it started, and nothing adopts it on restart. |
| 461 | if (input.liveResult.status === "server-gone") { |
| 462 | yield* Console.warn( |
| 463 | "The server that ran T3 Connect is gone, but its cloudflared process may still be running.\nStop that process if it is.", |
| 464 | ); |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | if (Exit.isFailure(input.relayResult)) { |
| 469 | yield* logCloudDisconnectFailure( |
| 470 | "relay-environment-unlink", |
| 471 | input.clearAuthorization, |
| 472 | input.relayResult.cause, |
| 473 | ); |
| 474 | yield* Console.warn( |
| 475 | input.clearAuthorization |
| 476 | ? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally." |
| 477 | : "Could not revoke the relay-side environment record yet.\nRun `t3 connect unlink` again when the relay is reachable, or deregister it from the T3 Connect page of your T3 account.", |
| 478 | ); |
| 479 | } else if (input.relayResult.value.status === "not-authenticated") { |
| 480 | yield* Console.warn( |
| 481 | "The relay-side environment record was not revoked.\nDeregister it from the T3 Connect page of your T3 account, or run `t3 connect login` and retry.", |
| 482 | ); |
| 483 | } else if (input.relayResult.value.status === "revoked") { |
| 484 | yield* Console.log("Revoked the relay-side environment record."); |
| 485 | } |
| 486 | }, |
| 487 | ); |
| 488 | |
| 489 | export const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: { |
| 490 | readonly clearAuthorization: boolean; |
| 491 | }) { |
| 492 | yield* CliState.setCliDesiredCloudLink(false); |
| 493 | const liveResult = yield* runLiveCloudUnlink(); |
| 494 | const relayResult = yield* Effect.exit(unlinkRelayEnvironment()); |
| 495 | yield* CliState.clearPersistedCloudLink; |
| 496 | |
| 497 | if (options.clearAuthorization) { |
| 498 | const tokens = yield* CliTokenManager.CloudCliTokenManager; |
| 499 | yield* tokens.clear; |
| 500 | } |
| 501 | |
| 502 | yield* reportCloudDisconnectResults({ |
| 503 | clearAuthorization: options.clearAuthorization, |
| 504 | liveResult, |
| 505 | relayResult, |
| 506 | }); |
| 507 | |
| 508 | if (options.clearAuthorization) { |
| 509 | yield* Console.log( |
| 510 | "Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.", |
| 511 | ); |
| 512 | } |
| 513 | return liveResult; |
| 514 | }); |
| 515 | |
| 516 | export const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>( |
| 517 | flags: { readonly baseDir: Option.Option<string> }, |
| 518 | run: Effect.Effect< |
| 519 | A, |
| 520 | E, |
| 521 | | ServerSecretStore.ServerSecretStore |
| 522 | | CliTokenManager.CloudCliTokenManager |
| 523 | | RelayClient.RelayClient |
| 524 | | EnvironmentAuth.EnvironmentAuth |
| 525 | | BootService.BootService |
| 526 | | SecureRandom.SecureRandom |
| 527 | | FileSystem.FileSystem |
| 528 | | Path.Path |
| 529 | | HttpClient.HttpClient |
| 530 | | Prompt.Environment |
| 531 | | ServerConfig.ServerConfig |
| 532 | | ServerEnvironment.ServerEnvironmentIdentity |
| 533 | | ManagedPolicy.ManagedPolicy |
| 534 | >, |
| 535 | options?: { |
| 536 | readonly quietLogs?: boolean; |
| 537 | }, |
| 538 | ) { |
| 539 | const logLevel = yield* GlobalFlag.LogLevel; |
| 540 | const config = yield* resolveCliAuthConfig(flags, logLevel, options); |
| 541 | const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel; |
| 542 | const layerRuntime = Layer.mergeAll( |
| 543 | ServerSecretStore.layer, |
| 544 | CliTokenManager.layer.pipe( |
| 545 | Layer.provide(ServerSecretStore.layer), |
| 546 | Layer.provide(ExternalLauncher.layer), |
| 547 | ), |
| 548 | RelayClient.layerCloudflared({ baseDir: config.baseDir }), |
| 549 | EnvironmentAuth.layerRuntime, |
| 550 | CliService.layer(config), |
| 551 | RelayTracing.layerHeadlessRelayClient.pipe(Layer.provide(ManagedPolicy.layer)), |
| 552 | ).pipe( |
| 553 | Layer.provideMerge(FetchHttpClient.layer), |
| 554 | Layer.provideMerge(ServerConfig.layer(config)), |
| 555 | Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)), |
| 556 | ); |
| 557 | return yield* run.pipe(Effect.provide(layerRuntime)); |
| 558 | }); |
| 559 | |
| 560 | /** Status, unlink, and logout stay available so a machine can leave Connect the policy turned off. */ |
| 561 | export const requireConnectAllowed = Effect.gen(function* () { |
| 562 | const policy = yield* ManagedPolicy.ManagedPolicy; |
| 563 | if (!ManagedLimits.allowsConnect(policy)) { |
| 564 | return yield* ManagedLimits.refuseConnect(policy); |
| 565 | } |
| 566 | }); |
| 567 | |
| 568 | const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : ""); |
| 569 | |
| 570 | function formatRelayClientReady(version: string): string { |
| 571 | return `✓ Relay client ready · cloudflared ${version}`; |
| 572 | } |
| 573 | |
| 574 | const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: { |
| 575 | readonly headless: boolean; |
| 576 | readonly publishOnly?: boolean; |
| 577 | /** For `t3 up`, where the user already chose T3 Connect: install it quietly, without asking. */ |
| 578 | readonly installRelayClient?: boolean; |
| 579 | }) { |
| 580 | const publishOnly = options.publishOnly ?? false; |
| 581 | if (!publishOnly) { |
| 582 | const relayClient = yield* RelayClient.RelayClient; |
| 583 | const installed = yield* acquireRelayClientForLink( |
| 584 | relayClient, |
| 585 | options.installRelayClient === true ? () => Effect.succeed(true) : confirmRelayClientInstall, |
| 586 | options.installRelayClient === true |
| 587 | ? (event) => |
| 588 | event.type === "progress" && event.stage === "downloading" |
| 589 | ? Console.log("Installing the T3 Connect relay client...") |
| 590 | : Effect.void |
| 591 | : reportRelayClientInstallProgress, |
| 592 | ); |
| 593 | if (Option.isNone(installed)) { |
| 594 | yield* Console.log("T3 Connect setup cancelled. The relay client was not installed."); |
| 595 | return null; |
| 596 | } |
| 597 | if (options.installRelayClient !== true) { |
| 598 | yield* Console.log(formatRelayClientReady(installed.value.version)); |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | const identity = yield* authorizeCli(options); |
| 603 | yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed"); |
| 604 | if (yield* CliState.dropRevokedCloudLink) { |
| 605 | yield* Console.log("Replacing the link T3 Connect revoked."); |
| 606 | } |
| 607 | if (publishOnly) { |
| 608 | const secrets = yield* ServerSecretStore.ServerSecretStore; |
| 609 | yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true")); |
| 610 | } |
| 611 | return { identity } as const; |
| 612 | }); |
| 613 | export { linkEnvironmentForConnect }; |
| 614 | |
| 615 | const connectLoginCommand = Command.make("login", { |
| 616 | ...projectLocationFlags, |
| 617 | headless: headlessFlag, |
| 618 | }).pipe( |
| 619 | Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."), |
| 620 | Command.withHandler((flags) => |
| 621 | runCloudCommand( |
| 622 | flags, |
| 623 | Effect.gen(function* () { |
| 624 | yield* requireConnectAllowed; |
| 625 | yield* Console.log("T3 Connect\n"); |
| 626 | const identity = yield* authorizeCli(flags); |
| 627 | yield* Console.log(`✓ Signed in${connectedAs(identity)}`); |
| 628 | }), |
| 629 | ), |
| 630 | ), |
| 631 | ); |
| 632 | |
| 633 | const connectLinkCommand = Command.make("link", { |
| 634 | ...projectLocationFlags, |
| 635 | headless: headlessFlag, |
| 636 | publishOnly: Flag.Boolean("publish-only").pipe( |
| 637 | Flag.withDescription( |
| 638 | "Link to publish agent activity only, with no managed tunnel. Reach this environment out of band (e.g. Tailscale).", |
| 639 | ), |
| 640 | Flag.withDefault(false), |
| 641 | ), |
| 642 | }).pipe( |
| 643 | Command.withDescription("Authorize this environment for T3 Connect on next start."), |
| 644 | Command.withHandler((flags) => |
| 645 | runCloudCommand( |
| 646 | flags, |
| 647 | Effect.gen(function* () { |
| 648 | yield* requireConnectAllowed; |
| 649 | yield* Console.log("T3 Connect\n"); |
| 650 | const linked = yield* linkEnvironmentForConnect(flags); |
| 651 | if (linked) { |
| 652 | const serveCommand = yield* resolveHostCliHint("serve", flags.baseDir); |
| 653 | yield* Console.log( |
| 654 | flags.publishOnly |
| 655 | ? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).` |
| 656 | : `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`, |
| 657 | ); |
| 658 | } |
| 659 | }), |
| 660 | ), |
| 661 | ), |
| 662 | ); |
| 663 | |
| 664 | const connectStatusCommand = Command.make("status", { |
| 665 | ...projectLocationFlags, |
| 666 | json: jsonFlag, |
| 667 | }).pipe( |
| 668 | Command.withDescription( |
| 669 | "Show T3 Connect setup and check that other devices can reach this machine.", |
| 670 | ), |
| 671 | Command.withHandler((flags) => |
| 672 | runCloudCommand( |
| 673 | flags, |
| 674 | Effect.gen(function* () { |
| 675 | const secrets = yield* ServerSecretStore.ServerSecretStore; |
| 676 | const relayClient = yield* RelayClient.RelayClient; |
| 677 | const tokens = yield* CliTokenManager.CloudCliTokenManager; |
| 678 | const [ |
| 679 | cliDesired, |
| 680 | managedTunnel, |
| 681 | cliAuthenticated, |
| 682 | relayCredential, |
| 683 | cloudUserId, |
| 684 | relayUrl, |
| 685 | publishAgentActivity, |
| 686 | revoked, |
| 687 | executable, |
| 688 | linkMode, |
| 689 | ] = yield* Effect.all( |
| 690 | [ |
| 691 | CliState.readCliDesiredCloudLink, |
| 692 | secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG), |
| 693 | tokens.hasCredential, |
| 694 | secrets.get(RELAY_ENVIRONMENT_CREDENTIAL_SECRET), |
| 695 | secrets.get(CLOUD_LINKED_USER_ID), |
| 696 | secrets.get(RELAY_URL_SECRET), |
| 697 | secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET), |
| 698 | secrets.get(CLOUD_LINK_REVOKED), |
| 699 | relayClient.resolve, |
| 700 | CliState.readCliDesiredLinkMode, |
| 701 | ], |
| 702 | { concurrency: "unbounded" }, |
| 703 | ); |
| 704 | // A link made in the desktop, web, or mobile app saves the tunnel config but no CLI marker. |
| 705 | const desired = cliDesired || Option.isSome(managedTunnel); |
| 706 | // Such a link authorizes the environment with its relay credential, not a CLI sign-in. |
| 707 | const authenticated = cliAuthenticated || Option.isSome(relayCredential); |
| 708 | // A publish-only link has no tunnel for other devices to reach. |
| 709 | const reachability = |
| 710 | desired && linkMode === "managed" ? yield* checkLiveReachability() : null; |
| 711 | const status: CloudCliStatus = { |
| 712 | desired, |
| 713 | authenticated, |
| 714 | linked: Option.isSome(cloudUserId), |
| 715 | revoked: Option.isSome(cloudUserId) && Option.isSome(revoked), |
| 716 | cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null, |
| 717 | relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null, |
| 718 | publishAgentActivity: isAgentActivityPublishingEnabledValue( |
| 719 | Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null, |
| 720 | ), |
| 721 | relayClient: executable, |
| 722 | linkMode, |
| 723 | reachability, |
| 724 | }; |
| 725 | const commands = { |
| 726 | link: yield* resolveHostCliHint("connect link", flags.baseDir), |
| 727 | serviceStatus: yield* resolveHostCliHint("service status", flags.baseDir), |
| 728 | }; |
| 729 | yield* Console.log(formatCloudStatus(status, commands, { json: flags.json })); |
| 730 | }), |
| 731 | { |
| 732 | quietLogs: flags.json, |
| 733 | }, |
| 734 | ), |
| 735 | ), |
| 736 | ); |
| 737 | |
| 738 | const connectPublishCommand = Command.make("publish", { |
| 739 | ...projectLocationFlags, |
| 740 | disable: Flag.Boolean("disable").pipe( |
| 741 | Flag.withDescription("Stop publishing agent activity to your mobile clients."), |
| 742 | Flag.withDefault(false), |
| 743 | ), |
| 744 | }).pipe( |
| 745 | Command.withDescription( |
| 746 | "Toggle publishing agent activity (push notifications and Live Activities) to your mobile clients.", |
| 747 | ), |
| 748 | Command.withHandler((flags) => |
| 749 | runCloudCommand( |
| 750 | flags, |
| 751 | Effect.gen(function* () { |
| 752 | const secrets = yield* ServerSecretStore.ServerSecretStore; |
| 753 | const tokens = yield* CliTokenManager.CloudCliTokenManager; |
| 754 | const enabled = !flags.disable; |
| 755 | if (enabled) yield* requireConnectAllowed; |
| 756 | yield* secrets.set( |
| 757 | PUBLISH_AGENT_ACTIVITY_SECRET, |
| 758 | stringToBytes(enabled ? "true" : "false"), |
| 759 | ); |
| 760 | if (!enabled) { |
| 761 | // Cancel unprovisioned publish-only links too, or the next start will recreate them. |
| 762 | // Managed links also serve the tunnel and must survive. |
| 763 | const linkedNow = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID)); |
| 764 | if (!linkedNow && (yield* CliState.readCliDesiredLinkMode) === "publish_only") { |
| 765 | yield* CliState.setCliDesiredCloudLink(false); |
| 766 | yield* Console.log("Cancelled the pending publish-only T3 Connect link."); |
| 767 | } |
| 768 | yield* Console.log("Publishing agent activity disabled."); |
| 769 | return; |
| 770 | } |
| 771 | |
| 772 | yield* Console.log("Publishing agent activity enabled."); |
| 773 | const linked = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID)); |
| 774 | if (linked) { |
| 775 | return; |
| 776 | } |
| 777 | |
| 778 | if (!(yield* tokens.hasCredential)) { |
| 779 | const loginCommand = yield* resolveHostCliHint("connect login", flags.baseDir); |
| 780 | yield* Console.log( |
| 781 | `Run \`${loginCommand}\` first so this environment can be authorized to publish.`, |
| 782 | ); |
| 783 | return; |
| 784 | } |
| 785 | // A desired managed link already covers publishing and must not be downgraded. |
| 786 | if (yield* CliState.readCliDesiredCloudLink) { |
| 787 | yield* Console.log( |
| 788 | "A T3 Connect link is already pending. Start T3 to finish provisioning it; publishing starts once it links.", |
| 789 | ); |
| 790 | return; |
| 791 | } |
| 792 | yield* CliState.setCliDesiredCloudLink(true, "publish_only"); |
| 793 | yield* Console.log( |
| 794 | "Restart T3 to finish authorizing this environment to publish (no managed tunnel is created).", |
| 795 | ); |
| 796 | }), |
| 797 | ), |
| 798 | ), |
| 799 | ); |
| 800 | |
| 801 | const connectUnlinkCommand = Command.make("unlink", { |
| 802 | ...projectLocationFlags, |
| 803 | }).pipe( |
| 804 | Command.withDescription("Disable T3 Connect while retaining the stored authorization."), |
| 805 | Command.withHandler((flags) => |
| 806 | runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })), |
| 807 | ), |
| 808 | ); |
| 809 | |
| 810 | const connectLogoutCommand = Command.make("logout", { |
| 811 | ...projectLocationFlags, |
| 812 | }).pipe( |
| 813 | Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."), |
| 814 | Command.withHandler((flags) => |
| 815 | runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })), |
| 816 | ), |
| 817 | ); |
| 818 | |
| 819 | // `t3 connect` itself is `t3 up --connect`, in up.ts. |
| 820 | export const connectSubcommands = [ |
| 821 | connectLoginCommand, |
| 822 | connectLinkCommand, |
| 823 | connectPublishCommand, |
| 824 | connectStatusCommand, |
| 825 | connectUnlinkCommand, |
| 826 | connectLogoutCommand, |
| 827 | ] as const; |