Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { RelayWebClientId } from "@t3tools/contracts/relay";
3import { afterEach, beforeEach, vi } from "vite-plus/test";
4import { describe, expect, it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import { HttpClient } from "effect/unstable/http";
8import {
9 managedRelayClientLayer,
10 ManagedRelayClient,
11 ManagedRelayDpopSigner,
12 remoteHttpClientLayer,
13} from "@t3tools/client-runtime";
14
15import type { SavedEnvironmentRecord } from "../environments/runtime";
16import {
17 connectManagedCloudEnvironment,
18 linkEnvironmentToCloud,
19 linkPrimaryEnvironmentToCloud,
20 listManagedCloudEnvironments,
21 normalizeRelayBaseUrl,
22 readPrimaryCloudLinkState,
23 unlinkPrimaryEnvironmentFromCloud,
24} from "./linkEnvironment";
25import {
26 readPrimaryEnvironmentDescriptor,
27 readPrimaryEnvironmentTarget,
28 resolvePrimaryEnvironmentHttpUrl,
29} from "../environments/primary";
30
31const getSavedEnvironmentSecretMock = vi.fn();
32const relayClientInstallDialogHarness = vi.hoisted(() => ({
33 requestConfirmation: vi.fn(),
34 reportProgress: vi.fn(),
35 finish: vi.fn(),
36}));
37const getRelayClientStatusMock = vi.fn();
38const installRelayClientMock = vi.fn();
39const environmentConnectionMock = {
40 client: {
41 cloud: {
42 getRelayClientStatus: getRelayClientStatusMock,
43 installRelayClient: installRelayClientMock,
44 },
45 },
46};
47
48const createProofMock = vi.fn(
49 (_input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>
50 Effect.succeed("web-dpop-proof"),
51);
52const testDpopSignerLayer = Layer.succeed(
53 ManagedRelayDpopSigner,
54 ManagedRelayDpopSigner.of({
55 thumbprint: Effect.succeed("web-thumbprint"),
56 createProof: (input) => createProofMock(input),
57 }),
58);
59
60function cloudClientLayer() {
61 const httpClientLayer = remoteHttpClientLayer(globalThis.fetch);
62 return Layer.mergeAll(
63 httpClientLayer,
64 managedRelayClientLayer({
65 relayUrl: "https://relay.example.test",
66 clientId: RelayWebClientId,
67 }).pipe(Layer.provideMerge(testDpopSignerLayer), Layer.provide(httpClientLayer)),
68 );
69}
70
71const withCloudServices = <A, E>(
72 effect: Effect.Effect<A, E, HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner>,
73) => effect.pipe(Effect.provide(cloudClientLayer()));
74
75vi.mock("../localApi", () => ({
76 ensureLocalApi: () => ({
77 persistence: {
78 getSavedEnvironmentSecret: getSavedEnvironmentSecretMock,
79 },
80 }),
81}));
82
83vi.mock("./relayClientInstallDialog", () => ({
84 requestRelayClientInstallConfirmation: relayClientInstallDialogHarness.requestConfirmation,
85 reportRelayClientInstallProgress: relayClientInstallDialogHarness.reportProgress,
86 finishRelayClientInstall: relayClientInstallDialogHarness.finish,
87}));
88
89vi.mock("../environments/primary", () => ({
90 readPrimaryEnvironmentDescriptor: vi.fn(() => null),
91 readPrimaryEnvironmentTarget: vi.fn(() => null),
92 resolvePrimaryEnvironmentHttpUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
93}));
94
95vi.mock("../environments/runtime", () => ({
96 getPrimaryEnvironmentConnection: () => environmentConnectionMock,
97 readEnvironmentConnection: () => environmentConnectionMock,
98}));
99
100const savedEnvironment: SavedEnvironmentRecord = {
101 environmentId: EnvironmentId.make("env-1"),
102 label: "Desktop",
103 httpBaseUrl: "http://127.0.0.1:3000",
104 wsBaseUrl: "ws://127.0.0.1:3000",
105 createdAt: "2026-05-25T00:00:00.000Z",
106 lastConnectedAt: null,
107};
108
109function validProof() {
110 return "signed-environment-link-jwt";
111}
112
113function validChallenge() {
114 return {
115 challenge: "link-challenge",
116 expiresAt: "2026-05-25T00:05:00.000Z",
117 };
118}
119
120function availableRelayClient() {
121 return {
122 status: "available",
123 executablePath: "/Users/test/.t3/tools/cloudflared/cloudflared",
124 source: "managed",
125 version: "2026.5.2",
126 };
127}
128
129function requestBodyText(body: BodyInit | null | undefined): string {
130 return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");
131}
132
133describe("web cloud link environment client", () => {
134 afterEach(() => {
135 if ("window" in globalThis) {
136 Reflect.deleteProperty(window, "desktopBridge");
137 }
138 vi.unstubAllGlobals();
139 });
140
141 beforeEach(() => {
142 vi.restoreAllMocks();
143 vi.clearAllMocks();
144 createProofMock.mockClear();
145 vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");
146 getSavedEnvironmentSecretMock.mockResolvedValue("local-bearer");
147 relayClientInstallDialogHarness.requestConfirmation.mockResolvedValue(true);
148 getRelayClientStatusMock.mockResolvedValue(availableRelayClient());
149 installRelayClientMock.mockResolvedValue(availableRelayClient());
150 vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue(null);
151 vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue(null);
152 vi.mocked(resolvePrimaryEnvironmentHttpUrl).mockImplementation(
153 (path: string) => `http://127.0.0.1:3000${path}`,
154 );
155 });
156
157 it("normalizes configured relay base URLs before building relay requests", () => {
158 expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe(
159 "https://relay.example.test",
160 );
161 expect(normalizeRelayBaseUrl(" ")).toBeNull();
162 });
163
164 it.effect(
165 "installs the relay client over environment RPC before requesting a cloud challenge",
166 () =>
167 Effect.gen(function* () {
168 getRelayClientStatusMock.mockResolvedValue({
169 status: "missing",
170 version: "2026.5.2",
171 });
172 vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({
173 environmentId: EnvironmentId.make("env-1"),
174 label: "Desktop",
175 platform: { os: "darwin", arch: "arm64" },
176 serverVersion: "0.0.0-test",
177 capabilities: { repositoryIdentity: true },
178 });
179 vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue({
180 source: "desktop-managed",
181 target: {
182 httpBaseUrl: "http://127.0.0.1:3000",
183 wsBaseUrl: "ws://127.0.0.1:3000",
184 },
185 });
186 const fetchMock = vi
187 .fn()
188 .mockResolvedValueOnce(Response.json(validChallenge()))
189 .mockResolvedValueOnce(Response.json({ malformed: true }));
190 vi.stubGlobal("fetch", fetchMock);
191 installRelayClientMock.mockImplementationOnce(async (onProgress) => {
192 onProgress({ type: "progress", stage: "downloading" });
193 return availableRelayClient();
194 });
195
196 yield* withCloudServices(
197 linkPrimaryEnvironmentToCloud({
198 clerkToken: "clerk-token",
199 }),
200 ).pipe(Effect.flip);
201
202 expect(relayClientInstallDialogHarness.requestConfirmation).toHaveBeenCalledWith(
203 "2026.5.2",
204 );
205 expect(getRelayClientStatusMock).toHaveBeenCalledOnce();
206 expect(installRelayClientMock).toHaveBeenCalledOnce();
207 expect(relayClientInstallDialogHarness.reportProgress).toHaveBeenCalledWith({
208 type: "progress",
209 stage: "downloading",
210 });
211 expect(relayClientInstallDialogHarness.finish).toHaveBeenCalledOnce();
212 expect(installRelayClientMock.mock.invocationCallOrder[0]).toBeLessThan(
213 fetchMock.mock.invocationCallOrder[0]!,
214 );
215 expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
216 "https://relay.example.test/v1/client/environment-link-challenges",
217 );
218 }),
219 );
220
221 it.effect("lists relay-managed environments for hosted and served web clients", () =>
222 Effect.gen(function* () {
223 const fetchMock = vi.fn().mockResolvedValueOnce(
224 Response.json({
225 environments: [
226 {
227 environmentId: "env-1",
228 label: "Managed desktop",
229 endpoint: {
230 httpBaseUrl: "https://managed.example.test",
231 wsBaseUrl: "wss://managed.example.test",
232 providerKind: "cloudflare_tunnel",
233 },
234 linkedAt: "2026-05-25T00:00:00.000Z",
235 },
236 ],
237 }),
238 );
239 vi.stubGlobal("fetch", fetchMock);
240
241 const environments = yield* withCloudServices(
242 listManagedCloudEnvironments({ clerkToken: "clerk-token" }),
243 );
244 expect(environments).toHaveLength(1);
245 expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
246 "https://relay.example.test/v1/environments",
247 );
248 expect(fetchMock.mock.calls[0]?.[1]?.headers.authorization).toBe("Bearer clerk-token");
249 expect(fetchMock.mock.calls[0]?.[1]?.credentials).not.toBe("include");
250 }),
251 );
252
253 it.effect("connects web clients to managed environments with a tunnel-only DPoP token", () =>
254 Effect.gen(function* () {
255 const environment = {
256 environmentId: EnvironmentId.make("env-1"),
257 label: "Managed desktop",
258 endpoint: {
259 httpBaseUrl: "https://managed.example.test",
260 wsBaseUrl: "wss://managed.example.test",
261 providerKind: "cloudflare_tunnel" as const,
262 },
263 linkedAt: "2026-05-25T00:00:00.000Z",
264 };
265 const fetchMock = vi
266 .fn()
267 .mockResolvedValueOnce(
268 Response.json({
269 access_token: "relay-access-token",
270 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
271 token_type: "DPoP",
272 expires_in: 300,
273 scope: "environment:connect",
274 }),
275 )
276 .mockResolvedValueOnce(
277 Response.json({
278 environmentId: "env-1",
279 endpoint: environment.endpoint,
280 credential: "environment-bootstrap",
281 expiresAt: "2026-05-25T00:05:00.000Z",
282 }),
283 )
284 .mockResolvedValueOnce(
285 Response.json({
286 environmentId: "env-1",
287 label: "Managed desktop",
288 platform: { os: "darwin", arch: "arm64" },
289 serverVersion: "0.0.0-test",
290 capabilities: { repositoryIdentity: true },
291 }),
292 )
293 .mockResolvedValueOnce(
294 Response.json({
295 access_token: "environment-access-token",
296 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
297 token_type: "DPoP",
298 expires_in: 3600,
299 scope: "orchestration:read orchestration:operate terminal:operate review:write",
300 }),
301 );
302 vi.stubGlobal("fetch", fetchMock);
303
304 const connection = yield* withCloudServices(
305 connectManagedCloudEnvironment({ clerkToken: "clerk-token", environment }),
306 );
307 expect(connection).toMatchObject({
308 environmentId: "env-1",
309 accessToken: "environment-access-token",
310 });
311
312 const tokenBody = requestBodyText(fetchMock.mock.calls[0]?.[1]?.body);
313 expect(new URLSearchParams(tokenBody).get("client_id")).toBe("t3-web");
314 expect(new URLSearchParams(tokenBody).get("scope")).toBe("environment:connect");
315 expect(fetchMock.mock.calls[1]?.[1]?.headers.authorization).toBe("DPoP relay-access-token");
316 expect(fetchMock.mock.calls[1]?.[1]?.headers.dpop).toBe("web-dpop-proof");
317 expect(createProofMock).toHaveBeenCalledWith({
318 method: "POST",
319 url: "https://managed.example.test/oauth/token",
320 });
321 }),
322 );
323
324 it.effect("rejects a stored managed connection for another relay origin", () =>
325 Effect.gen(function* () {
326 const environment = {
327 environmentId: EnvironmentId.make("env-1"),
328 label: "Managed desktop",
329 endpoint: {
330 httpBaseUrl: "https://managed.example.test",
331 wsBaseUrl: "wss://managed.example.test",
332 providerKind: "cloudflare_tunnel" as const,
333 },
334 linkedAt: "2026-05-25T00:00:00.000Z",
335 };
336
337 const error = yield* withCloudServices(
338 connectManagedCloudEnvironment({
339 clerkToken: "clerk-token",
340 environment,
341 relayUrl: "https://old-relay.example.test",
342 }),
343 ).pipe(Effect.flip);
344 expect(error).toMatchObject({
345 message: "The saved environment is linked through a different configured relay.",
346 });
347 }),
348 );
349
350 it.effect("rejects malformed local environment link proofs", () =>
351 Effect.gen(function* () {
352 vi.stubGlobal(
353 "fetch",
354 vi
355 .fn()
356 .mockResolvedValueOnce(Response.json(validChallenge()))
357 .mockResolvedValueOnce(
358 Response.json({
359 payload: {
360 environmentId: "env-1",
361 },
362 signature: "signature-1",
363 }),
364 ),
365 );
366
367 const error = yield* withCloudServices(
368 linkEnvironmentToCloud({
369 environment: savedEnvironment,
370 clerkToken: "clerk-token",
371 }),
372 ).pipe(Effect.flip);
373 expect(error).toMatchObject({
374 _tag: "CloudEnvironmentLinkError",
375 message: "Could not obtain environment link proof.",
376 });
377 }),
378 );
379
380 it.effect("preserves typed local environment failures while obtaining a link proof", () =>
381 Effect.gen(function* () {
382 vi.stubGlobal(
383 "fetch",
384 vi
385 .fn()
386 .mockResolvedValueOnce(Response.json(validChallenge()))
387 .mockResolvedValueOnce(
388 Response.json(
389 {
390 _tag: "EnvironmentHttpUnauthorizedError",
391 message: "Invalid environment bearer session.",
392 },
393 { status: 401 },
394 ),
395 ),
396 );
397
398 const error = yield* withCloudServices(
399 linkEnvironmentToCloud({
400 environment: savedEnvironment,
401 clerkToken: "clerk-token",
402 }),
403 ).pipe(Effect.flip);
404 expect(error._tag).toBe("CloudEnvironmentLinkError");
405 expect(error.message).toBe(
406 "Could not obtain environment link proof: Invalid environment bearer session.",
407 );
408 }),
409 );
410
411 it.effect("rejects malformed relay environment link responses", () =>
412 Effect.gen(function* () {
413 vi.stubGlobal(
414 "fetch",
415 vi
416 .fn()
417 .mockResolvedValueOnce(Response.json(validChallenge()))
418 .mockResolvedValueOnce(Response.json(validProof()))
419 .mockResolvedValueOnce(
420 Response.json({
421 ok: true,
422 environmentId: "env-1",
423 endpoint: {
424 httpBaseUrl: "https://desktop.example.test",
425 wsBaseUrl: "wss://desktop.example.test",
426 providerKind: "cloudflare_tunnel",
427 },
428 endpointRuntime: null,
429 relayIssuer: "https://issuer.example.test",
430 cloudUserId: "user_123",
431 environmentCredential: "",
432 cloudMintPublicKey: "cloud-mint-public-key",
433 }),
434 ),
435 );
436
437 const error = yield* withCloudServices(
438 linkEnvironmentToCloud({
439 environment: savedEnvironment,
440 clerkToken: "clerk-token",
441 }),
442 ).pipe(Effect.flip);
443 expect(error).toMatchObject({
444 _tag: "CloudEnvironmentLinkError",
445 message: "https://relay.example.test/v1/client/environment-links failed",
446 });
447 }),
448 );
449
450 it.effect(
451 "links the primary local environment through the relay using the owner cookie session",
452 () =>
453 Effect.gen(function* () {
454 vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({
455 environmentId: EnvironmentId.make("env-1"),
456 label: "Desktop",
457 platform: { os: "darwin", arch: "arm64" },
458 serverVersion: "0.0.0-test",
459 capabilities: { repositoryIdentity: true },
460 });
461 vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue({
462 source: "desktop-managed",
463 target: {
464 httpBaseUrl: "http://127.0.0.1:3000",
465 wsBaseUrl: "ws://127.0.0.1:3000",
466 },
467 });
468 vi.mocked(resolvePrimaryEnvironmentHttpUrl).mockImplementation(
469 (path: string) => `http://127.0.0.1:3000${path}`,
470 );
471
472 const fetchMock = vi
473 .fn()
474 .mockResolvedValueOnce(Response.json(validChallenge()))
475 .mockResolvedValueOnce(Response.json(validProof()))
476 .mockResolvedValueOnce(
477 Response.json({
478 ok: true,
479 environmentId: "env-1",
480 endpoint: {
481 httpBaseUrl: "https://desktop.example.test",
482 wsBaseUrl: "wss://desktop.example.test",
483 providerKind: "cloudflare_tunnel",
484 },
485 endpointRuntime: {
486 providerKind: "cloudflare_tunnel",
487 connectorToken: "connector-token",
488 tunnelId: "tunnel-id",
489 tunnelName: "tunnel-name",
490 },
491 relayIssuer: "https://issuer.example.test",
492 cloudUserId: "user_123",
493 environmentCredential: "t3env_test_credential",
494 cloudMintPublicKey: "cloud-mint-public-key",
495 }),
496 )
497 .mockResolvedValueOnce(
498 Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
499 );
500 vi.stubGlobal("fetch", fetchMock);
501
502 yield* withCloudServices(
503 linkPrimaryEnvironmentToCloud({
504 clerkToken: "clerk-token",
505 }),
506 );
507
508 expect(getRelayClientStatusMock).toHaveBeenCalledOnce();
509 expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
510 "https://relay.example.test/v1/client/environment-link-challenges",
511 );
512 expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");
513 expect(fetchMock.mock.calls[0]?.[1]?.headers.authorization).toBe("Bearer clerk-token");
514 expect(fetchMock.mock.calls[0]?.[1]?.credentials).not.toBe("include");
515
516 expect(String(fetchMock.mock.calls[1]?.[0])).toBe(
517 "http://127.0.0.1:3000/api/connect/link-proof",
518 );
519 expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({
520 method: "POST",
521 credentials: "include",
522 headers: expect.objectContaining({
523 "content-type": "application/json",
524 }),
525 });
526 // @effect-diagnostics-next-line preferSchemaOverJson:off
527 expect(JSON.parse(requestBodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
528 challenge: "link-challenge",
529 endpoint: {
530 httpBaseUrl: "http://127.0.0.1:3000",
531 wsBaseUrl: "ws://127.0.0.1:3000",
532 providerKind: "cloudflare_tunnel",
533 },
534 origin: {
535 localHttpHost: "127.0.0.1",
536 localHttpPort: 3000,
537 },
538 });
539
540 expect(String(fetchMock.mock.calls[2]?.[0])).toBe(
541 "https://relay.example.test/v1/client/environment-links",
542 );
543 expect(fetchMock.mock.calls[2]?.[1]?.method).toBe("POST");
544 expect(fetchMock.mock.calls[2]?.[1]?.headers.authorization).toBe("Bearer clerk-token");
545 expect(fetchMock.mock.calls[2]?.[1]?.credentials).not.toBe("include");
546 expect(fetchMock.mock.calls[2]?.[1]?.headers["content-type"]).toBe("application/json");
547 // @effect-diagnostics-next-line preferSchemaOverJson:off
548 expect(JSON.parse(requestBodyText(fetchMock.mock.calls[2]?.[1]?.body))).toMatchObject({
549 proof: validProof(),
550 notificationsEnabled: true,
551 liveActivitiesEnabled: true,
552 managedTunnelsEnabled: true,
553 });
554
555 expect(String(fetchMock.mock.calls[3]?.[0])).toBe(
556 "http://127.0.0.1:3000/api/connect/relay-config",
557 );
558 expect(fetchMock.mock.calls[3]?.[1]).toMatchObject({
559 method: "POST",
560 credentials: "include",
561 headers: expect.objectContaining({
562 "content-type": "application/json",
563 }),
564 });
565 // @effect-diagnostics-next-line preferSchemaOverJson:off
566 expect(JSON.parse(requestBodyText(fetchMock.mock.calls[3]?.[1]?.body))).toMatchObject({
567 relayUrl: "https://relay.example.test",
568 relayIssuer: "https://issuer.example.test",
569 cloudUserId: "user_123",
570 environmentCredential: "t3env_test_credential",
571 cloudMintPublicKey: "cloud-mint-public-key",
572 endpointRuntime: {
573 providerKind: "cloudflare_tunnel",
574 connectorToken: "connector-token",
575 tunnelId: "tunnel-id",
576 tunnelName: "tunnel-name",
577 },
578 });
579 }),
580 );
581
582 it.effect("reads the primary local cloud link state with the owner cookie session", () =>
583 Effect.gen(function* () {
584 vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({
585 environmentId: EnvironmentId.make("env-1"),
586 label: "Desktop",
587 platform: { os: "darwin", arch: "arm64" },
588 serverVersion: "0.0.0-test",
589 capabilities: { repositoryIdentity: true },
590 });
591 vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue({
592 source: "desktop-managed",
593 target: {
594 httpBaseUrl: "http://127.0.0.1:3000",
595 wsBaseUrl: "ws://127.0.0.1:3000",
596 },
597 });
598 const fetchMock = vi.fn().mockResolvedValueOnce(
599 Response.json({
600 linked: true,
601 cloudUserId: "user_123",
602 relayUrl: "https://relay.example.test",
603 relayIssuer: "https://issuer.example.test",
604 publishAgentActivity: false,
605 }),
606 );
607 vi.stubGlobal("fetch", fetchMock);
608
609 const state = yield* withCloudServices(readPrimaryCloudLinkState());
610 expect(state).toEqual({
611 linked: true,
612 cloudUserId: "user_123",
613 relayUrl: "https://relay.example.test",
614 relayIssuer: "https://issuer.example.test",
615 publishAgentActivity: false,
616 });
617 expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
618 "http://127.0.0.1:3000/api/connect/link-state",
619 );
620 expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
621 method: "GET",
622 credentials: "include",
623 });
624 }),
625 );
626
627 it.effect("clears local relay credentials before revoking the primary cloud link", () =>
628 Effect.gen(function* () {
629 vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({
630 environmentId: EnvironmentId.make("env-1"),
631 label: "Desktop",
632 platform: { os: "darwin", arch: "arm64" },
633 serverVersion: "0.0.0-test",
634 capabilities: { repositoryIdentity: true },
635 });
636 vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue({
637 source: "desktop-managed",
638 target: {
639 httpBaseUrl: "http://127.0.0.1:3000",
640 wsBaseUrl: "ws://127.0.0.1:3000",
641 },
642 });
643 const fetchMock = vi
644 .fn()
645 .mockResolvedValueOnce(
646 Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
647 )
648 .mockResolvedValueOnce(Response.json({ ok: true }));
649 vi.stubGlobal("fetch", fetchMock);
650
651 yield* withCloudServices(
652 unlinkPrimaryEnvironmentFromCloud({
653 clerkToken: "clerk-token",
654 }),
655 );
656
657 expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
658 expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
659 method: "POST",
660 credentials: "include",
661 });
662 expect(String(fetchMock.mock.calls[1]?.[0])).toBe(
663 "https://relay.example.test/v1/client/environment-links/env-1",
664 );
665 expect(fetchMock.mock.calls[1]?.[1]?.method).toBe("DELETE");
666 expect(fetchMock.mock.calls[1]?.[1]?.headers.authorization).toBe("Bearer clerk-token");
667 }),
668 );
669
670 it.effect("still clears local relay credentials when relay revocation fails", () =>
671 Effect.gen(function* () {
672 vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({
673 environmentId: EnvironmentId.make("env-1"),
674 label: "Desktop",
675 platform: { os: "darwin", arch: "arm64" },
676 serverVersion: "0.0.0-test",
677 capabilities: { repositoryIdentity: true },
678 });
679 vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue({
680 source: "desktop-managed",
681 target: {
682 httpBaseUrl: "http://127.0.0.1:3000",
683 wsBaseUrl: "ws://127.0.0.1:3000",
684 },
685 });
686 const fetchMock = vi
687 .fn()
688 .mockResolvedValueOnce(
689 Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
690 )
691 .mockResolvedValueOnce(Response.json({ error: "unavailable" }, { status: 503 }));
692 vi.stubGlobal("fetch", fetchMock);
693
694 yield* withCloudServices(
695 unlinkPrimaryEnvironmentFromCloud({
696 clerkToken: "clerk-token",
697 }),
698 );
699
700 expect(fetchMock).toHaveBeenCalledTimes(2);
701 expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
702 expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
703 method: "POST",
704 credentials: "include",
705 });
706 }),
707 );
708
709 it.effect("rejects primary environment linking when the local environment is not ready", () =>
710 Effect.gen(function* () {
711 vi.stubGlobal("fetch", vi.fn());
712
713 const error = yield* withCloudServices(
714 linkPrimaryEnvironmentToCloud({
715 clerkToken: "clerk-token",
716 }),
717 ).pipe(Effect.flip);
718 expect(error).toMatchObject({
719 _tag: "CloudEnvironmentLinkError",
720 message: "Local environment is not ready yet.",
721 });
722 expect(fetch).not.toHaveBeenCalled();
723 }),
724 );
725
726 it.effect("preserves relay transport failures while linking environments", () =>
727 Effect.gen(function* () {
728 vi.stubGlobal(
729 "fetch",
730 vi
731 .fn()
732 .mockResolvedValueOnce(Response.json(validChallenge()))
733 .mockResolvedValueOnce(Response.json(validProof()))
734 .mockResolvedValueOnce(Response.json({ error: "unavailable" }, { status: 503 })),
735 );
736
737 const error = yield* withCloudServices(
738 linkEnvironmentToCloud({
739 environment: savedEnvironment,
740 clerkToken: "clerk-token",
741 }),
742 ).pipe(Effect.flip);
743 expect(error).toMatchObject({
744 _tag: "CloudEnvironmentLinkError",
745 message: "https://relay.example.test/v1/client/environment-links failed",
746 });
747 }),
748 );
749
750 it.effect("preserves typed relay error bodies while linking environments", () =>
751 Effect.gen(function* () {
752 vi.stubGlobal(
753 "fetch",
754 vi
755 .fn()
756 .mockResolvedValueOnce(Response.json(validChallenge()))
757 .mockResolvedValueOnce(Response.json(validProof()))
758 .mockResolvedValueOnce(
759 Response.json(
760 {
761 _tag: "RelayEnvironmentLinkProofInvalidError",
762 code: "environment_link_proof_invalid",
763 reason: "origin_not_allowed",
764 traceId: "trace-test",
765 },
766 { status: 400 },
767 ),
768 ),
769 );
770
771 const error = yield* withCloudServices(
772 linkEnvironmentToCloud({
773 environment: savedEnvironment,
774 clerkToken: "clerk-token",
775 }),
776 ).pipe(Effect.flip);
777 expect(error).toMatchObject({
778 _tag: "CloudEnvironmentLinkError",
779 message:
780 "https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).",
781 });
782 }),
783 );
784
785 it.effect("rejects relay credentials for a different environment", () =>
786 Effect.gen(function* () {
787 const fetchMock = vi
788 .fn()
789 .mockResolvedValueOnce(Response.json(validChallenge()))
790 .mockResolvedValueOnce(Response.json(validProof()))
791 .mockResolvedValueOnce(
792 Response.json({
793 ok: true,
794 environmentId: "env-2",
795 endpoint: {
796 httpBaseUrl: "https://desktop.example.test",
797 wsBaseUrl: "wss://desktop.example.test",
798 providerKind: "cloudflare_tunnel",
799 },
800 endpointRuntime: null,
801 relayIssuer: "https://issuer.example.test",
802 cloudUserId: "user_123",
803 environmentCredential: "t3env_test_credential",
804 cloudMintPublicKey: "cloud-mint-public-key",
805 }),
806 );
807 vi.stubGlobal("fetch", fetchMock);
808
809 const error = yield* withCloudServices(
810 linkEnvironmentToCloud({
811 environment: savedEnvironment,
812 clerkToken: "clerk-token",
813 }),
814 ).pipe(Effect.flip);
815 expect(error).toMatchObject({
816 _tag: "CloudEnvironmentLinkError",
817 message: "Relay returned credentials for a different environment.",
818 });
819 expect(fetchMock).toHaveBeenCalledTimes(3);
820 }),
821 );
822
823 it.effect("rejects relay credentials for a different managed endpoint provider", () =>
824 Effect.gen(function* () {
825 const fetchMock = vi
826 .fn()
827 .mockResolvedValueOnce(Response.json(validChallenge()))
828 .mockResolvedValueOnce(Response.json(validProof()))
829 .mockResolvedValueOnce(
830 Response.json({
831 ok: true,
832 environmentId: "env-1",
833 endpoint: {
834 httpBaseUrl: "https://desktop.example.test",
835 wsBaseUrl: "wss://desktop.example.test",
836 providerKind: "manual",
837 },
838 endpointRuntime: null,
839 relayIssuer: "https://issuer.example.test",
840 cloudUserId: "user_123",
841 environmentCredential: "t3env_test_credential",
842 cloudMintPublicKey: "cloud-mint-public-key",
843 }),
844 );
845 vi.stubGlobal("fetch", fetchMock);
846
847 const error = yield* withCloudServices(
848 linkEnvironmentToCloud({
849 environment: savedEnvironment,
850 clerkToken: "clerk-token",
851 }),
852 ).pipe(Effect.flip);
853 expect(error).toMatchObject({
854 _tag: "CloudEnvironmentLinkError",
855 message: "Relay returned credentials for a different endpoint provider.",
856 });
857 expect(fetchMock).toHaveBeenCalledTimes(3);
858 }),
859 );
860
861 it.effect("passes the relay issuer from the link response into local relay config", () =>
862 Effect.gen(function* () {
863 const fetchMock = vi
864 .fn()
865 .mockResolvedValueOnce(Response.json(validChallenge()))
866 .mockResolvedValueOnce(Response.json(validProof()))
867 .mockResolvedValueOnce(
868 Response.json({
869 ok: true,
870 environmentId: "env-1",
871 endpoint: {
872 httpBaseUrl: "https://desktop.example.test",
873 wsBaseUrl: "wss://desktop.example.test",
874 providerKind: "cloudflare_tunnel",
875 },
876 endpointRuntime: null,
877 relayIssuer: "https://issuer.example.test",
878 cloudUserId: "user_123",
879 environmentCredential: "t3env_test_credential",
880 cloudMintPublicKey: "cloud-mint-public-key",
881 }),
882 )
883 .mockResolvedValueOnce(
884 Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
885 );
886 vi.stubGlobal("fetch", fetchMock);
887
888 yield* withCloudServices(
889 linkEnvironmentToCloud({
890 environment: savedEnvironment,
891 clerkToken: "clerk-token",
892 }),
893 );
894
895 // @effect-diagnostics-next-line preferSchemaOverJson:off
896 expect(JSON.parse(requestBodyText(fetchMock.mock.calls[3]?.[1]?.body))).toMatchObject({
897 relayUrl: "https://relay.example.test",
898 relayIssuer: "https://issuer.example.test",
899 cloudUserId: "user_123",
900 });
901 }),
902 );
903});