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 fetchRemoteDpopSessionState,
14 fetchRemoteSessionState,
15 issueRemoteDpopWebSocketTicket,
16 issueRemoteWebSocketTicket,
17 RemoteEnvironmentAuthInvalidJsonError,
18 RemoteEnvironmentAuthTimeoutError,
19 resolveRemoteWebSocketConnectionUrl,
20} from "./remote.ts";
21import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
22import { remoteHttpClientLayer } from "../rpc/http.ts";
23
24const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
25
26type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
27
28const recordedFetch = (...responses: ReadonlyArray<Response>) => {
29 const calls: Array<FetchCall> = [];
30 let responseIndex = 0;
31 const fetchFn = ((input, init) => {
32 calls.push([input, init ?? {}]);
33 const response = responses[responseIndex++];
34 if (!response) {
35 return Promise.reject(new Error("Unexpected fetch call"));
36 }
37 return Promise.resolve(response);
38 }) satisfies typeof fetch;
39
40 return { fetchFn, calls };
41};
42
43const hangingFetch = () => {
44 const calls: Array<FetchCall> = [];
45 const fetchFn = ((input, init) => {
46 calls.push([input, init ?? {}]);
47 return new Promise<Response>(() => undefined);
48 }) satisfies typeof fetch;
49
50 return { fetchFn, calls };
51};
52
53const provideRemoteHttp = (fetchFn: typeof fetch) => Effect.provide(remoteHttpClientLayer(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("loads remote session state with a DPoP-bound access token", () =>
384 Effect.gen(function* () {
385 const fetch = recordedFetch(
386 Response.json({
387 authenticated: true,
388 auth: {
389 policy: "remote-reachable",
390 bootstrapMethods: ["one-time-token"],
391 sessionMethods: ["dpop-access-token"],
392 sessionCookieName: "t3_session",
393 },
394 sessionMethod: "dpop-access-token",
395 scopes: [
396 "orchestration:read",
397 "orchestration:operate",
398 "terminal:operate",
399 "review:write",
400 ],
401 expiresAt: "2026-05-01T12:00:00.000Z",
402 }),
403 );
404
405 yield* fetchRemoteDpopSessionState({
406 httpBaseUrl: "https://remote.example.com/",
407 accessToken: "dpop-access-token",
408 dpopProof: "dpop-proof",
409 }).pipe(provideRemoteHttp(fetch.fetchFn));
410
411 expectFetchCall(fetch.calls, 1, {
412 url: "https://remote.example.com/api/auth/session",
413 method: "GET",
414 headers: {
415 authorization: "DPoP dpop-access-token",
416 dpop: "dpop-proof",
417 },
418 });
419 }),
420 );
421
422 it.effect("fails hung fetch requests on the configured timeout", () =>
423 Effect.gen(function* () {
424 const fetch = hangingFetch();
425
426 const errorFiber = yield* fetchRemoteEnvironmentDescriptor({
427 httpBaseUrl: "http://remote.example.com/",
428 timeoutMs: 25,
429 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip, Effect.forkScoped);
430 yield* Effect.yieldNow;
431 yield* TestClock.adjust(Duration.millis(25));
432 const error = yield* Fiber.join(errorFiber);
433
434 expect(error).toBeInstanceOf(RemoteEnvironmentAuthTimeoutError);
435 expect(error.message).toBe(
436 "Remote environment endpoint http://remote.example.com/.well-known/t3/environment timed out after 25ms.",
437 );
438 }).pipe(Effect.provide(TestClock.layer())),
439 );
440
441 it.effect("revives declared typed errors from remote auth failures", () =>
442 Effect.gen(function* () {
443 const fetch = recordedFetch(
444 Response.json(
445 {
446 _tag: "EnvironmentAuthInvalidError",
447 code: "auth_invalid",
448 reason: "missing_credential",
449 traceId: "trace-auth-test",
450 },
451 { status: 401 },
452 ),
453 );
454
455 const error = yield* issueRemoteWebSocketTicket({
456 httpBaseUrl: "https://remote.example.com/",
457 bearerToken: "expired-token",
458 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
459
460 expect(isEnvironmentAuthInvalidError(error)).toBe(true);
461 if (isEnvironmentAuthInvalidError(error)) {
462 expect(error.reason).toBe("missing_credential");
463 expect(error.traceId).toBe("trace-auth-test");
464 }
465 }),
466 );
467
468 it.effect("classifies malformed successful remote auth responses as invalid responses", () =>
469 Effect.gen(function* () {
470 const fetch = recordedFetch(
471 Response.json(
472 {
473 access_token: "",
474 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
475 token_type: "Bearer",
476 expires_in: 3600,
477 scope:
478 "orchestration:read orchestration:operate terminal:operate review:write relay:read",
479 },
480 { status: 200 },
481 ),
482 );
483
484 const error = yield* bootstrapRemoteBearerSession({
485 httpBaseUrl: "https://remote.example.com/",
486 credential: "pairing-token",
487 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
488
489 expect(error).toBeInstanceOf(RemoteEnvironmentAuthInvalidJsonError);
490 expect(error.message).toBe(
491 "Remote environment endpoint returned an invalid response from https://remote.example.com/oauth/token.",
492 );
493 }),
494 );
495
496 it.effect("mints a websocket url that targets the rpc route with a short-lived ticket", () =>
497 Effect.gen(function* () {
498 const fetch = recordedFetch(
499 Response.json(
500 {
501 ticket: "ws-ticket",
502 expiresAt: "2026-05-01T12:05:00.000Z",
503 },
504 { status: 200 },
505 ),
506 );
507
508 const url = yield* resolveRemoteWebSocketConnectionUrl({
509 wsBaseUrl: "wss://remote.example.com/",
510 httpBaseUrl: "https://remote.example.com/",
511 bearerToken: "bearer-token",
512 clientMetadata: {
513 surface: "mobile",
514 appVersion: "1.2.3",
515 deviceType: "mobile",
516 os: "Android",
517 osMajorVersion: 15,
518 deviceModel: "Pixel 9",
519 },
520 connectionMethod: "relay",
521 }).pipe(provideRemoteHttp(fetch.fetchFn));
522
523 expect(url).toBe(
524 "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",
525 );
526 }),
527 );
528});