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