Open History to see the last commit
1import { beforeEach, vi } from "vite-plus/test";
2import { describe, expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import { EnvironmentId } from "@t3tools/contracts";
6import { RelayMobileClientId } from "@t3tools/contracts/relay";
7import { ManagedRelay } from "@t3tools/client-runtime/relay";
8import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
9import { HttpClient } from "effect/unstable/http";
10import { MobilePreferencesStore } from "../../persistence/mobile-preferences";
11import { MobileStorage } from "../../persistence/mobile-storage";
12
13import {
14 cloudEnvironmentsPendingStatus,
15 linkEnvironmentToCloud,
16 linkEnvironmentToCloudWithPreference,
17 connectCloudEnvironment,
18 listCloudEnvironments,
19 listCloudEnvironmentsWithStatus,
20 normalizeRelayBaseUrl,
21 refreshCloudEnvironmentConnection,
22} from "./linkEnvironment";
23
24vi.mock("expo-constants", () => ({
25 default: {
26 expoConfig: {
27 extra: {
28 relay: {
29 url: "https://relay.example.test",
30 },
31 },
32 },
33 },
34}));
35
36vi.mock("react-native", () => ({
37 Platform: {
38 OS: "ios",
39 },
40}));
41
42vi.mock("expo-secure-store", () => ({
43 deleteItemAsync: vi.fn(),
44 getItemAsync: vi.fn(),
45 setItemAsync: vi.fn(),
46}));
47
48const loadPreferences = vi.fn(() => Effect.succeed({}));
49
50const savedConnection = {
51 environmentId: EnvironmentId.make("env-1"),
52 environmentLabel: "Desktop",
53 pairingUrl: "https://desktop.example.test/",
54 displayUrl: "https://desktop.example.test/",
55 httpBaseUrl: "https://desktop.example.test/",
56 wsBaseUrl: "wss://desktop.example.test/ws",
57 bearerToken: "local-bearer",
58};
59
60const stableClerkToken = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1c2VyXzEyMyJ9.test";
61
62const createProofMock = vi.fn(
63 (input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>
64 Effect.succeed(`dpop:${input.method}:${input.url}`),
65);
66const testDpopSignerLayer = Layer.succeed(
67 ManagedRelay.ManagedRelayDpopSigner,
68 ManagedRelay.ManagedRelayDpopSigner.of({
69 thumbprint: Effect.succeed("client-proof-key-thumbprint"),
70 createProof: (input) => createProofMock(input),
71 }),
72);
73
74function cloudClientLayer() {
75 const httpClientLayer = remoteHttpClientLayer((input, init) => globalThis.fetch(input, init));
76 return Layer.mergeAll(
77 httpClientLayer,
78 Layer.succeed(
79 MobilePreferencesStore,
80 MobilePreferencesStore.of({
81 load: loadPreferences(),
82 savePatch: (patch) => Effect.succeed(patch),
83 update: () => Effect.succeed({}),
84 }),
85 ),
86 Layer.succeed(
87 MobileStorage,
88 MobileStorage.of({
89 loadSavedConnections: Effect.succeed([]),
90 saveConnection: () => Effect.void,
91 clearSavedConnection: () => Effect.void,
92 loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),
93 loadAgentAwarenessDeviceId: Effect.succeed("device-1"),
94 loadAgentAwarenessRegistrationRecord: Effect.succeed(null),
95 saveAgentAwarenessRegistrationRecord: () => Effect.void,
96 clearAgentAwarenessRegistrationRecord: Effect.void,
97 loadRecentThreadShortcuts: Effect.succeed([]),
98 saveRecentThreadShortcuts: () => Effect.void,
99 }),
100 ),
101 ManagedRelay.layer({
102 relayUrl: "https://relay.example.test",
103 clientId: RelayMobileClientId,
104 }).pipe(Layer.provideMerge(testDpopSignerLayer), Layer.provide(httpClientLayer)),
105 );
106}
107
108const withCloudServices = <A, E>(
109 effect: Effect.Effect<
110 A,
111 E,
112 | HttpClient.HttpClient
113 | ManagedRelay.ManagedRelayClient
114 | ManagedRelay.ManagedRelayDpopSigner
115 | MobilePreferencesStore
116 | MobileStorage
117 >,
118) => effect.pipe(Effect.provide(cloudClientLayer()));
119
120function validLinkProof() {
121 return "signed-environment-link-jwt";
122}
123
124function validLinkResponse(environmentId = "env-1") {
125 return {
126 ok: true,
127 environmentId,
128 endpoint: {
129 httpBaseUrl: "https://managed.example.test/",
130 wsBaseUrl: "wss://managed.example.test/ws",
131 providerKind: "cloudflare_tunnel",
132 },
133 endpointRuntime: {
134 providerKind: "cloudflare_tunnel",
135 connectorToken: "connector-token",
136 },
137 relayIssuer: "https://relay.example.test",
138 cloudUserId: "user_123",
139 environmentCredential: "environment-credential",
140 cloudMintPublicKey: "cloud-mint-public-key",
141 };
142}
143
144function validLinkChallengeResponse() {
145 return {
146 challenge: "link-challenge",
147 expiresAt: "2026-05-25T00:05:00.000Z",
148 };
149}
150
151function requestBodyText(body: BodyInit | null | undefined): string {
152 return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");
153}
154
155function validDpopAccessTokenResponse(scope = "environment:status environment:connect") {
156 return {
157 access_token: "relay-dpop-token",
158 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
159 token_type: "DPoP",
160 expires_in: 300,
161 scope,
162 };
163}
164
165function listedEnvironment(environmentId: string) {
166 return {
167 environmentId: EnvironmentId.make(environmentId),
168 label: "Desktop",
169 endpoint: {
170 httpBaseUrl: `https://${environmentId}.example.test/`,
171 wsBaseUrl: `wss://${environmentId}.example.test/ws`,
172 providerKind: "cloudflare_tunnel" as const,
173 },
174 linkedAt: "2026-05-25T00:00:00.000Z",
175 };
176}
177
178describe("mobile cloud link environment client", () => {
179 beforeEach(() => {
180 vi.restoreAllMocks();
181 createProofMock.mockClear();
182 loadPreferences.mockClear();
183 });
184
185 it("normalizes configured relay base URLs before building DPoP-bound requests", () => {
186 expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe(
187 "https://relay.example.test",
188 );
189 expect(normalizeRelayBaseUrl(" ")).toBeNull();
190 });
191
192 it("makes linked environments visible while their status is still loading", () => {
193 expect(cloudEnvironmentsPendingStatus([listedEnvironment("env-1")])).toMatchObject([
194 {
195 environment: { environmentId: "env-1", label: "Desktop" },
196 status: null,
197 statusError: "Checking status...",
198 },
199 ]);
200 });
201
202 it.effect("decodes relay environment list responses before returning records", () =>
203 Effect.gen(function* () {
204 vi.stubGlobal(
205 "fetch",
206 vi.fn(() =>
207 Promise.resolve(
208 Response.json({
209 environments: [
210 {
211 environmentId: "env-1",
212 label: "Desktop",
213 endpoint: {
214 httpBaseUrl: "https://desktop.example.test/",
215 wsBaseUrl: "wss://desktop.example.test/ws",
216 providerKind: "cloudflare_tunnel",
217 },
218 linkedAt: "2026-05-25T00:00:00.000Z",
219 },
220 ],
221 }),
222 ),
223 ),
224 );
225
226 const records = yield* withCloudServices(
227 listCloudEnvironments({ clerkToken: "clerk-token" }),
228 );
229 expect(records).toEqual([
230 {
231 environmentId: "env-1",
232 label: "Desktop",
233 endpoint: {
234 httpBaseUrl: "https://desktop.example.test/",
235 wsBaseUrl: "wss://desktop.example.test/ws",
236 providerKind: "cloudflare_tunnel",
237 },
238 linkedAt: "2026-05-25T00:00:00.000Z",
239 },
240 ]);
241 }),
242 );
243
244 it.effect("rejects malformed relay environment list responses", () =>
245 Effect.gen(function* () {
246 vi.stubGlobal(
247 "fetch",
248 vi.fn(() =>
249 Promise.resolve(
250 Response.json({
251 environments: [
252 {
253 environmentId: "env-1",
254 label: "Desktop",
255 endpoint: {
256 httpBaseUrl: "",
257 wsBaseUrl: "wss://desktop.example.test/ws",
258 providerKind: "cloudflare_tunnel",
259 },
260 linkedAt: "2026-05-25T00:00:00.000Z",
261 },
262 ],
263 }),
264 ),
265 ),
266 );
267
268 const error = yield* withCloudServices(
269 listCloudEnvironments({ clerkToken: "clerk-token" }),
270 ).pipe(Effect.flip);
271 expect(error).toMatchObject({
272 _tag: "CloudEnvironmentLinkError",
273 message: "https://relay.example.test/v1/environments failed",
274 });
275 }),
276 );
277
278 it.effect("loads signed status for each advertised cloud environment", () =>
279 Effect.gen(function* () {
280 const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => {
281 if (String(url) === "https://relay.example.test/v1/environments") {
282 return Promise.resolve(
283 Response.json({
284 environments: [
285 {
286 environmentId: "env-1",
287 label: "Desktop",
288 endpoint: {
289 httpBaseUrl: "https://desktop.example.test/",
290 wsBaseUrl: "wss://desktop.example.test/ws",
291 providerKind: "cloudflare_tunnel",
292 },
293 linkedAt: "2026-05-25T00:00:00.000Z",
294 },
295 ],
296 }),
297 );
298 }
299 if (String(url) === "https://relay.example.test/v1/client/dpop-token") {
300 return Promise.resolve(Response.json(validDpopAccessTokenResponse()));
301 }
302 expect(String(url)).toBe("https://relay.example.test/v1/environments/env-1/status");
303 return Promise.resolve(
304 Response.json({
305 environmentId: "env-1",
306 endpoint: {
307 httpBaseUrl: "https://desktop.example.test/",
308 wsBaseUrl: "wss://desktop.example.test/ws",
309 providerKind: "cloudflare_tunnel",
310 },
311 status: "online",
312 checkedAt: "2026-05-25T00:01:00.000Z",
313 descriptor: {
314 environmentId: "env-1",
315 label: "Desktop",
316 platform: { os: "darwin", arch: "arm64" },
317 serverVersion: "0.0.0-test",
318 capabilities: { repositoryIdentity: true },
319 },
320 }),
321 );
322 });
323 vi.stubGlobal("fetch", fetchMock);
324
325 const records = yield* withCloudServices(
326 listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }),
327 );
328 expect(records).toMatchObject([
329 {
330 environment: {
331 environmentId: "env-1",
332 label: "Desktop",
333 },
334 status: {
335 environmentId: "env-1",
336 status: "online",
337 checkedAt: "2026-05-25T00:01:00.000Z",
338 },
339 statusError: null,
340 },
341 ]);
342 expect(String(fetchMock.mock.calls[2]?.[0])).toBe(
343 "https://relay.example.test/v1/environments/env-1/status",
344 );
345 expect(fetchMock.mock.calls[2]?.[1]?.method).toBe("POST");
346 const statusHeaders = new Headers(fetchMock.mock.calls[2]?.[1]?.headers);
347 expect(statusHeaders.get("authorization")).toBe("DPoP relay-dpop-token");
348 expect(statusHeaders.get("dpop")).toBe(
349 "dpop:POST:https://relay.example.test/v1/environments/env-1/status",
350 );
351 expect(createProofMock).toHaveBeenCalledWith({
352 method: "POST",
353 url: "https://relay.example.test/v1/environments/env-1/status",
354 accessToken: "relay-dpop-token",
355 });
356 }),
357 );
358
359 it.effect("reuses one valid DPoP access token while probing multiple environment statuses", () =>
360 Effect.gen(function* () {
361 const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => {
362 if (String(url).endsWith("/v1/environments")) {
363 return Promise.resolve(
364 Response.json({
365 environments: [listedEnvironment("env-1"), listedEnvironment("env-2")],
366 }),
367 );
368 }
369 if (String(url).endsWith("/v1/client/dpop-token")) {
370 return Promise.resolve(Response.json(validDpopAccessTokenResponse()));
371 }
372 const environmentId = String(url).includes("/env-1/") ? "env-1" : "env-2";
373 return Promise.resolve(
374 Response.json({
375 environmentId,
376 endpoint: listedEnvironment(environmentId).endpoint,
377 status: "online",
378 checkedAt: "2026-05-25T00:01:00.000Z",
379 descriptor: {
380 environmentId,
381 label: "Desktop",
382 platform: { os: "darwin", arch: "arm64" },
383 serverVersion: "0.0.0-test",
384 capabilities: { repositoryIdentity: true },
385 },
386 }),
387 );
388 });
389 vi.stubGlobal("fetch", fetchMock);
390
391 yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: stableClerkToken }));
392
393 expect(
394 fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")),
395 ).toHaveLength(1);
396 }),
397 );
398
399 it.effect("reuses the status-and-connect token when connecting from the cloud list", () =>
400 Effect.gen(function* () {
401 const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => {
402 if (String(url).endsWith("/v1/environments")) {
403 return Promise.resolve(
404 Response.json({
405 environments: [listedEnvironment("env-1")],
406 }),
407 );
408 }
409 if (String(url).endsWith("/v1/client/dpop-token")) {
410 return Promise.resolve(Response.json(validDpopAccessTokenResponse()));
411 }
412 if (String(url).endsWith("/status")) {
413 return Promise.resolve(
414 Response.json({
415 environmentId: "env-1",
416 endpoint: listedEnvironment("env-1").endpoint,
417 status: "online",
418 checkedAt: "2026-05-25T00:01:00.000Z",
419 descriptor: {
420 environmentId: "env-1",
421 label: "Desktop",
422 platform: { os: "darwin", arch: "arm64" },
423 serverVersion: "0.0.0-test",
424 capabilities: { repositoryIdentity: true },
425 },
426 }),
427 );
428 }
429 if (String(url).endsWith("/connect")) {
430 return Promise.resolve(
431 Response.json({
432 environmentId: "env-1",
433 endpoint: listedEnvironment("env-1").endpoint,
434 credential: "one-time-cloud-credential",
435 expiresAt: "2026-05-25T00:05:00.000Z",
436 }),
437 );
438 }
439 if (String(url).endsWith("/.well-known/t3/environment")) {
440 return Promise.resolve(
441 Response.json({
442 environmentId: "env-1",
443 label: "Desktop",
444 platform: { os: "darwin", arch: "arm64" },
445 serverVersion: "0.0.0-test",
446 capabilities: { repositoryIdentity: true },
447 }),
448 );
449 }
450 return Promise.resolve(
451 Response.json({
452 access_token: "environment-dpop-token",
453 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
454 token_type: "DPoP",
455 expires_in: 3600,
456 scope: "orchestration:read orchestration:operate terminal:operate review:write",
457 }),
458 );
459 });
460 vi.stubGlobal("fetch", fetchMock);
461
462 yield* withCloudServices(
463 Effect.gen(function* () {
464 const records = yield* listCloudEnvironmentsWithStatus({
465 clerkToken: stableClerkToken,
466 });
467 yield* connectCloudEnvironment({
468 clerkToken: stableClerkToken,
469 environment: records[0]!.environment,
470 });
471 }),
472 );
473
474 expect(
475 fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")),
476 ).toHaveLength(1);
477 const exchangeRequest = fetchMock.mock.calls.find(([url]) =>
478 String(url).endsWith("/v1/client/dpop-token"),
479 )?.[1];
480 expect(new URLSearchParams(requestBodyText(exchangeRequest?.body)).get("scope")).toBe(
481 "environment:status environment:connect",
482 );
483 const environmentTokenRequest = fetchMock.mock.calls.find(([url]) =>
484 String(url).endsWith("/oauth/token"),
485 )?.[1];
486 const environmentTokenBody = new URLSearchParams(
487 requestBodyText(environmentTokenRequest?.body),
488 );
489 expect(environmentTokenBody.get("client_label")).toBe("T3 Code Mobile");
490 expect(environmentTokenBody.get("client_device_type")).toBe("mobile");
491 expect(environmentTokenBody.get("client_os")).toBe("iOS");
492 }),
493 );
494
495 it.effect("keeps advertised environments visible when status probing fails", () =>
496 Effect.gen(function* () {
497 vi.stubGlobal(
498 "fetch",
499 vi.fn((url: string | URL) => {
500 if (String(url) === "https://relay.example.test/v1/environments") {
501 return Promise.resolve(
502 Response.json({
503 environments: [
504 {
505 environmentId: "env-1",
506 label: "Desktop",
507 endpoint: {
508 httpBaseUrl: "https://desktop.example.test/",
509 wsBaseUrl: "wss://desktop.example.test/ws",
510 providerKind: "cloudflare_tunnel",
511 },
512 linkedAt: "2026-05-25T00:00:00.000Z",
513 },
514 ],
515 }),
516 );
517 }
518 if (String(url) === "https://relay.example.test/v1/client/dpop-token") {
519 return Promise.resolve(Response.json(validDpopAccessTokenResponse()));
520 }
521 return Promise.resolve(Response.json({ error: "offline" }, { status: 503 }));
522 }),
523 );
524
525 const records = yield* withCloudServices(
526 listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }),
527 );
528 expect(records).toMatchObject([
529 {
530 environment: {
531 environmentId: "env-1",
532 label: "Desktop",
533 },
534 status: null,
535 statusError: "https://relay.example.test/v1/environments/env-1/status failed",
536 },
537 ]);
538 }),
539 );
540
541 it.effect("rejects status responses for a different advertised environment", () =>
542 Effect.gen(function* () {
543 vi.stubGlobal(
544 "fetch",
545 vi.fn((url: string | URL) => {
546 if (String(url) === "https://relay.example.test/v1/environments") {
547 return Promise.resolve(
548 Response.json({
549 environments: [
550 {
551 environmentId: "env-1",
552 label: "Desktop",
553 endpoint: {
554 httpBaseUrl: "https://desktop.example.test/",
555 wsBaseUrl: "wss://desktop.example.test/ws",
556 providerKind: "cloudflare_tunnel",
557 },
558 linkedAt: "2026-05-25T00:00:00.000Z",
559 },
560 ],
561 }),
562 );
563 }
564 if (String(url) === "https://relay.example.test/v1/client/dpop-token") {
565 return Promise.resolve(Response.json(validDpopAccessTokenResponse()));
566 }
567 return Promise.resolve(
568 Response.json({
569 environmentId: "env-other",
570 endpoint: {
571 httpBaseUrl: "https://desktop.example.test/",
572 wsBaseUrl: "wss://desktop.example.test/ws",
573 providerKind: "cloudflare_tunnel",
574 },
575 status: "online",
576 checkedAt: "2026-05-25T00:01:00.000Z",
577 descriptor: {
578 environmentId: "env-other",
579 label: "Other Desktop",
580 platform: { os: "darwin", arch: "arm64" },
581 serverVersion: "0.0.0-test",
582 capabilities: { repositoryIdentity: true },
583 },
584 }),
585 );
586 }),
587 );
588
589 const records = yield* withCloudServices(
590 listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }),
591 );
592 expect(records).toMatchObject([
593 {
594 environment: {
595 environmentId: "env-1",
596 label: "Desktop",
597 },
598 status: null,
599 statusError: "Relay returned status for a different environment.",
600 },
601 ]);
602 }),
603 );
604
605 it.effect(
606 "rejects relay link credentials for a different environment before persisting relay config",
607 () =>
608 Effect.gen(function* () {
609 const fetchMock = vi.fn((url: string | URL) => {
610 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
611 return Promise.resolve(Response.json(validLinkChallengeResponse()));
612 }
613 if (String(url).endsWith("/api/connect/link-proof")) {
614 return Promise.resolve(Response.json(validLinkProof()));
615 }
616 return Promise.resolve(Response.json(validLinkResponse("env-other")));
617 });
618 vi.stubGlobal("fetch", fetchMock);
619
620 const error = yield* withCloudServices(
621 linkEnvironmentToCloud({
622 clerkToken: "clerk-token",
623 connection: savedConnection,
624 }),
625 ).pipe(Effect.flip);
626 expect(error).toMatchObject({
627 _tag: "CloudEnvironmentLinkError",
628 message: "Relay returned credentials for a different environment.",
629 });
630 expect(fetchMock).toHaveBeenCalledTimes(3);
631 }),
632 );
633
634 it.effect("preserves typed local environment failures while obtaining a link proof", () =>
635 Effect.gen(function* () {
636 const fetchMock = vi.fn((url: string | URL) => {
637 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
638 return Promise.resolve(Response.json(validLinkChallengeResponse()));
639 }
640 return Promise.resolve(
641 Response.json(
642 {
643 _tag: "EnvironmentHttpUnauthorizedError",
644 message: "Invalid environment bearer session.",
645 },
646 { status: 401 },
647 ),
648 );
649 });
650 vi.stubGlobal("fetch", fetchMock);
651
652 const error = yield* withCloudServices(
653 linkEnvironmentToCloud({
654 clerkToken: "clerk-token",
655 connection: savedConnection,
656 }),
657 ).pipe(Effect.flip);
658 expect(error._tag).toBe("CloudEnvironmentLinkError");
659 expect(error.message).toBe(
660 "Could not obtain environment link proof: Invalid environment bearer session.",
661 );
662 expect(fetchMock).toHaveBeenCalledTimes(2);
663 }),
664 );
665
666 it.effect("preserves typed relay error bodies while linking environments", () =>
667 Effect.gen(function* () {
668 const fetchMock = vi.fn((url: string | URL) => {
669 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
670 return Promise.resolve(Response.json(validLinkChallengeResponse()));
671 }
672 if (String(url).endsWith("/api/connect/link-proof")) {
673 return Promise.resolve(Response.json(validLinkProof()));
674 }
675 return Promise.resolve(
676 Response.json(
677 {
678 _tag: "RelayEnvironmentLinkProofInvalidError",
679 code: "environment_link_proof_invalid",
680 reason: "origin_not_allowed",
681 traceId: "trace-test",
682 },
683 { status: 400 },
684 ),
685 );
686 });
687 vi.stubGlobal("fetch", fetchMock);
688
689 const error = yield* withCloudServices(
690 linkEnvironmentToCloud({
691 clerkToken: "clerk-token",
692 connection: savedConnection,
693 }),
694 ).pipe(Effect.flip);
695 expect(error).toMatchObject({
696 _tag: "CloudEnvironmentLinkError",
697 message:
698 "https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).",
699 traceId: "trace-test",
700 });
701 expect(fetchMock).toHaveBeenCalledTimes(3);
702 }),
703 );
704
705 it.effect("rejects relay link credentials for a different managed endpoint provider", () =>
706 Effect.gen(function* () {
707 const fetchMock = vi.fn((url: string | URL) => {
708 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
709 return Promise.resolve(Response.json(validLinkChallengeResponse()));
710 }
711 if (String(url).endsWith("/api/connect/link-proof")) {
712 return Promise.resolve(Response.json(validLinkProof()));
713 }
714 return Promise.resolve(
715 Response.json({
716 ...validLinkResponse(),
717 endpoint: {
718 ...validLinkResponse().endpoint,
719 providerKind: "manual",
720 },
721 }),
722 );
723 });
724 vi.stubGlobal("fetch", fetchMock);
725
726 const error = yield* withCloudServices(
727 linkEnvironmentToCloud({
728 clerkToken: "clerk-token",
729 connection: savedConnection,
730 }),
731 ).pipe(Effect.flip);
732 expect(error).toMatchObject({
733 _tag: "CloudEnvironmentLinkError",
734 message: "Relay returned credentials for a different endpoint provider.",
735 });
736 expect(fetchMock).toHaveBeenCalledTimes(3);
737 }),
738 );
739
740 it.effect("preserves disabled Live Activity preferences when linking an environment", () =>
741 Effect.gen(function* () {
742 loadPreferences.mockReturnValueOnce(Effect.succeed({ liveActivitiesEnabled: false }));
743 const bodies: Array<unknown> = [];
744 const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {
745 if (init?.body) {
746 // @effect-diagnostics-next-line preferSchemaOverJson:off
747 bodies.push(JSON.parse(requestBodyText(init.body)));
748 }
749 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
750 return Promise.resolve(Response.json(validLinkChallengeResponse()));
751 }
752 if (String(url).endsWith("/api/connect/link-proof")) {
753 return Promise.resolve(Response.json(validLinkProof()));
754 }
755 if (String(url).endsWith("/v1/client/environment-links")) {
756 return Promise.resolve(Response.json(validLinkResponse()));
757 }
758 return Promise.resolve(
759 Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
760 );
761 });
762 vi.stubGlobal("fetch", fetchMock);
763
764 yield* withCloudServices(
765 linkEnvironmentToCloud({
766 clerkToken: "clerk-token",
767 connection: savedConnection,
768 }),
769 );
770
771 expect(bodies[1]).toMatchObject({
772 endpoint: {
773 httpBaseUrl: "https://desktop.example.test/",
774 wsBaseUrl: "wss://desktop.example.test/ws",
775 providerKind: "cloudflare_tunnel",
776 },
777 origin: {
778 localHttpHost: "127.0.0.1",
779 localHttpPort: 443,
780 },
781 });
782 expect(bodies[2]).toMatchObject({
783 deviceId: "device-1",
784 notificationsEnabled: true,
785 liveActivitiesEnabled: false,
786 managedTunnelsEnabled: true,
787 });
788 expect(bodies[3]).toMatchObject({
789 cloudUserId: "user_123",
790 environmentCredential: "environment-credential",
791 });
792 }),
793 );
794
795 it.effect("uses an explicit Live Activity preference when persisted state is unavailable", () =>
796 Effect.gen(function* () {
797 loadPreferences.mockReturnValueOnce(Effect.die("persisted preferences must not be read"));
798 const bodies: Array<Record<string, unknown>> = [];
799 const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {
800 if (init?.body) {
801 // @effect-diagnostics-next-line preferSchemaOverJson:off
802 bodies.push(JSON.parse(requestBodyText(init.body)) as Record<string, unknown>);
803 }
804 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
805 return Promise.resolve(Response.json(validLinkChallengeResponse()));
806 }
807 if (String(url).endsWith("/api/connect/link-proof")) {
808 return Promise.resolve(Response.json(validLinkProof()));
809 }
810 if (String(url).endsWith("/v1/client/environment-links")) {
811 return Promise.resolve(Response.json(validLinkResponse()));
812 }
813 return Promise.resolve(
814 Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
815 );
816 });
817 vi.stubGlobal("fetch", fetchMock);
818
819 yield* withCloudServices(
820 linkEnvironmentToCloudWithPreference({
821 clerkToken: "clerk-token",
822 connection: savedConnection,
823 liveActivitiesEnabled: true,
824 }),
825 );
826
827 expect(bodies.filter((body) => "liveActivitiesEnabled" in body)).toEqual([
828 expect.objectContaining({ liveActivitiesEnabled: true }),
829 expect.objectContaining({ liveActivitiesEnabled: true }),
830 ]);
831 }),
832 );
833
834 it.effect(
835 "does not persist cloud connect bootstrap credentials in saved connection records",
836 () =>
837 Effect.gen(function* () {
838 let connectRequestBody = "";
839 const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {
840 if (String(url).endsWith("/v1/client/dpop-token")) {
841 return Promise.resolve(
842 Response.json(validDpopAccessTokenResponse("environment:connect")),
843 );
844 }
845 if (String(url).endsWith("/.well-known/t3/environment")) {
846 return Promise.resolve(
847 Response.json({
848 environmentId: "env-1",
849 label: "Desktop",
850 platform: { os: "darwin", arch: "arm64" },
851 serverVersion: "0.0.0-test",
852 capabilities: { repositoryIdentity: true },
853 }),
854 );
855 }
856 if (String(url).endsWith("/oauth/token")) {
857 return Promise.resolve(
858 Response.json({
859 access_token: "environment-dpop-token",
860 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
861 token_type: "DPoP",
862 expires_in: 3600,
863 scope: "orchestration:read orchestration:operate terminal:operate review:write",
864 }),
865 );
866 }
867 connectRequestBody = requestBodyText(init?.body);
868 return Promise.resolve(
869 Response.json({
870 environmentId: "env-1",
871 endpoint: {
872 httpBaseUrl: "https://desktop.example.test/",
873 wsBaseUrl: "wss://desktop.example.test/ws",
874 providerKind: "cloudflare_tunnel",
875 },
876 credential: "one-time-cloud-credential",
877 expiresAt: "2026-05-25T00:05:00.000Z",
878 }),
879 );
880 });
881 vi.stubGlobal("fetch", fetchMock);
882
883 const connection = yield* withCloudServices(
884 connectCloudEnvironment({
885 clerkToken: "clerk-token",
886 environment: {
887 environmentId: EnvironmentId.make("env-1"),
888 label: "Desktop",
889 endpoint: {
890 httpBaseUrl: "https://desktop.example.test/",
891 wsBaseUrl: "wss://desktop.example.test/ws",
892 providerKind: "cloudflare_tunnel",
893 },
894 linkedAt: "2026-05-25T00:00:00.000Z",
895 },
896 }),
897 );
898
899 expect(connection.pairingUrl).toBe("https://desktop.example.test/");
900 expect(connection.pairingUrl).not.toContain("one-time-cloud-credential");
901 expect(connection.bearerToken).toBeNull();
902 expect(connection.authenticationMethod).toBe("dpop");
903 expect(connection.dpopAccessToken).toBe("environment-dpop-token");
904 expect(connection.relayManaged).toBe(true);
905 // @effect-diagnostics-next-line preferSchemaOverJson:off
906 expect(JSON.parse(connectRequestBody)).toMatchObject({
907 deviceId: "device-1",
908 clientKeyThumbprint: "client-proof-key-thumbprint",
909 });
910 expect(createProofMock).toHaveBeenCalledWith({
911 method: "POST",
912 url: "https://relay.example.test/v1/environments/env-1/connect",
913 accessToken: "relay-dpop-token",
914 });
915 expect(createProofMock).toHaveBeenCalledWith({
916 method: "POST",
917 url: "https://desktop.example.test/oauth/token",
918 });
919 }),
920 );
921
922 it.effect("refreshes a saved environment against a rotated managed endpoint", () =>
923 Effect.gen(function* () {
924 vi.stubGlobal(
925 "fetch",
926 vi.fn((url: string | URL) => {
927 if (String(url).endsWith("/v1/client/dpop-token")) {
928 return Promise.resolve(
929 Response.json(validDpopAccessTokenResponse("environment:connect")),
930 );
931 }
932 if (String(url).endsWith("/.well-known/t3/environment")) {
933 return Promise.resolve(
934 Response.json({
935 environmentId: "env-1",
936 label: "Rotated Desktop",
937 platform: { os: "darwin", arch: "arm64" },
938 serverVersion: "0.0.0-test",
939 capabilities: { repositoryIdentity: true },
940 }),
941 );
942 }
943 if (String(url).endsWith("/oauth/token")) {
944 return Promise.resolve(
945 Response.json({
946 access_token: "fresh-environment-dpop-token",
947 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
948 token_type: "DPoP",
949 expires_in: 3600,
950 scope: "orchestration:read orchestration:operate terminal:operate review:write",
951 }),
952 );
953 }
954 return Promise.resolve(
955 Response.json({
956 environmentId: "env-1",
957 endpoint: {
958 httpBaseUrl: "https://rotated-desktop.example.test/",
959 wsBaseUrl: "wss://rotated-desktop.example.test/ws",
960 providerKind: "cloudflare_tunnel",
961 },
962 credential: "rotated-one-time-cloud-credential",
963 expiresAt: "2026-05-25T00:05:00.000Z",
964 }),
965 );
966 }),
967 );
968
969 const connection = yield* withCloudServices(
970 refreshCloudEnvironmentConnection({
971 clerkToken: "clerk-token",
972 connection: {
973 environmentId: EnvironmentId.make("env-1"),
974 environmentLabel: "Desktop",
975 pairingUrl: "https://desktop.example.test/",
976 displayUrl: "https://desktop.example.test/",
977 httpBaseUrl: "https://desktop.example.test/",
978 wsBaseUrl: "wss://desktop.example.test/ws",
979 bearerToken: null,
980 authenticationMethod: "dpop",
981 relayManaged: true,
982 },
983 }),
984 );
985
986 expect(connection).toMatchObject({
987 environmentId: "env-1",
988 environmentLabel: "Rotated Desktop",
989 displayUrl: "https://rotated-desktop.example.test/",
990 httpBaseUrl: "https://rotated-desktop.example.test/",
991 wsBaseUrl: "wss://rotated-desktop.example.test/ws",
992 dpopAccessToken: "fresh-environment-dpop-token",
993 });
994 }),
995 );
996
997 it.effect("rejects relay connect responses for a different environment", () =>
998 Effect.gen(function* () {
999 vi.stubGlobal(
1000 "fetch",
1001 vi.fn((url: string | URL) =>
1002 Promise.resolve(
1003 String(url).endsWith("/v1/client/dpop-token")
1004 ? Response.json(validDpopAccessTokenResponse("environment:connect"))
1005 : Response.json({
1006 environmentId: "env-other",
1007 endpoint: {
1008 httpBaseUrl: "https://desktop.example.test/",
1009 wsBaseUrl: "wss://desktop.example.test/ws",
1010 providerKind: "cloudflare_tunnel",
1011 },
1012 credential: "one-time-cloud-credential",
1013 expiresAt: "2026-05-25T00:05:00.000Z",
1014 }),
1015 ),
1016 ),
1017 );
1018
1019 const error = yield* withCloudServices(
1020 connectCloudEnvironment({
1021 clerkToken: "clerk-token",
1022 environment: {
1023 environmentId: EnvironmentId.make("env-1"),
1024 label: "Desktop",
1025 endpoint: {
1026 httpBaseUrl: "https://desktop.example.test/",
1027 wsBaseUrl: "wss://desktop.example.test/ws",
1028 providerKind: "cloudflare_tunnel",
1029 },
1030 linkedAt: "2026-05-25T00:00:00.000Z",
1031 },
1032 }),
1033 ).pipe(Effect.flip);
1034 expect(error).toMatchObject({
1035 _tag: "CloudEnvironmentLinkError",
1036 message: "Relay returned credentials for a different environment.",
1037 });
1038 }),
1039 );
1040
1041 it.effect("preserves relay DPoP auth failures while connecting environments", () =>
1042 Effect.gen(function* () {
1043 vi.stubGlobal(
1044 "fetch",
1045 vi.fn((url: string | URL) =>
1046 Promise.resolve(
1047 String(url).endsWith("/v1/client/dpop-token")
1048 ? Response.json(validDpopAccessTokenResponse("environment:connect"))
1049 : Response.json(
1050 {
1051 _tag: "RelayAuthInvalidError",
1052 code: "auth_invalid",
1053 reason: "invalid_dpop",
1054 traceId: "trace-connect",
1055 },
1056 { status: 401 },
1057 ),
1058 ),
1059 ),
1060 );
1061
1062 const error = yield* withCloudServices(
1063 connectCloudEnvironment({
1064 clerkToken: "clerk-token",
1065 environment: {
1066 environmentId: EnvironmentId.make("env-1"),
1067 label: "Desktop",
1068 endpoint: {
1069 httpBaseUrl: "https://desktop.example.test/",
1070 wsBaseUrl: "wss://desktop.example.test/ws",
1071 providerKind: "cloudflare_tunnel",
1072 },
1073 linkedAt: "2026-05-25T00:00:00.000Z",
1074 },
1075 }),
1076 ).pipe(Effect.flip);
1077 expect(error).toMatchObject({
1078 _tag: "CloudEnvironmentLinkError",
1079 message:
1080 "https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.",
1081 traceId: "trace-connect",
1082 });
1083 }),
1084 );
1085
1086 it.effect("rejects relay connect responses for a different endpoint", () =>
1087 Effect.gen(function* () {
1088 vi.stubGlobal(
1089 "fetch",
1090 vi.fn((url: string | URL) =>
1091 Promise.resolve(
1092 String(url).endsWith("/v1/client/dpop-token")
1093 ? Response.json(validDpopAccessTokenResponse("environment:connect"))
1094 : Response.json({
1095 environmentId: "env-1",
1096 endpoint: {
1097 httpBaseUrl: "https://other-desktop.example.test/",
1098 wsBaseUrl: "wss://other-desktop.example.test/ws",
1099 providerKind: "cloudflare_tunnel",
1100 },
1101 credential: "one-time-cloud-credential",
1102 expiresAt: "2026-05-25T00:05:00.000Z",
1103 }),
1104 ),
1105 ),
1106 );
1107
1108 const error = yield* withCloudServices(
1109 connectCloudEnvironment({
1110 clerkToken: "clerk-token",
1111 environment: {
1112 environmentId: EnvironmentId.make("env-1"),
1113 label: "Desktop",
1114 endpoint: {
1115 httpBaseUrl: "https://desktop.example.test/",
1116 wsBaseUrl: "wss://desktop.example.test/ws",
1117 providerKind: "cloudflare_tunnel",
1118 },
1119 linkedAt: "2026-05-25T00:00:00.000Z",
1120 },
1121 }),
1122 ).pipe(Effect.flip);
1123 expect(error).toMatchObject({
1124 _tag: "CloudEnvironmentLinkError",
1125 message: "Relay returned credentials for a different endpoint.",
1126 });
1127 }),
1128 );
1129
1130 it.effect(
1131 "rejects managed endpoints whose descriptor does not match the selected environment",
1132 () =>
1133 Effect.gen(function* () {
1134 vi.stubGlobal(
1135 "fetch",
1136 vi.fn((url: string | URL) =>
1137 Promise.resolve(
1138 String(url).endsWith("/v1/client/dpop-token")
1139 ? Response.json(validDpopAccessTokenResponse("environment:connect"))
1140 : String(url).endsWith("/.well-known/t3/environment")
1141 ? Response.json({
1142 environmentId: "env-other",
1143 label: "Other Desktop",
1144 platform: { os: "darwin", arch: "arm64" },
1145 serverVersion: "0.0.0-test",
1146 capabilities: { repositoryIdentity: true },
1147 })
1148 : Response.json({
1149 environmentId: "env-1",
1150 endpoint: {
1151 httpBaseUrl: "https://desktop.example.test/",
1152 wsBaseUrl: "wss://desktop.example.test/ws",
1153 providerKind: "cloudflare_tunnel",
1154 },
1155 credential: "one-time-cloud-credential",
1156 expiresAt: "2026-05-25T00:05:00.000Z",
1157 }),
1158 ),
1159 ),
1160 );
1161
1162 const error = yield* withCloudServices(
1163 connectCloudEnvironment({
1164 clerkToken: "clerk-token",
1165 environment: {
1166 environmentId: EnvironmentId.make("env-1"),
1167 label: "Desktop",
1168 endpoint: {
1169 httpBaseUrl: "https://desktop.example.test/",
1170 wsBaseUrl: "wss://desktop.example.test/ws",
1171 providerKind: "cloudflare_tunnel",
1172 },
1173 linkedAt: "2026-05-25T00:00:00.000Z",
1174 },
1175 }),
1176 ).pipe(Effect.flip);
1177 expect(error).toMatchObject({
1178 _tag: "CloudEnvironmentLinkError",
1179 message: "Connected endpoint descriptor does not match the selected environment.",
1180 });
1181 }),
1182 );
1183});