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

resolver.ts

333 lines12.0 KB

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