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