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