Open History to see the last commit
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;
46}
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;
53}
54
55export interface BearerConnectionUpdateInput {
56 readonly environmentId: EnvironmentId;
57 readonly label: string;
58 readonly httpBaseUrl: string;
59}
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}`;
102}
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 });
109}
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 scopes: presentation.scopes,
135 clientMetadata: presentation.metadata,
136 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
137 const connectionId = bearerConnectionId(descriptor.environmentId, target.httpBaseUrl);
138
139 return new BearerConnectionRegistration({
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 credential: new BearerConnectionCredential({
153 token: access.access_token,
154 }),
155 });
156});
157
158const registerPairingConnection = Effect.fn(
159 "clientRuntime.connection.onboarding.registerPairingConnection",
160)(function* (input: PairingConnectionInput) {
161 const registration = yield* preparePairingRegistration(input);
162 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
163 yield* registry.register(registration);
164 return registration.target.environmentId;
165});
166
167const isBearerCredential = Schema.is(BearerConnectionCredential);
168const isBearerProfile = Schema.is(BearerConnectionProfile);
169
170const updateBearerConnection = Effect.fn(
171 "clientRuntime.connection.onboarding.updateBearerConnection",
172)(function* (input: BearerConnectionUpdateInput) {
173 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
174 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
175 const saved = (yield* SubscriptionRef.get(registry.entries)).get(input.environmentId);
176 // Editing changes the environment's first direct route; others stay as saved.
177 const route =
178 saved === undefined
179 ? undefined
180 : connectionRoutes(saved).find(
181 (candidate) => candidate.target._tag === "BearerConnectionTarget",
182 );
183 const entry = saved === undefined || route === undefined ? saved : routeEntry(saved, route);
184 const credential =
185 entry?.target._tag === "BearerConnectionTarget"
186 ? yield* credentials.get(entry.target.connectionId)
187 : Option.none();
188 const registration = yield* prepareBearerConnectionUpdate({
189 input,
190 entry: Option.fromUndefinedOr(entry),
191 credential,
192 });
193 yield* registry.register(registration);
194});
195
196export const prepareBearerConnectionUpdate = Effect.fn(
197 "clientRuntime.connection.onboarding.prepareBearerConnectionUpdate",
198)(function* (options: {
199 readonly input: BearerConnectionUpdateInput;
200 readonly entry: Option.Option<ConnectionCatalogEntry>;
201 readonly credential: Option.Option<ConnectionCredential>;
202}) {
203 const entry = Option.getOrNull(options.entry);
204 if (
205 entry === undefined ||
206 entry === null ||
207 entry.target._tag !== "BearerConnectionTarget" ||
208 Option.isNone(entry.profile) ||
209 !isBearerProfile(entry.profile.value)
210 ) {
211 return yield* new ConnectionBlockedError({
212 reason: "configuration",
213 detail: "Only saved bearer environments can be edited.",
214 });
215 }
216
217 const credential = options.credential;
218 if (Option.isNone(credential) || !isBearerCredential(credential.value)) {
219 return yield* new ConnectionBlockedError({
220 reason: "authentication",
221 detail: "The saved bearer credential is unavailable.",
222 });
223 }
224
225 const label = options.input.label.trim();
226 if (label === "") {
227 return yield* new ConnectionBlockedError({
228 reason: "configuration",
229 detail: "Environment label cannot be empty.",
230 });
231 }
232 const httpBaseUrl = yield* Effect.try({
233 try: () => normalizeHttpBaseUrl(options.input.httpBaseUrl),
234 catch: (cause) =>
235 new ConnectionBlockedError({
236 reason: "configuration",
237 detail: cause instanceof Error ? cause.message : "The environment URL is invalid.",
238 }),
239 });
240 const connectionId = entry.target.connectionId;
241 return new BearerConnectionRegistration({
242 target: new BearerConnectionTarget({
243 environmentId: options.input.environmentId,
244 label,
245 connectionId,
246 }),
247 profile: new BearerConnectionProfile({
248 connectionId,
249 environmentId: options.input.environmentId,
250 label,
251 httpBaseUrl,
252 wsBaseUrl: deriveWsBaseUrl(httpBaseUrl),
253 }),
254 credential: credential.value,
255 });
256});
257
258export const prepareSshRegistration = Effect.fn(
259 "clientRuntime.connection.onboarding.prepareSshRegistration",
260)(function* (input: SshConnectionInput) {
261 const gateway = yield* ClientCapabilities.SshEnvironmentGateway;
262 const provisioned = yield* gateway.provision(input.target, input.expectedEnvironmentId);
263 // One id per SSH target, so a second host or alias for the same machine
264 // adds a route instead of replacing the first.
265 const connectionId = `ssh:${provisioned.environmentId}:${sshTargetKey(provisioned.bootstrap.target)}`;
266 const label = input.label?.trim() || provisioned.label || provisioned.bootstrap.target.alias;
267
268 return new SshConnectionRegistration({
269 target: new SshConnectionTarget({
270 environmentId: provisioned.environmentId,
271 label,
272 connectionId,
273 }),
274 profile: new SshConnectionProfile({
275 connectionId,
276 environmentId: provisioned.environmentId,
277 label,
278 target: provisioned.bootstrap.target,
279 }),
280 });
281});
282
283const registerSshConnection = Effect.fn(
284 "clientRuntime.connection.onboarding.registerSshConnection",
285)(function* (input: SshConnectionInput) {
286 const registration = yield* prepareSshRegistration(input);
287 if (
288 input.expectedEnvironmentId !== undefined &&
289 registration.target.environmentId !== input.expectedEnvironmentId
290 ) {
291 return yield* differentMachineError(registration.target.label);
292 }
293 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
294 yield* registry.register(registration);
295 return registration.target.environmentId;
296});
297
298/** @public Service construction is part of the canonical Effect module API. */
299export const make = Effect.gen(function* () {
300 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
301 const presentation = yield* ClientCapabilities.ClientPresentation;
302 const httpClient = yield* HttpClient.HttpClient;
303 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
304 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
305
306 return ConnectionOnboarding.of({
307 registerPairing: (input) =>
308 registerPairingConnection(input).pipe(
309 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
310 Effect.provideService(ClientCapabilities.ClientPresentation, presentation),
311 Effect.provideService(HttpClient.HttpClient, httpClient),
312 ),
313 registerSsh: (input) =>
314 registerSshConnection(input).pipe(
315 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
316 Effect.provideService(ClientCapabilities.SshEnvironmentGateway, ssh),
317 ),
318 updateBearer: (input) =>
319 updateBearerConnection(input).pipe(
320 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
321 Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials),
322 ),
323 });
324});
325
326export const layer = Layer.effect(ConnectionOnboarding, make);