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

linkEnvironment.test.ts

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