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