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