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