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

connect.ts

579 lines20.7 KB

1import {
2 AuthRelayWriteScope,
3 EnvironmentHttpApi,
4 type RelayClientInstallProgressEvent,
5 type RelayClientInstallProgressStage,
6} from "@v12/contracts";
7import { RelayOkResponse } from "@v12/contracts/relay";
8import * as RelayClient from "@v12/shared/relayClient";
9import { withRelayClientTracing } from "@v12/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 {
33 CLOUD_LINKED_USER_ID,
34 PUBLISH_AGENT_ACTIVITY_SECRET,
35 RELAY_URL_SECRET,
36} from "../cloud/config.ts";
37import { relayUrlConfig } from "../cloud/publicConfig.ts";
38import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
39import * as ServerConfig from "../config.ts";
40import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
41import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
42import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
43​
44const jsonFlag = Flag.boolean("json").pipe(
45 Flag.withDescription("Emit JSON instead of human-readable output."),
46 Flag.withDefault(false),
47);
48​
49function bytesToString(value: Uint8Array): string {
50 return new TextDecoder().decode(value);
52​
53function stringToBytes(value: string): Uint8Array {
54 return new TextEncoder().encode(value);
56​
57export function isPublishAgentActivityEnabledValue(value: string | null): boolean {
58 return value === "true";
60​
61interface CloudCliStatus {
62 readonly desired: boolean;
63 readonly authenticated: boolean;
64 readonly linked: boolean;
65 readonly cloudUserId: string | null;
66 readonly relayUrl: string | null;
67 readonly publishAgentActivity: boolean;
68 readonly relayClient: RelayClient.RelayClientStatus;
70​
71function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
72 switch (executable.status) {
73 case "available": {
74 const source =
75 executable.source === "path"
76 ? "PATH"
77 : executable.source === "managed"
78 ? "managed install"
79 : "configured override";
80 return [
81 ` Relay client: available via ${source}`,
82 ` Path: ${executable.executablePath}`,
83 ` Version: ${executable.version}`,
84 ];
85 }
86 case "missing":
87 return [" Relay client: not installed"];
88 case "unsupported":
89 return [
90 ` Relay client: unsupported on ${executable.platform}-${executable.arch}`,
91 ` Managed version: ${executable.version}`,
92 ];
93 }
95​
96function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: boolean }): string {
97 if (options?.json) {
98 return JSON.stringify(status, null, 2);
99 }
100​
101 const provisioned = status.linked
102 ? "provisioned"
103 : status.desired && status.authenticated
104 ? "pending server startup"
105 : "not provisioned";
106 const nextStep = !status.authenticated
107 ? "Run `v12 connect link` to authorize and enable V12 Connect."
108 : !status.desired
109 ? "Run `v12 connect link` to enable V12 Connect."
110 : !status.linked
111 ? "Start V12 to provision the environment link and launch its managed tunnel."
112 : undefined;
113​
114 return [
115 "V12 Connect",
116 ` Exposure: ${status.desired ? "enabled" : "disabled"}`,
117 ` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
118 ` Environment link: ${provisioned}`,
119 ` Relay: ${status.relayUrl ?? "not provisioned"}`,
120 ` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`,
121 ...formatRelayClientStatus(status.relayClient),
122 ...(nextStep ? ["", `Next: ${nextStep}`] : []),
123 ].join("\n");
125​
126const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);
127​
128const confirmRelayClientInstall = (version: string) =>
129 Prompt.run(
130 Prompt.confirm({
131 message: `The V12 relay client is required for V12 Connect. Download and install version ${version}?`,
132 initial: false,
133 }),
134 );
135​
136function relayClientInstallProgressMessage(stage: RelayClientInstallProgressStage): string {
137 switch (stage) {
138 case "checking":
139 return "Checking existing installation";
140 case "waiting_for_lock":
141 return "Waiting for installation lock";
142 case "downloading":
143 return "Downloading";
144 case "verifying":
145 return "Verifying download";
146 case "installing":
147 return "Installing";
148 case "validating":
149 return "Validating executable";
150 case "activating":
151 return "Activating installation";
152 }
154​
155const reportRelayClientInstallProgress = (event: RelayClientInstallProgressEvent) =>
156 event.type === "progress"
157 ? Console.log(`Relay client: ${relayClientInstallProgressMessage(event.stage)}...`)
158 : Effect.void;
159​
160export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_client_for_link")(
161 function* <ConfirmError, ConfirmContext>(
162 relayClient: RelayClient.RelayClient["Service"],
163 confirmInstall: (version: string) => Effect.Effect<boolean, ConfirmError, ConfirmContext>,
164 reportProgress: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
165 ) {
166 const executable = yield* relayClient.resolve;
167 if (executable.status === "available") {
168 return Option.some(executable);
169 }
170 if (executable.status === "unsupported") {
171 return Option.some(yield* relayClient.installWithProgress(reportProgress));
172 }
173 if (!(yield* confirmInstall(executable.version))) {
174 return Option.none();
175 }
176 return Option.some(yield* relayClient.installWithProgress(reportProgress));
177 },
178);
179​
180const withCloudCliSessionToken = <A, E, R>(
181 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
182 run: (token: string) => Effect.Effect<A, E, R>,
183) =>
184 Effect.acquireUseRelease(
185 environmentAuth.issueSession({
186 scopes: [AuthRelayWriteScope],
187 subject: "cloud-cli",
188 label: "v12 connect cli",
189 }),
190 (issued) => run(issued.token),
191 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
192 );
193​
194type LiveCloudActionResult =
195 | { readonly status: "not-running" }
196 | { readonly status: "succeeded" }
197 | { readonly status: "failed"; readonly cause: Cause.Cause<unknown> };
198​
199const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
200 const config = yield* ServerConfig.ServerConfig;
201 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
202 if (Option.isNone(runtimeState)) {
203 return { status: "not-running" } satisfies LiveCloudActionResult;
204 }
205​
206 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
207 const result = yield* Effect.exit(
208 withCloudCliSessionToken(environmentAuth, (token) =>
209 HttpApiClient.make(EnvironmentHttpApi, {
210 baseUrl: runtimeState.value.origin,
211 }).pipe(
212 Effect.flatMap((client) =>
213 client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
214 ),
215 Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
216 ),
217 ),
218 );
219 return Exit.isSuccess(result)
220 ? ({ status: "succeeded" } satisfies LiveCloudActionResult)
221 : ({ status: "failed", cause: result.cause } satisfies LiveCloudActionResult);
222});
223​
224type RelayUnlinkResult =
225 | { readonly status: "not-authenticated" }
226 | { readonly status: "revoked" }
227 | { readonly status: "not-linked" };
228​
229type CloudDisconnectOperation = "live-server-unlink" | "relay-environment-unlink";
230​
231const logCloudDisconnectFailure = (
232 operation: CloudDisconnectOperation,
233 clearAuthorization: boolean,
234 cause: Cause.Cause<unknown>,
235) =>
236 Effect.logWarning("V12 Connect disconnect operation failed.").pipe(
237 Effect.annotateLogs({
238 operation,
239 clearAuthorization,
240 cause: Cause.pretty(cause),
241 }),
242 );
243​
244const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () {
245 const tokens = yield* CliTokenManager.CloudCliTokenManager;
246 const token = yield* tokens.getExisting;
247 if (Option.isNone(token)) {
248 return { status: "not-authenticated" } satisfies RelayUnlinkResult;
249 }
250​
251 const environment = yield* ServerEnvironment.ServerEnvironment;
252 const environmentId = yield* environment.getEnvironmentId;
253 const relayUrl = yield* relayUrlConfig;
254 const httpClient = yield* HttpClient.HttpClient;
255 const response = yield* HttpClientRequest.delete(
256 `${relayUrl}/v1/client/environment-links/${encodeURIComponent(environmentId)}`,
257 ).pipe(
258 HttpClientRequest.bearerToken(token.value.accessToken),
259 httpClient.execute,
260 Effect.flatMap(HttpClientResponse.filterStatusOk),
261 Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
262 withRelayClientTracing,
263 );
264 return response.ok
265 ? ({ status: "revoked" } satisfies RelayUnlinkResult)
266 : ({ status: "not-linked" } satisfies RelayUnlinkResult);
267});
268​
269export const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(
270 function* (input: {
271 readonly clearAuthorization: boolean;
272 readonly liveResult: LiveCloudActionResult;
273 readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>;
274 }) {
275 if (input.liveResult.status === "failed") {
276 yield* logCloudDisconnectFailure(
277 "live-server-unlink",
278 input.clearAuthorization,
279 input.liveResult.cause,
280 );
281 yield* Console.warn(
282 "V12 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.",
283 );
284 } else {
285 yield* Console.log("V12 Connect is disabled locally.");
286 }
287​
288 if (Exit.isFailure(input.relayResult)) {
289 yield* logCloudDisconnectFailure(
290 "relay-environment-unlink",
291 input.clearAuthorization,
292 input.relayResult.cause,
293 );
294 yield* Console.warn(
295 input.clearAuthorization
296 ? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally."
297 : "Could not revoke the relay-side environment record yet.\nRun `v12 connect unlink` again when the relay is reachable.",
298 );
299 } else if (input.relayResult.value.status === "revoked") {
300 yield* Console.log("Revoked the relay-side environment record.");
301 }
302 },
303);
304​
305const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
306 readonly clearAuthorization: boolean;
307}) {
308 yield* CliState.setCliDesiredCloudLink(false);
309 const liveResult = yield* runLiveCloudUnlink();
310 const relayResult = yield* Effect.exit(unlinkRelayEnvironment());
311 yield* CliState.clearPersistedCloudLink;
312​
313 if (options.clearAuthorization) {
314 const tokens = yield* CliTokenManager.CloudCliTokenManager;
315 yield* tokens.clear;
316 }
317​
318 yield* reportCloudDisconnectResults({
319 clearAuthorization: options.clearAuthorization,
320 liveResult,
321 relayResult,
322 });
323​
324 if (options.clearAuthorization) {
325 yield* Console.log("Signed out of V12 Connect locally.");
326 }
327});
328​
329const runCloudCommand = <A, E>(
330 flags: { readonly baseDir: Option.Option<string> },
331 run: Effect.Effect<
332 A,
333 E,
334 | ServerSecretStore.ServerSecretStore
335 | CliTokenManager.CloudCliTokenManager
336 | RelayClient.RelayClient
337 | EnvironmentAuth.EnvironmentAuth
338 | FileSystem.FileSystem
339 | HttpClient.HttpClient
340 | Prompt.Environment
341 | ServerConfig.ServerConfig
342 | ServerEnvironment.ServerEnvironment
343 >,
344 options?: {
345 readonly quietLogs?: boolean;
346 },
347) =>
348 Effect.gen(function* () {
349 const logLevel = yield* GlobalFlag.LogLevel;
350 const config = yield* resolveCliAuthConfig(flags, logLevel);
351 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
352 const runtimeLayer = Layer.mergeAll(
353 ServerSecretStore.layer,
354 CliTokenManager.layer.pipe(Layer.provide(ServerSecretStore.layer)),
355 RelayClient.layerCloudflared({ baseDir: config.baseDir }),
356 EnvironmentAuth.runtimeLayer,
357 ServerEnvironment.layer,
358 headlessRelayClientTracingLayer,
359 ).pipe(
360 Layer.provideMerge(FetchHttpClient.layer),
361 Layer.provideMerge(ServerConfig.layer(config)),
362 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
363 );
364 return yield* run.pipe(Effect.provide(runtimeLayer));
365 });
366​
367const connectLoginCommand = Command.make("login", {
368 ...projectLocationFlags,
369}).pipe(
370 Command.withDescription("Authorize the V12 Connect CLI without enabling remote access."),
371 Command.withHandler((flags) =>
372 runCloudCommand(
373 flags,
374 Effect.gen(function* () {
375 const tokens = yield* CliTokenManager.CloudCliTokenManager;
376 yield* tokens.get;
377 yield* Console.log("Signed in to V12 Connect.");
378 }),
379 ),
380 ),
381);
382​
383const connectLinkCommand = Command.make("link", {
384 ...projectLocationFlags,
385 publishOnly: Flag.boolean("publish-only").pipe(
386 Flag.withDescription(
387 "Link to publish agent activity only — no managed tunnel. Reach this environment out of band (e.g. Tailscale).",
388 ),
389 Flag.withDefault(false),
390 ),
391}).pipe(
392 Command.withDescription("Authorize this environment for V12 Connect on next start."),
393 Command.withHandler((flags) =>
394 runCloudCommand(
395 flags,
396 Effect.gen(function* () {
397 // A publish-only link needs no Cloudflare tunnel, so skip installing the
398 // relay client entirely.
399 if (!flags.publishOnly) {
400 const relayClient = yield* RelayClient.RelayClient;
401 const installed = yield* acquireRelayClientForLink(
402 relayClient,
403 confirmRelayClientInstall,
404 reportRelayClientInstallProgress,
405 );
406 if (Option.isNone(installed)) {
407 yield* Console.log("V12 Connect setup cancelled. The relay client was not installed.");
408 return;
409 }
410 yield* Console.log(
411 `Using relay client ${installed.value.version} from ${installed.value.executablePath}.`,
412 );
413 }
414​
415 const tokens = yield* CliTokenManager.CloudCliTokenManager;
416 yield* tokens.get;
417 yield* CliState.setCliDesiredCloudLink(
418 true,
419 flags.publishOnly ? "publish_only" : "managed",
420 );
421 if (flags.publishOnly) {
422 // A publish-only link exists solely to publish; without the publish
423 // flag the link would be inert and the success message a lie.
424 const secrets = yield* ServerSecretStore.ServerSecretStore;
425 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));
426 }
427 yield* Console.log(
428 flags.publishOnly
429 ? "This environment will publish agent activity to your mobile clients the next time V12 starts (no managed tunnel)."
430 : "This V12 environment will be available through V12 Connect the next time V12 starts.",
431 );
432 }),
433 ),
434 ),
435);
436​
437const connectStatusCommand = Command.make("status", {
438 ...projectLocationFlags,
439 json: jsonFlag,
440}).pipe(
441 Command.withDescription("Show persisted V12 Connect and relay client state."),
442 Command.withHandler((flags) =>
443 runCloudCommand(
444 flags,
445 Effect.gen(function* () {
446 const secrets = yield* ServerSecretStore.ServerSecretStore;
447 const relayClient = yield* RelayClient.RelayClient;
448 const tokens = yield* CliTokenManager.CloudCliTokenManager;
449 const [desired, authenticated, cloudUserId, relayUrl, publishAgentActivity, executable] =
450 yield* Effect.all(
451 [
452 CliState.readCliDesiredCloudLink,
453 tokens.hasCredential,
454 secrets.get(CLOUD_LINKED_USER_ID),
455 secrets.get(RELAY_URL_SECRET),
456 secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
457 relayClient.resolve,
458 ],
459 { concurrency: "unbounded" },
460 );
461 const status: CloudCliStatus = {
462 desired,
463 authenticated,
464 linked: Option.isSome(cloudUserId),
465 cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
466 relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
467 publishAgentActivity: isPublishAgentActivityEnabledValue(
468 Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null,
469 ),
470 relayClient: executable,
471 };
472 yield* Console.log(formatCloudStatus(status, { json: flags.json }));
473 }),
474 {
475 quietLogs: flags.json,
476 },
477 ),
478 ),
479);
480​
481const connectPublishCommand = Command.make("publish", {
482 ...projectLocationFlags,
483 disable: Flag.boolean("disable").pipe(
484 Flag.withDescription("Stop publishing agent activity to your mobile clients."),
485 Flag.withDefault(false),
486 ),
487}).pipe(
488 Command.withDescription(
489 "Toggle publishing agent activity (push notifications and Live Activities) to your mobile clients.",
490 ),
491 Command.withHandler((flags) =>
492 runCloudCommand(
493 flags,
494 Effect.gen(function* () {
495 const secrets = yield* ServerSecretStore.ServerSecretStore;
496 const tokens = yield* CliTokenManager.CloudCliTokenManager;
497 const enabled = !flags.disable;
498 yield* secrets.set(
499 PUBLISH_AGENT_ACTIVITY_SECRET,
500 stringToBytes(enabled ? "true" : "false"),
501 );
502 if (!enabled) {
503 // If enabling scheduled a publish-only link that hasn't been
504 // provisioned yet, disabling must cancel it too — otherwise the next
505 // start still links an environment whose only purpose was publishing.
506 // A pending managed link is left alone; it exists for the tunnel.
507 const linkedNow = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
508 if (!linkedNow && (yield* CliState.readCliDesiredLinkMode) === "publish_only") {
509 yield* CliState.setCliDesiredCloudLink(false);
510 yield* Console.log("Cancelled the pending publish-only V12 Connect link.");
511 }
512 yield* Console.log("Publishing agent activity disabled.");
513 return;
514 }
515​
516 yield* Console.log("Publishing agent activity enabled.");
517 const linked = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));
518 if (linked) {
519 return;
520 }
521​
522 // Publishing needs the relay to know this environment belongs to you.
523 // Establish a tunnel-free publish-only link automatically so signing in
524 // is all it takes — the mobile client can still reach the environment
525 // out of band without V12 Connect.
526 if (!(yield* tokens.hasCredential)) {
527 yield* Console.log(
528 "Run `v12 connect login` first so this environment can be authorized to publish.",
529 );
530 return;
531 }
532 // A link may already be desired (e.g. `v12 connect link` before the
533 // server's first start). Never downgrade it: a desired managed link
534 // also covers publishing, so only request a publish-only link when no
535 // link is pending at all.
536 if (yield* CliState.readCliDesiredCloudLink) {
537 yield* Console.log(
538 "A V12 Connect link is already pending. Start V12 to finish provisioning it; publishing starts once it links.",
539 );
540 return;
541 }
542 yield* CliState.setCliDesiredCloudLink(true, "publish_only");
543 yield* Console.log(
544 "Restart V12 to finish authorizing this environment to publish (no managed tunnel is created).",
545 );
546 }),
547 ),
548 ),
549);
550​
551const connectUnlinkCommand = Command.make("unlink", {
552 ...projectLocationFlags,
553}).pipe(
554 Command.withDescription("Disable V12 Connect while retaining the stored authorization."),
555 Command.withHandler((flags) =>
556 runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),
557 ),
558);
559​
560const connectLogoutCommand = Command.make("logout", {
561 ...projectLocationFlags,
562}).pipe(
563 Command.withDescription("Disable V12 Connect and clear the stored CLI authorization."),
564 Command.withHandler((flags) =>
565 runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),
566 ),
567);
568​
569export const connectCommand = Command.make("connect").pipe(
570 Command.withDescription("Manage headless V12 Connect access."),
571 Command.withSubcommands([
572 connectLoginCommand,
573 connectLinkCommand,
574 connectPublishCommand,
575 connectStatusCommand,
576 connectUnlinkCommand,
577 connectLogoutCommand,
578 ]),
579);