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

linkEnvironment.test.ts

395 lines13.1 KB

1import {
2 type DesktopBridge,
3 EnvironmentId,
4 type RelayClientInstallProgressEvent,
5 WS_METHODS,
6} from "@t3tools/contracts";
7import { RelayWebClientId } from "@t3tools/contracts/relay";
8import { describe, expect, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14import { HttpClient } from "effect/unstable/http";
15import { afterEach, beforeEach, vi } from "vite-plus/test";
16import {
17 AVAILABLE_CONNECTION_STATE,
18 EnvironmentSupervisor,
19 type PreparedConnection,
20 PrimaryConnectionTarget,
21} from "@t3tools/client-runtime/connection";
22import { type RpcSession } from "@t3tools/client-runtime/rpc";
23import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
24import { ManagedRelay } from "@t3tools/client-runtime/relay";
25import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
26import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
27​
28import {
29 linkPrimaryEnvironmentToCloud,
30 readPrimaryCloudLinkState,
31 type CloudLinkTarget,
32 unlinkPrimaryEnvironmentFromCloud,
33 updatePrimaryCloudPreferences,
34} from "./linkEnvironment";
35​
36const TARGET: CloudLinkTarget = {
37 environmentId: "environment-1",
38 label: "Desktop",
39 httpBaseUrl: "http://127.0.0.1:3000",
40 wsBaseUrl: "ws://127.0.0.1:3000",
41};
42​
43const relayClientInstallDialog = vi.hoisted(() => ({
44 requestConfirmation: vi.fn(),
45 reportProgress: vi.fn(),
46 finish: vi.fn(),
47}));
48​
49vi.mock("./relayClientInstallDialog", () => ({
50 requestRelayClientInstallConfirmation: relayClientInstallDialog.requestConfirmation,
51 reportRelayClientInstallProgress: relayClientInstallDialog.reportProgress,
52 finishRelayClientInstall: relayClientInstallDialog.finish,
53}));
54​
55const createProof = vi.fn(() => Effect.succeed("dpop-proof"));
56const dpopSignerLayer = Layer.succeed(
57 ManagedRelay.ManagedRelayDpopSigner,
58 ManagedRelay.ManagedRelayDpopSigner.of({
59 thumbprint: Effect.succeed("thumbprint"),
60 createProof,
61 }),
62);
63​
64function relayLayer() {
65 const http = remoteHttpClientLayer(globalThis.fetch);
66 return Layer.mergeAll(
67 http,
68 ManagedRelay.layer({
69 relayUrl: "https://relay.example.test",
70 clientId: RelayWebClientId,
71 }).pipe(Layer.provideMerge(dpopSignerLayer), Layer.provide(http)),
72 );
74​
75function registryLayer(options?: {
76 readonly status?: { readonly status: "available"; readonly version: string };
77 readonly installEvents?: ReadonlyArray<RelayClientInstallProgressEvent>;
78}) {
79 return Layer.effect(
80 EnvironmentRegistry,
81 Effect.gen(function* () {
82 const client = {
83 [WS_METHODS.cloudGetRelayClientStatus]: () =>
84 Effect.succeed(options?.status ?? { status: "available", version: "2026.6.0" }),
85 [WS_METHODS.cloudInstallRelayClient]: () =>
86 Stream.fromIterable(options?.installEvents ?? []),
87 } as unknown as RpcSession["client"];
88 const session: RpcSession = {
89 client,
90 initialConfig: Effect.never,
91 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
92 ready: Effect.void,
93 probe: Effect.void,
94 closed: Effect.never,
95 };
96 const target = new PrimaryConnectionTarget({
97 environmentId: EnvironmentId.make(TARGET.environmentId),
98 label: TARGET.label,
99 httpBaseUrl: TARGET.httpBaseUrl,
100 wsBaseUrl: TARGET.wsBaseUrl,
101 });
102 const supervisor = EnvironmentSupervisor.of({
103 target,
104 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
105 session: yield* SubscriptionRef.make(Option.some(session)),
106 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
107 connect: Effect.void,
108 disconnect: Effect.void,
109 retryNow: Effect.void,
110 } satisfies EnvironmentSupervisor["Service"]);
111 const registry = {
112 run: <A, E, R>(_environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>
113 Effect.provideService(effect, EnvironmentSupervisor, supervisor),
114 runStream: <A, E, R>(_environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>
115 Stream.provideService(stream, EnvironmentSupervisor, supervisor),
116 } as unknown as EnvironmentRegistry["Service"];
117 return EnvironmentRegistry.of(registry);
118 }),
119 );
121​
122function services(options?: Parameters<typeof registryLayer>[0]) {
123 return Layer.mergeAll(relayLayer(), registryLayer(options));
125​
126function withServices<A, E>(
127 effect: Effect.Effect<
128 A,
129 E,
130 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | EnvironmentRegistry
131 >,
132 options?: Parameters<typeof registryLayer>[0],
133) {
134 return effect.pipe(Effect.provide(services(options)));
136​
137function bodyText(body: BodyInit | null | undefined): string {
138 return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");
140​
141beforeEach(() => {
142 vi.clearAllMocks();
143 vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");
144 relayClientInstallDialog.requestConfirmation.mockResolvedValue(true);
145});
146​
147afterEach(() => {
148 __resetDesktopPrimaryAuthForTests();
149 vi.unstubAllGlobals();
150 vi.unstubAllEnvs();
151 vi.restoreAllMocks();
152});
153​
154describe("web cloud link environment client", () => {
155 it.effect("reads primary cloud link state from the explicit target", () =>
156 Effect.gen(function* () {
157 const fetchMock = vi.fn().mockResolvedValue(
158 Response.json({
159 linked: true,
160 cloudUserId: "user-1",
161 relayUrl: "https://relay.example.test",
162 relayIssuer: "https://relay.example.test",
163 managedTunnelActive: true,
164 publishAgentActivity: false,
165 }),
166 );
167 vi.stubGlobal("fetch", fetchMock);
168​
169 const state = yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
170​
171 expect(Option.fromNullishOr(state)).toEqual(
172 Option.some({
173 linked: true,
174 cloudUserId: "user-1",
175 relayUrl: "https://relay.example.test",
176 relayIssuer: "https://relay.example.test",
177 managedTunnelActive: true,
178 publishAgentActivity: false,
179 }),
180 );
181 expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
182 "http://127.0.0.1:3000/api/connect/link-state",
183 );
184 }),
185 );
186​
187 it.effect("uses desktop bearer auth for primary cloud link state", () =>
188 Effect.gen(function* () {
189 const fetchMock = vi.fn().mockResolvedValue(
190 Response.json({
191 linked: true,
192 cloudUserId: "user-1",
193 relayUrl: "https://relay.example.test",
194 relayIssuer: "https://relay.example.test",
195 managedTunnelActive: true,
196 publishAgentActivity: false,
197 }),
198 );
199 vi.stubGlobal("fetch", fetchMock);
200 vi.stubGlobal("window", {
201 location: { origin: "t3code://app" },
202 desktopBridge: {
203 getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
204 } as unknown as DesktopBridge,
205 });
206​
207 yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
208​
209 const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
210 expect(request.credentials).not.toBe("include");
211 expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
212 }),
213 );
214​
215 it.effect("updates agent activity publishing for the explicit primary target", () =>
216 Effect.gen(function* () {
217 const fetchMock = vi.fn().mockResolvedValue(
218 Response.json({
219 linked: true,
220 cloudUserId: "user-1",
221 relayUrl: "https://relay.example.test",
222 relayIssuer: "https://relay.example.test",
223 managedTunnelActive: true,
224 publishAgentActivity: true,
225 }),
226 );
227 vi.stubGlobal("fetch", fetchMock);
228​
229 const state = yield* withServices(
230 updatePrimaryCloudPreferences({
231 target: TARGET,
232 publishAgentActivity: true,
233 }),
234 );
235​
236 expect(state.publishAgentActivity).toBe(true);
237 expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
238 "http://127.0.0.1:3000/api/connect/preferences",
239 );
240 expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");
241 // @effect-diagnostics-next-line preferSchemaOverJson:off
242 expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
243 publishAgentActivity: true,
244 });
245 }),
246 );
247​
248 it.effect("links an available primary environment without invoking installation", () =>
249 Effect.gen(function* () {
250 const fetchMock = vi
251 .fn()
252 .mockResolvedValueOnce(
253 Response.json({
254 challenge: "challenge",
255 expiresAt: "2026-06-06T00:05:00.000Z",
256 }),
257 )
258 .mockResolvedValueOnce(Response.json("signed-proof"))
259 .mockResolvedValueOnce(
260 Response.json({
261 ok: true,
262 environmentId: TARGET.environmentId,
263 endpoint: {
264 httpBaseUrl: "https://desktop.example.test",
265 wsBaseUrl: "wss://desktop.example.test",
266 providerKind: "cloudflare_tunnel",
267 },
268 endpointRuntime: null,
269 relayIssuer: "https://relay.example.test",
270 cloudUserId: "user-1",
271 environmentCredential: "environment-credential",
272 cloudMintPublicKey: "public-key",
273 }),
274 )
275 .mockResolvedValueOnce(
276 Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
277 );
278 vi.stubGlobal("fetch", fetchMock);
279​
280 yield* withServices(
281 linkPrimaryEnvironmentToCloud({
282 target: TARGET,
283 clerkToken: "clerk-token",
284 }),
285 );
286​
287 expect(relayClientInstallDialog.requestConfirmation).not.toHaveBeenCalled();
288 expect(String(fetchMock.mock.calls[1]?.[0])).toBe(
289 "http://127.0.0.1:3000/api/connect/link-proof",
290 );
291 // @effect-diagnostics-next-line preferSchemaOverJson:off
292 expect(JSON.parse(bodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
293 challenge: "challenge",
294 endpoint: {
295 httpBaseUrl: TARGET.httpBaseUrl,
296 wsBaseUrl: TARGET.wsBaseUrl,
297 },
298 });
299 }),
300 );
301​
302 it.effect("links publish-only without a managed tunnel", () =>
303 Effect.gen(function* () {
304 const fetchMock = vi
305 .fn()
306 .mockResolvedValueOnce(
307 Response.json({
308 challenge: "challenge",
309 expiresAt: "2026-06-06T00:05:00.000Z",
310 }),
311 )
312 .mockResolvedValueOnce(Response.json("signed-proof"))
313 .mockResolvedValueOnce(
314 Response.json({
315 ok: true,
316 environmentId: TARGET.environmentId,
317 endpoint: {
318 httpBaseUrl: TARGET.httpBaseUrl,
319 wsBaseUrl: TARGET.wsBaseUrl,
320 providerKind: "manual",
321 },
322 endpointRuntime: null,
323 relayIssuer: "https://relay.example.test",
324 cloudUserId: "user-1",
325 environmentCredential: "environment-credential",
326 cloudMintPublicKey: "public-key",
327 }),
328 )
329 .mockResolvedValueOnce(
330 Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
331 );
332 vi.stubGlobal("fetch", fetchMock);
333​
334 yield* withServices(
335 linkPrimaryEnvironmentToCloud({
336 target: TARGET,
337 clerkToken: "clerk-token",
338 mode: "publish_only",
339 }),
340 );
341​
342 // @effect-diagnostics-next-line preferSchemaOverJson:off
343 expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({
344 managedTunnelsEnabled: false,
345 });
346 // @effect-diagnostics-next-line preferSchemaOverJson:off
347 expect(JSON.parse(bodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
348 endpoint: { providerKind: "manual" },
349 });
350 }),
351 );
352​
353 it.effect("installs a missing relay client before linking", () =>
354 Effect.gen(function* () {
355 vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ malformed: true })));
356​
357 yield* withServices(
358 linkPrimaryEnvironmentToCloud({
359 target: TARGET,
360 clerkToken: "clerk-token",
361 }),
362 {
363 status: { status: "available", version: "2026.6.0" },
364 installEvents: [],
365 },
366 ).pipe(Effect.flip);
367​
368 expect(relayClientInstallDialog.requestConfirmation).not.toHaveBeenCalled();
369 }),
370 );
371​
372 it.effect("unlinks locally before revoking the relay record", () =>
373 Effect.gen(function* () {
374 const fetchMock = vi
375 .fn()
376 .mockResolvedValueOnce(
377 Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),
378 )
379 .mockResolvedValueOnce(Response.json({ ok: true }));
380 vi.stubGlobal("fetch", fetchMock);
381​
382 yield* withServices(
383 unlinkPrimaryEnvironmentFromCloud({
384 target: TARGET,
385 clerkToken: "clerk-token",
386 }),
387 );
388​
389 expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
390 expect(String(fetchMock.mock.calls[1]?.[0])).toContain(
391 `/v1/client/environment-links/${TARGET.environmentId}`,
392 );
393 }),
394 );
395});