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

resolver.ts

251 lines8.9 KB

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