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

resolver.test.ts

532 lines20.2 KB

1import {
2 EnvironmentId,
3 ORCHESTRATION_PROTOCOL_VERSION,
4 type DesktopSshEnvironmentTarget,
5} from "@t3tools/contracts";
6import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";
7import { RelayClientTracer } from "@t3tools/shared/relayTracing";
8import { describe, expect, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Ref from "effect/Ref";
13import * as Tracer from "effect/Tracer";
14​
15import * as ManagedRelay from "../relay/managedRelay.ts";
16import * as ConnectionResolver from "./resolver.ts";
17import * as ClientCapabilities from "../platform/capabilities.ts";
18import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
19import {
20 BearerConnectionCredential,
21 BearerConnectionProfile,
22 type ConnectionCatalogEntry,
23 SshConnectionProfile,
24 type ConnectionCredential,
25 type ConnectionProfile,
26} from "./catalog.ts";
27import * as ConnectionCredentialStore from "./credentialStore.ts";
28import {
29 BearerConnectionTarget,
30 ConnectionTransientError,
31 PrimaryConnectionTarget,
32 RelayConnectionTarget,
33 SshConnectionTarget,
34 type ConnectionTarget,
35} from "./model.ts";
36import * as ConnectionProfileStore from "./profileStore.ts";
37import { remoteHttpClientLayer } from "../rpc/http.ts";
38​
39const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
40const ENDPOINT = {
41 httpBaseUrl: "https://environment.example.test",
42 wsBaseUrl: "wss://environment.example.test",
43 providerKind: "cloudflare_tunnel" as const,
44};
45const SSH_TARGET: DesktopSshEnvironmentTarget = {
46 alias: "development",
47 hostname: "development.example.test",
48 username: "developer",
49 port: 22,
50};
51​
52function catalogEntry(
53 target: ConnectionTarget,
54 profile: Option.Option<ConnectionProfile> = Option.none(),
55): ConnectionCatalogEntry {
56 return { target, profile };
58​
59function unsupported<A>(name: string): Effect.Effect<A> {
60 return Effect.die(new Error(`Unexpected relay call: ${name}`));
62​
63function collectingTracer(spans: Array<string>): Tracer.Tracer {
64 return Tracer.make({
65 span: (options) => {
66 const span = new Tracer.NativeSpan(options);
67 const end = span.end.bind(span);
68 span.end = (endTime, exit) => {
69 end(endTime, exit);
70 spans.push(span.name);
71 };
72 return span;
73 },
74 });
76​
77function relayClient(
78 connectEnvironment: ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"],
79) {
80 return ManagedRelay.ManagedRelayClient.of({
81 relayUrl: "https://relay.example.test",
82 listEnvironments: () => unsupported("listEnvironments"),
83 listDevices: () => unsupported("listDevices"),
84 createEnvironmentLinkChallenge: () => unsupported("createEnvironmentLinkChallenge"),
85 linkEnvironment: () => unsupported("linkEnvironment"),
86 unlinkEnvironment: () => unsupported("unlinkEnvironment"),
87 getEnvironmentStatus: () => unsupported("getEnvironmentStatus"),
88 connectEnvironment,
89 registerDevice: () => unsupported("registerDevice"),
90 unregisterDevice: () => unsupported("unregisterDevice"),
91 registerLiveActivity: () => unsupported("registerLiveActivity"),
92 getAgentActivitySnapshot: () => unsupported("getAgentActivitySnapshot"),
93 resetTokenCache: Effect.void,
94 });
96​
97const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((options?: {
98 readonly profiles?: ReadonlyArray<ConnectionProfile>;
99 readonly credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>;
100 readonly connectEnvironment?: ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"];
101 readonly authorizeBearer?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];
102 readonly authorizeDpop?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];
103 readonly primaryBearerToken?: string;
104 readonly prepareSsh?: ClientCapabilities.SshEnvironmentGateway["Service"]["prepare"];
105 readonly descriptorProtocolVersion?: number | null | undefined;
106}) => {
107 const profiles = new Map(
108 (options?.profiles ?? []).map((profile) => [profile.connectionId, profile]),
109 );
110 const credentials = new Map(options?.credentials ?? []);
111​
112 const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({
113 get: (connectionId) => Effect.succeed(Option.fromNullishOr(profiles.get(connectionId))),
114 put: (profile) => Effect.sync(() => void profiles.set(profile.connectionId, profile)),
115 remove: (connectionId) => Effect.sync(() => void profiles.delete(connectionId)),
116 });
117 const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({
118 get: (connectionId) => Effect.succeed(Option.fromNullishOr(credentials.get(connectionId))),
119 put: (connectionId, credential) =>
120 Effect.sync(() => void credentials.set(connectionId, credential)),
121 remove: (connectionId) => Effect.sync(() => void credentials.delete(connectionId)),
122 });
123 const remote = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
124 authorizeBearer:
125 options?.authorizeBearer ??
126 ((input) =>
127 Effect.succeed({
128 environmentId: input.expectedEnvironmentId,
129 label: "Authorized bearer environment",
130 httpBaseUrl: input.httpBaseUrl,
131 socketUrl: "wss://authorized.example.test/ws?wsTicket=bearer",
132 httpAuthorization: {
133 _tag: "Bearer" as const,
134 token: input.bearerToken,
135 },
136 })),
137 authorizeDpop:
138 options?.authorizeDpop ??
139 ((input) =>
140 input.obtainBootstrap.pipe(
141 Effect.as({
142 environmentId: input.expectedEnvironmentId,
143 label: "Authorized relay environment",
144 httpBaseUrl: ENDPOINT.httpBaseUrl,
145 socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",
146 httpAuthorization: {
147 _tag: "Dpop" as const,
148 accessToken: "dpop-access-token",
149 },
150 }),
151 )),
152 });
153 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
154 provision: () => Effect.die("unused"),
155 prepare:
156 options?.prepareSsh ??
157 (() =>
158 Effect.succeed({
159 bootstrap: {
160 target: SSH_TARGET,
161 httpBaseUrl: "http://127.0.0.1:4010",
162 wsBaseUrl: "ws://127.0.0.1:4010",
163 pairingToken: null,
164 },
165 bearerToken: "ssh-bearer",
166 })),
167 disconnect: () => Effect.void,
168 });
169​
170 const dependencies = Layer.mergeAll(
171 remoteHttpClientLayer((() =>
172 Promise.resolve(
173 Response.json({
174 environmentId: ENVIRONMENT_ID,
175 label: "Compatible environment",
176 platform: { os: "linux", arch: "x64" },
177 serverVersion: "0.0.0-test",
178 ...(options?.descriptorProtocolVersion === undefined
179 ? { orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION }
180 : options.descriptorProtocolVersion === null
181 ? {}
182 : { orchestrationProtocolVersion: options.descriptorProtocolVersion }),
183 capabilities: { repositoryIdentity: true },
184 }),
185 )) satisfies typeof fetch),
186 Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),
187 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
188 Layer.succeed(
189 ClientCapabilities.CloudSession,
190 ClientCapabilities.CloudSession.of({ clerkToken: Effect.succeed("clerk-session") }),
191 ),
192 Layer.succeed(
193 ClientCapabilities.PrimaryEnvironmentAuth,
194 ClientCapabilities.PrimaryEnvironmentAuth.of({
195 bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),
196 }),
197 ),
198 Layer.succeed(
199 ClientCapabilities.ClientPresentation,
200 ClientCapabilities.ClientPresentation.of({
201 metadata: { label: "Test Client", deviceType: "desktop", surface: "web" },
202 scopes: [],
203 }),
204 ),
205 Layer.succeed(
206 ClientCapabilities.RelayDeviceIdentity,
207 ClientCapabilities.RelayDeviceIdentity.of({
208 deviceId: Effect.succeed(Option.some("device-1")),
209 }),
210 ),
211 Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
212 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),
213 Layer.succeed(
214 ManagedRelay.ManagedRelayClient,
215 relayClient(
216 options?.connectEnvironment ??
217 ((input) =>
218 Effect.succeed({
219 environmentId: input.environmentId,
220 endpoint: ENDPOINT,
221 credential: "relay-bootstrap",
222 expiresAt: "2026-06-06T00:00:00.000Z",
223 })),
224 ),
225 ),
226 );
227​
228 return Effect.succeed(ConnectionResolver.layer.pipe(Layer.provide(dependencies)));
229});
230​
231describe("ConnectionResolver", () => {
232 it.effect("blocks an old host during discovery before opening orchestration RPC", () =>
233 Effect.gen(function* () {
234 const brokerLayer = yield* makeDependencies({ descriptorProtocolVersion: null });
235 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
236 const target = new PrimaryConnectionTarget({
237 environmentId: ENVIRONMENT_ID,
238 label: "Primary",
239 httpBaseUrl: "http://127.0.0.1:3777",
240 wsBaseUrl: "ws://127.0.0.1:3777",
241 });
242​
243 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
244​
245 expect(error).toMatchObject({ reason: "unsupported" });
246 expect(error.message).toContain("Update T3 Code on Compatible environment");
247 }),
248 );
249​
250 it.effect("prepares a primary environment without remote capabilities", () =>
251 Effect.gen(function* () {
252 const brokerLayer = yield* makeDependencies();
253 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
254 const target = new PrimaryConnectionTarget({
255 environmentId: ENVIRONMENT_ID,
256 label: "Primary",
257 httpBaseUrl: "http://127.0.0.1:3777",
258 wsBaseUrl: "ws://127.0.0.1:3777",
259 });
260​
261 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
262 environmentId: ENVIRONMENT_ID,
263 label: "Primary",
264 httpBaseUrl: "http://127.0.0.1:3777",
265 socketUrl:
266 "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct&orchestrationProtocol=2",
267 httpAuthorization: null,
268 target,
269 });
270 }),
271 );
272​
273 it.effect("authorizes a desktop primary environment with its platform bearer token", () =>
274 Effect.gen(function* () {
275 const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
276 const brokerLayer = yield* makeDependencies({
277 primaryBearerToken: "desktop-bearer",
278 authorizeBearer: (input) =>
279 Ref.update(bearerInputs, (values) => [
280 ...values,
281 { token: input.bearerToken, method: input.connectionMethod },
282 ]).pipe(
283 Effect.as({
284 environmentId: input.expectedEnvironmentId,
285 label: "Primary",
286 httpBaseUrl: input.httpBaseUrl,
287 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
288 httpAuthorization: {
289 _tag: "Bearer" as const,
290 token: input.bearerToken,
291 },
292 }),
293 ),
294 });
295 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
296 const target = new PrimaryConnectionTarget({
297 environmentId: ENVIRONMENT_ID,
298 label: "Primary",
299 httpBaseUrl: "http://127.0.0.1:3777",
300 wsBaseUrl: "ws://127.0.0.1:3777",
301 });
302​
303 expect(yield* broker.prepare(catalogEntry(target))).toMatchObject({
304 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop&orchestrationProtocol=2",
305 httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },
306 target,
307 });
308 expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "desktop-bearer", method: "direct" }]);
309 }),
310 );
311​
312 it.effect("uses the registered bearer profile without re-reading the profile store", () =>
313 Effect.gen(function* () {
314 const bearerInputs = yield* Ref.make<ReadonlyArray<{ token: string; method: string }>>([]);
315 const target = new BearerConnectionTarget({
316 environmentId: ENVIRONMENT_ID,
317 label: "Saved",
318 connectionId: "saved-1",
319 });
320 const profile = new BearerConnectionProfile({
321 connectionId: "saved-1",
322 environmentId: ENVIRONMENT_ID,
323 label: "Saved",
324 httpBaseUrl: ENDPOINT.httpBaseUrl,
325 wsBaseUrl: ENDPOINT.wsBaseUrl,
326 });
327 const brokerLayer = yield* makeDependencies({
328 credentials: [["saved-1", new BearerConnectionCredential({ token: "secret-bearer" })]],
329 authorizeBearer: (input) =>
330 Ref.update(bearerInputs, (values) => [
331 ...values,
332 { token: input.bearerToken, method: input.connectionMethod },
333 ]).pipe(
334 Effect.as({
335 environmentId: input.expectedEnvironmentId,
336 label: "Saved",
337 httpBaseUrl: input.httpBaseUrl,
338 socketUrl: "wss://environment.example.test/ws?wsTicket=ticket",
339 httpAuthorization: {
340 _tag: "Bearer" as const,
341 token: input.bearerToken,
342 },
343 }),
344 ),
345 });
346 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
347​
348 expect(
349 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
350 ).toContain("wsTicket=ticket");
351 expect(yield* Ref.get(bearerInputs)).toEqual([{ token: "secret-bearer", method: "direct" }]);
352 }),
353 );
354​
355 it.effect("brokers relay credentials with the current cloud session and device identity", () =>
356 Effect.gen(function* () {
357 const relayInputs = yield* Ref.make<
358 ReadonlyArray<{
359 readonly clerkToken: string;
360 readonly scopes: ReadonlyArray<string>;
361 readonly deviceId?: string;
362 }>
363 >([]);
364 const bootstrapCredentials = yield* Ref.make<ReadonlyArray<string>>([]);
365 const target = new RelayConnectionTarget({
366 environmentId: ENVIRONMENT_ID,
367 label: "Cloud",
368 });
369 const brokerLayer = yield* makeDependencies({
370 connectEnvironment: (input) =>
371 Ref.update(relayInputs, (values) => [
372 ...values,
373 {
374 clerkToken: input.clerkToken,
375 scopes: input.scopes,
376 ...(input.deviceId ? { deviceId: input.deviceId } : {}),
377 },
378 ]).pipe(
379 Effect.as({
380 environmentId: input.environmentId,
381 endpoint: ENDPOINT,
382 credential: "relay-bootstrap",
383 expiresAt: "2026-06-06T00:00:00.000Z",
384 }),
385 ),
386 authorizeDpop: (input) =>
387 input.obtainBootstrap.pipe(
388 Effect.tap((bootstrap) =>
389 Ref.update(bootstrapCredentials, (values) => [...values, bootstrap.credential]),
390 ),
391 Effect.as({
392 environmentId: input.expectedEnvironmentId,
393 label: "Cloud",
394 httpBaseUrl: ENDPOINT.httpBaseUrl,
395 socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
396 httpAuthorization: {
397 _tag: "Dpop" as const,
398 accessToken: "dpop-access-token",
399 },
400 }),
401 ),
402 });
403 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
404​
405 expect((yield* broker.prepare(catalogEntry(target))).socketUrl).toContain("wsTicket=dpop");
406 expect(yield* Ref.get(relayInputs)).toEqual([
407 {
408 clerkToken: "clerk-session",
409 scopes: [RelayEnvironmentConnectScope],
410 deviceId: "device-1",
411 },
412 ]);
413 expect(yield* Ref.get(bootstrapCredentials)).toEqual(["relay-bootstrap"]);
414 }),
415 );
416​
417 it.effect("exports the complete relay authorization flow through the product tracer", () =>
418 Effect.gen(function* () {
419 const userSpans: Array<string> = [];
420 const productSpans: Array<string> = [];
421 const target = new RelayConnectionTarget({
422 environmentId: ENVIRONMENT_ID,
423 label: "Cloud",
424 });
425 const brokerLayer = yield* makeDependencies({
426 authorizeDpop: (input) =>
427 input.obtainBootstrap.pipe(
428 Effect.as({
429 environmentId: input.expectedEnvironmentId,
430 label: "Cloud",
431 httpBaseUrl: ENDPOINT.httpBaseUrl,
432 socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
433 httpAuthorization: {
434 _tag: "Dpop" as const,
435 accessToken: "dpop-access-token",
436 },
437 }),
438 Effect.withSpan("test.remote.authorizeDpop"),
439 ),
440 });
441 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
442​
443 yield* broker
444 .prepare(catalogEntry(target))
445 .pipe(
446 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
447 Effect.withTracer(collectingTracer(userSpans)),
448 );
449​
450 expect(productSpans).toContain("clientRuntime.connection.broker.relay");
451 expect(productSpans).toContain("test.remote.authorizeDpop");
452 expect(userSpans).toContain("clientRuntime.connection.broker.prepare");
453 expect(userSpans).not.toContain("test.remote.authorizeDpop");
454 }),
455 );
456​
457 it.effect("delegates SSH launch to the platform gateway before remote authorization", () =>
458 Effect.gen(function* () {
459 const preparedTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
460 const connectionMethods = yield* Ref.make<ReadonlyArray<string>>([]);
461 const target = new SshConnectionTarget({
462 environmentId: ENVIRONMENT_ID,
463 label: "SSH",
464 connectionId: "ssh-1",
465 });
466 const profile = new SshConnectionProfile({
467 connectionId: "ssh-1",
468 environmentId: ENVIRONMENT_ID,
469 label: "SSH",
470 target: SSH_TARGET,
471 });
472 const brokerLayer = yield* makeDependencies({
473 prepareSsh: (input) =>
474 Ref.update(preparedTargets, (values) => [...values, input.target]).pipe(
475 Effect.as({
476 bootstrap: {
477 target: input.target,
478 httpBaseUrl: "http://127.0.0.1:4010",
479 wsBaseUrl: "ws://127.0.0.1:4010",
480 pairingToken: null,
481 },
482 bearerToken: "ssh-bearer",
483 }),
484 ),
485 authorizeBearer: (input) =>
486 Ref.update(connectionMethods, (methods) => [...methods, input.connectionMethod]).pipe(
487 Effect.as({
488 environmentId: input.expectedEnvironmentId,
489 label: "SSH",
490 httpBaseUrl: input.httpBaseUrl,
491 socketUrl: "wss://environment.example.test/ws?wsTicket=bearer",
492 httpAuthorization: {
493 _tag: "Bearer" as const,
494 token: input.bearerToken,
495 },
496 }),
497 ),
498 });
499 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
500​
501 expect(
502 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
503 ).toContain("wsTicket=bearer");
504 expect(yield* Ref.get(preparedTargets)).toEqual([SSH_TARGET]);
505 expect(yield* Ref.get(connectionMethods)).toEqual(["ssh"]);
506 }),
507 );
508​
509 it.effect("classifies relay request timeouts as retryable connection failures", () =>
510 Effect.gen(function* () {
511 const target = new RelayConnectionTarget({
512 environmentId: ENVIRONMENT_ID,
513 label: "Cloud",
514 });
515 const brokerLayer = yield* makeDependencies({
516 connectEnvironment: () =>
517 Effect.fail(
518 new ManagedRelay.ManagedRelayRequestTimeoutError({
519 activity: "Relay environment connection",
520 timeoutMs: ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS,
521 traceId: null,
522 }),
523 ),
524 });
525 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
526 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
527​
528 expect(error).toBeInstanceOf(ConnectionTransientError);
529 expect(error).toMatchObject({ reason: "timeout" });
530 }),
531 );
532});