Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

resolver.ts

323 lines11.4 KB

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