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 RelayClient from "@t3tools/shared/relayClient";
9import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
10import * as Cause from "effect/Cause";
11import * as Config from "effect/Config";
12import * as Console from "effect/Console";
13import * as Crypto from "effect/Crypto";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as References from "effect/References";
21import * as Schema from "effect/Schema";
22import * as Terminal from "effect/Terminal";
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 {
38 CLOUD_LINKED_USER_ID,
39 PUBLISH_AGENT_ACTIVITY_SECRET,
40 RELAY_URL_SECRET,
41} from "../cloud/config.ts";
42import { relayUrlConfig } from "../cloud/publicConfig.ts";
43import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
44import * as ServerConfig from "../config.ts";
45import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
46import * as ExternalLauncher from "../process/externalLauncher.ts";
47import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
48import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
49import { resolveCliCommand } from "./invocation.ts";
50import {
51 bootServiceLayer,
52 offerServiceDuringOnboarding,
53 recoverServiceOnboardingOffer,
54} from "./service.ts";
55
56const jsonFlag = Flag.boolean("json").pipe(
57 Flag.withDescription("Emit JSON instead of human-readable output."),
58 Flag.withDefault(false),
59);
60
61const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
62
63const headlessFlag = Flag.boolean("headless").pipe(
64 Flag.withDescription("Authorize without a local browser using out-of-band OAuth."),
65 Flag.withDefault(false),
66);
67
68/**
69 * Inside an SSH session there is no local browser to complete the loopback
70 * OAuth callback, so out-of-band OAuth is the only flow that can work.
71 */
72export const headlessSessionConfig = Config.all({
73 sshConnection: Config.string("SSH_CONNECTION").pipe(Config.option),
74 sshTty: Config.string("SSH_TTY").pipe(Config.option),
75}).pipe(
76 Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)),
77);
78
79const promptForOutOfBandOAuthCode = Effect.fn("cloud.cli.prompt_for_out_of_band_oauth_code")(
80 function* ({ authorizeUrl, validate }: CliTokenManager.OutOfBandOAuthPromptInput) {
81 yield* Console.log(formatHeadlessAuthorizationPrompt(authorizeUrl));
82 return yield* Prompt.run(Prompt.text({ message: "Authorization code", validate }));
83 },
84);
85
86export function formatHeadlessAuthorizationPrompt(authorizeUrl: string): string {
87 return [
88 "Headless authorization",
89 "Open this URL on a device with a browser:",
90 ` ${authorizeUrl}`,
91 "",
92 "After signing in, return here and enter the code shown in your browser.",
93 ].join("\n");
94}
95
96/** Returns the connected account identity, if the flow could determine one. */
97const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
98 readonly headless: boolean;
99}) {
100 const tokens = yield* CliTokenManager.CloudCliTokenManager;
101 const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);
102 if (!useOutOfBandOAuth) {
103 const authorization = yield* tokens.get;
104 if (authorization._tag === "Authorized") {
105 return authorization.token.identity ?? null;
106 }
107 yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
108 }
109 // A stored credential whose refresh fails (revoked, expired grant) must
110 // fall through to a fresh out-of-band authorization, not dead-end the command.
111 const existing = yield* tokens.getExisting.pipe(
112 Effect.catchTag("CloudCliCredentialRefreshError", () =>
113 Console.log(
114 "The stored T3 Connect credential could not be refreshed; signing in again.",
115 ).pipe(Effect.as(Option.none())),
116 ),
117 );
118 if (Option.isSome(existing)) {
119 return existing.value.identity ?? null;
120 }
121 const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(
122 promptForOutOfBandOAuthCode,
123 ).pipe(
124 Effect.mapError((cause) =>
125 // Ctrl-C / EOF at the prompt is a QuitError; let it propagate so the CLI
126 // cancels quietly instead of dumping an authorization error.
127 Terminal.isQuitError(cause) || isCloudCliTokenManagerError(cause)
128 ? cause
129 : new CliTokenManager.CloudCliAuthorizationError({ cause }),
130 ),
131 );
132 yield* tokens.store(token);
133 return identity;
134});
135
136function bytesToString(value: Uint8Array): string {
137 return new TextDecoder().decode(value);
138}
139
140function stringToBytes(value: string): Uint8Array {
141 return new TextEncoder().encode(value);
142}
143
144export function isPublishAgentActivityEnabledValue(value: string | null): boolean {
145 return value === "true";
146}
147
148interface CloudCliStatus {
149 readonly desired: boolean;
150 readonly authenticated: boolean;
151 readonly linked: boolean;
152 readonly cloudUserId: string | null;
153 readonly relayUrl: string | null;
154 readonly publishAgentActivity: boolean;
155 readonly relayClient: RelayClient.RelayClientStatus;
156}
157
158function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
159 switch (executable.status) {
160 case "available": {
161 const source =
162 executable.source === "path"
163 ? "PATH"
164 : executable.source === "managed"
165 ? "managed install"
166 : "configured override";
167 return [
168 ` Relay client: available via ${source}`,
169 ` Path: ${executable.executablePath}`,
170 ` Version: ${executable.version}`,
171 ];
172 }
173 case "missing":
174 return [" Relay client: not installed"];
175 case "unsupported":
176 return [
177 ` Relay client: unsupported on ${executable.platform}-${executable.arch}`,
178 ` Managed version: ${executable.version}`,
179 ];
180 }
181}
182
183function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: boolean }): string {
184 if (options?.json) {
185 return JSON.stringify(status, null, 2);
186 }
187
188 const provisioned = status.linked
189 ? "provisioned"
190 : status.desired && status.authenticated
191 ? "pending server startup"
192 : "not provisioned";
193 const nextStep = !status.authenticated
194 ? "Run `t3 connect link` to authorize and enable T3 Connect."
195 : !status.desired
196 ? "Run `t3 connect link` to enable T3 Connect."
197 : !status.linked
198 ? "Start T3 to provision the environment link and launch its managed tunnel."
199 : undefined;
200
201 return [
202 "T3 Connect",
203 ` Exposure: ${status.desired ? "enabled" : "disabled"}`,
204 ` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
205 ` Environment link: ${provisioned}`,
206 ` Relay: ${status.relayUrl ?? "not provisioned"}`,
207 ` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`,
208 ...formatRelayClientStatus(status.relayClient),
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.ServerEnvironment;
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(HttpClientResponse.filterStatusOk),
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.ServerEnvironment
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 ServerEnvironment.layer,
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
463export function 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: isPublishAgentActivityEnabledValue(
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(`✓ Connected${connectedAs(linked.identity)}`);
692
693 // Connect itself already succeeded; a boot-service failure must not
694 // fail the command, just tell the user what happened and move on.
695 const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
696 if (background) {
697 yield* Console.log(
698 "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
699 );
700 return;
701 }
702 const serveCommand = yield* resolveCliCommand("serve");
703 yield* Console.log(
704 `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
705 );
706 }),
707 ),
708 ),
709 Command.withSubcommands([
710 connectLoginCommand,
711 connectLinkCommand,
712 connectPublishCommand,
713 connectStatusCommand,
714 connectUnlinkCommand,
715 connectLogoutCommand,
716 ]),
717);