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