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

linkEnvironment.test.ts

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