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

linkEnvironment.test.ts

343 lines11.2 KB

1import { beforeEach, vi } from "vite-plus/test";
2import { describe, expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as SubscriptionRef from "effect/SubscriptionRef";
6import * as Layer from "effect/Layer";
7import { EnvironmentId } from "@t3tools/contracts";
8import { RelayMobileClientId } from "@t3tools/contracts/relay";
9import {
10 EnvironmentSupervisor,
11 AVAILABLE_CONNECTION_STATE,
12 PrimaryConnectionTarget,
13 type PreparedConnection,
14} from "@t3tools/client-runtime/connection";
15import { ManagedRelay } from "@t3tools/client-runtime/relay";
16import { layerRemoteHttpClient, type RpcSession } from "@t3tools/client-runtime/rpc";
17import { HttpClient } from "effect/http";
18​
19import * as MobileStorage from "../../persistence/mobile-storage";
20​
21import {
22 linkEnvironmentToCloudWithPreference,
23 updateLinkedEnvironmentLiveActivityPreference,
24} from "./linkEnvironment";
25​
26vi.mock("expo-constants", () => ({
27 default: {
28 expoConfig: {
29 extra: {
30 relay: {
31 url: "https://relay.example.test",
32 },
33 },
34 },
35 },
36}));
37​
38vi.mock("expo-device", () => ({
39 deviceType: 1,
40 DeviceType: {
41 UNKNOWN: 0,
42 PHONE: 1,
43 TABLET: 2,
44 DESKTOP: 3,
45 TV: 4,
46 },
47 osVersion: "18.4.1",
48 modelName: "iPhone 15 Pro",
49}));
50​
51vi.mock("react-native", () => ({
52 Platform: {
53 OS: "ios",
54 },
55}));
56​
57vi.mock("expo-secure-store", () => ({
58 deleteItemAsync: vi.fn(),
59 getItemAsync: vi.fn(),
60 setItemAsync: vi.fn(),
61}));
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 createProofMock = vi.fn(
74 (input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>
75 Effect.succeed(`dpop:${input.method}:${input.url}`),
76);
77const layerTestDpopSigner = Layer.succeed(
78 ManagedRelay.ManagedRelayDpopSigner,
79 ManagedRelay.ManagedRelayDpopSigner.of({
80 thumbprint: Effect.succeed("client-proof-key-thumbprint"),
81 createProof: (input) => createProofMock(input),
82 }),
83);
84​
85function layerCloudClient() {
86 const layerHttpClient = layerRemoteHttpClient((input, init) => globalThis.fetch(input, init));
87 return Layer.mergeAll(
88 layerHttpClient,
89 Layer.succeed(
90 MobileStorage.MobileStorage,
91 MobileStorage.MobileStorage.of({
92 loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),
93 loadOrCreateAnalyticsDeviceId: Effect.succeed("analytics-device-1"),
94 loadAgentAwarenessDeviceId: Effect.succeed("device-1"),
95 loadAgentAwarenessRegistrationRecord: Effect.succeed(null),
96 saveAgentAwarenessRegistrationRecord: () => Effect.void,
97 clearAgentAwarenessRegistrationRecord: Effect.void,
98 loadRecentThreadShortcuts: Effect.succeed([]),
99 saveRecentThreadShortcuts: () => Effect.void,
100 }),
101 ),
102 ManagedRelay.layer({
103 relayUrl: "https://relay.example.test",
104 clientId: RelayMobileClientId,
105 }).pipe(Layer.provideMerge(layerTestDpopSigner), Layer.provide(layerHttpClient)),
106 );
108​
109const withCloudServices = <A, E>(
110 effect: Effect.Effect<
111 A,
112 E,
113 | HttpClient.HttpClient
114 | ManagedRelay.ManagedRelayClient
115 | ManagedRelay.ManagedRelayDpopSigner
116 | MobileStorage.MobileStorage
117 >,
118) => effect.pipe(Effect.provide(layerCloudClient()));
119​
120const linkedSupervisor = Effect.gen(function* () {
121 const target = new PrimaryConnectionTarget({
122 environmentId: savedConnection.environmentId,
123 label: savedConnection.environmentLabel,
124 httpBaseUrl: savedConnection.httpBaseUrl,
125 wsBaseUrl: savedConnection.wsBaseUrl,
126 });
127 return EnvironmentSupervisor.EnvironmentSupervisor.of({
128 target,
129 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
130 session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
131 prepared: yield* SubscriptionRef.make(
132 Option.some<PreparedConnection>({
133 environmentId: savedConnection.environmentId,
134 label: savedConnection.environmentLabel,
135 httpBaseUrl: savedConnection.httpBaseUrl,
136 socketUrl: savedConnection.wsBaseUrl,
137 httpAuthorization: { _tag: "Bearer", token: "local-bearer" },
138 target,
139 }),
140 ),
141 connect: Effect.void,
142 disconnect: Effect.void,
143 retryNow: Effect.void,
144 });
145});
146​
147const linkPreparedEnvironment = (liveActivitiesEnabled: boolean) =>
148 Effect.flatMap(linkedSupervisor, (supervisor) =>
149 withCloudServices(
150 linkEnvironmentToCloudWithPreference({
151 clerkToken: "clerk-token",
152 liveActivitiesEnabled,
153 }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)),
154 ),
155 );
156​
157function validLinkProof() {
158 return "signed-environment-link-jwt";
160​
161function validLinkResponse(environmentId = "env-1") {
162 return {
163 ok: true,
164 environmentId,
165 endpoint: {
166 httpBaseUrl: "https://desktop.example.test/",
167 wsBaseUrl: "wss://desktop.example.test/ws",
168 providerKind: "manual",
169 },
170 endpointRuntime: null,
171 relayIssuer: "https://relay.example.test",
172 cloudUserId: "user_123",
173 environmentCredential: "environment-credential",
174 cloudMintPublicKey: "cloud-mint-public-key",
175 };
177​
178function linkStateResponse() {
179 return {
180 linked: false,
181 cloudUserId: null,
182 relayUrl: null,
183 relayIssuer: null,
184 publishAgentActivity: true,
185 };
187​
188function validLinkChallengeResponse() {
189 return {
190 challenge: "link-challenge",
191 expiresAt: "2026-05-25T00:05:00.000Z",
192 };
194​
195function requestBodyText(body: BodyInit | null | undefined): string {
196 return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");
198​
199describe("mobile cloud link environment client", () => {
200 beforeEach(() => {
201 vi.restoreAllMocks();
202 createProofMock.mockClear();
203 });
204​
205 it.effect("skips Live Activity updates when the environment has no prepared connection", () =>
206 Effect.gen(function* () {
207 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
208 target: new PrimaryConnectionTarget({
209 environmentId: savedConnection.environmentId,
210 label: savedConnection.environmentLabel,
211 httpBaseUrl: savedConnection.httpBaseUrl,
212 wsBaseUrl: savedConnection.wsBaseUrl,
213 }),
214 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
215 session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
216 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
217 connect: Effect.void,
218 disconnect: Effect.void,
219 retryNow: Effect.void,
220 });
221 const result = yield* updateLinkedEnvironmentLiveActivityPreference(true).pipe(
222 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
223 Effect.provideService(
224 HttpClient.HttpClient,
225 HttpClient.make(() => Effect.die("unexpected HTTP request")),
226 ),
227 );
228 expect(result).toBe("disconnected");
229 }),
230 );
231​
232 it.effect(
233 "rejects relay link credentials for a different environment before persisting relay config",
234 () =>
235 Effect.gen(function* () {
236 const fetchMock = vi.fn((url: string | URL) => {
237 if (String(url).endsWith("/api/connect/preferences")) {
238 return Promise.resolve(Response.json(linkStateResponse()));
239 }
240 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
241 return Promise.resolve(Response.json(validLinkChallengeResponse()));
242 }
243 if (String(url).endsWith("/api/connect/link-proof")) {
244 return Promise.resolve(Response.json(validLinkProof()));
245 }
246 return Promise.resolve(Response.json(validLinkResponse("env-other")));
247 });
248 vi.stubGlobal("fetch", fetchMock);
249​
250 const error = yield* linkPreparedEnvironment(true).pipe(Effect.flip);
251 expect(error).toMatchObject({
252 _tag: "CloudEnvironmentLinkError",
253 message: "Relay returned credentials for a different environment.",
254 });
255 expect(fetchMock).toHaveBeenCalledTimes(4);
256 }),
257 );
258​
259 it.effect("rejects relay link credentials for a different managed endpoint provider", () =>
260 Effect.gen(function* () {
261 const fetchMock = vi.fn((url: string | URL) => {
262 if (String(url).endsWith("/api/connect/preferences")) {
263 return Promise.resolve(Response.json(linkStateResponse()));
264 }
265 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
266 return Promise.resolve(Response.json(validLinkChallengeResponse()));
267 }
268 if (String(url).endsWith("/api/connect/link-proof")) {
269 return Promise.resolve(Response.json(validLinkProof()));
270 }
271 return Promise.resolve(
272 Response.json({
273 ...validLinkResponse(),
274 endpoint: {
275 ...validLinkResponse().endpoint,
276 providerKind: "cloudflare_tunnel",
277 },
278 }),
279 );
280 });
281 vi.stubGlobal("fetch", fetchMock);
282​
283 const error = yield* linkPreparedEnvironment(true).pipe(Effect.flip);
284 expect(error).toMatchObject({
285 _tag: "CloudEnvironmentLinkError",
286 message: "Relay returned credentials for a different endpoint provider.",
287 });
288 expect(fetchMock).toHaveBeenCalledTimes(4);
289 }),
290 );
291​
292 it.effect("preserves disabled Live Activity preferences when linking an environment", () =>
293 Effect.gen(function* () {
294 const bodies: Array<unknown> = [];
295 const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {
296 if (init?.body) {
297 bodies.push(JSON.parse(requestBodyText(init.body)));
298 }
299 if (String(url).endsWith("/v1/client/environment-link-challenges")) {
300 return Promise.resolve(Response.json(validLinkChallengeResponse()));
301 }
302 if (String(url).endsWith("/api/connect/link-proof")) {
303 return Promise.resolve(Response.json(validLinkProof()));
304 }
305 if (String(url).endsWith("/v1/client/environment-links")) {
306 return Promise.resolve(Response.json(validLinkResponse()));
307 }
308 if (String(url).endsWith("/api/connect/preferences")) {
309 return Promise.resolve(Response.json(linkStateResponse()));
310 }
311 return Promise.resolve(
312 Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
313 );
314 });
315 vi.stubGlobal("fetch", fetchMock);
316​
317 yield* linkPreparedEnvironment(false);
318​
319 expect(bodies[0]).toEqual({ publishAgentActivity: true });
320 expect(bodies[2]).toMatchObject({
321 endpoint: {
322 httpBaseUrl: "https://desktop.example.test/",
323 wsBaseUrl: "wss://desktop.example.test/ws",
324 providerKind: "manual",
325 },
326 origin: {
327 localHttpHost: "127.0.0.1",
328 localHttpPort: 443,
329 },
330 });
331 expect(bodies[3]).toMatchObject({
332 deviceId: "device-1",
333 notificationsEnabled: true,
334 liveActivitiesEnabled: false,
335 managedTunnelsEnabled: false,
336 });
337 expect(bodies[4]).toMatchObject({
338 cloudUserId: "user_123",
339 environmentCredential: "environment-credential",
340 });
341 }),
342 );
343});