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

connect.ts

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