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