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: "ws://127.0.0.1:3777/ws?clientSurface=web",
227 httpAuthorization: null,
228 target,
229 });
230 }),
231 );
232
233 it.effect("authorizes a desktop primary environment with its platform bearer token", () =>
234 Effect.gen(function* () {
235 const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);
236 const brokerLayer = yield* makeDependencies({
237 primaryBearerToken: "desktop-bearer",
238 authorizeBearer: (input) =>
239 Ref.update(bearerInputs, (values) => [...values, input.bearerToken]).pipe(
240 Effect.as({
241 environmentId: input.expectedEnvironmentId,
242 label: "Primary",
243 httpBaseUrl: input.httpBaseUrl,
244 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
245 httpAuthorization: {
246 _tag: "Bearer" as const,
247 token: input.bearerToken,
248 },
249 }),
250 ),
251 });
252 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
253 const target = new PrimaryConnectionTarget({
254 environmentId: ENVIRONMENT_ID,
255 label: "Primary",
256 httpBaseUrl: "http://127.0.0.1:3777",
257 wsBaseUrl: "ws://127.0.0.1:3777",
258 });
259
260 expect(yield* broker.prepare(catalogEntry(target))).toMatchObject({
261 socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",
262 httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },
263 target,
264 });
265 expect(yield* Ref.get(bearerInputs)).toEqual(["desktop-bearer"]);
266 }),
267 );
268
269 it.effect("uses the registered bearer profile without re-reading the profile store", () =>
270 Effect.gen(function* () {
271 const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);
272 const target = new BearerConnectionTarget({
273 environmentId: ENVIRONMENT_ID,
274 label: "Saved",
275 connectionId: "saved-1",
276 });
277 const profile = new BearerConnectionProfile({
278 connectionId: "saved-1",
279 environmentId: ENVIRONMENT_ID,
280 label: "Saved",
281 httpBaseUrl: ENDPOINT.httpBaseUrl,
282 wsBaseUrl: ENDPOINT.wsBaseUrl,
283 });
284 const brokerLayer = yield* makeDependencies({
285 credentials: [["saved-1", new BearerConnectionCredential({ token: "secret-bearer" })]],
286 authorizeBearer: (input) =>
287 Ref.update(bearerInputs, (values) => [...values, input.bearerToken]).pipe(
288 Effect.as({
289 environmentId: input.expectedEnvironmentId,
290 label: "Saved",
291 httpBaseUrl: input.httpBaseUrl,
292 socketUrl: "wss://environment.example.test/ws?wsTicket=ticket",
293 httpAuthorization: {
294 _tag: "Bearer" as const,
295 token: input.bearerToken,
296 },
297 }),
298 ),
299 });
300 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
301
302 expect(
303 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
304 ).toContain("wsTicket=ticket");
305 expect(yield* Ref.get(bearerInputs)).toEqual(["secret-bearer"]);
306 }),
307 );
308
309 it.effect("brokers relay credentials with the current cloud session and device identity", () =>
310 Effect.gen(function* () {
311 const relayInputs = yield* Ref.make<
312 ReadonlyArray<{
313 readonly clerkToken: string;
314 readonly scopes: ReadonlyArray<string>;
315 readonly deviceId?: string;
316 }>
317 >([]);
318 const bootstrapCredentials = yield* Ref.make<ReadonlyArray<string>>([]);
319 const target = new RelayConnectionTarget({
320 environmentId: ENVIRONMENT_ID,
321 label: "Cloud",
322 });
323 const brokerLayer = yield* makeDependencies({
324 connectEnvironment: (input) =>
325 Ref.update(relayInputs, (values) => [
326 ...values,
327 {
328 clerkToken: input.clerkToken,
329 scopes: input.scopes,
330 ...(input.deviceId ? { deviceId: input.deviceId } : {}),
331 },
332 ]).pipe(
333 Effect.as({
334 environmentId: input.environmentId,
335 endpoint: ENDPOINT,
336 credential: "relay-bootstrap",
337 expiresAt: "2026-06-06T00:00:00.000Z",
338 }),
339 ),
340 authorizeDpop: (input) =>
341 input.obtainBootstrap.pipe(
342 Effect.tap((bootstrap) =>
343 Ref.update(bootstrapCredentials, (values) => [...values, bootstrap.credential]),
344 ),
345 Effect.as({
346 environmentId: input.expectedEnvironmentId,
347 label: "Cloud",
348 httpBaseUrl: ENDPOINT.httpBaseUrl,
349 socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
350 httpAuthorization: {
351 _tag: "Dpop" as const,
352 accessToken: "dpop-access-token",
353 },
354 }),
355 ),
356 });
357 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
358
359 expect((yield* broker.prepare(catalogEntry(target))).socketUrl).toContain("wsTicket=dpop");
360 expect(yield* Ref.get(relayInputs)).toEqual([
361 {
362 clerkToken: "clerk-session",
363 scopes: [RelayEnvironmentConnectScope],
364 deviceId: "device-1",
365 },
366 ]);
367 expect(yield* Ref.get(bootstrapCredentials)).toEqual(["relay-bootstrap"]);
368 }),
369 );
370
371 it.effect("exports the complete relay authorization flow through the product tracer", () =>
372 Effect.gen(function* () {
373 const userSpans: Array<string> = [];
374 const productSpans: Array<string> = [];
375 const target = new RelayConnectionTarget({
376 environmentId: ENVIRONMENT_ID,
377 label: "Cloud",
378 });
379 const brokerLayer = yield* makeDependencies({
380 authorizeDpop: (input) =>
381 input.obtainBootstrap.pipe(
382 Effect.as({
383 environmentId: input.expectedEnvironmentId,
384 label: "Cloud",
385 httpBaseUrl: ENDPOINT.httpBaseUrl,
386 socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",
387 httpAuthorization: {
388 _tag: "Dpop" as const,
389 accessToken: "dpop-access-token",
390 },
391 }),
392 Effect.withSpan("test.remote.authorizeDpop"),
393 ),
394 });
395 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
396
397 yield* broker
398 .prepare(catalogEntry(target))
399 .pipe(
400 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
401 Effect.withTracer(collectingTracer(userSpans)),
402 );
403
404 expect(productSpans).toContain("clientRuntime.connection.broker.relay");
405 expect(productSpans).toContain("test.remote.authorizeDpop");
406 expect(userSpans).toContain("clientRuntime.connection.broker.prepare");
407 expect(userSpans).not.toContain("test.remote.authorizeDpop");
408 }),
409 );
410
411 it.effect("delegates SSH launch to the platform gateway before remote authorization", () =>
412 Effect.gen(function* () {
413 const preparedTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
414 const target = new SshConnectionTarget({
415 environmentId: ENVIRONMENT_ID,
416 label: "SSH",
417 connectionId: "ssh-1",
418 });
419 const profile = new SshConnectionProfile({
420 connectionId: "ssh-1",
421 environmentId: ENVIRONMENT_ID,
422 label: "SSH",
423 target: SSH_TARGET,
424 });
425 const brokerLayer = yield* makeDependencies({
426 prepareSsh: (input) =>
427 Ref.update(preparedTargets, (values) => [...values, input.target]).pipe(
428 Effect.as({
429 bootstrap: {
430 target: input.target,
431 httpBaseUrl: "http://127.0.0.1:4010",
432 wsBaseUrl: "ws://127.0.0.1:4010",
433 pairingToken: null,
434 },
435 bearerToken: "ssh-bearer",
436 }),
437 ),
438 });
439 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
440
441 expect(
442 (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,
443 ).toContain("wsTicket=bearer");
444 expect(yield* Ref.get(preparedTargets)).toEqual([SSH_TARGET]);
445 }),
446 );
447
448 it.effect("classifies relay request timeouts as retryable connection failures", () =>
449 Effect.gen(function* () {
450 const target = new RelayConnectionTarget({
451 environmentId: ENVIRONMENT_ID,
452 label: "Cloud",
453 });
454 const brokerLayer = yield* makeDependencies({
455 connectEnvironment: () =>
456 Effect.fail(
457 new ManagedRelay.ManagedRelayRequestTimeoutError({
458 activity: "Relay environment connection",
459 timeoutMs: ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS,
460 traceId: null,
461 }),
462 ),
463 });
464 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
465 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
466
467 expect(error).toBeInstanceOf(ConnectionTransientError);
468 expect(error).toMatchObject({ reason: "timeout" });
469 }),
470 );
471});