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

connect.ts

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