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

linkEnvironment.test.ts

288 lines10.3 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/http";
15import { afterEach, beforeEach, vi } from "vite-plus/test";
16import {
17 AVAILABLE_CONNECTION_STATE,
18 type PreparedConnection,
19 BearerConnectionTarget,
20 PrimaryConnectionTarget,
21 EnvironmentSupervisor,
22} from "@t3tools/client-runtime/connection";
23import { type RpcSession } from "@t3tools/client-runtime/rpc";
24import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
25import { ManagedRelay } from "@t3tools/client-runtime/relay";
26import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
27import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
28​
29import { readCloudLinkState, unlinkEnvironmentFromCloud } from "./linkEnvironment";
30​
31const TARGET = {
32 environmentId: "environment-1",
33 label: "Desktop",
34 httpBaseUrl: "http://127.0.0.1:3000",
35 wsBaseUrl: "ws://127.0.0.1:3000",
36};
37​
38const SAVED_SERVICE_TARGET = {
39 environmentId: "saved-service",
40 label: "Service",
41 httpBaseUrl: "http://127.0.0.1:3773",
42 wsBaseUrl: "ws://127.0.0.1:3773",
43};
44​
45const relayClientInstallDialog = vi.hoisted(() => ({
46 requestConfirmation: vi.fn(),
47 reportProgress: vi.fn(),
48 finish: vi.fn(),
49}));
50​
51vi.mock("./relayClientInstallDialog", () => ({
52 requestRelayClientInstallConfirmation: relayClientInstallDialog.requestConfirmation,
53 reportRelayClientInstallProgress: relayClientInstallDialog.reportProgress,
54 finishRelayClientInstall: relayClientInstallDialog.finish,
55}));
56​
57const createProof = vi.fn(() => Effect.succeed("dpop-proof"));
58const layerDpopSigner = Layer.succeed(
59 ManagedRelay.ManagedRelayDpopSigner,
60 ManagedRelay.ManagedRelayDpopSigner.of({
61 thumbprint: Effect.succeed("thumbprint"),
62 createProof,
63 }),
64);
65​
66function layerRelay() {
67 const layerHttp = layerRemoteHttpClient(globalThis.fetch);
68 return Layer.mergeAll(
69 layerHttp,
70 ManagedRelay.layer({
71 relayUrl: "https://relay.example.test",
72 clientId: RelayWebClientId,
73 }).pipe(Layer.provideMerge(layerDpopSigner), Layer.provide(layerHttp)),
74 );
76​
77function layerRegistry(options?: {
78 readonly status?: { readonly status: "available"; readonly version: string };
79 readonly installEvents?: ReadonlyArray<RelayClientInstallProgressEvent>;
80}) {
81 return Layer.effect(
82 EnvironmentRegistry.EnvironmentRegistry,
83 Effect.gen(function* () {
84 const client = {
85 [WS_METHODS.cloudGetRelayClientStatus]: () =>
86 Effect.succeed(options?.status ?? { status: "available", version: "2026.6.0" }),
87 [WS_METHODS.cloudInstallRelayClient]: () =>
88 Stream.fromIterable(options?.installEvents ?? []),
89 } as unknown as RpcSession["client"];
90 const session: RpcSession = {
91 client,
92 initialConfig: Effect.never,
93 subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input),
94 ready: Effect.void,
95 probe: Effect.void,
96 inboundFrames: Effect.succeed(0),
97 awaitingReply: Effect.succeed(false),
98 closed: Effect.never,
99 };
100 const makeSupervisor = Effect.fn(function* (prepared: Option.Option<PreparedConnection>) {
101 return EnvironmentSupervisor.EnvironmentSupervisor.of({
102 target: new PrimaryConnectionTarget({
103 environmentId: EnvironmentId.make(TARGET.environmentId),
104 label: TARGET.label,
105 httpBaseUrl: TARGET.httpBaseUrl,
106 wsBaseUrl: TARGET.wsBaseUrl,
107 }),
108 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
109 session: yield* SubscriptionRef.make(Option.some(session)),
110 prepared: yield* SubscriptionRef.make(prepared),
111 connect: Effect.void,
112 disconnect: Effect.void,
113 retryNow: Effect.void,
114 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
115 });
116 const supervisors = new Map([
117 [
118 TARGET.environmentId,
119 yield* makeSupervisor(
120 Option.some({
121 environmentId: EnvironmentId.make(TARGET.environmentId),
122 label: TARGET.label,
123 httpBaseUrl: TARGET.httpBaseUrl,
124 socketUrl: `${TARGET.wsBaseUrl}/ws`,
125 httpAuthorization: { _tag: "Bearer", token: "desktop-bearer-token" },
126 target: new PrimaryConnectionTarget({
127 environmentId: EnvironmentId.make(TARGET.environmentId),
128 label: TARGET.label,
129 httpBaseUrl: TARGET.httpBaseUrl,
130 wsBaseUrl: TARGET.wsBaseUrl,
131 }),
132 }),
133 ),
134 ],
135 [
136 SAVED_SERVICE_TARGET.environmentId,
137 yield* makeSupervisor(
138 Option.some({
139 environmentId: EnvironmentId.make(SAVED_SERVICE_TARGET.environmentId),
140 label: SAVED_SERVICE_TARGET.label,
141 httpBaseUrl: SAVED_SERVICE_TARGET.httpBaseUrl,
142 socketUrl: `${SAVED_SERVICE_TARGET.wsBaseUrl}/ws`,
143 httpAuthorization: { _tag: "Bearer", token: "saved-service-token" },
144 target: new BearerConnectionTarget({
145 environmentId: EnvironmentId.make(SAVED_SERVICE_TARGET.environmentId),
146 label: SAVED_SERVICE_TARGET.label,
147 connectionId: "saved-service-connection",
148 }),
149 }),
150 ),
151 ],
152 ]);
153 const supervisorFor = (environmentId: EnvironmentId) => supervisors.get(environmentId)!;
154 const registry = {
155 run: <A, E, R>(environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>
156 Effect.provideService(
157 effect,
158 EnvironmentSupervisor.EnvironmentSupervisor,
159 supervisorFor(environmentId),
160 ),
161 runStream: <A, E, R>(environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>
162 Stream.provideService(
163 stream,
164 EnvironmentSupervisor.EnvironmentSupervisor,
165 supervisorFor(environmentId),
166 ),
167 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"];
168 return EnvironmentRegistry.EnvironmentRegistry.of(registry);
169 }),
170 );
172​
173function layerServices(options?: Parameters<typeof layerRegistry>[0]) {
174 return Layer.mergeAll(layerRelay(), layerRegistry(options));
176​
177function withServices<A, E>(
178 effect: Effect.Effect<
179 A,
180 E,
181 | HttpClient.HttpClient
182 | ManagedRelay.ManagedRelayClient
183 | EnvironmentRegistry.EnvironmentRegistry
184 >,
185 options?: Parameters<typeof layerRegistry>[0],
186) {
187 return effect.pipe(Effect.provide(layerServices(options)));
189​
190beforeEach(() => {
191 vi.clearAllMocks();
192 vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");
193 relayClientInstallDialog.requestConfirmation.mockResolvedValue(true);
194});
195​
196afterEach(() => {
197 __resetDesktopPrimaryAuthForTests();
198 vi.unstubAllGlobals();
199 vi.unstubAllEnvs();
200 vi.restoreAllMocks();
201});
202​
203describe("web cloud link environment client", () => {
204 it.effect("reads link state from the chosen environment with its own credentials", () =>
205 Effect.gen(function* () {
206 const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
207 Response.json({
208 linked: true,
209 cloudUserId: "user-1",
210 relayUrl: "https://relay.example.test",
211 relayIssuer: "https://relay.example.test",
212 managedTunnelActive: true,
213 publishAgentActivity: false,
214 }),
215 );
216 vi.stubGlobal("fetch", fetchMock);
217 vi.stubGlobal("window", {
218 location: { origin: "t3code://app" },
219 desktopBridge: {
220 getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
221 } as unknown as DesktopBridge,
222 });
223​
224 for (const [target, token] of [
225 [TARGET, "desktop-bearer-token"],
226 [SAVED_SERVICE_TARGET, "saved-service-token"],
227 ] as const) {
228 fetchMock.mockClear();
229 yield* withServices(
230 readCloudLinkState({
231 target: { environmentId: EnvironmentId.make(target.environmentId) },
232 }),
233 );
234​
235 const [input, init] = fetchMock.mock.calls[0]!;
236 const request = new Request(input, init);
237 expect(new URL(request.url).origin).toBe(target.httpBaseUrl);
238 expect(request.credentials).not.toBe("include");
239 expect(request.headers.get("authorization")).toBe(`Bearer ${token}`);
240 }
241 }),
242 );
243​
244 it.effect("reports why the relay kept the environment after a local unlink", () =>
245 Effect.gen(function* () {
246 const fetchMock = vi.fn((input: RequestInfo | URL) =>
247 Promise.resolve(
248 String(input).startsWith("https://relay.example.test/")
249 ? Response.json(
250 {
251 _tag: "RelayInternalError",
252 code: "internal_error",
253 reason: "upstream_unavailable",
254 traceId: "trace-unlink",
255 },
256 { status: 500 },
257 )
258 : Response.json({ ok: true, endpointRuntimeStatus: null }),
259 ),
260 );
261 vi.stubGlobal("fetch", fetchMock);
262 vi.stubGlobal("window", {
263 location: { origin: "t3code://app" },
264 desktopBridge: {
265 getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
266 } as unknown as DesktopBridge,
267 });
268​
269 const error = yield* withServices(
270 unlinkEnvironmentFromCloud({
271 target: { environmentId: EnvironmentId.make(TARGET.environmentId) },
272 clerkToken: "clerk-token",
273 }),
274 ).pipe(Effect.flip);
275​
276 expect(fetchMock.mock.calls.map(([input]) => String(input))).toEqual([
277 "http://127.0.0.1:3000/api/connect/unlink",
278 "https://relay.example.test/v1/client/environment-links/environment-1",
279 ]);
280 expect(error).toMatchObject({
281 _tag: "CloudEnvironmentLinkError",
282 message:
283 "Disconnected locally, but T3 Connect did not confirm it removed this environment: Relay encountered an internal error (upstream_unavailable).",
284 traceId: "trace-unlink",
285 });
286 }),
287 );
288});