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

onboarding.ts

325 lines12.1 KB

1import type { DesktopSshEnvironmentTarget, EnvironmentId } from "@t3tools/contracts";
2import { resolveRemotePairingTarget } from "@t3tools/shared/remote";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as SubscriptionRef from "effect/SubscriptionRef";
9import * as HttpClient from "effect/http/HttpClient";
10​
11import { bootstrapRemoteBearerSession } from "../authorization/remote.ts";
12import { deriveWsBaseUrl, normalizeHttpBaseUrl } from "../environment/endpoint.ts";
13import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
14import * as ClientCapabilities from "../platform/capabilities.ts";
15import {
16 BearerConnectionCredential,
17 BearerConnectionProfile,
18 BearerConnectionRegistration,
19 type ConnectionCatalogEntry,
20 type ConnectionCredential,
21 SshConnectionProfile,
22 SshConnectionRegistration,
23} from "./catalog.ts";
24import * as ConnectionCredentialStore from "./credentialStore.ts";
25import { mapRemoteEnvironmentError } from "./errors.ts";
26import {
27 BearerConnectionTarget,
28 ConnectionBlockedError,
29 SshConnectionTarget,
30 type ConnectionAttemptError,
31} from "./model.ts";
32import * as Persistence from "../platform/persistence.ts";
33import * as EnvironmentRegistry from "./registry.ts";
34import { orchestrationProtocolCompatibilityError } from "./compatibility.ts";
35import { connectionRoutes, routeEntry, sshTargetKey } from "./routes.ts";
36​
37export interface PairingConnectionInput {
38 readonly pairingUrl?: string;
39 readonly host?: string;
40 readonly pairingCode?: string;
41 /**
42 * Set when adding a route to a saved machine: the pairing must reach this
43 * environment, or nothing is saved.
44 */
45 readonly expectedEnvironmentId?: EnvironmentId;
47​
48export interface SshConnectionInput {
49 readonly target: DesktopSshEnvironmentTarget;
50 readonly label?: string;
51 /** Set when adding a route to a saved machine; see `PairingConnectionInput`. */
52 readonly expectedEnvironmentId?: EnvironmentId;
54​
55export interface BearerConnectionUpdateInput {
56 readonly environmentId: EnvironmentId;
57 readonly label: string;
58 readonly httpBaseUrl: string;
60​
61export class ConnectionOnboarding extends Context.Service<
62 ConnectionOnboarding,
63 {
64 readonly registerPairing: (
65 input: PairingConnectionInput,
66 ) => Effect.Effect<
67 EnvironmentId,
68 ConnectionAttemptError | Persistence.ConnectionPersistenceError
69 >;
70 readonly registerSsh: (
71 input: SshConnectionInput,
72 ) => Effect.Effect<
73 EnvironmentId,
74 ConnectionAttemptError | Persistence.ConnectionPersistenceError
75 >;
76 readonly updateBearer: (
77 input: BearerConnectionUpdateInput,
78 ) => Effect.Effect<void, ConnectionAttemptError | Persistence.ConnectionPersistenceError>;
79 }
80>()("@t3tools/client-runtime/connection/onboarding/ConnectionOnboarding") {}
81​
82const resolvePairingTarget = Effect.fn("clientRuntime.connection.onboarding.resolvePairingTarget")(
83 function* (input: PairingConnectionInput) {
84 return yield* Effect.try({
85 try: () => resolveRemotePairingTarget(input),
86 catch: (cause) =>
87 new ConnectionBlockedError({
88 reason: "configuration",
89 detail: cause instanceof Error ? cause.message : "The pairing details are invalid.",
90 }),
91 });
92 },
93);
94​
95/**
96 * One bearer route per address, so pairing over Tailscale adds a route next
97 * to the LAN one instead of replacing it. Pairing the same address again
98 * reuses the id and replaces that route.
99 */
100function bearerConnectionId(environmentId: EnvironmentId, httpBaseUrl: string): string {
101 return `bearer:${environmentId}:${new URL(httpBaseUrl).origin}`;
103​
104function differentMachineError(label: string) {
105 return new ConnectionBlockedError({
106 reason: "configuration",
107 detail: `That address reaches ${label}, a different machine. Add it as its own environment instead.`,
108 });
110​
111export const preparePairingRegistration = Effect.fn(
112 "clientRuntime.connection.onboarding.preparePairingRegistration",
113)(function* (input: PairingConnectionInput) {
114 const target = yield* resolvePairingTarget(input);
115 const presentation = yield* ClientCapabilities.ClientPresentation;
116 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
117 httpBaseUrl: target.httpBaseUrl,
118 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
119 // Checked before redeeming the one-time code, so a wrong link is not spent.
120 if (
121 input.expectedEnvironmentId !== undefined &&
122 descriptor.environmentId !== input.expectedEnvironmentId
123 ) {
124 return yield* differentMachineError(descriptor.label);
125 }
126 const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);
127 // An outdated server is still saved so it can be updated from this client.
128 if (compatibilityError !== null && compatibilityError.serverUpdateRequired !== true) {
129 return yield* compatibilityError;
130 }
131 const access = yield* bootstrapRemoteBearerSession({
132 httpBaseUrl: target.httpBaseUrl,
133 credential: target.credential,
134 clientMetadata: presentation.metadata,
135 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
136 const connectionId = bearerConnectionId(descriptor.environmentId, target.httpBaseUrl);
137​
138 return new BearerConnectionRegistration({
139 target: new BearerConnectionTarget({
140 environmentId: descriptor.environmentId,
141 label: descriptor.label,
142 connectionId,
143 }),
144 profile: new BearerConnectionProfile({
145 connectionId,
146 environmentId: descriptor.environmentId,
147 label: descriptor.label,
148 httpBaseUrl: target.httpBaseUrl,
149 wsBaseUrl: target.wsBaseUrl,
150 }),
151 credential: new BearerConnectionCredential({
152 token: access.access_token,
153 }),
154 });
155});
156​
157const registerPairingConnection = Effect.fn(
158 "clientRuntime.connection.onboarding.registerPairingConnection",
159)(function* (input: PairingConnectionInput) {
160 const registration = yield* preparePairingRegistration(input);
161 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
162 yield* registry.register(registration);
163 return registration.target.environmentId;
164});
165​
166const isBearerCredential = Schema.is(BearerConnectionCredential);
167const isBearerProfile = Schema.is(BearerConnectionProfile);
168​
169const updateBearerConnection = Effect.fn(
170 "clientRuntime.connection.onboarding.updateBearerConnection",
171)(function* (input: BearerConnectionUpdateInput) {
172 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
173 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
174 const saved = (yield* SubscriptionRef.get(registry.entries)).get(input.environmentId);
175 // Editing changes the environment's first direct route; others stay as saved.
176 const route =
177 saved === undefined
178 ? undefined
179 : connectionRoutes(saved).find(
180 (candidate) => candidate.target._tag === "BearerConnectionTarget",
181 );
182 const entry = saved === undefined || route === undefined ? saved : routeEntry(saved, route);
183 const credential =
184 entry?.target._tag === "BearerConnectionTarget"
185 ? yield* credentials.get(entry.target.connectionId)
186 : Option.none();
187 const registration = yield* prepareBearerConnectionUpdate({
188 input,
189 entry: Option.fromUndefinedOr(entry),
190 credential,
191 });
192 yield* registry.register(registration);
193});
194​
195export const prepareBearerConnectionUpdate = Effect.fn(
196 "clientRuntime.connection.onboarding.prepareBearerConnectionUpdate",
197)(function* (options: {
198 readonly input: BearerConnectionUpdateInput;
199 readonly entry: Option.Option<ConnectionCatalogEntry>;
200 readonly credential: Option.Option<ConnectionCredential>;
201}) {
202 const entry = Option.getOrNull(options.entry);
203 if (
204 entry === undefined ||
205 entry === null ||
206 entry.target._tag !== "BearerConnectionTarget" ||
207 Option.isNone(entry.profile) ||
208 !isBearerProfile(entry.profile.value)
209 ) {
210 return yield* new ConnectionBlockedError({
211 reason: "configuration",
212 detail: "Only saved bearer environments can be edited.",
213 });
214 }
215​
216 const credential = options.credential;
217 if (Option.isNone(credential) || !isBearerCredential(credential.value)) {
218 return yield* new ConnectionBlockedError({
219 reason: "authentication",
220 detail: "The saved bearer credential is unavailable.",
221 });
222 }
223​
224 const label = options.input.label.trim();
225 if (label === "") {
226 return yield* new ConnectionBlockedError({
227 reason: "configuration",
228 detail: "Environment label cannot be empty.",
229 });
230 }
231 const httpBaseUrl = yield* Effect.try({
232 try: () => normalizeHttpBaseUrl(options.input.httpBaseUrl),
233 catch: (cause) =>
234 new ConnectionBlockedError({
235 reason: "configuration",
236 detail: cause instanceof Error ? cause.message : "The environment URL is invalid.",
237 }),
238 });
239 const connectionId = entry.target.connectionId;
240 return new BearerConnectionRegistration({
241 target: new BearerConnectionTarget({
242 environmentId: options.input.environmentId,
243 label,
244 connectionId,
245 }),
246 profile: new BearerConnectionProfile({
247 connectionId,
248 environmentId: options.input.environmentId,
249 label,
250 httpBaseUrl,
251 wsBaseUrl: deriveWsBaseUrl(httpBaseUrl),
252 }),
253 credential: credential.value,
254 });
255});
256​
257export const prepareSshRegistration = Effect.fn(
258 "clientRuntime.connection.onboarding.prepareSshRegistration",
259)(function* (input: SshConnectionInput) {
260 const gateway = yield* ClientCapabilities.SshEnvironmentGateway;
261 const provisioned = yield* gateway.provision(input.target, input.expectedEnvironmentId);
262 // One id per SSH target, so a second host or alias for the same machine
263 // adds a route instead of replacing the first.
264 const connectionId = `ssh:${provisioned.environmentId}:${sshTargetKey(provisioned.bootstrap.target)}`;
265 const label = input.label?.trim() || provisioned.label || provisioned.bootstrap.target.alias;
266​
267 return new SshConnectionRegistration({
268 target: new SshConnectionTarget({
269 environmentId: provisioned.environmentId,
270 label,
271 connectionId,
272 }),
273 profile: new SshConnectionProfile({
274 connectionId,
275 environmentId: provisioned.environmentId,
276 label,
277 target: provisioned.bootstrap.target,
278 }),
279 });
280});
281​
282const registerSshConnection = Effect.fn(
283 "clientRuntime.connection.onboarding.registerSshConnection",
284)(function* (input: SshConnectionInput) {
285 const registration = yield* prepareSshRegistration(input);
286 if (
287 input.expectedEnvironmentId !== undefined &&
288 registration.target.environmentId !== input.expectedEnvironmentId
289 ) {
290 return yield* differentMachineError(registration.target.label);
291 }
292 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
293 yield* registry.register(registration);
294 return registration.target.environmentId;
295});
296​
297/** @public Service construction is part of the canonical Effect module API. */
298export const make = Effect.gen(function* () {
299 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
300 const presentation = yield* ClientCapabilities.ClientPresentation;
301 const httpClient = yield* HttpClient.HttpClient;
302 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
303 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
304​
305 return ConnectionOnboarding.of({
306 registerPairing: (input) =>
307 registerPairingConnection(input).pipe(
308 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
309 Effect.provideService(ClientCapabilities.ClientPresentation, presentation),
310 Effect.provideService(HttpClient.HttpClient, httpClient),
311 ),
312 registerSsh: (input) =>
313 registerSshConnection(input).pipe(
314 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
315 Effect.provideService(ClientCapabilities.SshEnvironmentGateway, ssh),
316 ),
317 updateBearer: (input) =>
318 updateBearerConnection(input).pipe(
319 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
320 Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials),
321 ),
322 });
323});
324​
325export const layer = Layer.effect(ConnectionOnboarding, make);