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

connect.ts

721 lines26.0 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 {
39 CLOUD_LINKED_USER_ID,
40 isAgentActivityPublishingEnabledValue,
41 PUBLISH_AGENT_ACTIVITY_SECRET,
42 RELAY_URL_SECRET,
43} from "../cloud/config.ts";
44import { relayUrlConfig } from "../cloud/publicConfig.ts";
45import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
46import * as ServerConfig from "../config.ts";
47import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
48import * as ExternalLauncher from "../process/externalLauncher.ts";
49import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
50import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
51import { resolveCliCommand } from "./invocation.ts";
52import {
53 bootServiceLayer,
54 offerServiceDuringOnboarding,
55 recoverServiceOnboardingOffer,
56} from "./service.ts";
57​
58const jsonFlag = Flag.boolean("json").pipe(
59 Flag.withDescription("Emit JSON instead of human-readable output."),
60 Flag.withDefault(false),
61);
62​
63const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
64​
65const headlessFlag = Flag.boolean("headless").pipe(
66 Flag.withDescription("Authorize without a local browser using out-of-band OAuth."),
67 Flag.withDefault(false),
68);
69​
70/**
71 * Inside an SSH session there is no local browser to complete the loopback
72 * OAuth callback, so out-of-band OAuth is the only flow that can work.
73 */
74export const headlessSessionConfig = Config.all({
75 sshConnection: Config.string("SSH_CONNECTION").pipe(Config.option),
76 sshTty: Config.string("SSH_TTY").pipe(Config.option),
77}).pipe(
78 Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)),
79);
80​
81const promptForOutOfBandOAuthCode = Effect.fn("cloud.cli.prompt_for_out_of_band_oauth_code")(
82 function* ({ authorizeUrl, validate }: CliTokenManager.OutOfBandOAuthPromptInput) {
83 yield* Console.log(formatHeadlessAuthorizationPrompt(authorizeUrl));
84 return yield* Prompt.run(Prompt.text({ message: "Authorization code", validate }));
85 },
86);
87​
88export function formatHeadlessAuthorizationPrompt(authorizeUrl: string): string {
89 return [
90 "Headless authorization",
91 "Open this URL on a device with a browser:",
92 ` ${authorizeUrl}`,
93 "",
94 "After signing in, return here and enter the code shown in your browser.",
95 ].join("\n");
97​
98/** Returns the connected account identity, if the flow could determine one. */
99const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
100 readonly headless: boolean;
101}) {
102 const tokens = yield* CliTokenManager.CloudCliTokenManager;
103 const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);
104 if (!useOutOfBandOAuth) {
105 const authorization = yield* tokens.get;
106 if (authorization._tag === "Authorized") {
107 return authorization.token.identity ?? null;
108 }
109 yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
110 }
111 // A stored credential whose refresh fails (revoked, expired grant) must
112 // fall through to a fresh out-of-band authorization, not dead-end the command.
113 const existing = yield* tokens.getExisting.pipe(
114 Effect.catchTag("CloudCliCredentialRefreshError", () =>
115 Console.log(
116 "The stored T3 Connect credential could not be refreshed; signing in again.",
117 ).pipe(Effect.as(Option.none())),
118 ),
119 );
120 if (Option.isSome(existing)) {
121 return existing.value.identity ?? null;
122 }
123 const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(
124 promptForOutOfBandOAuthCode,
125 ).pipe(
126 Effect.mapError((cause) =>
127 // Ctrl-C / EOF at the prompt is a QuitError; let it propagate so the CLI
128 // cancels quietly instead of dumping an authorization error.
129 Terminal.isQuitError(cause) || isCloudCliTokenManagerError(cause)
130 ? cause
131 : new CliTokenManager.CloudCliAuthorizationError({ cause }),
132 ),
133 );
134 yield* tokens.store(token);
135 return identity;
136});
137​
138function bytesToString(value: Uint8Array): string {
139 return new TextDecoder().decode(value);
141​
142function stringToBytes(value: string): Uint8Array {
143 return new TextEncoder().encode(value);
145​
146export function isPublishAgentActivityEnabledValue(value: string | null): boolean {
147 return isAgentActivityPublishingEnabledValue(value);
149​
150interface CloudCliStatus {
151 readonly desired: boolean;
152 readonly authenticated: boolean;
153 readonly linked: boolean;
154 readonly cloudUserId: string | null;
155 readonly relayUrl: string | null;
156 readonly publishAgentActivity: boolean;
157 readonly relayClient: RelayClient.RelayClientStatus;
159​
160function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
161 switch (executable.status) {
162 case "available": {
163 const source =
164 executable.source === "path"
165 ? "PATH"
166 : executable.source === "managed"
167 ? "managed install"
168 : "configured override";
169 return [
170 ` Relay client: available via ${source}`,
171 ` Path: ${executable.executablePath}`,
172 ` Version: ${executable.version}`,
173 ];
174 }
175 case "missing":
176 return [" Relay client: not installed"];
177 case "unsupported":
178 return [
179 ` Relay client: unsupported on ${executable.platform}-${executable.arch}`,
180 ` Managed version: ${executable.version}`,
181 ];
182 }
184​
185function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: boolean }): string {
186 if (options?.json) {
187 return JSON.stringify(status, null, 2);
188 }
189​
190 const provisioned = status.linked
191 ? "provisioned"
192 : status.desired && status.authenticated
193 ? "pending server startup"
194 : "not provisioned";
195 const nextStep = !status.authenticated
196 ? "Run `t3 connect link` to authorize and enable T3 Connect."
197 : !status.desired
198 ? "Run `t3 connect link` to enable T3 Connect."
199 : !status.linked
200 ? "Start T3 to provision the environment link and launch its managed tunnel."
201 : undefined;
202​
203 return [
204 "T3 Connect",
205 ` Exposure: ${status.desired ? "enabled" : "disabled"}`,
206 ` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
207 ` Environment link: ${provisioned}`,
208 ` Relay: ${status.relayUrl ?? "not provisioned"}`,
209 ` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`,
210 ...formatRelayClientStatus(status.relayClient),
211 ...(nextStep ? ["", `Next: ${nextStep}`] : []),
212 ].join("\n");
214​
215const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);
216​
217const confirmRelayClientInstall = (version: string) =>
218 Prompt.run(
219 Prompt.confirm({
220 message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`,
221 initial: false,
222 }),
223 );
224​
225function relayClientInstallProgressMessage(stage: RelayClientInstallProgressStage): string {
226 switch (stage) {
227 case "checking":
228 return "Checking existing installation";
229 case "waiting_for_lock":
230 return "Waiting for installation lock";
231 case "downloading":
232 return "Downloading";
233 case "verifying":
234 return "Verifying download";
235 case "installing":
236 return "Installing";
237 case "validating":
238 return "Validating executable";
239 case "activating":
240 return "Activating installation";
241 }
243​
244const reportRelayClientInstallProgress = (event: RelayClientInstallProgressEvent) =>
245 event.type === "progress"
246 ? Console.log(`Relay client: ${relayClientInstallProgressMessage(event.stage)}...`)
247 : Effect.void;
248​
249export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_client_for_link")(
250 function* <ConfirmError, ConfirmContext>(
251 relayClient: RelayClient.RelayClient["Service"],
252 confirmInstall: (version: string) => Effect.Effect<boolean, ConfirmError, ConfirmContext>,
253 reportProgress: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
254 ) {
255 const executable = yield* relayClient.resolve;
256 if (executable.status === "available") {
257 return Option.some(executable);
258 }
259 if (executable.status === "unsupported") {
260 return Option.some(yield* relayClient.installWithProgress(reportProgress));
261 }
262 if (!(yield* confirmInstall(executable.version))) {
263 return Option.none();
264 }
265 return Option.some(yield* relayClient.installWithProgress(reportProgress));
266 },
267);
268​
269const withCloudCliSessionToken = <A, E, R>(
270 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
271 run: (token: string) => Effect.Effect<A, E, R>,
272) =>
273 Effect.acquireUseRelease(
274 environmentAuth.issueSession({
275 scopes: [AuthRelayWriteScope],
276 subject: "cloud-cli",
277 label: "t3 connect cli",
278 }),
279 (issued) => run(issued.token),
280 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
281 );
282​
283type LiveCloudActionResult =
284 | { readonly status: "not-running" }
285 | { readonly status: "succeeded" }
286 | { readonly status: "failed"; readonly cause: Cause.Cause<unknown> };
287​
288const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
289 const config = yield* ServerConfig.ServerConfig;
290 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
291 if (Option.isNone(runtimeState)) {
292 return { status: "not-running" } satisfies LiveCloudActionResult;
293 }
294​
295 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
296 const result = yield* Effect.exit(
297 withCloudCliSessionToken(environmentAuth, (token) =>
298 HttpApiClient.make(EnvironmentHttpApi, {
299 baseUrl: runtimeState.value.origin,
300 }).pipe(
301 Effect.flatMap((client) =>
302 client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
303 ),
304 Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
305 ),
306 ),
307 );
308 return Exit.isSuccess(result)
309 ? ({ status: "succeeded" } satisfies LiveCloudActionResult)
310 : ({ status: "failed", cause: result.cause } satisfies LiveCloudActionResult);
311});
312​
313type RelayUnlinkResult =
314 | { readonly status: "not-authenticated" }
315 | { readonly status: "revoked" }
316 | { readonly status: "not-linked" };
317​
318type CloudDisconnectOperation = "live-server-unlink" | "relay-environment-unlink";
319​
320const logCloudDisconnectFailure = (
321 operation: CloudDisconnectOperation,
322 clearAuthorization: boolean,
323 cause: Cause.Cause<unknown>,
324) =>
325 Effect.logWarning("T3 Connect disconnect operation failed.").pipe(
326 Effect.annotateLogs({
327 operation,
328 clearAuthorization,
329 cause: Cause.pretty(cause),
330 }),
331 );
332​
333const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () {
334 const tokens = yield* CliTokenManager.CloudCliTokenManager;
335 const token = yield* tokens.getExisting;
336 if (Option.isNone(token)) {
337 return { status: "not-authenticated" } satisfies RelayUnlinkResult;
338 }
339​
340 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
341 const environmentId = yield* environment.getEnvironmentId;
342 const relayUrl = yield* relayUrlConfig;
343 const httpClient = yield* HttpClient.HttpClient;
344 const response = yield* HttpClientRequest.delete(
345 `${relayUrl}/v1/client/environment-links/${encodeURIComponent(environmentId)}`,
346 ).pipe(
347 HttpClientRequest.bearerToken(token.value.accessToken),
348 httpClient.execute,
349 Effect.flatMap(HttpClientResponse.filterStatusOk),
350 Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
351 withRelayClientTracing,
352 );
353 return response.ok
354 ? ({ status: "revoked" } satisfies RelayUnlinkResult)
355 : ({ status: "not-linked" } satisfies RelayUnlinkResult);
356});
357​
358export const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
359 function* (input: {
360 readonly clearAuthorization: boolean;
361 readonly liveResult: LiveCloudActionResult;
362 readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>;
363 }) {
364 if (input.liveResult.status === "failed") {
365 yield* logCloudDisconnectFailure(
366 "live-server-unlink",
367 input.clearAuthorization,
368 input.liveResult.cause,
369 );
370 yield* Console.warn(
371 "T3 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.",
372 );
373 } else {
374 yield* Console.log("T3 Connect is disabled locally.");
375 }
376​
377 if (Exit.isFailure(input.relayResult)) {
378 yield* logCloudDisconnectFailure(
379 "relay-environment-unlink",
380 input.clearAuthorization,
381 input.relayResult.cause,
382 );
383 yield* Console.warn(
384 input.clearAuthorization
385 ? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally."
386 : "Could not revoke the relay-side environment record yet.\nRun `t3 connect unlink` again when the relay is reachable.",
387 );
388 } else if (input.relayResult.value.status === "revoked") {
389 yield* Console.log("Revoked the relay-side environment record.");
390 }
391 },
392);
393​
394const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
395 readonly clearAuthorization: boolean;
396}) {
397 yield* CliState.setCliDesiredCloudLink(false);
398 const liveResult = yield* runLiveCloudUnlink();
399 const relayResult = yield* Effect.exit(unlinkRelayEnvironment());
400 yield* CliState.clearPersistedCloudLink;
401​
402 if (options.clearAuthorization) {
403 const tokens = yield* CliTokenManager.CloudCliTokenManager;
404 yield* tokens.clear;
405 }
406​
407 yield* reportCloudDisconnectResults({
408 clearAuthorization: options.clearAuthorization,
409 liveResult,
410 relayResult,
411 });
412​
413 if (options.clearAuthorization) {
414 yield* Console.log(
415 "Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
416 );
417 }
418});
419​
420const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
421 flags: { readonly baseDir: Option.Option<string> },
422 run: Effect.Effect<
423 A,
424 E,
425 | ServerSecretStore.ServerSecretStore
426 | CliTokenManager.CloudCliTokenManager
427 | RelayClient.RelayClient
428 | EnvironmentAuth.EnvironmentAuth
429 | BootService.BootService
430 | Crypto.Crypto
431 | FileSystem.FileSystem
432 | HttpClient.HttpClient
433 | Prompt.Environment
434 | ServerConfig.ServerConfig
435 | ServerEnvironment.ServerEnvironmentIdentity
436 >,
437 options?: {
438 readonly quietLogs?: boolean;
439 },
440) {
441 const logLevel = yield* GlobalFlag.LogLevel;
442 const config = yield* resolveCliAuthConfig(flags, logLevel);
443 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
444 const runtimeLayer = Layer.mergeAll(
445 ServerSecretStore.layer,
446 CliTokenManager.layer.pipe(
447 Layer.provide(ServerSecretStore.layer),
448 Layer.provide(ExternalLauncher.layer),
449 ),
450 RelayClient.layerCloudflared({ baseDir: config.baseDir }),
451 EnvironmentAuth.runtimeLayer,
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 const platform = yield* HostProcessPlatform;
699 yield* Console.log(
700 platform === "darwin"
701 ? "\n✓ Background service ready\n\nT3 Code will stay reachable while you are logged in to this Mac."
702 : "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
703 );
704 return;
705 }
706 const serveCommand = yield* resolveCliCommand("serve");
707 yield* Console.log(
708 `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
709 );
710 }),
711 ),
712 ),
713 Command.withSubcommands([
714 connectLoginCommand,
715 connectLinkCommand,
716 connectPublishCommand,
717 connectStatusCommand,
718 connectUnlinkCommand,
719 connectLogoutCommand,
720 ]),
721);