Open History to see the last commit
1import {
2 AuthRelayWriteScope,
3 EnvironmentHttpApi,
4 type RelayClientInstallProgressEvent,
5 type RelayClientInstallProgressStage,
6} from "@t3tools/contracts";
7import { RelayOkResponse } from "@t3tools/contracts/relay";
8import * as HostProcess 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_LINK_REVOKED,
35 CLOUD_LINKED_USER_ID,
36 isAgentActivityPublishingEnabledValue,
37 PUBLISH_AGENT_ACTIVITY_SECRET,
38 RELAY_URL_SECRET,
39} from "../cloud/config.ts";
40import { relayUrlConfig } from "../cloud/publicConfig.ts";
41import * as RelayTracing from "../cloud/relayTracing.ts";
42import * as ServerConfig from "../config.ts";
43import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
44import * as ExternalLauncher from "../process/externalLauncher.ts";
45import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
46import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
47import { resolveCliCommand } from "./invocation.ts";
48import * as CliService from "./service.ts";
49
50const jsonFlag = Flag.Boolean("json").pipe(
51 Flag.withDescription("Emit JSON instead of human-readable output."),
52 Flag.withDefault(false),
53);
54
55const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
56
57const headlessFlag = Flag.Boolean("headless").pipe(
58 Flag.withDescription("Authorize without a local browser using the OAuth device flow."),
59 Flag.withDefault(false),
60);
61
62/**
63 * Inside an SSH session there is no local browser to complete the loopback
64 * OAuth callback, so the device authorization grant is the only flow that
65 * can work.
66 */
67export const headlessSessionConfig = Config.all({
68 sshConnection: Config.String("SSH_CONNECTION").pipe(Config.option),
69 sshTty: Config.String("SSH_TTY").pipe(Config.option),
70}).pipe(
71 Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)),
72);
73
74const showDeviceAuthorizationPrompt = (prompt: CliTokenManager.DeviceAuthorizationPrompt) =>
75 Console.log(formatDeviceAuthorizationPrompt(prompt));
76
77function formatDeviceAuthorizationPrompt(
78 prompt: CliTokenManager.DeviceAuthorizationPrompt,
79): string {
80 const minutes = Math.max(1, Math.round(Duration.toMinutes(prompt.expiresIn)));
81 return [
82 "Headless authorization",
83 "Open this URL on a device with a browser:",
84 ` ${prompt.verificationUriComplete ?? prompt.verificationUri}`,
85 "",
86 `Confirm this code when asked: ${prompt.userCode}`,
87 "",
88 `Waiting for approval (expires in ${minutes} min). Press Ctrl+C to cancel.`,
89 ].join("\n");
90}
91
92const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
93 readonly headless: boolean;
94}) {
95 const tokens = yield* CliTokenManager.CloudCliTokenManager;
96 const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);
97 if (!useOutOfBandOAuth) {
98 const authorization = yield* tokens.get;
99 if (authorization._tag === "Authorized") {
100 return authorization.token.identity ?? null;
101 }
102 yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
103 }
104 const existing = yield* tokens.getExisting.pipe(
105 Effect.catchTags({
106 CloudCliCredentialRefreshError: () =>
107 Console.log(
108 "The stored T3 Connect credential could not be refreshed; signing in again.",
109 ).pipe(Effect.as(Option.none())),
110 }),
111 );
112 if (Option.isSome(existing)) {
113 return existing.value.identity ?? null;
114 }
115 const { token, identity } = yield* CliTokenManager.deviceAuthorizationLogin(
116 showDeviceAuthorizationPrompt,
117 ).pipe(
118 Effect.mapError((cause) =>
119 isCloudCliTokenManagerError(cause)
120 ? cause
121 : new CliTokenManager.CloudCliAuthorizationError({ cause }),
122 ),
123 );
124 yield* tokens.store(token);
125 return identity;
126});
127
128function bytesToString(value: Uint8Array): string {
129 return new TextDecoder().decode(value);
130}
131
132function stringToBytes(value: string): Uint8Array {
133 return new TextEncoder().encode(value);
134}
135
136interface CloudCliStatus {
137 readonly desired: boolean;
138 readonly authenticated: boolean;
139 readonly linked: boolean;
140 readonly revoked: boolean;
141 readonly cloudUserId: string | null;
142 readonly relayUrl: string | null;
143 readonly publishAgentActivity: boolean;
144 readonly relayClient: RelayClient.RelayClientStatus;
145}
146
147function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
148 switch (executable.status) {
149 case "available": {
150 const source =
151 executable.source === "path"
152 ? "PATH"
153 : executable.source === "managed"
154 ? "managed install"
155 : "configured override";
156 return [
157 ` Relay client: available via ${source}`,
158 ` Path: ${executable.executablePath}`,
159 ` Version: ${executable.version}`,
160 ];
161 }
162 case "missing":
163 return [" Relay client: not installed"];
164 case "unsupported":
165 return [
166 ` Relay client: unsupported on ${executable.platform}-${executable.arch}`,
167 ` Managed version: ${executable.version}`,
168 ];
169 }
170}
171
172function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: boolean }): string {
173 if (options?.json) {
174 return JSON.stringify(status, null, 2);
175 }
176
177 const provisioned = status.revoked
178 ? "removed from T3 Connect"
179 : status.linked
180 ? "provisioned"
181 : status.desired && status.authenticated
182 ? "pending server startup"
183 : "not provisioned";
184 const nextStep = !status.authenticated
185 ? "Run `t3 connect link` to authorize and enable T3 Connect."
186 : status.revoked
187 ? "Run `t3 connect link` to link this environment again."
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");
206}
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 }
235}
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
351/**
352 * Prints the local disconnect outcome, then whether the relay record was revoked.
353 * A missing CLI login or a failed relay DELETE leaves that record registered, so
354 * those outcomes warn to deregister it from the T3 Connect account page.
355 */
356export const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
357 function* (input: {
358 readonly clearAuthorization: boolean;
359 readonly liveResult: LiveCloudActionResult;
360 readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>;
361 }) {
362 if (input.liveResult.status === "failed") {
363 yield* logCloudDisconnectFailure(
364 "live-server-unlink",
365 input.clearAuthorization,
366 input.liveResult.cause,
367 );
368 yield* Console.warn(
369 "T3 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.",
370 );
371 } else {
372 yield* Console.log("T3 Connect is disabled locally.");
373 }
374
375 if (Exit.isFailure(input.relayResult)) {
376 yield* logCloudDisconnectFailure(
377 "relay-environment-unlink",
378 input.clearAuthorization,
379 input.relayResult.cause,
380 );
381 yield* Console.warn(
382 input.clearAuthorization
383 ? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally."
384 : "Could not revoke the relay-side environment record yet.\nRun `t3 connect unlink` again when the relay is reachable, or deregister it from the T3 Connect page of your T3 account.",
385 );
386 } else if (input.relayResult.value.status === "not-authenticated") {
387 yield* Console.warn(
388 "The relay-side environment record was not revoked.\nDeregister it from the T3 Connect page of your T3 account, or run `t3 connect login` and retry.",
389 );
390 } else if (input.relayResult.value.status === "revoked") {
391 yield* Console.log("Revoked the relay-side environment record.");
392 }
393 },
394);
395
396const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
397 readonly clearAuthorization: boolean;
398}) {
399 yield* CliState.setCliDesiredCloudLink(false);
400 const liveResult = yield* runLiveCloudUnlink();
401 const relayResult = yield* Effect.exit(unlinkRelayEnvironment());
402 yield* CliState.clearPersistedCloudLink;
403
404 if (options.clearAuthorization) {
405 const tokens = yield* CliTokenManager.CloudCliTokenManager;
406 yield* tokens.clear;
407 }
408
409 yield* reportCloudDisconnectResults({
410 clearAuthorization: options.clearAuthorization,
411 liveResult,
412 relayResult,
413 });
414
415 if (options.clearAuthorization) {
416 yield* Console.log(
417 "Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
418 );
419 }
420});
421
422const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
423 flags: { readonly baseDir: Option.Option<string> },
424 run: Effect.Effect<
425 A,
426 E,
427 | ServerSecretStore.ServerSecretStore
428 | CliTokenManager.CloudCliTokenManager
429 | RelayClient.RelayClient
430 | EnvironmentAuth.EnvironmentAuth
431 | BootService.BootService
432 | Crypto.Crypto
433 | FileSystem.FileSystem
434 | HttpClient.HttpClient
435 | Prompt.Environment
436 | ServerConfig.ServerConfig
437 | ServerEnvironment.ServerEnvironmentIdentity
438 >,
439 options?: {
440 readonly quietLogs?: boolean;
441 },
442) {
443 const logLevel = yield* GlobalFlag.LogLevel;
444 const config = yield* resolveCliAuthConfig(flags, logLevel);
445 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
446 const layerRuntime = Layer.mergeAll(
447 ServerSecretStore.layer,
448 CliTokenManager.layer.pipe(
449 Layer.provide(ServerSecretStore.layer),
450 Layer.provide(ExternalLauncher.layer),
451 ),
452 RelayClient.layerCloudflared({ baseDir: config.baseDir }),
453 EnvironmentAuth.layerRuntime,
454 CliService.layer(config),
455 RelayTracing.layerHeadlessRelayClient,
456 ).pipe(
457 Layer.provideMerge(FetchHttpClient.layer),
458 Layer.provideMerge(ServerConfig.layer(config)),
459 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
460 );
461 return yield* run.pipe(Effect.provide(layerRuntime));
462});
463
464const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : "");
465
466function formatRelayClientReady(version: string): string {
467 return `✓ Relay client ready · cloudflared ${version}`;
468}
469
470const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: {
471 readonly headless: boolean;
472 readonly publishOnly?: boolean;
473}) {
474 const publishOnly = options.publishOnly ?? false;
475 if (!publishOnly) {
476 const relayClient = yield* RelayClient.RelayClient;
477 const installed = yield* acquireRelayClientForLink(
478 relayClient,
479 confirmRelayClientInstall,
480 reportRelayClientInstallProgress,
481 );
482 if (Option.isNone(installed)) {
483 yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
484 return null;
485 }
486 yield* Console.log(formatRelayClientReady(installed.value.version));
487 }
488
489 const identity = yield* authorizeCli(options);
490 yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed");
491 if (yield* CliState.dropRevokedCloudLink) {
492 yield* Console.log(
493 "Removed the link T3 Connect no longer accepts. The next start links this environment again.",
494 );
495 }
496 if (publishOnly) {
497 const secrets = yield* ServerSecretStore.ServerSecretStore;
498 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));
499 }
500 return { identity } as const;
501});
502
503const connectLoginCommand = Command.make("login", {
504 ...projectLocationFlags,
505 headless: headlessFlag,
506}).pipe(
507 Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
508 Command.withHandler((flags) =>
509 runCloudCommand(
510 flags,
511 Effect.gen(function* () {
512 yield* Console.log("T3 Connect\n");
513 const identity = yield* authorizeCli(flags);
514 yield* Console.log(`✓ Signed in${connectedAs(identity)}`);
515 }),
516 ),
517 ),
518);
519
520const connectLinkCommand = Command.make("link", {
521 ...projectLocationFlags,
522 headless: headlessFlag,
523 publishOnly: Flag.Boolean("publish-only").pipe(
524 Flag.withDescription(
525 "Link to publish agent activity only — no managed tunnel. Reach this environment out of band (e.g. Tailscale).",
526 ),
527 Flag.withDefault(false),
528 ),
529}).pipe(
530 Command.withDescription("Authorize this environment for T3 Connect on next start."),
531 Command.withHandler((flags) =>
532 runCloudCommand(
533 flags,
534 Effect.gen(function* () {
535 yield* Console.log("T3 Connect\n");
536 const linked = yield* linkEnvironmentForConnect(flags);
537 if (linked) {
538 const serveCommand = yield* resolveCliCommand("serve");
539 yield* Console.log(
540 flags.publishOnly
541 ? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`
542 : `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
543 );
544 }
545 }),
546 ),
547 ),
548);
549
550const connectStatusCommand = Command.make("status", {
551 ...projectLocationFlags,
552 json: jsonFlag,
553}).pipe(
554 Command.withDescription("Show persisted T3 Connect and relay client state."),
555 Command.withHandler((flags) =>
556 runCloudCommand(
557 flags,
558 Effect.gen(function* () {
559 const secrets = yield* ServerSecretStore.ServerSecretStore;
560 const relayClient = yield* RelayClient.RelayClient;
561 const tokens = yield* CliTokenManager.CloudCliTokenManager;
562 const [
563 desired,
564 authenticated,
565 cloudUserId,
566 relayUrl,
567 publishAgentActivity,
568 revoked,
569 executable,
570 ] = yield* Effect.all(
571 [
572 CliState.readCliDesiredCloudLink,
573 tokens.hasCredential,
574 secrets.get(CLOUD_LINKED_USER_ID),
575 secrets.get(RELAY_URL_SECRET),
576 secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
577 secrets.get(CLOUD_LINK_REVOKED),
578 relayClient.resolve,
579 ],
580 { concurrency: "unbounded" },
581 );
582 const status: CloudCliStatus = {
583 desired,
584 authenticated,
585 linked: Option.isSome(cloudUserId),
586 revoked: Option.isSome(cloudUserId) && Option.isSome(revoked),
587 cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
588 relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
589 publishAgentActivity: isAgentActivityPublishingEnabledValue(
590 Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null,
591 ),
592 relayClient: executable,
593 };
594 yield* Console.log(formatCloudStatus(status, { json: flags.json }));
595 }),
596 {
597 quietLogs: flags.json,
598 },
599 ),
600 ),
601);
602
603const connectPublishCommand = Command.make("publish", {
604 ...projectLocationFlags,
605 disable: Flag.Boolean("disable").pipe(
606 Flag.withDescription("Stop publishing agent activity to your mobile clients."),
607 Flag.withDefault(false),
608 ),
609}).pipe(
610 Command.withDescription(
611 "Toggle publishing agent activity (push notifications and Live Activities) to your mobile clients.",
612 ),
613 Command.withHandler((flags) =>
614 runCloudCommand(
615 flags,
616 Effect.gen(function* () {
617 const secrets = yield* ServerSecretStore.ServerSecretStore;
618 const tokens = yield* CliTokenManager.CloudCliTokenManager;
619 const enabled = !flags.disable;
620 yield* secrets.set(
621 PUBLISH_AGENT_ACTIVITY_SECRET,
622 stringToBytes(enabled ? "true" : "false"),
623 );
624 if (!enabled) {
625 // If enabling scheduled a publish-only link that hasn't been
626 // provisioned yet, disabling must cancel it too — otherwise the next
627 // start still links an environment whose only purpose was publishing.
628 // A pending managed link is left alone; it exists for the tunnel.
629 const linkedNow = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
630 if (!linkedNow && (yield* CliState.readCliDesiredLinkMode) === "publish_only") {
631 yield* CliState.setCliDesiredCloudLink(false);
632 yield* Console.log("Cancelled the pending publish-only T3 Connect link.");
633 }
634 yield* Console.log("Publishing agent activity disabled.");
635 return;
636 }
637
638 yield* Console.log("Publishing agent activity enabled.");
639 const linked = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
640 if (linked) {
641 return;
642 }
643
644 if (!(yield* tokens.hasCredential)) {
645 yield* Console.log(
646 "Run `t3 connect login` first so this environment can be authorized to publish.",
647 );
648 return;
649 }
650 // A link may already be desired (e.g. `t3 connect link` before the
651 // server's first start). Never downgrade it: a desired managed link
652 // also covers publishing, so only request a publish-only link when no
653 // link is pending at all.
654 if (yield* CliState.readCliDesiredCloudLink) {
655 yield* Console.log(
656 "A T3 Connect link is already pending. Start T3 to finish provisioning it; publishing starts once it links.",
657 );
658 return;
659 }
660 yield* CliState.setCliDesiredCloudLink(true, "publish_only");
661 yield* Console.log(
662 "Restart T3 to finish authorizing this environment to publish (no managed tunnel is created).",
663 );
664 }),
665 ),
666 ),
667);
668
669const connectUnlinkCommand = Command.make("unlink", {
670 ...projectLocationFlags,
671}).pipe(
672 Command.withDescription("Disable T3 Connect while retaining the stored authorization."),
673 Command.withHandler((flags) =>
674 runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),
675 ),
676);
677
678const connectLogoutCommand = Command.make("logout", {
679 ...projectLocationFlags,
680}).pipe(
681 Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."),
682 Command.withHandler((flags) =>
683 runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),
684 ),
685);
686
687export const reportServiceOnboarding = Effect.fn("cli.connect.report_service_onboarding")(
688 function* (outcome: CliService.ServiceOnboardingOutcome) {
689 if (outcome === "pending") {
690 yield* Console.log(
691 "\nBackground service restarting\n\nThe server establishes the T3 Connect link once it is back. Check the log above if it does not come back.",
692 );
693 return;
694 }
695 if (outcome === "ready") {
696 const platform = yield* HostProcess.Platform;
697 yield* Console.log(
698 platform === "darwin"
699 ? "\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."
700 : "\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.",
701 );
702 return;
703 }
704 const serveCommand = yield* resolveCliCommand("serve");
705 yield* Console.log(
706 `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
707 );
708 },
709);
710
711export const connectCommand = Command.make("connect", {
712 ...projectLocationFlags,
713 headless: headlessFlag,
714}).pipe(
715 Command.withDescription("Set up T3 Connect for this machine."),
716 Command.withHandler((flags) =>
717 runCloudCommand(
718 flags,
719 Effect.gen(function* () {
720 yield* Console.log("T3 Connect\n");
721 const linked = yield* linkEnvironmentForConnect(flags);
722 if (!linked) {
723 return;
724 }
725 yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}`);
726
727 yield* reportServiceOnboarding(
728 yield* CliService.recoverServiceOnboardingOffer(CliService.offerServiceDuringOnboarding),
729 );
730 }),
731 ),
732 ),
733 Command.withSubcommands([
734 connectLoginCommand,
735 connectLinkCommand,
736 connectPublishCommand,
737 connectStatusCommand,
738 connectUnlinkCommand,
739 connectLogoutCommand,
740 ]),
741);