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

connect.ts

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