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

onboarding.ts

335 lines12.8 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 // A platform-managed environment belongs to the host, so pairing leaves it alone.
163 if (!(yield* registry.register(registration))) return registration.target.environmentId;
164 // Registering keeps a previous entry's switched-off flag and unsupported
165 // reason, which is right for label or URL edits. A pairing is an explicit
166 // request to connect, so the stale reason is cleared and the environment
167 // turned on after the pair succeeded; a server that is still incompatible,
168 // such as an outdated one awaiting an update, is flagged again on connect.
169 yield* registry.setCompatibility(registration.target.environmentId, null);
170 yield* registry
171 .setEnabled(registration.target.environmentId, true)
172 .pipe(Effect.catchTags({ EnvironmentNotRegisteredError: () => Effect.void }));
173 return registration.target.environmentId;
174});
175​
176const isBearerCredential = Schema.is(BearerConnectionCredential);
177const isBearerProfile = Schema.is(BearerConnectionProfile);
178​
179const updateBearerConnection = Effect.fn(
180 "clientRuntime.connection.onboarding.updateBearerConnection",
181)(function* (input: BearerConnectionUpdateInput) {
182 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
183 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
184 const saved = (yield* SubscriptionRef.get(registry.entries)).get(input.environmentId);
185 // Editing changes the environment's first direct route; others stay as saved.
186 const route =
187 saved === undefined
188 ? undefined
189 : connectionRoutes(saved).find(
190 (candidate) => candidate.target._tag === "BearerConnectionTarget",
191 );
192 const entry = saved === undefined || route === undefined ? saved : routeEntry(saved, route);
193 const credential =
194 entry?.target._tag === "BearerConnectionTarget"
195 ? yield* credentials.get(entry.target.connectionId)
196 : Option.none();
197 const registration = yield* prepareBearerConnectionUpdate({
198 input,
199 entry: Option.fromUndefinedOr(entry),
200 credential,
201 });
202 yield* registry.register(registration);
203});
204​
205export const prepareBearerConnectionUpdate = Effect.fn(
206 "clientRuntime.connection.onboarding.prepareBearerConnectionUpdate",
207)(function* (options: {
208 readonly input: BearerConnectionUpdateInput;
209 readonly entry: Option.Option<ConnectionCatalogEntry>;
210 readonly credential: Option.Option<ConnectionCredential>;
211}) {
212 const entry = Option.getOrNull(options.entry);
213 if (
214 entry === undefined ||
215 entry === null ||
216 entry.target._tag !== "BearerConnectionTarget" ||
217 Option.isNone(entry.profile) ||
218 !isBearerProfile(entry.profile.value)
219 ) {
220 return yield* new ConnectionBlockedError({
221 reason: "configuration",
222 detail: "Only saved bearer environments can be edited.",
223 });
224 }
225​
226 const credential = options.credential;
227 if (Option.isNone(credential) || !isBearerCredential(credential.value)) {
228 return yield* new ConnectionBlockedError({
229 reason: "authentication",
230 detail: "The saved bearer credential is unavailable.",
231 });
232 }
233​
234 const label = options.input.label.trim();
235 if (label === "") {
236 return yield* new ConnectionBlockedError({
237 reason: "configuration",
238 detail: "Environment label cannot be empty.",
239 });
240 }
241 const httpBaseUrl = yield* Effect.try({
242 try: () => normalizeHttpBaseUrl(options.input.httpBaseUrl),
243 catch: (cause) =>
244 new ConnectionBlockedError({
245 reason: "configuration",
246 detail: cause instanceof Error ? cause.message : "The environment URL is invalid.",
247 }),
248 });
249 const connectionId = entry.target.connectionId;
250 return new BearerConnectionRegistration({
251 target: new BearerConnectionTarget({
252 environmentId: options.input.environmentId,
253 label,
254 connectionId,
255 }),
256 profile: new BearerConnectionProfile({
257 connectionId,
258 environmentId: options.input.environmentId,
259 label,
260 httpBaseUrl,
261 wsBaseUrl: deriveWsBaseUrl(httpBaseUrl),
262 }),
263 credential: credential.value,
264 });
265});
266​
267export const prepareSshRegistration = Effect.fn(
268 "clientRuntime.connection.onboarding.prepareSshRegistration",
269)(function* (input: SshConnectionInput) {
270 const gateway = yield* ClientCapabilities.SshEnvironmentGateway;
271 const provisioned = yield* gateway.provision(input.target, input.expectedEnvironmentId);
272 // One id per SSH target, so a second host or alias for the same machine
273 // adds a route instead of replacing the first.
274 const connectionId = `ssh:${provisioned.environmentId}:${sshTargetKey(provisioned.bootstrap.target)}`;
275 const label = input.label?.trim() || provisioned.label || provisioned.bootstrap.target.alias;
276​
277 return new SshConnectionRegistration({
278 target: new SshConnectionTarget({
279 environmentId: provisioned.environmentId,
280 label,
281 connectionId,
282 }),
283 profile: new SshConnectionProfile({
284 connectionId,
285 environmentId: provisioned.environmentId,
286 label,
287 target: provisioned.bootstrap.target,
288 }),
289 });
290});
291​
292const registerSshConnection = Effect.fn(
293 "clientRuntime.connection.onboarding.registerSshConnection",
294)(function* (input: SshConnectionInput) {
295 const registration = yield* prepareSshRegistration(input);
296 if (
297 input.expectedEnvironmentId !== undefined &&
298 registration.target.environmentId !== input.expectedEnvironmentId
299 ) {
300 return yield* differentMachineError(registration.target.label);
301 }
302 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
303 yield* registry.register(registration);
304 return registration.target.environmentId;
305});
306​
307/** @public Service construction is part of the canonical Effect module API. */
308export const make = Effect.gen(function* () {
309 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
310 const presentation = yield* ClientCapabilities.ClientPresentation;
311 const httpClient = yield* HttpClient.HttpClient;
312 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
313 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
314​
315 return ConnectionOnboarding.of({
316 registerPairing: (input) =>
317 registerPairingConnection(input).pipe(
318 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
319 Effect.provideService(ClientCapabilities.ClientPresentation, presentation),
320 Effect.provideService(HttpClient.HttpClient, httpClient),
321 ),
322 registerSsh: (input) =>
323 registerSshConnection(input).pipe(
324 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
325 Effect.provideService(ClientCapabilities.SshEnvironmentGateway, ssh),
326 ),
327 updateBearer: (input) =>
328 updateBearerConnection(input).pipe(
329 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
330 Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials),
331 ),
332 });
333});
334​
335export const layer = Layer.effect(ConnectionOnboarding, make);