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