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

connect.ts

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