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

resolver.ts

313 lines11.3 KB

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