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

connect.ts

425 lines14.7 KB

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