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

main
ts 347 lines 12.2 KB
Raw
1 import { msg } from "gt-i18n";
2 import { translatableDetail } from "../errors/translatable.ts";
3 import type {
4 AuthClientPresentationMetadata,
5 ExecutionEnvironmentDescriptor,
6 } from "@t3tools/contracts";
7 import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
8 import * as Context from "effect/Context";
9 import * as Effect from "effect/Effect";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Schema from "effect/Schema";
13 import * as HttpClient from "effect/http/HttpClient";
14
15 import {
16 appendClientConnectionParams,
17 type ClientOwnerParams,
18 readClientOwnerParams,
19 } from "../authorization/remote.ts";
20 import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
21 import * as ClientCapabilities from "../platform/capabilities.ts";
22 import {
23 BearerConnectionCredential,
24 BearerConnectionProfile,
25 type ConnectionCatalogEntry,
26 SshConnectionProfile,
27 } from "./catalog.ts";
28 import * as ConnectionCredentialStore from "./credentialStore.ts";
29 import {
30 credentialMissingError,
31 environmentMismatchError,
32 mapRemoteEnvironmentError,
33 profileMissingError,
34 } from "./errors.ts";
35 import {
36 PullRequestRoutingPermissions,
37 pullRequestRoutingConnectionKey,
38 } from "./pullRequestRoutingPermissions.ts";
39 import type {
40 BearerConnectionTarget,
41 ConnectionTarget,
42 PreparedConnection,
43 PrimaryConnectionTarget,
44 RelayConnectionTarget,
45 SshConnectionTarget,
46 } from "./model.ts";
47 import { ConnectionBlockedError, type ConnectionAttemptError } from "./model.ts";
48 import * as ConnectionProfileStore from "./profileStore.ts";
49 import {
50 appendOrchestrationProtocol,
51 orchestrationProtocolCompatibilityError,
52 } from "./compatibility.ts";
53 import { credentialConnectionId } from "./routes.ts";
54 import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
55
56 export class ConnectionResolver extends Context.Service<
57 ConnectionResolver,
58 {
59 readonly prepare: (
60 entry: ConnectionCatalogEntry,
61 ) => Effect.Effect<PreparedConnection, ConnectionAttemptError>;
62 /**
63 * Authorizes a socket without the orchestration protocol gate, for hosts
64 * too old to connect normally. Only update RPCs may run over it.
65 */
66 readonly prepareForUpdate: (entry: ConnectionCatalogEntry) => Effect.Effect<
67 {
68 readonly prepared: PreparedConnection;
69 readonly descriptor: ExecutionEnvironmentDescriptor;
70 },
71 ConnectionAttemptError
72 >;
73 }
74 >()("@t3tools/client-runtime/connection/resolver/ConnectionResolver") {}
75
76 const isBearerProfile = Schema.is(BearerConnectionProfile);
77 const isSshProfile = Schema.is(SshConnectionProfile);
78 const isBearerCredential = Schema.is(BearerConnectionCredential);
79
80 function primarySocketUrl(
81 target: PrimaryConnectionTarget,
82 clientMetadata: AuthClientPresentationMetadata | undefined,
83 owners: ClientOwnerParams,
84 ): string {
85 const url = new URL(target.wsBaseUrl);
86 if (url.pathname === "" || url.pathname === "/") {
87 url.pathname = "/ws";
88 }
89 appendClientConnectionParams(url, clientMetadata, "direct", owners);
90 return url.toString();
91 }
92
93 const makePrimaryBroker = Effect.fn("clientRuntime.connection.broker.makePrimary")(function* () {
94 const auth = yield* ClientCapabilities.PrimaryEnvironmentAuth;
95 const presentation = yield* ClientCapabilities.ClientPresentation;
96 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
97
98 return Effect.fn("clientRuntime.connection.broker.primary")(function* (
99 target: PrimaryConnectionTarget,
100 ) {
101 const bearerToken = yield* auth.bearerToken;
102 if (Option.isNone(bearerToken)) {
103 return {
104 environmentId: target.environmentId,
105 label: target.label,
106 httpBaseUrl: target.httpBaseUrl,
107 socketUrl: primarySocketUrl(target, presentation.metadata, yield* readClientOwnerParams),
108 httpAuthorization: null,
109 target,
110 } satisfies PreparedConnection;
111 }
112
113 const authorized = yield* remote.authorizeBearer({
114 expectedEnvironmentId: target.environmentId,
115 httpBaseUrl: target.httpBaseUrl,
116 wsBaseUrl: target.wsBaseUrl,
117 bearerToken: bearerToken.value,
118 connectionMethod: "direct",
119 });
120 return {
121 ...authorized,
122 target,
123 } satisfies PreparedConnection;
124 });
125 });
126
127 const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer")(function* () {
128 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
129 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
130
131 return Effect.fn("clientRuntime.connection.broker.bearer")(function* (
132 entry: ConnectionCatalogEntry & { readonly target: BearerConnectionTarget },
133 ) {
134 const target = entry.target;
135 const profile = yield* Effect.fromOption(entry.profile, () =>
136 profileMissingError(target.connectionId),
137 );
138 if (!isBearerProfile(profile)) {
139 return yield* new ConnectionBlockedError({
140 reason: "configuration",
141 ...translatableDetail(
142 msg("Connection profile {connectionId} is not a bearer connection.", {
143 connectionId: target.connectionId,
144 }),
145 ),
146 });
147 }
148 if (profile.environmentId !== target.environmentId) {
149 return yield* environmentMismatchError({
150 expected: target.environmentId,
151 actual: profile.environmentId,
152 });
153 }
154 if (profile.authorization === "t3-connect") {
155 const authorized = yield* remote.authorizeDpop({
156 expectedEnvironmentId: target.environmentId,
157 directEndpoint: { httpBaseUrl: profile.httpBaseUrl, wsBaseUrl: profile.wsBaseUrl },
158 });
159 return { ...authorized, target } satisfies PreparedConnection;
160 }
161 const credential = yield* credentials.get(credentialConnectionId(target.connectionId)).pipe(
162 Effect.flatMap(
163 Option.match({
164 onNone: () => Effect.fail(credentialMissingError(target.connectionId)),
165 onSome: Effect.succeed,
166 }),
167 ),
168 );
169 const authorized =
170 credential._tag === "DpopConnectionCredential"
171 ? yield* remote.authorizeDirectDpop({
172 expectedEnvironmentId: target.environmentId,
173 connectionId: credentialConnectionId(target.connectionId),
174 httpBaseUrl: profile.httpBaseUrl,
175 wsBaseUrl: profile.wsBaseUrl,
176 })
177 : yield* remote.authorizeBearer({
178 expectedEnvironmentId: target.environmentId,
179 httpBaseUrl: profile.httpBaseUrl,
180 wsBaseUrl: profile.wsBaseUrl,
181 bearerToken: credential.token,
182 connectionMethod: "direct",
183 });
184 return {
185 ...authorized,
186 target,
187 } satisfies PreparedConnection;
188 });
189 });
190
191 const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(function* () {
192 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
193
194 return Effect.fnUntraced(
195 function* (target: RelayConnectionTarget) {
196 const authorized = yield* remote.authorizeDpop({
197 expectedEnvironmentId: target.environmentId,
198 });
199 return {
200 ...authorized,
201 target,
202 } satisfies PreparedConnection;
203 },
204 Effect.withSpan("clientRuntime.connection.broker.relay"),
205 withRelayClientTracing,
206 );
207 });
208
209 const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(function* () {
210 const profiles = yield* ConnectionProfileStore.ConnectionProfileStore;
211 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
212 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
213 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
214
215 return Effect.fn("clientRuntime.connection.broker.ssh")(function* (
216 entry: ConnectionCatalogEntry & { readonly target: SshConnectionTarget },
217 ) {
218 const target = entry.target;
219 const profile = yield* Effect.fromOption(entry.profile, () =>
220 profileMissingError(target.connectionId),
221 );
222 if (!isSshProfile(profile)) {
223 return yield* new ConnectionBlockedError({
224 reason: "configuration",
225 ...translatableDetail(
226 msg("Connection profile {connectionId} is not an SSH connection.", {
227 connectionId: target.connectionId,
228 }),
229 ),
230 });
231 }
232 if (profile.environmentId !== target.environmentId) {
233 return yield* environmentMismatchError({
234 expected: target.environmentId,
235 actual: profile.environmentId,
236 });
237 }
238 // Each pairing adds a session on the host, so connects reuse the saved token.
239 const saved = Option.getOrUndefined(yield* credentials.get(target.connectionId));
240 const savedToken = saved !== undefined && isBearerCredential(saved) ? saved.token : undefined;
241 const prepared = yield* ssh.prepare({
242 connectionId: target.connectionId,
243 expectedEnvironmentId: target.environmentId,
244 target: profile.target,
245 ...(savedToken === undefined ? {} : { bearerToken: savedToken }),
246 });
247 if (prepared.bearerToken !== savedToken) {
248 yield* credentials.put(
249 target.connectionId,
250 new BearerConnectionCredential({ token: prepared.bearerToken }),
251 );
252 }
253 const preparedProfile = new SshConnectionProfile({
254 connectionId: profile.connectionId,
255 environmentId: profile.environmentId,
256 label: profile.label,
257 target: prepared.bootstrap.target,
258 });
259 if (
260 pullRequestRoutingConnectionKey(entry) !==
261 pullRequestRoutingConnectionKey({ ...entry, profile: Option.some(preparedProfile) })
262 ) {
263 const permissions = yield* PullRequestRoutingPermissions;
264 yield* permissions.forget(target.environmentId);
265 }
266 yield* profiles.put(preparedProfile);
267 const authorized = yield* remote.authorizeBearer({
268 expectedEnvironmentId: target.environmentId,
269 httpBaseUrl: prepared.bootstrap.httpBaseUrl,
270 wsBaseUrl: prepared.bootstrap.wsBaseUrl,
271 bearerToken: prepared.bearerToken,
272 connectionMethod: "ssh",
273 });
274 return {
275 ...authorized,
276 target,
277 } satisfies PreparedConnection;
278 });
279 });
280
281 /** @public */
282 export const make = Effect.gen(function* () {
283 const primary = yield* makePrimaryBroker();
284 const bearer = yield* makeBearerBroker();
285 const relay = yield* makeRelayBroker();
286 const ssh = yield* makeSshBroker();
287 const httpClient = yield* HttpClient.HttpClient;
288
289 const authorize = Effect.fn("clientRuntime.connection.broker.authorize")(function* (
290 entry: ConnectionCatalogEntry,
291 ) {
292 const target: ConnectionTarget = entry.target;
293 yield* Effect.annotateCurrentSpan({
294 "connection.environment.id": target.environmentId,
295 "connection.target.kind": target._tag,
296 });
297 const authorized: PreparedConnection & {
298 readonly descriptor?: ExecutionEnvironmentDescriptor;
299 } = yield* (() => {
300 switch (target._tag) {
301 case "PrimaryConnectionTarget":
302 return primary(target);
303 case "BearerConnectionTarget":
304 return bearer({ ...entry, target });
305 case "RelayConnectionTarget":
306 return relay(target);
307 case "SshConnectionTarget":
308 return ssh({ ...entry, target });
309 }
310 })();
311 const { descriptor: authorizedDescriptor, ...prepared } = authorized;
312 const descriptor =
313 authorizedDescriptor ??
314 (yield* fetchRemoteEnvironmentDescriptor({
315 httpBaseUrl: prepared.httpBaseUrl,
316 }).pipe(
317 Effect.mapError(mapRemoteEnvironmentError),
318 Effect.provideService(HttpClient.HttpClient, httpClient),
319 ));
320 if (descriptor.environmentId !== target.environmentId) {
321 return yield* environmentMismatchError({
322 expected: target.environmentId,
323 actual: descriptor.environmentId,
324 });
325 }
326 return { prepared, descriptor };
327 });
328
329 const prepare = Effect.fn("clientRuntime.connection.broker.prepare")(function* (
330 entry: ConnectionCatalogEntry,
331 ) {
332 const { prepared, descriptor } = yield* authorize(entry);
333 const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);
334 if (compatibilityError !== null) {
335 return yield* compatibilityError;
336 }
337 return {
338 ...prepared,
339 descriptor,
340 socketUrl: appendOrchestrationProtocol(prepared.socketUrl),
341 };
342 });
343
344 return ConnectionResolver.of({ prepare, prepareForUpdate: authorize });
345 });
346
347 export const layer = Layer.effect(ConnectionResolver, make);