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