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