Open History to see the last commit
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 HttpClient from "effect/unstable/http/HttpClient";
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 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();
69}
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* Effect.fromOption(entry.profile, () =>
114 profileMissingError(target.connectionId),
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 remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
159
160 return Effect.fnUntraced(
161 function* (target: RelayConnectionTarget) {
162 const authorized = yield* remote.authorizeDpop({
163 expectedEnvironmentId: target.environmentId,
164 });
165 return {
166 environmentId: authorized.environmentId,
167 label: authorized.label,
168 httpBaseUrl: authorized.httpBaseUrl,
169 socketUrl: authorized.socketUrl,
170 httpAuthorization: authorized.httpAuthorization,
171 target,
172 } satisfies PreparedConnection;
173 },
174 Effect.withSpan("clientRuntime.connection.broker.relay"),
175 withRelayClientTracing,
176 );
177});
178
179const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(function* () {
180 const profiles = yield* ConnectionProfileStore.ConnectionProfileStore;
181 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
182 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
183
184 return Effect.fn("clientRuntime.connection.broker.ssh")(function* (
185 entry: ConnectionCatalogEntry & { readonly target: SshConnectionTarget },
186 ) {
187 const target = entry.target;
188 const profile = yield* Effect.fromOption(entry.profile, () =>
189 profileMissingError(target.connectionId),
190 );
191 if (!isSshProfile(profile)) {
192 return yield* new ConnectionBlockedError({
193 reason: "configuration",
194 detail: `Connection profile ${target.connectionId} is not an SSH connection.`,
195 });
196 }
197 if (profile.environmentId !== target.environmentId) {
198 return yield* environmentMismatchError({
199 expected: target.environmentId,
200 actual: profile.environmentId,
201 });
202 }
203 const prepared = yield* ssh.prepare({
204 connectionId: target.connectionId,
205 expectedEnvironmentId: target.environmentId,
206 target: profile.target,
207 });
208 const preparedProfile = new SshConnectionProfile({
209 connectionId: profile.connectionId,
210 environmentId: profile.environmentId,
211 label: profile.label,
212 target: prepared.bootstrap.target,
213 });
214 if (
215 gitHubRoutingConnectionKey(entry) !==
216 gitHubRoutingConnectionKey({ ...entry, profile: Option.some(preparedProfile) })
217 ) {
218 const permissions = yield* GitHubRoutingPermissions;
219 yield* permissions.forget(target.environmentId);
220 }
221 yield* profiles.put(preparedProfile);
222 const authorized = yield* remote.authorizeBearer({
223 expectedEnvironmentId: target.environmentId,
224 httpBaseUrl: prepared.bootstrap.httpBaseUrl,
225 wsBaseUrl: prepared.bootstrap.wsBaseUrl,
226 bearerToken: prepared.bearerToken,
227 connectionMethod: "ssh",
228 });
229 return {
230 environmentId: authorized.environmentId,
231 label: authorized.label,
232 httpBaseUrl: authorized.httpBaseUrl,
233 socketUrl: authorized.socketUrl,
234 httpAuthorization: authorized.httpAuthorization,
235 target,
236 } satisfies PreparedConnection;
237 });
238});
239
240/** @public Service construction is part of the canonical Effect module API. */
241export const make = Effect.gen(function* () {
242 const primary = yield* makePrimaryBroker();
243 const bearer = yield* makeBearerBroker();
244 const relay = yield* makeRelayBroker();
245 const ssh = yield* makeSshBroker();
246 const httpClient = yield* HttpClient.HttpClient;
247
248 const prepare = Effect.fn("clientRuntime.connection.broker.prepare")(function* (
249 entry: ConnectionCatalogEntry,
250 ) {
251 const target: ConnectionTarget = entry.target;
252 yield* Effect.annotateCurrentSpan({
253 "connection.environment.id": target.environmentId,
254 "connection.target.kind": target._tag,
255 });
256 const prepared = yield* (() => {
257 switch (target._tag) {
258 case "PrimaryConnectionTarget":
259 return primary(target);
260 case "BearerConnectionTarget":
261 return bearer({ ...entry, target });
262 case "RelayConnectionTarget":
263 return relay(target);
264 case "SshConnectionTarget":
265 return ssh({ ...entry, target });
266 }
267 })();
268 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
269 httpBaseUrl: prepared.httpBaseUrl,
270 }).pipe(
271 Effect.mapError(mapRemoteEnvironmentError),
272 Effect.provideService(HttpClient.HttpClient, httpClient),
273 );
274 if (descriptor.environmentId !== target.environmentId) {
275 return yield* environmentMismatchError({
276 expected: target.environmentId,
277 actual: descriptor.environmentId,
278 });
279 }
280 const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);
281 if (compatibilityError !== null) {
282 return yield* compatibilityError;
283 }
284 return { ...prepared, socketUrl: appendOrchestrationProtocol(prepared.socketUrl) };
285 });
286
287 return ConnectionResolver.of({ prepare });
288});
289
290export const layer = Layer.effect(ConnectionResolver, make);