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

connect.ts

842 lines30.6 KB

1import {
2 AuthRelayReadScope,
3 AuthRelayWriteScope,
4 type AuthEnvironmentScope,
5 type EnvironmentConnectReachability,
6 EnvironmentHttpApi,
7 formatConnectReachable,
8 type RelayClientInstallProgressEvent,
9 type RelayClientInstallProgressStage,
10} from "@t3tools/contracts";
11import { RelayOkResponse } from "@t3tools/contracts/relay";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import * as RelayClient from "@t3tools/shared/relayClient";
14import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
15import * as Cause from "effect/Cause";
16import * as Clock from "effect/Clock";
17import * as Config from "effect/Config";
18import * as Console from "effect/Console";
19import * as Crypto from "effect/Crypto";
20import * as Duration from "effect/Duration";
21import * as Effect from "effect/Effect";
22import * as Exit from "effect/Exit";
23import * as FileSystem from "effect/FileSystem";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as References from "effect/References";
27import * as Schema from "effect/Schema";
28import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
29import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
30import * as HttpApiClient from "effect/http-api/HttpApiClient";
31​
32import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
33import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
34import * as BootService from "../cloud/bootService.ts";
35import * as CliState from "../cloud/CliState.ts";
36import * as CliTokenManager from "../cloud/CliTokenManager.ts";
37import { formatReachabilityFailure } from "../cloud/ConnectReachability.ts";
38import { filterRelayResponse } from "../cloud/relayResponse.ts";
39import {
40 CLOUD_LINK_REVOKED,
41 CLOUD_LINKED_USER_ID,
42 isAgentActivityPublishingEnabledValue,
43 PUBLISH_AGENT_ACTIVITY_SECRET,
44 RELAY_URL_SECRET,
45} from "../cloud/config.ts";
46import { relayUrlConfig } from "../cloud/publicConfig.ts";
47import * as RelayTracing from "../cloud/relayTracing.ts";
48import * as ServerConfig from "../config.ts";
49import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
50import * as ExternalLauncher from "../process/externalLauncher.ts";
51import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
52import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
53import { resolveCliCommand } from "./invocation.ts";
54import * as CliService from "./service.ts";
55​
56const jsonFlag = Flag.Boolean("json").pipe(
57 Flag.withDescription("Emit JSON instead of human-readable output."),
58 Flag.withDefault(false),
59);
60​
61const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
62​
63const headlessFlag = Flag.Boolean("headless").pipe(
64 Flag.withDescription("Authorize without a local browser using the OAuth device flow."),
65 Flag.withDefault(false),
66);
67​
68/**
69 * Inside an SSH session there is no local browser to complete the loopback
70 * OAuth callback, so the device authorization grant is the only flow that
71 * can work.
72 */
73const headlessSessionConfig = Config.all({
74 sshConnection: Config.String("SSH_CONNECTION").pipe(Config.option),
75 sshTty: Config.String("SSH_TTY").pipe(Config.option),
76}).pipe(
77 Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)),
78);
79​
80const showDeviceAuthorizationPrompt = (prompt: CliTokenManager.DeviceAuthorizationPrompt) =>
81 Console.log(formatDeviceAuthorizationPrompt(prompt));
82​
83function formatDeviceAuthorizationPrompt(
84 prompt: CliTokenManager.DeviceAuthorizationPrompt,
85): string {
86 const minutes = Math.max(1, Math.round(Duration.toMinutes(prompt.expiresIn)));
87 return [
88 "Headless authorization",
89 "Open this URL on a device with a browser:",
90 ` ${prompt.verificationUriComplete ?? prompt.verificationUri}`,
91 "",
92 `Confirm this code when asked: ${prompt.userCode}`,
93 "",
94 `Waiting for approval (expires in ${minutes} min). Press Ctrl+C to cancel.`,
95 ].join("\n");
97​
98const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
99 readonly headless: boolean;
100}) {
101 const tokens = yield* CliTokenManager.CloudCliTokenManager;
102 const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);
103 if (!useOutOfBandOAuth) {
104 const authorization = yield* tokens.get;
105 if (authorization._tag === "Authorized") {
106 return authorization.token.identity ?? null;
107 }
108 yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
109 }
110 const existing = yield* tokens.getExisting.pipe(
111 Effect.catchTags({
112 CloudCliCredentialRefreshError: () =>
113 Console.log(
114 "The stored T3 Connect credential could not be refreshed; signing in again.",
115 ).pipe(Effect.as(Option.none())),
116 }),
117 );
118 if (Option.isSome(existing)) {
119 return existing.value.identity ?? null;
120 }
121 const { token, identity } = yield* CliTokenManager.deviceAuthorizationLogin(
122 showDeviceAuthorizationPrompt,
123 ).pipe(
124 Effect.mapError((cause) =>
125 isCloudCliTokenManagerError(cause)
126 ? cause
127 : new CliTokenManager.CloudCliAuthorizationError({ cause }),
128 ),
129 );
130 yield* tokens.store(token);
131 return identity;
132});
133​
134function bytesToString(value: Uint8Array): string {
135 return new TextDecoder().decode(value);
137​
138function stringToBytes(value: string): Uint8Array {
139 return new TextEncoder().encode(value);
141​
142interface CloudCliStatus {
143 readonly desired: boolean;
144 readonly authenticated: boolean;
145 readonly linked: boolean;
146 readonly revoked: boolean;
147 readonly cloudUserId: string | null;
148 readonly relayUrl: string | null;
149 readonly publishAgentActivity: boolean;
150 readonly relayClient: RelayClient.RelayClientStatus;
151 readonly linkMode: CliState.CliDesiredLinkMode;
152 /** `null` when no server answered the live check, or none ran because no tunnel is wanted. */
153 readonly reachability: EnvironmentConnectReachability | null;
155​
156function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
157 switch (executable.status) {
158 case "available": {
159 const source =
160 executable.source === "path"
161 ? "PATH"
162 : executable.source === "managed"
163 ? "managed install"
164 : "configured override";
165 return [
166 ` Relay client: available via ${source}`,
167 ` Path: ${executable.executablePath}`,
168 ` Version: ${executable.version}`,
169 ];
170 }
171 case "missing":
172 return [" Relay client: not installed"];
173 case "unsupported":
174 return [
175 ` Relay client: unsupported on ${executable.platform}-${executable.arch}`,
176 ` Managed version: ${executable.version}`,
177 ];
178 }
180​
181function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: boolean }): string {
182 if (options?.json) {
183 return JSON.stringify(status, null, 2);
184 }
185​
186 const provisioned = status.revoked
187 ? "removed from T3 Connect"
188 : status.linked
189 ? "provisioned"
190 : status.desired && status.authenticated
191 ? "pending server startup"
192 : "not provisioned";
193 const nextStep = !status.authenticated
194 ? "Run `t3 connect link` to authorize and enable T3 Connect."
195 : status.revoked
196 ? "Run `t3 connect link` to link this environment again."
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 ...(!status.desired || status.linkMode !== "managed"
212 ? []
213 : status.reachability === null
214 ? [
215 "",
216 "No running server answered, so reachability was not checked. Check the background service with `t3 service status`.",
217 ]
218 : status.reachability.status === "reachable"
219 ? [
220 "",
221 `✓ Other devices can reach this machine · ${formatConnectReachable(status.reachability)}`,
222 ]
223 : ["", formatReachabilityFailure(status.reachability)]),
224 ...(nextStep ? ["", `Next: ${nextStep}`] : []),
225 ].join("\n");
227​
228const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);
229​
230const confirmRelayClientInstall = (version: string) =>
231 Prompt.run(
232 Prompt.Confirm({
233 message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`,
234 initial: false,
235 }),
236 );
237​
238function relayClientInstallProgressMessage(stage: RelayClientInstallProgressStage): string {
239 switch (stage) {
240 case "checking":
241 return "Checking existing installation";
242 case "waiting_for_lock":
243 return "Waiting for installation lock";
244 case "downloading":
245 return "Downloading";
246 case "verifying":
247 return "Verifying download";
248 case "installing":
249 return "Installing";
250 case "validating":
251 return "Validating executable";
252 case "activating":
253 return "Activating installation";
254 }
256​
257const reportRelayClientInstallProgress = (event: RelayClientInstallProgressEvent) =>
258 event.type === "progress"
259 ? Console.log(`Relay client: ${relayClientInstallProgressMessage(event.stage)}...`)
260 : Effect.void;
261​
262export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_client_for_link")(
263 function* <ConfirmError, ConfirmContext>(
264 relayClient: RelayClient.RelayClient["Service"],
265 confirmInstall: (version: string) => Effect.Effect<boolean, ConfirmError, ConfirmContext>,
266 reportProgress: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
267 ) {
268 const executable = yield* relayClient.resolve;
269 if (executable.status === "available") {
270 return Option.some(executable);
271 }
272 if (executable.status === "unsupported") {
273 return Option.some(yield* relayClient.installWithProgress(reportProgress));
274 }
275 if (!(yield* confirmInstall(executable.version))) {
276 return Option.none();
277 }
278 return Option.some(yield* relayClient.installWithProgress(reportProgress));
279 },
280);
281​
282const withCloudCliSessionToken = <A, E, R>(
283 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
284 scope: AuthEnvironmentScope,
285 run: (token: string) => Effect.Effect<A, E, R>,
286) =>
287 Effect.acquireUseRelease(
288 environmentAuth.issueSession({
289 scopes: [scope],
290 subject: "cloud-cli",
291 label: "t3 connect cli",
292 }),
293 (issued) => run(issued.token),
294 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
295 );
296​
297type LiveCloudActionResult =
298 | { readonly status: "not-running" }
299 | { readonly status: "succeeded" }
300 | { readonly status: "failed"; readonly cause: Cause.Cause<unknown> };
301​
302const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
303 const config = yield* ServerConfig.ServerConfig;
304 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
305 if (Option.isNone(runtimeState)) {
306 return { status: "not-running" } satisfies LiveCloudActionResult;
307 }
308​
309 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
310 const result = yield* Effect.exit(
311 withCloudCliSessionToken(environmentAuth, AuthRelayWriteScope, (token) =>
312 HttpApiClient.make(EnvironmentHttpApi, {
313 baseUrl: runtimeState.value.origin,
314 }).pipe(
315 Effect.flatMap((client) =>
316 client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
317 ),
318 Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
319 ),
320 ),
321 );
322 return Exit.isSuccess(result)
323 ? ({ status: "succeeded" } satisfies LiveCloudActionResult)
324 : ({ status: "failed", cause: result.cause } satisfies LiveCloudActionResult);
325});
326​
327// One check probes the endpoint, the tunnel edge, and Tailscale, each with its own timeout.
328const CLOUD_CLI_REACHABILITY_TIMEOUT = Duration.seconds(30);
329const CLOUD_CLI_REACHABILITY_WAIT = Duration.seconds(60);
330const CLOUD_CLI_REACHABILITY_RETRY = Duration.seconds(5);
331​
332/** Asks the running server to check T3 Connect now. `null` when no server answers. */
333const checkLiveReachability = Effect.fn("cloud.cli.check_live_reachability")(function* () {
334 const config = yield* ServerConfig.ServerConfig;
335 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
336 if (Option.isNone(runtimeState)) return null;
337 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
338 return yield* withCloudCliSessionToken(environmentAuth, AuthRelayReadScope, (token) =>
339 HttpApiClient.make(EnvironmentHttpApi, { baseUrl: runtimeState.value.origin }).pipe(
340 Effect.flatMap((client) =>
341 client.connect.checkReachability({ headers: { authorization: `Bearer ${token}` } }),
342 ),
343 Effect.timeout(CLOUD_CLI_REACHABILITY_TIMEOUT),
344 ),
345 ).pipe(Effect.orElseSucceed(() => null));
346});
347​
348function formatAlertBox(text: string): string {
349 const lines = text.split("\n");
350 const width = Math.max(...lines.map((line) => line.length));
351 const color = process.stdout.isTTY === true && !process.env.NO_COLOR;
352 const red = (line: string) => (color ? `\x1b[1;31m${line}\x1b[0m` : line);
353 return [
354 `┌${"─".repeat(width + 2)}┐`,
355 ...lines.map((line) => `│ ${line.padEnd(width)} │`),
356 `└${"─".repeat(width + 2)}┘`,
357 ]
358 .map(red)
359 .join("\n");
361​
362/**
363 * Waits for the server that `t3 connect` just started to prove other devices
364 * can reach it, so a broken tunnel fails setup instead of looking green.
365 */
366const waitForReachability = Effect.fn("cloud.cli.wait_for_reachability")(function* () {
367 yield* Console.log("\nChecking that other devices can reach this machine...");
368 const deadline =
369 (yield* Clock.currentTimeMillis) + Duration.toMillis(CLOUD_CLI_REACHABILITY_WAIT);
370 let last: EnvironmentConnectReachability | null = null;
371 while (true) {
372 last = (yield* checkLiveReachability()) ?? last;
373 if (last?.status === "reachable") {
374 yield* Console.log(
375 `✓ Other devices can reach this machine · ${formatConnectReachable(last)}`,
376 );
377 return;
378 }
379 if ((yield* Clock.currentTimeMillis) >= deadline) break;
380 yield* Effect.sleep(CLOUD_CLI_REACHABILITY_RETRY);
381 }
382 yield* Console.error(
383 formatAlertBox(
384 last === null
385 ? "✕ Could not check T3 Connect\n The T3 server on this machine did not answer.\n Fix: run `t3 service status`, then `t3 connect status`."
386 : formatReachabilityFailure(last),
387 ),
388 );
389 yield* Effect.sync(() => {
390 process.exitCode = 1;
391 });
392});
393​
394type RelayUnlinkResult =
395 | { readonly status: "not-authenticated" }
396 | { readonly status: "revoked" }
397 | { readonly status: "not-linked" };
398​
399type CloudDisconnectOperation = "live-server-unlink" | "relay-environment-unlink";
400​
401const logCloudDisconnectFailure = (
402 operation: CloudDisconnectOperation,
403 clearAuthorization: boolean,
404 cause: Cause.Cause<unknown>,
405) =>
406 Effect.logWarning("T3 Connect disconnect operation failed.").pipe(
407 Effect.annotateLogs({
408 operation,
409 clearAuthorization,
410 cause: Cause.pretty(cause),
411 }),
412 );
413​
414const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () {
415 const tokens = yield* CliTokenManager.CloudCliTokenManager;
416 const token = yield* tokens.getExisting;
417 if (Option.isNone(token)) {
418 return { status: "not-authenticated" } satisfies RelayUnlinkResult;
419 }
420​
421 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
422 const environmentId = yield* environment.getEnvironmentId;
423 const relayUrl = yield* relayUrlConfig;
424 const httpClient = yield* HttpClient.HttpClient;
425 const response = yield* HttpClientRequest.delete(
426 `${relayUrl}/v1/client/environment-links/${encodeURIComponent(environmentId)}`,
427 ).pipe(
428 HttpClientRequest.bearerToken(token.value.accessToken),
429 httpClient.execute,
430 Effect.flatMap(filterRelayResponse),
431 Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
432 withRelayClientTracing,
433 );
434 return response.ok
435 ? ({ status: "revoked" } satisfies RelayUnlinkResult)
436 : ({ status: "not-linked" } satisfies RelayUnlinkResult);
437});
438​
439/**
440 * Prints the local disconnect outcome, then whether the relay record was revoked.
441 * A missing CLI login or a failed relay DELETE leaves that record registered, so
442 * those outcomes warn to deregister it from the T3 Connect account page.
443 */
444const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
445 function* (input: {
446 readonly clearAuthorization: boolean;
447 readonly liveResult: LiveCloudActionResult;
448 readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>;
449 }) {
450 if (input.liveResult.status === "failed") {
451 yield* logCloudDisconnectFailure(
452 "live-server-unlink",
453 input.clearAuthorization,
454 input.liveResult.cause,
455 );
456 yield* Console.warn(
457 "T3 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.",
458 );
459 } else {
460 yield* Console.log("T3 Connect is disabled locally.");
461 }
462​
463 if (Exit.isFailure(input.relayResult)) {
464 yield* logCloudDisconnectFailure(
465 "relay-environment-unlink",
466 input.clearAuthorization,
467 input.relayResult.cause,
468 );
469 yield* Console.warn(
470 input.clearAuthorization
471 ? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally."
472 : "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.",
473 );
474 } else if (input.relayResult.value.status === "not-authenticated") {
475 yield* Console.warn(
476 "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.",
477 );
478 } else if (input.relayResult.value.status === "revoked") {
479 yield* Console.log("Revoked the relay-side environment record.");
480 }
481 },
482);
483​
484const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
485 readonly clearAuthorization: boolean;
486}) {
487 yield* CliState.setCliDesiredCloudLink(false);
488 const liveResult = yield* runLiveCloudUnlink();
489 const relayResult = yield* Effect.exit(unlinkRelayEnvironment());
490 yield* CliState.clearPersistedCloudLink;
491​
492 if (options.clearAuthorization) {
493 const tokens = yield* CliTokenManager.CloudCliTokenManager;
494 yield* tokens.clear;
495 }
496​
497 yield* reportCloudDisconnectResults({
498 clearAuthorization: options.clearAuthorization,
499 liveResult,
500 relayResult,
501 });
502​
503 if (options.clearAuthorization) {
504 yield* Console.log(
505 "Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
506 );
507 }
508});
509​
510const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
511 flags: { readonly baseDir: Option.Option<string> },
512 run: Effect.Effect<
513 A,
514 E,
515 | ServerSecretStore.ServerSecretStore
516 | CliTokenManager.CloudCliTokenManager
517 | RelayClient.RelayClient
518 | EnvironmentAuth.EnvironmentAuth
519 | BootService.BootService
520 | Crypto.Crypto
521 | FileSystem.FileSystem
522 | HttpClient.HttpClient
523 | Prompt.Environment
524 | ServerConfig.ServerConfig
525 | ServerEnvironment.ServerEnvironmentIdentity
526 >,
527 options?: {
528 readonly quietLogs?: boolean;
529 },
530) {
531 const logLevel = yield* GlobalFlag.LogLevel;
532 const config = yield* resolveCliAuthConfig(flags, logLevel);
533 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
534 const layerRuntime = Layer.mergeAll(
535 ServerSecretStore.layer,
536 CliTokenManager.layer.pipe(
537 Layer.provide(ServerSecretStore.layer),
538 Layer.provide(ExternalLauncher.layer),
539 ),
540 RelayClient.layerCloudflared({ baseDir: config.baseDir }),
541 EnvironmentAuth.layerRuntime,
542 CliService.layer(config),
543 RelayTracing.layerHeadlessRelayClient,
544 ).pipe(
545 Layer.provideMerge(FetchHttpClient.layer),
546 Layer.provideMerge(ServerConfig.layer(config)),
547 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
548 );
549 return yield* run.pipe(Effect.provide(layerRuntime));
550});
551​
552const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : "");
553​
554function formatRelayClientReady(version: string): string {
555 return `✓ Relay client ready · cloudflared ${version}`;
557​
558const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: {
559 readonly headless: boolean;
560 readonly publishOnly?: boolean;
561}) {
562 const publishOnly = options.publishOnly ?? false;
563 if (!publishOnly) {
564 const relayClient = yield* RelayClient.RelayClient;
565 const installed = yield* acquireRelayClientForLink(
566 relayClient,
567 confirmRelayClientInstall,
568 reportRelayClientInstallProgress,
569 );
570 if (Option.isNone(installed)) {
571 yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
572 return null;
573 }
574 yield* Console.log(formatRelayClientReady(installed.value.version));
575 }
576​
577 const identity = yield* authorizeCli(options);
578 yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed");
579 if (yield* CliState.dropRevokedCloudLink) {
580 yield* Console.log(
581 "Removed the link T3 Connect no longer accepts. The next start links this environment again.",
582 );
583 }
584 if (publishOnly) {
585 const secrets = yield* ServerSecretStore.ServerSecretStore;
586 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));
587 }
588 return { identity } as const;
589});
590​
591const connectLoginCommand = Command.make("login", {
592 ...projectLocationFlags,
593 headless: headlessFlag,
594}).pipe(
595 Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
596 Command.withHandler((flags) =>
597 runCloudCommand(
598 flags,
599 Effect.gen(function* () {
600 yield* Console.log("T3 Connect\n");
601 const identity = yield* authorizeCli(flags);
602 yield* Console.log(`✓ Signed in${connectedAs(identity)}`);
603 }),
604 ),
605 ),
606);
607​
608const connectLinkCommand = Command.make("link", {
609 ...projectLocationFlags,
610 headless: headlessFlag,
611 publishOnly: Flag.Boolean("publish-only").pipe(
612 Flag.withDescription(
613 "Link to publish agent activity only — no managed tunnel. Reach this environment out of band (e.g. Tailscale).",
614 ),
615 Flag.withDefault(false),
616 ),
617}).pipe(
618 Command.withDescription("Authorize this environment for T3 Connect on next start."),
619 Command.withHandler((flags) =>
620 runCloudCommand(
621 flags,
622 Effect.gen(function* () {
623 yield* Console.log("T3 Connect\n");
624 const linked = yield* linkEnvironmentForConnect(flags);
625 if (linked) {
626 const serveCommand = yield* resolveCliCommand("serve");
627 yield* Console.log(
628 flags.publishOnly
629 ? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`
630 : `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
631 );
632 }
633 }),
634 ),
635 ),
636);
637​
638const connectStatusCommand = Command.make("status", {
639 ...projectLocationFlags,
640 json: jsonFlag,
641}).pipe(
642 Command.withDescription(
643 "Show T3 Connect setup and check that other devices can reach this machine.",
644 ),
645 Command.withHandler((flags) =>
646 runCloudCommand(
647 flags,
648 Effect.gen(function* () {
649 const secrets = yield* ServerSecretStore.ServerSecretStore;
650 const relayClient = yield* RelayClient.RelayClient;
651 const tokens = yield* CliTokenManager.CloudCliTokenManager;
652 const [
653 desired,
654 authenticated,
655 cloudUserId,
656 relayUrl,
657 publishAgentActivity,
658 revoked,
659 executable,
660 linkMode,
661 ] = yield* Effect.all(
662 [
663 CliState.readCliDesiredCloudLink,
664 tokens.hasCredential,
665 secrets.get(CLOUD_LINKED_USER_ID),
666 secrets.get(RELAY_URL_SECRET),
667 secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
668 secrets.get(CLOUD_LINK_REVOKED),
669 relayClient.resolve,
670 CliState.readCliDesiredLinkMode,
671 ],
672 { concurrency: "unbounded" },
673 );
674 // A publish-only link has no tunnel for other devices to reach.
675 const reachability =
676 desired && linkMode === "managed" ? yield* checkLiveReachability() : null;
677 const status: CloudCliStatus = {
678 desired,
679 authenticated,
680 linked: Option.isSome(cloudUserId),
681 revoked: Option.isSome(cloudUserId) && Option.isSome(revoked),
682 cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
683 relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
684 publishAgentActivity: isAgentActivityPublishingEnabledValue(
685 Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null,
686 ),
687 relayClient: executable,
688 linkMode,
689 reachability,
690 };
691 yield* Console.log(formatCloudStatus(status, { json: flags.json }));
692 }),
693 {
694 quietLogs: flags.json,
695 },
696 ),
697 ),
698);
699​
700const connectPublishCommand = Command.make("publish", {
701 ...projectLocationFlags,
702 disable: Flag.Boolean("disable").pipe(
703 Flag.withDescription("Stop publishing agent activity to your mobile clients."),
704 Flag.withDefault(false),
705 ),
706}).pipe(
707 Command.withDescription(
708 "Toggle publishing agent activity (push notifications and Live Activities) to your mobile clients.",
709 ),
710 Command.withHandler((flags) =>
711 runCloudCommand(
712 flags,
713 Effect.gen(function* () {
714 const secrets = yield* ServerSecretStore.ServerSecretStore;
715 const tokens = yield* CliTokenManager.CloudCliTokenManager;
716 const enabled = !flags.disable;
717 yield* secrets.set(
718 PUBLISH_AGENT_ACTIVITY_SECRET,
719 stringToBytes(enabled ? "true" : "false"),
720 );
721 if (!enabled) {
722 // If enabling scheduled a publish-only link that hasn't been
723 // provisioned yet, disabling must cancel it too — otherwise the next
724 // start still links an environment whose only purpose was publishing.
725 // A pending managed link is left alone; it exists for the tunnel.
726 const linkedNow = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
727 if (!linkedNow && (yield* CliState.readCliDesiredLinkMode) === "publish_only") {
728 yield* CliState.setCliDesiredCloudLink(false);
729 yield* Console.log("Cancelled the pending publish-only T3 Connect link.");
730 }
731 yield* Console.log("Publishing agent activity disabled.");
732 return;
733 }
734​
735 yield* Console.log("Publishing agent activity enabled.");
736 const linked = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
737 if (linked) {
738 return;
739 }
740​
741 if (!(yield* tokens.hasCredential)) {
742 yield* Console.log(
743 "Run `t3 connect login` first so this environment can be authorized to publish.",
744 );
745 return;
746 }
747 // A link may already be desired (e.g. `t3 connect link` before the
748 // server's first start). Never downgrade it: a desired managed link
749 // also covers publishing, so only request a publish-only link when no
750 // link is pending at all.
751 if (yield* CliState.readCliDesiredCloudLink) {
752 yield* Console.log(
753 "A T3 Connect link is already pending. Start T3 to finish provisioning it; publishing starts once it links.",
754 );
755 return;
756 }
757 yield* CliState.setCliDesiredCloudLink(true, "publish_only");
758 yield* Console.log(
759 "Restart T3 to finish authorizing this environment to publish (no managed tunnel is created).",
760 );
761 }),
762 ),
763 ),
764);
765​
766const connectUnlinkCommand = Command.make("unlink", {
767 ...projectLocationFlags,
768}).pipe(
769 Command.withDescription("Disable T3 Connect while retaining the stored authorization."),
770 Command.withHandler((flags) =>
771 runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),
772 ),
773);
774​
775const connectLogoutCommand = Command.make("logout", {
776 ...projectLocationFlags,
777}).pipe(
778 Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."),
779 Command.withHandler((flags) =>
780 runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),
781 ),
782);
783​
784const reportServiceOnboarding = Effect.fn("cli.connect.report_service_onboarding")(function* (
785 outcome: CliService.ServiceOnboardingOutcome,
786) {
787 if (outcome === "pending") {
788 yield* Console.log(
789 "\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.",
790 );
791 return;
792 }
793 if (outcome === "ready") {
794 const platform = yield* HostProcess.Platform;
795 yield* Console.log(
796 platform === "darwin"
797 ? "\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."
798 : "\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.",
799 );
800 return;
801 }
802 const serveCommand = yield* resolveCliCommand("serve");
803 yield* Console.log(
804 `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.\n It checks that other devices can reach this machine when it starts.`,
805 );
806});
807​
808export const connectCommand = Command.make("connect", {
809 ...projectLocationFlags,
810 headless: headlessFlag,
811}).pipe(
812 Command.withDescription("Set up T3 Connect for this machine."),
813 Command.withHandler((flags) =>
814 runCloudCommand(
815 flags,
816 Effect.gen(function* () {
817 yield* Console.log("T3 Connect\n");
818 const linked = yield* linkEnvironmentForConnect(flags);
819 if (!linked) {
820 return;
821 }
822 yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}`);
823​
824 const outcome = yield* CliService.recoverServiceOnboardingOffer(
825 CliService.offerServiceDuringOnboarding,
826 );
827 yield* reportServiceOnboarding(outcome);
828 if (outcome !== "skipped") {
829 yield* waitForReachability();
830 }
831 }),
832 ),
833 ),
834 Command.withSubcommands([
835 connectLoginCommand,
836 connectLinkCommand,
837 connectPublishCommand,
838 connectStatusCommand,
839 connectUnlinkCommand,
840 connectLogoutCommand,
841 ]),
842);