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