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

connect.ts

718 lines25.8 KB

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