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