Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

connect.ts

829 lines31.1 KB

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