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