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

linkEnvironment.test.ts

440 lines14.6 KB

1import {
2 type DesktopBridge,
3 EnvironmentId,
4 type RelayClientInstallProgressEvent,
5 WS_METHODS,
6} from "@t3tools/contracts";
7import { RelayWebClientId } from "@t3tools/contracts/relay";
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 Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14import { HttpClient } from "effect/unstable/http";
15import { afterEach, beforeEach, vi } from "vite-plus/test";
16import {
17 AVAILABLE_CONNECTION_STATE,
18 EnvironmentSupervisor,
19 type PreparedConnection,
20 PrimaryConnectionTarget,
21} from "@t3tools/client-runtime/connection";
22import { type RpcSession } from "@t3tools/client-runtime/rpc";
23import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
24import { ManagedRelay } from "@t3tools/client-runtime/relay";
25import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
26import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
27​
28import {
29 collectCloudLinkTargets,
30 linkPrimaryEnvironmentToCloud,
31 listManagedCloudEnvironments,
32 normalizeRelayBaseUrl,
33 readPrimaryCloudLinkState,
34 type CloudLinkTarget,
35 unlinkPrimaryEnvironmentFromCloud,
36 updatePrimaryCloudPreferences,
37} from "./linkEnvironment";
38​
39const TARGET: CloudLinkTarget = {
40 environmentId: "environment-1",
41 label: "Desktop",
42 httpBaseUrl: "http://127.0.0.1:3000",
43 wsBaseUrl: "ws://127.0.0.1:3000",
44};
45​
46const relayClientInstallDialog = vi.hoisted(() => ({
47 requestConfirmation: vi.fn(),
48 reportProgress: vi.fn(),
49 finish: vi.fn(),
50}));
51​
52vi.mock("./relayClientInstallDialog", () => ({
53 requestRelayClientInstallConfirmation: relayClientInstallDialog.requestConfirmation,
54 reportRelayClientInstallProgress: relayClientInstallDialog.reportProgress,
55 finishRelayClientInstall: relayClientInstallDialog.finish,
56}));
57​
58const createProof = vi.fn(() => Effect.succeed("dpop-proof"));
59const dpopSignerLayer = Layer.succeed(
60 ManagedRelay.ManagedRelayDpopSigner,
61 ManagedRelay.ManagedRelayDpopSigner.of({
62 thumbprint: Effect.succeed("thumbprint"),
63 createProof,
64 }),
65);
66​
67function relayLayer() {
68 const http = remoteHttpClientLayer(globalThis.fetch);
69 return Layer.mergeAll(
70 http,
71 ManagedRelay.layer({
72 relayUrl: "https://relay.example.test",
73 clientId: RelayWebClientId,
74 }).pipe(Layer.provideMerge(dpopSignerLayer), Layer.provide(http)),
75 );
77​
78function registryLayer(options?: {
79 readonly status?: { readonly status: "available"; readonly version: string };
80 readonly installEvents?: ReadonlyArray<RelayClientInstallProgressEvent>;
81}) {
82 return Layer.effect(
83 EnvironmentRegistry,
84 Effect.gen(function* () {
85 const client = {
86 [WS_METHODS.cloudGetRelayClientStatus]: () =>
87 Effect.succeed(options?.status ?? { status: "available", version: "2026.6.0" }),
88 [WS_METHODS.cloudInstallRelayClient]: () =>
89 Stream.fromIterable(options?.installEvents ?? []),
90 } as unknown as RpcSession["client"];
91 const session: RpcSession = {
92 client,
93 initialConfig: Effect.never,
94 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
95 ready: Effect.void,
96 probe: Effect.void,
97 closed: Effect.never,
98 };
99 const target = new PrimaryConnectionTarget({
100 environmentId: EnvironmentId.make(TARGET.environmentId),
101 label: TARGET.label,
102 httpBaseUrl: TARGET.httpBaseUrl,
103 wsBaseUrl: TARGET.wsBaseUrl,
104 });
105 const supervisor = EnvironmentSupervisor.of({
106 target,
107 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
108 session: yield* SubscriptionRef.make(Option.some(session)),
109 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
110 connect: Effect.void,
111 disconnect: Effect.void,
112 retryNow: Effect.void,
113 } satisfies EnvironmentSupervisor["Service"]);
114 const registry = {
115 run: <A, E, R>(_environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>
116 Effect.provideService(effect, EnvironmentSupervisor, supervisor),
117 runStream: <A, E, R>(_environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>
118 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
119 } as unknown as EnvironmentRegistry["Service"];
120 return EnvironmentRegistry.of(registry);
121 }),
122 );
124​
125function services(options?: Parameters<typeof registryLayer>[0]) {
126 return Layer.mergeAll(relayLayer(), registryLayer(options));
128​
129function withServices<A, E>(
130 effect: Effect.Effect<
131 A,
132 E,
133 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | EnvironmentRegistry
134 >,
135 options?: Parameters<typeof registryLayer>[0],
136) {
137 return effect.pipe(Effect.provide(services(options)));
139​
140function bodyText(body: BodyInit | null | undefined): string {
141 return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");
143​
144beforeEach(() => {
145 vi.clearAllMocks();
146 vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");
147 relayClientInstallDialog.requestConfirmation.mockResolvedValue(true);
148});
149​
150afterEach(() => {
151 __resetDesktopPrimaryAuthForTests();
152 vi.unstubAllGlobals();
153 vi.unstubAllEnvs();
154 vi.restoreAllMocks();
155});
156​
157describe("web cloud link environment client", () => {
158 it("normalizes relay URLs and de-duplicates cloud link targets", () => {
159 expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe(
160 "https://relay.example.test",
161 );
162 expect(normalizeRelayBaseUrl(" ")).toBeNull();
163 expect(
164 collectCloudLinkTargets({
165 primary: TARGET,
166 saved: [TARGET, { ...TARGET, environmentId: "environment-2" }],
167 }).map((target) => target.environmentId),
168 ).toEqual(["environment-1", "environment-2"]);
169 });
170​
171 it.effect("lists relay-managed environments through the typed relay client", () =>
172 Effect.gen(function* () {
173 const fetchMock = vi.fn().mockResolvedValue(
174 Response.json({
175 environments: [
176 {
177 environmentId: "environment-1",
178 label: "Desktop",
179 endpoint: {
180 httpBaseUrl: "https://desktop.example.test",
181 wsBaseUrl: "wss://desktop.example.test",
182 providerKind: "cloudflare_tunnel",
183 },
184 linkedAt: "2026-06-06T00:00:00.000Z",
185 },
186 ],
187 }),
188 );
189 vi.stubGlobal("fetch", fetchMock);
190​
191 const environments = yield* withServices(
192 listManagedCloudEnvironments({ clerkToken: "clerk-token" }),
193 );
194​
195 expect(environments).toHaveLength(1);
196 expect(fetchMock.mock.calls[0]?.[1]?.headers.authorization).toBe("Bearer clerk-token");
197 }),
198 );
199​
200 it.effect("reads primary cloud link state from the explicit target", () =>
201 Effect.gen(function* () {
202 const fetchMock = vi.fn().mockResolvedValue(
203 Response.json({
204 linked: true,
205 cloudUserId: "user-1",
206 relayUrl: "https://relay.example.test",
207 relayIssuer: "https://relay.example.test",
208 managedTunnelActive: true,
209 publishAgentActivity: false,
210 }),
211 );
212 vi.stubGlobal("fetch", fetchMock);
213​
214 const state = yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
215​
216 expect(Option.fromNullishOr(state)).toEqual(
217 Option.some({
218 linked: true,
219 cloudUserId: "user-1",
220 relayUrl: "https://relay.example.test",
221 relayIssuer: "https://relay.example.test",
222 managedTunnelActive: true,
223 publishAgentActivity: false,
224 }),
225 );
226 expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
227 "http://127.0.0.1:3000/api/connect/link-state",
228 );
229 }),
230 );
231​
232 it.effect("uses desktop bearer auth for primary cloud link state", () =>
233 Effect.gen(function* () {
234 const fetchMock = vi.fn().mockResolvedValue(
235 Response.json({
236 linked: true,
237 cloudUserId: "user-1",
238 relayUrl: "https://relay.example.test",
239 relayIssuer: "https://relay.example.test",
240 managedTunnelActive: true,
241 publishAgentActivity: false,
242 }),
243 );
244 vi.stubGlobal("fetch", fetchMock);
245 vi.stubGlobal("window", {
246 location: { origin: "t3code://app" },
247 desktopBridge: {
248 getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
249 } as unknown as DesktopBridge,
250 });
251​
252 yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
253​
254 const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
255 expect(request.credentials).not.toBe("include");
256 expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
257 }),
258 );
259​
260 it.effect("updates agent activity publishing for the explicit primary target", () =>
261 Effect.gen(function* () {
262 const fetchMock = vi.fn().mockResolvedValue(
263 Response.json({
264 linked: true,
265 cloudUserId: "user-1",
266 relayUrl: "https://relay.example.test",
267 relayIssuer: "https://relay.example.test",
268 managedTunnelActive: true,
269 publishAgentActivity: true,
270 }),
271 );
272 vi.stubGlobal("fetch", fetchMock);
273​
274 const state = yield* withServices(
275 updatePrimaryCloudPreferences({
276 target: TARGET,
277 publishAgentActivity: true,
278 }),
279 );
280​
281 expect(state.publishAgentActivity).toBe(true);
282 expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
283 "http://127.0.0.1:3000/api/connect/preferences",
284 );
285 expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");
286 // @effect-diagnostics-next-line preferSchemaOverJson:off
287 expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
288 publishAgentActivity: true,
289 });
290 }),
291 );
292​
293 it.effect("links an available primary environment without invoking installation", () =>
294 Effect.gen(function* () {
295 const fetchMock = vi
296 .fn()
297 .mockResolvedValueOnce(
298 Response.json({
299 challenge: "challenge",
300 expiresAt: "2026-06-06T00:05:00.000Z",
301 }),
302 )
303 .mockResolvedValueOnce(Response.json("signed-proof"))
304 .mockResolvedValueOnce(
305 Response.json({
306 ok: true,
307 environmentId: TARGET.environmentId,
308 endpoint: {
309 httpBaseUrl: "https://desktop.example.test",
310 wsBaseUrl: "wss://desktop.example.test",
311 providerKind: "cloudflare_tunnel",
312 },
313 endpointRuntime: null,
314 relayIssuer: "https://relay.example.test",
315 cloudUserId: "user-1",
316 environmentCredential: "environment-credential",
317 cloudMintPublicKey: "public-key",
318 }),
319 )
320 .mockResolvedValueOnce(
321 Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
322 );
323 vi.stubGlobal("fetch", fetchMock);
324​
325 yield* withServices(
326 linkPrimaryEnvironmentToCloud({
327 target: TARGET,
328 clerkToken: "clerk-token",
329 }),
330 );
331​
332 expect(relayClientInstallDialog.requestConfirmation).not.toHaveBeenCalled();
333 expect(String(fetchMock.mock.calls[1]?.[0])).toBe(
334 "http://127.0.0.1:3000/api/connect/link-proof",
335 );
336 // @effect-diagnostics-next-line preferSchemaOverJson:off
337 expect(JSON.parse(bodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
338 challenge: "challenge",
339 endpoint: {
340 httpBaseUrl: TARGET.httpBaseUrl,
341 wsBaseUrl: TARGET.wsBaseUrl,
342 },
343 });
344 }),
345 );
346​
347 it.effect("links publish-only without a managed tunnel", () =>
348 Effect.gen(function* () {
349 const fetchMock = vi
350 .fn()
351 .mockResolvedValueOnce(
352 Response.json({
353 challenge: "challenge",
354 expiresAt: "2026-06-06T00:05:00.000Z",
355 }),
356 )
357 .mockResolvedValueOnce(Response.json("signed-proof"))
358 .mockResolvedValueOnce(
359 Response.json({
360 ok: true,
361 environmentId: TARGET.environmentId,
362 endpoint: {
363 httpBaseUrl: TARGET.httpBaseUrl,
364 wsBaseUrl: TARGET.wsBaseUrl,
365 providerKind: "manual",
366 },
367 endpointRuntime: null,
368 relayIssuer: "https://relay.example.test",
369 cloudUserId: "user-1",
370 environmentCredential: "environment-credential",
371 cloudMintPublicKey: "public-key",
372 }),
373 )
374 .mockResolvedValueOnce(
375 Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
376 );
377 vi.stubGlobal("fetch", fetchMock);
378​
379 yield* withServices(
380 linkPrimaryEnvironmentToCloud({
381 target: TARGET,
382 clerkToken: "clerk-token",
383 mode: "publish_only",
384 }),
385 );
386​
387 // @effect-diagnostics-next-line preferSchemaOverJson:off
388 expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({
389 managedTunnelsEnabled: false,
390 });
391 // @effect-diagnostics-next-line preferSchemaOverJson:off
392 expect(JSON.parse(bodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
393 endpoint: { providerKind: "manual" },
394 });
395 }),
396 );
397​
398 it.effect("installs a missing relay client before linking", () =>
399 Effect.gen(function* () {
400 vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ malformed: true })));
401​
402 yield* withServices(
403 linkPrimaryEnvironmentToCloud({
404 target: TARGET,
405 clerkToken: "clerk-token",
406 }),
407 {
408 status: { status: "available", version: "2026.6.0" },
409 installEvents: [],
410 },
411 ).pipe(Effect.flip);
412​
413 expect(relayClientInstallDialog.requestConfirmation).not.toHaveBeenCalled();
414 }),
415 );
416​
417 it.effect("unlinks locally before revoking the relay record", () =>
418 Effect.gen(function* () {
419 const fetchMock = vi
420 .fn()
421 .mockResolvedValueOnce(
422 Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
423 )
424 .mockResolvedValueOnce(Response.json({ ok: true }));
425 vi.stubGlobal("fetch", fetchMock);
426​
427 yield* withServices(
428 unlinkPrimaryEnvironmentFromCloud({
429 target: TARGET,
430 clerkToken: "clerk-token",
431 }),
432 );
433​
434 expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
435 expect(String(fetchMock.mock.calls[1]?.[0])).toContain(
436 `/v1/client/environment-links/${TARGET.environmentId}`,
437 );
438 }),
439 );
440});