Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as TestClock from "effect/testing/TestClock";
6import { HttpClient } from "effect/unstable/http";
7
8import {
9 bootstrapRemoteBearerSession,
10 fetchRemoteEnvironmentDescriptor,
11 fetchRemoteSessionState,
12 issueRemoteWebSocketToken,
13 remoteHttpClientLayer,
14 RemoteEnvironmentAuthTimeoutError,
15 resolveRemoteWebSocketConnectionUrl,
16} from "./remote.ts";
17
18type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
19
20const recordedFetch = (...responses: ReadonlyArray<Response>) => {
21 const calls: Array<FetchCall> = [];
22 let responseIndex = 0;
23 const fetchFn = ((input, init) => {
24 calls.push([input, init ?? {}]);
25 const response = responses[responseIndex++];
26 if (!response) {
27 return Promise.reject(new Error("Unexpected fetch call"));
28 }
29 return Promise.resolve(response);
30 }) satisfies typeof fetch;
31
32 return { fetchFn, calls };
33};
34
35const hangingFetch = () => {
36 const calls: Array<FetchCall> = [];
37 const fetchFn = ((input, init) => {
38 calls.push([input, init ?? {}]);
39 return new Promise<Response>(() => undefined);
40 }) satisfies typeof fetch;
41
42 return { fetchFn, calls };
43};
44
45const provideRemoteHttp =
46 (fetchFn: typeof fetch) =>
47 <A, E, R>(effect: Effect.Effect<A, E, R | HttpClient.HttpClient>) =>
48 effect.pipe(Effect.provide(remoteHttpClientLayer(fetchFn)));
49
50const expectFetchCall = (
51 calls: ReadonlyArray<FetchCall>,
52 index: number,
53 expected: {
54 readonly url: string;
55 readonly method: string;
56 readonly headers?: Record<string, string>;
57 readonly body?: string;
58 },
59): void => {
60 const call = calls[index - 1];
61 expect(call).toBeDefined();
62 if (!call) {
63 return;
64 }
65
66 const [url, init] = call;
67 expect(String(url)).toBe(expected.url);
68 expect(init).toEqual(
69 expect.objectContaining({
70 method: expected.method,
71 }),
72 );
73 expect(init.headers).toEqual(expect.objectContaining(expected.headers ?? {}));
74
75 if ("body" in expected) {
76 const body = init.body;
77 if (typeof body === "string") {
78 expect(body).toBe(expected.body);
79 } else if (body instanceof Uint8Array) {
80 expect(new TextDecoder().decode(body)).toBe(expected.body);
81 } else {
82 throw new Error("Expected fetch request body");
83 }
84 }
85};
86
87describe("remote", () => {
88 it.effect("bootstraps bearer auth against a remote backend", () =>
89 Effect.gen(function* () {
90 const fetch = recordedFetch(
91 Response.json(
92 {
93 authenticated: true,
94 role: "client",
95 sessionMethod: "bearer-session-token",
96 expiresAt: "2026-05-01T12:00:00.000Z",
97 sessionToken: "bearer-token",
98 },
99 { status: 200 },
100 ),
101 );
102
103 const result = yield* bootstrapRemoteBearerSession({
104 httpBaseUrl: "https://remote.example.com/",
105 credential: "pairing-token",
106 }).pipe(provideRemoteHttp(fetch.fetchFn));
107
108 expect(result).toMatchObject({
109 sessionMethod: "bearer-session-token",
110 sessionToken: "bearer-token",
111 });
112 expectFetchCall(fetch.calls, 1, {
113 url: "https://remote.example.com/api/auth/bootstrap/bearer",
114 method: "POST",
115 headers: {
116 "content-type": "application/json",
117 },
118 body: `{"credential":"pairing-token"}`,
119 });
120 }),
121 );
122
123 it.effect("loads remote session state and websocket tokens over bearer auth", () =>
124 Effect.gen(function* () {
125 const fetch = recordedFetch(
126 Response.json(
127 {
128 environmentId: "environment-remote",
129 label: "Remote environment",
130 platform: {
131 os: "linux",
132 arch: "x64",
133 },
134 serverVersion: "0.0.0-test",
135 capabilities: {
136 repositoryIdentity: true,
137 },
138 },
139 { status: 200 },
140 ),
141 Response.json(
142 {
143 authenticated: true,
144 auth: {
145 policy: "remote-reachable",
146 bootstrapMethods: ["one-time-token"],
147 sessionMethods: ["browser-session-cookie", "bearer-session-token"],
148 sessionCookieName: "t3_session",
149 },
150 role: "client",
151 sessionMethod: "bearer-session-token",
152 expiresAt: "2026-05-01T12:00:00.000Z",
153 },
154 { status: 200 },
155 ),
156 Response.json(
157 {
158 token: "ws-token",
159 expiresAt: "2026-05-01T12:05:00.000Z",
160 },
161 { status: 200 },
162 ),
163 );
164
165 const environment = yield* fetchRemoteEnvironmentDescriptor({
166 httpBaseUrl: "https://remote.example.com/",
167 }).pipe(provideRemoteHttp(fetch.fetchFn));
168 expect(environment).toMatchObject({
169 environmentId: "environment-remote",
170 label: "Remote environment",
171 });
172
173 const session = yield* fetchRemoteSessionState({
174 httpBaseUrl: "https://remote.example.com/",
175 bearerToken: "bearer-token",
176 }).pipe(provideRemoteHttp(fetch.fetchFn));
177 expect(session).toMatchObject({
178 authenticated: true,
179 role: "client",
180 });
181
182 const token = yield* issueRemoteWebSocketToken({
183 httpBaseUrl: "https://remote.example.com/",
184 bearerToken: "bearer-token",
185 }).pipe(provideRemoteHttp(fetch.fetchFn));
186 expect(token).toMatchObject({
187 token: "ws-token",
188 });
189
190 expectFetchCall(fetch.calls, 1, {
191 url: "https://remote.example.com/.well-known/t3/environment",
192 method: "GET",
193 });
194 expectFetchCall(fetch.calls, 2, {
195 url: "https://remote.example.com/api/auth/session",
196 method: "GET",
197 headers: {
198 authorization: "Bearer bearer-token",
199 },
200 });
201 expectFetchCall(fetch.calls, 3, {
202 url: "https://remote.example.com/api/auth/ws-token",
203 method: "POST",
204 headers: {
205 authorization: "Bearer bearer-token",
206 },
207 });
208 }),
209 );
210
211 it.effect("fails hung fetch requests on the configured timeout", () =>
212 Effect.gen(function* () {
213 const fetch = hangingFetch();
214
215 const errorFiber = yield* fetchRemoteEnvironmentDescriptor({
216 httpBaseUrl: "http://remote.example.com/",
217 timeoutMs: 25,
218 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip, Effect.forkScoped);
219 yield* Effect.yieldNow;
220 yield* TestClock.adjust(Duration.millis(25));
221 const error = yield* Fiber.join(errorFiber);
222
223 expect(error).toBeInstanceOf(RemoteEnvironmentAuthTimeoutError);
224 expect(error.message).toBe(
225 "Remote auth endpoint http://remote.example.com/.well-known/t3/environment timed out after 25ms.",
226 );
227 }).pipe(Effect.provide(TestClock.layer())),
228 );
229
230 it.effect("mints a websocket url that targets the rpc route with a short-lived ws token", () =>
231 Effect.gen(function* () {
232 const fetch = recordedFetch(
233 Response.json(
234 {
235 token: "ws-token",
236 expiresAt: "2026-05-01T12:05:00.000Z",
237 },
238 { status: 200 },
239 ),
240 );
241
242 const url = yield* resolveRemoteWebSocketConnectionUrl({
243 wsBaseUrl: "wss://remote.example.com/",
244 httpBaseUrl: "https://remote.example.com/",
245 bearerToken: "bearer-token",
246 }).pipe(provideRemoteHttp(fetch.fetchFn));
247
248 expect(url).toBe("wss://remote.example.com/ws?wsToken=ws-token");
249 }),
250 );
251});