Open History to see the last commit
1import {
2 AuthRelayWriteScope,
3 EnvironmentHttpApi,
4 type RelayClientInstallProgressEvent,
5 type RelayClientInstallProgressStage,
6} from "@t3tools/contracts";
7import { RelayOkResponse } from "@t3tools/contracts/relay";
8import * as RelayClient from "@t3tools/shared/relayClient";
9import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
10import * as Cause from "effect/Cause";
11import * as Console from "effect/Console";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as References from "effect/References";
19import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
20import {
21 FetchHttpClient,
22 HttpClient,
23 HttpClientRequest,
24 HttpClientResponse,
25} from "effect/unstable/http";
26import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
27
28import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
29import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
30import * as CliState from "../cloud/CliState.ts";
31import * as CliTokenManager from "../cloud/CliTokenManager.ts";
32import { CLOUD_LINKED_USER_ID, RELAY_URL_SECRET } from "../cloud/config.ts";
33import { relayUrlConfig } from "../cloud/publicConfig.ts";
34import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
35import * as ServerConfig from "../config.ts";
36import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
37import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
38import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
39
40const jsonFlag = Flag.boolean("json").pipe(
41 Flag.withDescription("Emit JSON instead of human-readable output."),
42 Flag.withDefault(false),
43);
44
45function bytesToString(value: Uint8Array): string {
46 return new TextDecoder().decode(value);
47}
48
49interface CloudCliStatus {
50 readonly desired: boolean;
51 readonly authenticated: boolean;
52 readonly linked: boolean;
53 readonly cloudUserId: string | null;
54 readonly relayUrl: string | null;
55 readonly relayClient: RelayClient.RelayClientStatus;
56}
57
58function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
59 switch (executable.status) {
60 case "available": {
61 const source =
62 executable.source === "path"
63 ? "PATH"
64 : executable.source === "managed"
65 ? "managed install"
66 : "configured override";
67 return [
68 ` Relay client: available via ${source}`,
69 ` Path: ${executable.executablePath}`,
70 ` Version: ${executable.version}`,
71 ];
72 }
73 case "missing":
74 return [" Relay client: not installed"];
75 case "unsupported":
76 return [
77 ` Relay client: unsupported on ${executable.platform}-${executable.arch}`,
78 ` Managed version: ${executable.version}`,
79 ];
80 }
81}
82
83function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: boolean }): string {
84 if (options?.json) {
85 return JSON.stringify(status, null, 2);
86 }
87
88 const provisioned = status.linked
89 ? "provisioned"
90 : status.desired && status.authenticated
91 ? "pending server startup"
92 : "not provisioned";
93 const nextStep = !status.authenticated
94 ? "Run `t3 connect link` to authorize and enable T3 Connect."
95 : !status.desired
96 ? "Run `t3 connect link` to enable T3 Connect."
97 : !status.linked
98 ? "Start T3 to provision the environment link and launch its managed tunnel."
99 : undefined;
100
101 return [
102 "T3 Connect",
103 ` Exposure: ${status.desired ? "enabled" : "disabled"}`,
104 ` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
105 ` Environment link: ${provisioned}`,
106 ` Relay: ${status.relayUrl ?? "not provisioned"}`,
107 ...formatRelayClientStatus(status.relayClient),
108 ...(nextStep ? ["", `Next: ${nextStep}`] : []),
109 ].join("\n");
110}
111
112const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);
113
114const confirmRelayClientInstall = (version: string) =>
115 Prompt.run(
116 Prompt.confirm({
117 message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`,
118 initial: false,
119 }),
120 );
121
122function relayClientInstallProgressMessage(stage: RelayClientInstallProgressStage): string {
123 switch (stage) {
124 case "checking":
125 return "Checking existing installation";
126 case "waiting_for_lock":
127 return "Waiting for installation lock";
128 case "downloading":
129 return "Downloading";
130 case "verifying":
131 return "Verifying download";
132 case "installing":
133 return "Installing";
134 case "validating":
135 return "Validating executable";
136 case "activating":
137 return "Activating installation";
138 }
139}
140
141const reportRelayClientInstallProgress = (event: RelayClientInstallProgressEvent) =>
142 event.type === "progress"
143 ? Console.log(`Relay client: ${relayClientInstallProgressMessage(event.stage)}...`)
144 : Effect.void;
145
146export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_client_for_link")(
147 function* <ConfirmError, ConfirmContext>(
148 relayClient: RelayClient.RelayClient["Service"],
149 confirmInstall: (version: string) => Effect.Effect<boolean, ConfirmError, ConfirmContext>,
150 reportProgress: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
151 ) {
152 const executable = yield* relayClient.resolve;
153 if (executable.status === "available") {
154 return Option.some(executable);
155 }
156 if (executable.status === "unsupported") {
157 return Option.some(yield* relayClient.installWithProgress(reportProgress));
158 }
159 if (!(yield* confirmInstall(executable.version))) {
160 return Option.none();
161 }
162 return Option.some(yield* relayClient.installWithProgress(reportProgress));
163 },
164);
165
166const withCloudCliSessionToken = <A, E, R>(
167 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
168 run: (token: string) => Effect.Effect<A, E, R>,
169) =>
170 Effect.acquireUseRelease(
171 environmentAuth.issueSession({
172 scopes: [AuthRelayWriteScope],
173 subject: "cloud-cli",
174 label: "t3 connect cli",
175 }),
176 (issued) => run(issued.token),
177 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
178 );
179
180type LiveCloudActionResult =
181 | { readonly status: "not-running" }
182 | { readonly status: "succeeded" }
183 | { readonly status: "failed"; readonly cause: Cause.Cause<unknown> };
184
185const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
186 const config = yield* ServerConfig.ServerConfig;
187 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
188 if (Option.isNone(runtimeState)) {
189 return { status: "not-running" } satisfies LiveCloudActionResult;
190 }
191
192 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
193 const result = yield* Effect.exit(
194 withCloudCliSessionToken(environmentAuth, (token) =>
195 HttpApiClient.make(EnvironmentHttpApi, {
196 baseUrl: runtimeState.value.origin,
197 }).pipe(
198 Effect.flatMap((client) =>
199 client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
200 ),
201 Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
202 ),
203 ),
204 );
205 return Exit.isSuccess(result)
206 ? ({ status: "succeeded" } satisfies LiveCloudActionResult)
207 : ({ status: "failed", cause: result.cause } satisfies LiveCloudActionResult);
208});
209
210type RelayUnlinkResult =
211 | { readonly status: "not-authenticated" }
212 | { readonly status: "revoked" }
213 | { readonly status: "not-linked" };
214
215type CloudDisconnectOperation = "live-server-unlink" | "relay-environment-unlink";
216
217const logCloudDisconnectFailure = (
218 operation: CloudDisconnectOperation,
219 clearAuthorization: boolean,
220 cause: Cause.Cause<unknown>,
221) =>
222 Effect.logWarning("T3 Connect disconnect operation failed.").pipe(
223 Effect.annotateLogs({
224 operation,
225 clearAuthorization,
226 cause: Cause.pretty(cause),
227 }),
228 );
229
230const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () {
231 const tokens = yield* CliTokenManager.CloudCliTokenManager;
232 const token = yield* tokens.getExisting;
233 if (Option.isNone(token)) {
234 return { status: "not-authenticated" } satisfies RelayUnlinkResult;
235 }
236
237 const environment = yield* ServerEnvironment.ServerEnvironment;
238 const environmentId = yield* environment.getEnvironmentId;
239 const relayUrl = yield* relayUrlConfig;
240 const httpClient = yield* HttpClient.HttpClient;
241 const response = yield* HttpClientRequest.delete(
242 `${relayUrl}/v1/client/environment-links/${encodeURIComponent(environmentId)}`,
243 ).pipe(
244 HttpClientRequest.bearerToken(token.value.accessToken),
245 httpClient.execute,
246 Effect.flatMap(HttpClientResponse.filterStatusOk),
247 Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
248 withRelayClientTracing,
249 );
250 return response.ok
251 ? ({ status: "revoked" } satisfies RelayUnlinkResult)
252 : ({ status: "not-linked" } satisfies RelayUnlinkResult);
253});
254
255export const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
256 function* (input: {
257 readonly clearAuthorization: boolean;
258 readonly liveResult: LiveCloudActionResult;
259 readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>;
260 }) {
261 if (input.liveResult.status === "failed") {
262 yield* logCloudDisconnectFailure(
263 "live-server-unlink",
264 input.clearAuthorization,
265 input.liveResult.cause,
266 );
267 yield* Console.warn(
268 "T3 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.",
269 );
270 } else {
271 yield* Console.log("T3 Connect is disabled locally.");
272 }
273
274 if (Exit.isFailure(input.relayResult)) {
275 yield* logCloudDisconnectFailure(
276 "relay-environment-unlink",
277 input.clearAuthorization,
278 input.relayResult.cause,
279 );
280 yield* Console.warn(
281 input.clearAuthorization
282 ? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally."
283 : "Could not revoke the relay-side environment record yet.\nRun `t3 connect unlink` again when the relay is reachable.",
284 );
285 } else if (input.relayResult.value.status === "revoked") {
286 yield* Console.log("Revoked the relay-side environment record.");
287 }
288 },
289);
290
291const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
292 readonly clearAuthorization: boolean;
293}) {
294 yield* CliState.setCliDesiredCloudLink(false);
295 const liveResult = yield* runLiveCloudUnlink();
296 const relayResult = yield* Effect.exit(unlinkRelayEnvironment());
297 yield* CliState.clearPersistedCloudLink;
298
299 if (options.clearAuthorization) {
300 const tokens = yield* CliTokenManager.CloudCliTokenManager;
301 yield* tokens.clear;
302 }
303
304 yield* reportCloudDisconnectResults({
305 clearAuthorization: options.clearAuthorization,
306 liveResult,
307 relayResult,
308 });
309
310 if (options.clearAuthorization) {
311 yield* Console.log("Signed out of T3 Connect locally.");
312 }
313});
314
315const runCloudCommand = <A, E>(
316 flags: { readonly baseDir: Option.Option<string> },
317 run: Effect.Effect<
318 A,
319 E,
320 | ServerSecretStore.ServerSecretStore
321 | CliTokenManager.CloudCliTokenManager
322 | RelayClient.RelayClient
323 | EnvironmentAuth.EnvironmentAuth
324 | FileSystem.FileSystem
325 | HttpClient.HttpClient
326 | Prompt.Environment
327 | ServerConfig.ServerConfig
328 | ServerEnvironment.ServerEnvironment
329 >,
330 options?: {
331 readonly quietLogs?: boolean;
332 },
333) =>
334 Effect.gen(function* () {
335 const logLevel = yield* GlobalFlag.LogLevel;
336 const config = yield* resolveCliAuthConfig(flags, logLevel);
337 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
338 const runtimeLayer = Layer.mergeAll(
339 ServerSecretStore.layer,
340 CliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)),
341 RelayClient.layerCloudflared({ baseDir: config.baseDir }),
342 EnvironmentAuth.runtimeLayer,
343 ServerEnvironment.layer,
344 headlessRelayClientTracingLayer,
345 ).pipe(
346 Layer.provideMerge(FetchHttpClient.layer),
347 Layer.provideMerge(ServerConfig.layer(config)),
348 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
349 );
350 return yield* run.pipe(Effect.provide(runtimeLayer));
351 });
352
353const connectLoginCommand = Command.make("login", {
354 ...projectLocationFlags,
355}).pipe(
356 Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
357 Command.withHandler((flags) =>
358 runCloudCommand(
359 flags,
360 Effect.gen(function* () {
361 const tokens = yield* CliTokenManager.CloudCliTokenManager;
362 yield* tokens.get;
363 yield* Console.log("Signed in to T3 Connect.");
364 }),
365 ),
366 ),
367);
368
369const connectLinkCommand = Command.make("link", {
370 ...projectLocationFlags,
371}).pipe(
372 Command.withDescription("Authorize this environment for T3 Connect on next start."),
373 Command.withHandler((flags) =>
374 runCloudCommand(
375 flags,
376 Effect.gen(function* () {
377 const relayClient = yield* RelayClient.RelayClient;
378 const installed = yield* acquireRelayClientForLink(
379 relayClient,
380 confirmRelayClientInstall,
381 reportRelayClientInstallProgress,
382 );
383 if (Option.isNone(installed)) {
384 yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
385 return;
386 }
387 yield* Console.log(
388 `Using relay client ${installed.value.version} from ${installed.value.executablePath}.`,
389 );
390
391 const tokens = yield* CliTokenManager.CloudCliTokenManager;
392 yield* tokens.get;
393 yield* CliState.setCliDesiredCloudLink(true);
394 yield* Console.log(
395 "This T3 environment will be available through T3 Connect the next time T3 starts.",
396 );
397 }),
398 ),
399 ),
400);
401
402const connectStatusCommand = Command.make("status", {
403 ...projectLocationFlags,
404 json: jsonFlag,
405}).pipe(
406 Command.withDescription("Show persisted T3 Connect and relay client state."),
407 Command.withHandler((flags) =>
408 runCloudCommand(
409 flags,
410 Effect.gen(function* () {
411 const secrets = yield* ServerSecretStore.ServerSecretStore;
412 const relayClient = yield* RelayClient.RelayClient;
413 const tokens = yield* CliTokenManager.CloudCliTokenManager;
414 const [desired, authenticated, cloudUserId, relayUrl, executable] = yield* Effect.all(
415 [
416 CliState.readCliDesiredCloudLink,
417 tokens.hasCredential,
418 secrets.get(CLOUD_LINKED_USER_ID),
419 secrets.get(RELAY_URL_SECRET),
420 relayClient.resolve,
421 ],
422 { concurrency: "unbounded" },
423 );
424 const status: CloudCliStatus = {
425 desired,
426 authenticated,
427 linked: Option.isSome(cloudUserId),
428 cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
429 relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
430 relayClient: executable,
431 };
432 yield* Console.log(formatCloudStatus(status, { json: flags.json }));
433 }),
434 {
435 quietLogs: flags.json,
436 },
437 ),
438 ),
439);
440
441const connectUnlinkCommand = Command.make("unlink", {
442 ...projectLocationFlags,
443}).pipe(
444 Command.withDescription("Disable T3 Connect while retaining the stored authorization."),
445 Command.withHandler((flags) =>
446 runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),
447 ),
448);
449
450const connectLogoutCommand = Command.make("logout", {
451 ...projectLocationFlags,
452}).pipe(
453 Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."),
454 Command.withHandler((flags) =>
455 runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),
456 ),
457);
458
459export const connectCommand = Command.make("connect").pipe(
460 Command.withDescription("Manage headless T3 Connect access."),
461 Command.withSubcommands([
462 connectLoginCommand,
463 connectLinkCommand,
464 connectStatusCommand,
465 connectUnlinkCommand,
466 connectLogoutCommand,
467 ]),
468);