Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

connect.ts

724 lines26.3 KB

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