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