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