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 Schema from "effect/Schema";
6import * as TestClock from "effect/testing/TestClock";
7
8import { EnvironmentAuthInvalidError } from "@t3tools/contracts";
9import {
10 appendClientConnectionParams,
11 bootstrapRemoteBearerSession,
12 exchangeRemoteDpopAccessToken,
13 fetchRemoteSessionState,
14 issueRemoteDpopWebSocketTicket,
15 issueRemoteWebSocketTicket,
16 RemoteEnvironmentAuthInvalidJsonError,
17 RemoteEnvironmentAuthTimeoutError,
18 resolveRemoteWebSocketConnectionUrl,
19} from "./remote.ts";
20import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
21import * as RpcHttp from "../rpc/http.ts";
22
23const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
24
25type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
26
27const recordedFetch = (...responses: ReadonlyArray<Response>) => {
28 const calls: Array<FetchCall> = [];
29 let responseIndex = 0;
30 const fetchFn = ((input, init) => {
31 calls.push([input, init ?? {}]);
32 const response = responses[responseIndex++];
33 if (!response) {
34 return Promise.reject(new Error("Unexpected fetch call"));
35 }
36 return Promise.resolve(response);
37 }) satisfies typeof fetch;
38
39 return { fetchFn, calls };
40};
41
42const hangingFetch = () => {
43 const calls: Array<FetchCall> = [];
44 const fetchFn = ((input, init) => {
45 calls.push([input, init ?? {}]);
46 return new Promise<Response>(() => undefined);
47 }) satisfies typeof fetch;
48
49 return { fetchFn, calls };
50};
51
52const provideRemoteHttp = (fetchFn: typeof fetch) =>
53 Effect.provide(RpcHttp.layerRemoteHttpClient(fetchFn));
54
55const expectFetchCall = (
56 calls: ReadonlyArray<FetchCall>,
57 index: number,
58 expected: {
59 readonly url: string;
60 readonly method: string;
61 readonly headers?: Record<string, string>;
62 readonly body?: string;
63 },
64): void => {
65 const call = calls[index - 1];
66 expect(call).toBeDefined();
67 if (!call) {
68 return;
69 }
70
71 const [url, init] = call;
72 expect(String(url)).toBe(expected.url);
73 expect(init).toEqual(
74 expect.objectContaining({
75 method: expected.method,
76 }),
77 );
78 expect(init.headers).toEqual(expect.objectContaining(expected.headers ?? {}));
79
80 if ("body" in expected) {
81 const body = init.body;
82 if (typeof body === "string") {
83 expect(body).toBe(expected.body);
84 } else if (body instanceof Uint8Array) {
85 expect(new TextDecoder().decode(body)).toBe(expected.body);
86 } else {
87 throw new Error("Expected fetch request body");
88 }
89 }
90};
91
92describe("remote environment authorization", () => {
93 it.effect("bootstraps bearer auth against a remote backend", () =>
94 Effect.gen(function* () {
95 const fetch = recordedFetch(
96 Response.json(
97 {
98 access_token: "bearer-token",
99 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
100 token_type: "Bearer",
101 expires_in: 3600,
102 scope:
103 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
104 },
105 { status: 200 },
106 ),
107 );
108
109 const result = yield* bootstrapRemoteBearerSession({
110 httpBaseUrl: "https://remote.example.com/",
111 credential: "pairing-token",
112 }).pipe(provideRemoteHttp(fetch.fetchFn));
113
114 expect(result).toMatchObject({
115 token_type: "Bearer",
116 access_token: "bearer-token",
117 scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",
118 });
119 expectFetchCall(fetch.calls, 1, {
120 url: "https://remote.example.com/oauth/token",
121 method: "POST",
122 headers: {
123 "content-type": "application/x-www-form-urlencoded",
124 },
125 body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=pairing-token&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token",
126 });
127 }),
128 );
129
130 it.effect("exchanges managed credentials and admits websocket requests with DPoP", () =>
131 Effect.gen(function* () {
132 const fetch = recordedFetch(
133 Response.json({
134 access_token: "dpop-access-token",
135 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
136 token_type: "DPoP",
137 expires_in: 3600,
138 scope: "orchestration:read orchestration:operate terminal:operate review:write",
139 }),
140 Response.json({
141 ticket: "ws-ticket",
142 expiresAt: "2026-05-01T12:05:00.000Z",
143 }),
144 );
145
146 const token = yield* exchangeRemoteDpopAccessToken({
147 httpBaseUrl: "https://remote.example.com/",
148 credential: "one-time-credential",
149 dpopProof: "token-proof",
150 clientMetadata: {
151 label: "T3 Code Mobile",
152 deviceType: "mobile",
153 os: "iOS",
154 },
155 }).pipe(provideRemoteHttp(fetch.fetchFn));
156 yield* issueRemoteDpopWebSocketTicket({
157 httpBaseUrl: "https://remote.example.com/",
158 accessToken: token.access_token,
159 dpopProof: "resource-proof",
160 }).pipe(provideRemoteHttp(fetch.fetchFn));
161
162 expectFetchCall(fetch.calls, 1, {
163 url: "https://remote.example.com/oauth/token",
164 method: "POST",
165 headers: { dpop: "token-proof", "content-type": "application/x-www-form-urlencoded" },
166 body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=one-time-credential&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&client_label=T3+Code+Mobile&client_device_type=mobile&client_os=iOS",
167 });
168 expectFetchCall(fetch.calls, 2, {
169 url: "https://remote.example.com/api/auth/websocket-ticket",
170 method: "POST",
171 headers: {
172 authorization: "DPoP dpop-access-token",
173 dpop: "resource-proof",
174 },
175 });
176 }),
177 );
178
179 it.effect("submits optional client display metadata during bearer token exchange", () =>
180 Effect.gen(function* () {
181 const fetch = recordedFetch(
182 Response.json(
183 {
184 access_token: "bearer-token",
185 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
186 token_type: "Bearer",
187 expires_in: 3600,
188 scope:
189 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
190 },
191 { status: 200 },
192 ),
193 );
194
195 yield* bootstrapRemoteBearerSession({
196 httpBaseUrl: "https://remote.example.com/",
197 credential: "pairing-token",
198 clientMetadata: {
199 label: "T3 Code Mobile",
200 deviceType: "mobile",
201 os: "iOS",
202 },
203 }).pipe(provideRemoteHttp(fetch.fetchFn));
204
205 expectFetchCall(fetch.calls, 1, {
206 url: "https://remote.example.com/oauth/token",
207 method: "POST",
208 body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=pairing-token&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&client_label=T3+Code+Mobile&client_device_type=mobile&client_os=iOS",
209 });
210 }),
211 );
212
213 it.effect("keeps OS sentinels in telemetry but out of display metadata", () =>
214 Effect.gen(function* () {
215 const tokenResponse = () =>
216 Response.json(
217 {
218 access_token: "bearer-token",
219 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
220 token_type: "Bearer",
221 expires_in: 3600,
222 scope: "orchestration:read",
223 },
224 { status: 200 },
225 );
226 const fetch = recordedFetch(tokenResponse(), tokenResponse());
227
228 for (const os of ["unknown", "other"] as const) {
229 yield* bootstrapRemoteBearerSession({
230 httpBaseUrl: "https://remote.example.com/",
231 credential: "pairing-token",
232 clientMetadata: {
233 label: "T3 Code Web",
234 deviceType: "desktop",
235 os,
236 },
237 }).pipe(provideRemoteHttp(fetch.fetchFn));
238 }
239
240 for (const [, init] of fetch.calls) {
241 expect(String(init.body)).not.toContain("client_os=");
242 }
243
244 const websocketUrl = new URL("wss://remote.example.com/ws");
245 appendClientConnectionParams(websocketUrl, {
246 surface: "web",
247 deviceType: "desktop",
248 os: "unknown",
249 });
250 expect(websocketUrl.searchParams.get("clientOs")).toBe("unknown");
251 }),
252 );
253
254 it.effect("allows a client to explicitly narrow a pairing grant", () =>
255 Effect.gen(function* () {
256 const fetch = recordedFetch(
257 Response.json(
258 {
259 access_token: "read-only-token",
260 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
261 token_type: "Bearer",
262 expires_in: 3600,
263 scope: "orchestration:read",
264 },
265 { status: 200 },
266 ),
267 );
268
269 yield* bootstrapRemoteBearerSession({
270 httpBaseUrl: "https://remote.example.com/",
271 credential: "pairing-token",
272 scopes: ["orchestration:read"],
273 }).pipe(provideRemoteHttp(fetch.fetchFn));
274
275 expectFetchCall(fetch.calls, 1, {
276 url: "https://remote.example.com/oauth/token",
277 method: "POST",
278 body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=pairing-token&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&scope=orchestration%3Aread",
279 });
280 }),
281 );
282
283 it.effect("loads remote session state and websocket tickets over bearer auth", () =>
284 Effect.gen(function* () {
285 const fetch = recordedFetch(
286 Response.json(
287 {
288 environmentId: "environment-remote",
289 label: "Remote environment",
290 platform: {
291 os: "linux",
292 arch: "x64",
293 },
294 serverVersion: "0.0.0-test",
295 capabilities: {
296 repositoryIdentity: true,
297 },
298 },
299 { status: 200 },
300 ),
301 Response.json(
302 {
303 authenticated: true,
304 auth: {
305 policy: "remote-reachable",
306 bootstrapMethods: ["one-time-token"],
307 sessionMethods: ["browser-session-cookie", "bearer-access-token"],
308 sessionCookieName: "t3_session",
309 },
310 scopes: [
311 "orchestration:read",
312 "orchestration:operate",
313 "terminal:operate",
314 "review:write",
315 "relay:read",
316 ],
317 sessionMethod: "bearer-access-token",
318 expiresAt: "2026-05-01T12:00:00.000Z",
319 },
320 { status: 200 },
321 ),
322 Response.json(
323 {
324 ticket: "ws-ticket",
325 expiresAt: "2026-05-01T12:05:00.000Z",
326 },
327 { status: 200 },
328 ),
329 );
330
331 const environment = yield* fetchRemoteEnvironmentDescriptor({
332 httpBaseUrl: "https://remote.example.com/",
333 }).pipe(provideRemoteHttp(fetch.fetchFn));
334 expect(environment).toMatchObject({
335 environmentId: "environment-remote",
336 label: "Remote environment",
337 });
338
339 const session = yield* fetchRemoteSessionState({
340 httpBaseUrl: "https://remote.example.com/",
341 bearerToken: "bearer-token",
342 }).pipe(provideRemoteHttp(fetch.fetchFn));
343 expect(session).toMatchObject({
344 authenticated: true,
345 scopes: [
346 "orchestration:read",
347 "orchestration:operate",
348 "terminal:operate",
349 "review:write",
350 "relay:read",
351 ],
352 });
353
354 const ticket = yield* issueRemoteWebSocketTicket({
355 httpBaseUrl: "https://remote.example.com/",
356 bearerToken: "bearer-token",
357 }).pipe(provideRemoteHttp(fetch.fetchFn));
358 expect(ticket).toMatchObject({
359 ticket: "ws-ticket",
360 });
361
362 expectFetchCall(fetch.calls, 1, {
363 url: "https://remote.example.com/.well-known/t3/environment",
364 method: "GET",
365 });
366 expectFetchCall(fetch.calls, 2, {
367 url: "https://remote.example.com/api/auth/session",
368 method: "GET",
369 headers: {
370 authorization: "Bearer bearer-token",
371 },
372 });
373 expectFetchCall(fetch.calls, 3, {
374 url: "https://remote.example.com/api/auth/websocket-ticket",
375 method: "POST",
376 headers: {
377 authorization: "Bearer bearer-token",
378 },
379 });
380 }),
381 );
382
383 it.effect("fails hung fetch requests on the configured timeout", () =>
384 Effect.gen(function* () {
385 const fetch = hangingFetch();
386
387 const errorFiber = yield* fetchRemoteEnvironmentDescriptor({
388 httpBaseUrl: "http://remote.example.com/",
389 timeoutMs: 25,
390 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip, Effect.forkScoped);
391 yield* Effect.yieldNow;
392 yield* TestClock.adjust(Duration.millis(25));
393 const error = yield* Fiber.join(errorFiber);
394
395 expect(error).toBeInstanceOf(RemoteEnvironmentAuthTimeoutError);
396 expect(error.message).toBe(
397 "Remote environment endpoint http://remote.example.com/.well-known/t3/environment timed out after 25ms.",
398 );
399 }).pipe(Effect.provide(TestClock.layer())),
400 );
401
402 it.effect("revives declared typed errors from remote auth failures", () =>
403 Effect.gen(function* () {
404 const fetch = recordedFetch(
405 Response.json(
406 {
407 _tag: "EnvironmentAuthInvalidError",
408 code: "auth_invalid",
409 reason: "missing_credential",
410 traceId: "trace-auth-test",
411 },
412 { status: 401 },
413 ),
414 );
415
416 const error = yield* issueRemoteWebSocketTicket({
417 httpBaseUrl: "https://remote.example.com/",
418 bearerToken: "expired-token",
419 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
420
421 expect(isEnvironmentAuthInvalidError(error)).toBe(true);
422 if (isEnvironmentAuthInvalidError(error)) {
423 expect(error.reason).toBe("missing_credential");
424 expect(error.traceId).toBe("trace-auth-test");
425 }
426 }),
427 );
428
429 it.effect("classifies malformed successful remote auth responses as invalid responses", () =>
430 Effect.gen(function* () {
431 const fetch = recordedFetch(
432 Response.json(
433 {
434 access_token: "",
435 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
436 token_type: "Bearer",
437 expires_in: 3600,
438 scope:
439 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
440 },
441 { status: 200 },
442 ),
443 );
444
445 const error = yield* bootstrapRemoteBearerSession({
446 httpBaseUrl: "https://remote.example.com/",
447 credential: "pairing-token",
448 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
449
450 expect(error).toBeInstanceOf(RemoteEnvironmentAuthInvalidJsonError);
451 expect(error.message).toBe(
452 "Remote environment endpoint returned an invalid response from https://remote.example.com/oauth/token.",
453 );
454 }),
455 );
456
457 it.effect("mints a websocket url that targets the rpc route with a short-lived ticket", () =>
458 Effect.gen(function* () {
459 const fetch = recordedFetch(
460 Response.json(
461 {
462 ticket: "ws-ticket",
463 expiresAt: "2026-05-01T12:05:00.000Z",
464 },
465 { status: 200 },
466 ),
467 );
468
469 const url = yield* resolveRemoteWebSocketConnectionUrl({
470 wsBaseUrl: "wss://remote.example.com/",
471 httpBaseUrl: "https://remote.example.com/",
472 bearerToken: "bearer-token",
473 clientMetadata: {
474 surface: "mobile",
475 appVersion: "1.2.3",
476 deviceType: "mobile",
477 os: "Android",
478 osMajorVersion: 15,
479 deviceModel: "Pixel 9",
480 },
481 connectionMethod: "relay",
482 }).pipe(provideRemoteHttp(fetch.fetchFn));
483
484 expect(url).toBe(
485 "wss://remote.example.com/ws?wsTicket=ws-ticket&clientSurface=mobile&clientAppVersion=1.2.3&clientDeviceType=phone&clientOs=Android&clientOsMajorVersion=15&clientDeviceModel=Pixel+9&connectionMethod=relay",
486 );
487 }),
488 );
489});