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

connect.ts

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