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