The best way to control Claude Code, Codex and more from any computer or phone

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