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

resolver.ts

295 lines10.4 KB

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