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

resolver.ts

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