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