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