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