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 { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
9import { HttpClient } from "effect/http";
10
11import * as MobileStorage from "../../persistence/mobile-storage";
12
13import { linkEnvironmentToCloudWithPreference } from "./linkEnvironment";
14
15vi.mock("expo-constants", () => ({
16 default: {
17 expoConfig: {
18 extra: {
19 relay: {
20 url: "https://relay.example.test",
21 },
22 },
23 },
24 },
25}));
26
27vi.mock("expo-device", () => ({
28 deviceType: 1,
29 DeviceType: {
30 UNKNOWN: 0,
31 PHONE: 1,
32 TABLET: 2,
33 DESKTOP: 3,
34 TV: 4,
35 },
36 osVersion: "18.4.1",
37 modelName: "iPhone 15 Pro",
38}));
39
40vi.mock("react-native", () => ({
41 Platform: {
42 OS: "ios",
43 },
44}));
45
46vi.mock("expo-secure-store", () => ({
47 deleteItemAsync: vi.fn(),
48 getItemAsync: vi.fn(),
49 setItemAsync: vi.fn(),
50}));
51
52const savedConnection = {
53 environmentId: EnvironmentId.make("env-1"),
54 environmentLabel: "Desktop",
55 pairingUrl: "https://desktop.example.test/",
56 displayUrl: "https://desktop.example.test/",
57 httpBaseUrl: "https://desktop.example.test/",
58 wsBaseUrl: "wss://desktop.example.test/ws",
59 bearerToken: "local-bearer",
60};
61
62const createProofMock = vi.fn(
63 (input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>
64 Effect.succeed(`dpop:${input.method}:${input.url}`),
65);
66const layerTestDpopSigner = Layer.succeed(
67 ManagedRelay.ManagedRelayDpopSigner,
68 ManagedRelay.ManagedRelayDpopSigner.of({
69 thumbprint: Effect.succeed("client-proof-key-thumbprint"),
70 createProof: (input) => createProofMock(input),
71 }),
72);
73
74function layerCloudClient() {
75 const layerHttpClient = layerRemoteHttpClient((input, init) => globalThis.fetch(input, init));
76 return Layer.mergeAll(
77 layerHttpClient,
78 Layer.succeed(
79 MobileStorage.MobileStorage,
80 MobileStorage.MobileStorage.of({
81 loadSavedConnections: Effect.succeed([]),
82 saveConnection: () => Effect.void,
83 clearSavedConnection: () => Effect.void,
84 loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),
85 loadAgentAwarenessDeviceId: Effect.succeed("device-1"),
86 loadAgentAwarenessRegistrationRecord: Effect.succeed(null),
87 saveAgentAwarenessRegistrationRecord: () => Effect.void,
88 clearAgentAwarenessRegistrationRecord: Effect.void,
89 loadRecentThreadShortcuts: Effect.succeed([]),
90 saveRecentThreadShortcuts: () => Effect.void,
91 }),
92 ),
93 ManagedRelay.layer({
94 relayUrl: "https://relay.example.test",
95 clientId: RelayMobileClientId,
96 }).pipe(Layer.provideMerge(layerTestDpopSigner), Layer.provide(layerHttpClient)),
97 );
98}
99
100const withCloudServices = <A, E>(
101 effect: Effect.Effect<
102 A,
103 E,
104 | HttpClient.HttpClient
105 | ManagedRelay.ManagedRelayClient
106 | ManagedRelay.ManagedRelayDpopSigner
107 | MobileStorage.MobileStorage
108 >,
109) => effect.pipe(Effect.provide(layerCloudClient()));
110
111function validLinkProof() {
112 return "signed-environment-link-jwt";
113}
114
115function validLinkResponse(environmentId = "env-1") {
116 return {
117 ok: true,
118 environmentId,
119 endpoint: {
120 httpBaseUrl: "https://managed.example.test/",
121 wsBaseUrl: "wss://managed.example.test/ws",
122 providerKind: "cloudflare_tunnel",
123 },
124 endpointRuntime: {
125 providerKind: "cloudflare_tunnel",
126 connectorToken: "connector-token",
127 },
128 relayIssuer: "https://relay.example.test",
129 cloudUserId: "user_123",
130 environmentCredential: "environment-credential",
131 cloudMintPublicKey: "cloud-mint-public-key",
132 };
133}
134
135function validLinkChallengeResponse() {
136 return {
137 challenge: "link-challenge",
138 expiresAt: "2026-05-25T00:05:00.000Z",
139 };
140}
141
142function requestBodyText(body: BodyInit | null | undefined): string {
143 return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");
144}
145
146describe("mobile cloud link environment client", () => {
147 beforeEach(() => {
148 vi.restoreAllMocks();
149 createProofMock.mockClear();
150 });
151
152 it.effect(
153 "rejects relay link credentials for a different environment before persisting relay config",
154 () =>
155 Effect.gen(function* () {
156 const fetchMock = vi.fn((url: string | URL) => {
157 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
158 return Promise.resolve(Response.json(validLinkChallengeResponse()));
159 }
160 if (String(url).endsWith("/api/connect/link-proof")) {
161 return Promise.resolve(Response.json(validLinkProof()));
162 }
163 return Promise.resolve(Response.json(validLinkResponse("env-other")));
164 });
165 vi.stubGlobal("fetch", fetchMock);
166
167 const error = yield* withCloudServices(
168 linkEnvironmentToCloudWithPreference({
169 clerkToken: "clerk-token",
170 connection: savedConnection,
171 liveActivitiesEnabled: true,
172 }),
173 ).pipe(Effect.flip);
174 expect(error).toMatchObject({
175 _tag: "CloudEnvironmentLinkError",
176 message: "Relay returned credentials for a different environment.",
177 });
178 expect(fetchMock).toHaveBeenCalledTimes(3);
179 }),
180 );
181
182 it.effect("rejects relay link credentials for a different managed endpoint provider", () =>
183 Effect.gen(function* () {
184 const fetchMock = vi.fn((url: string | URL) => {
185 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
186 return Promise.resolve(Response.json(validLinkChallengeResponse()));
187 }
188 if (String(url).endsWith("/api/connect/link-proof")) {
189 return Promise.resolve(Response.json(validLinkProof()));
190 }
191 return Promise.resolve(
192 Response.json({
193 ...validLinkResponse(),
194 endpoint: {
195 ...validLinkResponse().endpoint,
196 providerKind: "manual",
197 },
198 }),
199 );
200 });
201 vi.stubGlobal("fetch", fetchMock);
202
203 const error = yield* withCloudServices(
204 linkEnvironmentToCloudWithPreference({
205 clerkToken: "clerk-token",
206 connection: savedConnection,
207 liveActivitiesEnabled: true,
208 }),
209 ).pipe(Effect.flip);
210 expect(error).toMatchObject({
211 _tag: "CloudEnvironmentLinkError",
212 message: "Relay returned credentials for a different endpoint provider.",
213 });
214 expect(fetchMock).toHaveBeenCalledTimes(3);
215 }),
216 );
217
218 it.effect("preserves disabled Live Activity preferences when linking an environment", () =>
219 Effect.gen(function* () {
220 const bodies: Array<unknown> = [];
221 const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {
222 if (init?.body) {
223 bodies.push(JSON.parse(requestBodyText(init.body)));
224 }
225 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
226 return Promise.resolve(Response.json(validLinkChallengeResponse()));
227 }
228 if (String(url).endsWith("/api/connect/link-proof")) {
229 return Promise.resolve(Response.json(validLinkProof()));
230 }
231 if (String(url).endsWith("/v1/client/environment-links")) {
232 return Promise.resolve(Response.json(validLinkResponse()));
233 }
234 return Promise.resolve(
235 Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
236 );
237 });
238 vi.stubGlobal("fetch", fetchMock);
239
240 yield* withCloudServices(
241 linkEnvironmentToCloudWithPreference({
242 clerkToken: "clerk-token",
243 connection: savedConnection,
244 liveActivitiesEnabled: false,
245 }),
246 );
247
248 expect(bodies[1]).toMatchObject({
249 endpoint: {
250 httpBaseUrl: "https://desktop.example.test/",
251 wsBaseUrl: "wss://desktop.example.test/ws",
252 providerKind: "cloudflare_tunnel",
253 },
254 origin: {
255 localHttpHost: "127.0.0.1",
256 localHttpPort: 443,
257 },
258 });
259 expect(bodies[2]).toMatchObject({
260 deviceId: "device-1",
261 notificationsEnabled: true,
262 liveActivitiesEnabled: false,
263 managedTunnelsEnabled: true,
264 });
265 expect(bodies[3]).toMatchObject({
266 cloudUserId: "user_123",
267 environmentCredential: "environment-credential",
268 });
269 }),
270 );
271});