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

resolver.ts

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