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

onboarding.ts

450 lines16.7 KB

1import { msg } from "gt-i18n";
2import { detailFromError, translatableDetail } from "../errors/translatable.ts";
3import type { DesktopSshEnvironmentTarget, EnvironmentId } from "@t3tools/contracts";
4import { resolveRemotePairingTarget } from "@t3tools/shared/remote";
5import * as Clock from "effect/Clock";
6import * as Context from "effect/Context";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import * as SubscriptionRef from "effect/SubscriptionRef";
13import * as HttpClient from "effect/http/HttpClient";
14​
15import {
16 bootstrapRemoteBearerSession,
17 exchangeRemoteDpopAccessToken,
18} from "../authorization/remote.ts";
19import {
20 deriveWsBaseUrl,
21 environmentEndpointUrl,
22 normalizeHttpBaseUrl,
23} from "../environment/endpoint.ts";
24import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
25import * as ClientCapabilities from "../platform/capabilities.ts";
26import * as ManagedRelay from "../relay/managedRelay.ts";
27import {
28 BearerConnectionCredential,
29 BearerConnectionProfile,
30 BearerConnectionRegistration,
31 type ConnectionCatalogEntry,
32 type ConnectionCredential,
33 DpopConnectionCredential,
34 SshConnectionProfile,
35 SshConnectionRegistration,
36} from "./catalog.ts";
37import * as ConnectionCredentialStore from "./credentialStore.ts";
38import { mapRemoteDpopEnvironmentError, mapRemoteEnvironmentError } from "./errors.ts";
39import {
40 BearerConnectionTarget,
41 ConnectionBlockedError,
42 SshConnectionTarget,
43 type ConnectionAttemptError,
44} from "./model.ts";
45import * as Persistence from "../platform/persistence.ts";
46import * as EnvironmentRegistry from "./registry.ts";
47import { orchestrationProtocolCompatibilityError } from "./compatibility.ts";
48import { connectionRoutes, routeEntry, sshTargetKey } from "./routes.ts";
49​
50export interface PairingConnectionInput {
51 readonly pairingUrl?: string;
52 readonly host?: string;
53 readonly pairingCode?: string;
54 readonly expectedEnvironmentId?: EnvironmentId;
56​
57export interface SshConnectionInput {
58 readonly target: DesktopSshEnvironmentTarget;
59 readonly label?: string;
60 readonly expectedEnvironmentId?: EnvironmentId;
62​
63export interface BearerConnectionUpdateInput {
64 readonly environmentId: EnvironmentId;
65 readonly label: string;
66 readonly httpBaseUrl: string;
68​
69export class ConnectionOnboarding extends Context.Service<
70 ConnectionOnboarding,
71 {
72 readonly registerPairing: (
73 input: PairingConnectionInput,
74 ) => Effect.Effect<
75 EnvironmentId,
76 ConnectionAttemptError | Persistence.ConnectionPersistenceError
77 >;
78 readonly registerSsh: (
79 input: SshConnectionInput,
80 ) => Effect.Effect<
81 EnvironmentId,
82 ConnectionAttemptError | Persistence.ConnectionPersistenceError
83 >;
84 readonly updateBearer: (
85 input: BearerConnectionUpdateInput,
86 ) => Effect.Effect<void, ConnectionAttemptError | Persistence.ConnectionPersistenceError>;
87 /** Whether `host` answers this device as `environmentId`. Nothing is sent but the question. */
88 readonly reaches: (input: {
89 readonly host: string;
90 readonly environmentId: EnvironmentId;
91 }) => Effect.Effect<boolean>;
92 }
93>()("@t3tools/client-runtime/connection/onboarding/ConnectionOnboarding") {}
94​
95const resolvePairingTarget = Effect.fn("clientRuntime.connection.onboarding.resolvePairingTarget")(
96 function* (input: PairingConnectionInput) {
97 return yield* Effect.try({
98 try: () => resolveRemotePairingTarget(input),
99 catch: (cause) =>
100 new ConnectionBlockedError({
101 reason: "configuration",
102 ...(cause instanceof Error
103 ? detailFromError(cause)
104 : translatableDetail(msg("The pairing details are invalid."))),
105 }),
106 });
107 },
108);
109​
110function bearerConnectionId(environmentId: EnvironmentId, httpBaseUrl: string): string {
111 return `bearer:${environmentId}:${new URL(httpBaseUrl).origin}`;
113​
114function differentMachineError(label: string) {
115 return new ConnectionBlockedError({
116 reason: "configuration",
117 ...translatableDetail(
118 msg`That address reaches ${{ host: label }}, a different machine. Add it as its own environment instead.`,
119 ),
120 });
122​
123export const preparePairingRegistration = Effect.fn(
124 "clientRuntime.connection.onboarding.preparePairingRegistration",
125)(function* (input: PairingConnectionInput) {
126 const target = yield* resolvePairingTarget(input);
127 const presentation = yield* ClientCapabilities.ClientPresentation;
128 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
129 httpBaseUrl: target.httpBaseUrl,
130 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
131 // Checked before redeeming the one-time code, so a wrong link is not spent.
132 if (
133 input.expectedEnvironmentId !== undefined &&
134 descriptor.environmentId !== input.expectedEnvironmentId
135 ) {
136 return yield* differentMachineError(descriptor.label);
137 }
138 const connectionId = bearerConnectionId(descriptor.environmentId, target.httpBaseUrl);
139 const route = {
140 target: new BearerConnectionTarget({
141 environmentId: descriptor.environmentId,
142 label: descriptor.label,
143 connectionId,
144 }),
145 profile: new BearerConnectionProfile({
146 connectionId,
147 environmentId: descriptor.environmentId,
148 label: descriptor.label,
149 httpBaseUrl: target.httpBaseUrl,
150 wsBaseUrl: target.wsBaseUrl,
151 }),
152 };
153 // The registry checks again under its lease; this early check keeps a refused code unspent.
154 if (input.expectedEnvironmentId === undefined) {
155 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
156 yield* registry.assertKnownAddress({ ...route, profile: Option.some(route.profile) });
157 }
158 const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);
159 // An outdated server is still saved so it can be updated from this client.
160 if (compatibilityError !== null && compatibilityError.serverUpdateRequired !== true) {
161 return yield* compatibilityError;
162 }
163 // A key-bound session renews itself, but only on a host that can renew it. The proof is made
164 // before the one-time code is sent, so a device that cannot sign keeps the code for bearer.
165 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
166 const dpopProof =
167 descriptor.capabilities.accessTokenRenewal === true && Option.isSome(signer)
168 ? yield* signer.value
169 .createProof({
170 method: "POST",
171 url: environmentEndpointUrl(target.httpBaseUrl, "/oauth/token"),
172 })
173 .pipe(Effect.option)
174 : Option.none<string>();
175 if (Option.isSome(dpopProof)) {
176 const access = yield* exchangeRemoteDpopAccessToken({
177 httpBaseUrl: target.httpBaseUrl,
178 credential: target.credential,
179 clientMetadata: presentation.metadata,
180 dpopProof: dpopProof.value,
181 }).pipe(
182 // A rejected pairing code carries no DPoP reason; only a reported DPoP failure gets its hint.
183 Effect.mapError((error) =>
184 error._tag === "EnvironmentAuthInvalidError" && error.dpopFailureReason !== undefined
185 ? mapRemoteDpopEnvironmentError(error, "direct")
186 : mapRemoteEnvironmentError(error),
187 ),
188 );
189 return new BearerConnectionRegistration({
190 ...route,
191 credential: new DpopConnectionCredential({
192 accessToken: access.access_token,
193 expiresAtEpochMs: (yield* Clock.currentTimeMillis) + access.expires_in * 1_000,
194 }),
195 });
196 }
197 const access = yield* bootstrapRemoteBearerSession({
198 httpBaseUrl: target.httpBaseUrl,
199 credential: target.credential,
200 clientMetadata: presentation.metadata,
201 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
202​
203 return new BearerConnectionRegistration({
204 ...route,
205 credential: new BearerConnectionCredential({
206 token: access.access_token,
207 }),
208 });
209});
210​
211const registerPairingConnection = Effect.fn(
212 "clientRuntime.connection.onboarding.registerPairingConnection",
213)(function* (input: PairingConnectionInput) {
214 const registration = yield* preparePairingRegistration(input);
215 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
216 const knownAddressOnly = input.expectedEnvironmentId === undefined;
217 if (!(yield* registry.register(registration, { knownAddressOnly }))) {
218 return registration.target.environmentId;
219 }
220 yield* registry.setCompatibility(registration.target.environmentId, null);
221 yield* registry
222 .setEnabled(registration.target.environmentId, true)
223 .pipe(Effect.catchTags({ EnvironmentNotRegisteredError: () => Effect.void }));
224 return registration.target.environmentId;
225});
226​
227const REACHABILITY_TIMEOUT_MS = 6_000;
228​
229const reachesEnvironment = Effect.fn("clientRuntime.connection.onboarding.reachesEnvironment")(
230 function* (input: { readonly host: string; readonly environmentId: EnvironmentId }) {
231 const httpBaseUrl = yield* Effect.try({
232 try: () => normalizeHttpBaseUrl(input.host),
233 catch: () =>
234 new ConnectionBlockedError({
235 reason: "configuration",
236 ...translatableDetail(msg("The environment URL is invalid.")),
237 }),
238 });
239 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
240 httpBaseUrl,
241 timeoutMs: REACHABILITY_TIMEOUT_MS,
242 });
243 return descriptor.environmentId === input.environmentId;
244 },
245 Effect.orElseSucceed(() => false),
246);
247​
248const isBearerProfile = Schema.is(BearerConnectionProfile);
249​
250const updateBearerConnection = Effect.fn(
251 "clientRuntime.connection.onboarding.updateBearerConnection",
252)(function* (input: BearerConnectionUpdateInput) {
253 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
254 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
255 const saved = (yield* SubscriptionRef.get(registry.entries)).get(input.environmentId);
256 const route =
257 saved === undefined
258 ? undefined
259 : connectionRoutes(saved).find(
260 (candidate) => candidate.target._tag === "BearerConnectionTarget",
261 );
262 const entry = saved === undefined || route === undefined ? saved : routeEntry(saved, route);
263 const credential =
264 entry?.target._tag === "BearerConnectionTarget"
265 ? yield* credentials.get(entry.target.connectionId)
266 : Option.none();
267 const registration = yield* prepareBearerConnectionUpdate({
268 input,
269 entry: Option.fromUndefinedOr(entry),
270 credential,
271 });
272 yield* registry.register(registration, { useRegistrationLabel: true });
273});
274​
275export const prepareBearerConnectionUpdate = Effect.fn(
276 "clientRuntime.connection.onboarding.prepareBearerConnectionUpdate",
277)(function* (options: {
278 readonly input: BearerConnectionUpdateInput;
279 readonly entry: Option.Option<ConnectionCatalogEntry>;
280 readonly credential: Option.Option<ConnectionCredential>;
281}) {
282 const entry = Option.getOrNull(options.entry);
283 if (
284 entry === undefined ||
285 entry === null ||
286 entry.target._tag !== "BearerConnectionTarget" ||
287 Option.isNone(entry.profile) ||
288 !isBearerProfile(entry.profile.value)
289 ) {
290 return yield* new ConnectionBlockedError({
291 reason: "configuration",
292 ...translatableDetail(msg("Only saved bearer environments can be edited.")),
293 });
294 }
295​
296 const credential = options.credential;
297 if (Option.isNone(credential)) {
298 return yield* new ConnectionBlockedError({
299 reason: "authentication",
300 ...translatableDetail(msg("The saved bearer credential is unavailable.")),
301 });
302 }
303​
304 const label = options.input.label.trim();
305 if (label === "") {
306 return yield* new ConnectionBlockedError({
307 reason: "configuration",
308 ...translatableDetail(msg("Environment label cannot be empty.")),
309 });
310 }
311 const httpBaseUrl = yield* Effect.try({
312 try: () => normalizeHttpBaseUrl(options.input.httpBaseUrl),
313 catch: (cause) =>
314 new ConnectionBlockedError({
315 reason: "configuration",
316 ...(cause instanceof Error
317 ? detailFromError(cause)
318 : translatableDetail(msg("The environment URL is invalid."))),
319 }),
320 });
321 const connectionId = entry.target.connectionId;
322 return new BearerConnectionRegistration({
323 target: new BearerConnectionTarget({
324 environmentId: options.input.environmentId,
325 label,
326 connectionId,
327 }),
328 profile: new BearerConnectionProfile({
329 connectionId,
330 environmentId: options.input.environmentId,
331 label,
332 httpBaseUrl,
333 wsBaseUrl: deriveWsBaseUrl(httpBaseUrl),
334 }),
335 credential: credential.value,
336 });
337});
338​
339const provisionSshRegistration = Effect.fn(
340 "clientRuntime.connection.onboarding.prepareSshRegistration",
341)(function* (input: SshConnectionInput) {
342 const gateway = yield* ClientCapabilities.SshEnvironmentGateway;
343 const provisioned = yield* gateway.provision(input.target, input.expectedEnvironmentId);
344 const connectionId = `ssh:${provisioned.environmentId}:${sshTargetKey(provisioned.bootstrap.target)}`;
345 const label = input.label?.trim() || provisioned.label || provisioned.bootstrap.target.alias;
346​
347 const registration = new SshConnectionRegistration({
348 target: new SshConnectionTarget({
349 environmentId: provisioned.environmentId,
350 label,
351 connectionId,
352 }),
353 profile: new SshConnectionProfile({
354 connectionId,
355 environmentId: provisioned.environmentId,
356 label,
357 target: provisioned.bootstrap.target,
358 }),
359 credential: new BearerConnectionCredential({ token: provisioned.bearerToken }),
360 });
361 return {
362 registration,
363 finishTunnelClaim: provisioned.finishTunnelClaim,
364 sshTunnelClaim: provisioned.bootstrap.tunnelClaim,
365 };
366});
367​
368export const prepareSshRegistration = (input: SshConnectionInput) =>
369 provisionSshRegistration(input).pipe(Effect.map(({ registration }) => registration));
370​
371const registerSshConnection = Effect.fn(
372 "clientRuntime.connection.onboarding.registerSshConnection",
373)(function* (input: SshConnectionInput) {
374 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
375 return yield* Effect.uninterruptibleMask((restore) =>
376 Effect.gen(function* () {
377 const { registration, finishTunnelClaim, sshTunnelClaim } = yield* restore(
378 provisionSshRegistration(input),
379 );
380 const { environmentId, label } = registration.target;
381 // Once the write starts, its outcome must decide whether the tunnel is retained.
382 const registered = yield* Effect.gen(function* () {
383 if (
384 input.expectedEnvironmentId !== undefined &&
385 environmentId !== input.expectedEnvironmentId
386 ) {
387 return yield* differentMachineError(label);
388 }
389 return yield* registry.register(registration, {
390 knownAddressOnly: input.expectedEnvironmentId === undefined,
391 ...(sshTunnelClaim === undefined ? {} : { sshTunnelClaim }),
392 });
393 }).pipe(
394 Effect.onExit(
395 (exit) => finishTunnelClaim?.(Exit.isSuccess(exit) && exit.value) ?? Effect.void,
396 ),
397 );
398 if (registered) {
399 yield* registry.setCompatibility(environmentId, null);
400 yield* registry
401 .setEnabled(environmentId, true)
402 .pipe(Effect.catchTags({ EnvironmentNotRegisteredError: () => Effect.void }));
403 }
404 return environmentId;
405 }),
406 );
407});
408​
409/** @public */
410export const make = Effect.gen(function* () {
411 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
412 const presentation = yield* ClientCapabilities.ClientPresentation;
413 const httpClient = yield* HttpClient.HttpClient;
414 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
415 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
416​
417 // Provisioning retains the delegated onboarding operation spans.
418 return ConnectionOnboarding.of({
419 registerPairing: Effect.fnUntraced(
420 function* (input) {
421 return yield* registerPairingConnection(input);
422 },
423 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
424 Effect.provideService(ClientCapabilities.ClientPresentation, presentation),
425 Effect.provideService(HttpClient.HttpClient, httpClient),
426 ),
427 registerSsh: Effect.fnUntraced(
428 function* (input) {
429 return yield* registerSshConnection(input);
430 },
431 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
432 Effect.provideService(ClientCapabilities.SshEnvironmentGateway, ssh),
433 ),
434 updateBearer: Effect.fnUntraced(
435 function* (input) {
436 return yield* updateBearerConnection(input);
437 },
438 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
439 Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials),
440 ),
441 reaches: Effect.fnUntraced(
442 function* (input) {
443 return yield* reachesEnvironment(input);
444 },
445 Effect.provideService(HttpClient.HttpClient, httpClient),
446 ),
447 });
448});
449​
450export const layer = Layer.effect(ConnectionOnboarding, make);