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

linkEnvironment.test.ts

1,271 lines43.6 KB

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