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

remote.test.ts

350 lines12.4 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5​
6import { EnvironmentAuthInvalidError } from "@t3tools/contracts";
7import { hashTelemetryId } from "@t3tools/shared/telemetryId";
8import {
9 bootstrapRemoteBearerSession,
10 exchangeRemoteDpopAccessToken,
11 issueRemoteDpopWebSocketTicket,
12 issueRemoteWebSocketTicket,
13 resolveRemoteDpopWebSocketConnectionUrl,
14 resolveRemoteWebSocketConnectionUrl,
15} from "./remote.ts";
16import * as ClientCapabilities from "../platform/capabilities.ts";
17import * as RpcHttp from "../rpc/http.ts";
18​
19const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
20​
21type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
22​
23const recordedFetch = (...responses: ReadonlyArray<Response>) => {
24 const calls: Array<FetchCall> = [];
25 let responseIndex = 0;
26 const fetchFn = ((input, init) => {
27 calls.push([input, init ?? {}]);
28 const response = responses[responseIndex++];
29 if (!response) {
30 return Promise.reject(new Error("Unexpected fetch call"));
31 }
32 return Promise.resolve(response);
33 }) satisfies typeof fetch;
34​
35 return { fetchFn, calls };
36};
37​
38const provideRemoteHttp = (fetchFn: typeof fetch) =>
39 Effect.provide(RpcHttp.layerRemoteHttpClient(fetchFn));
40​
41const expectFetchCall = (
42 calls: ReadonlyArray<FetchCall>,
43 index: number,
44 expected: {
45 readonly url: string;
46 readonly method: string;
47 readonly headers?: Record<string, string>;
48 readonly body?: string;
49 },
50): void => {
51 const call = calls[index - 1];
52 expect(call).toBeDefined();
53 if (!call) {
54 return;
55 }
56​
57 const [url, init] = call;
58 expect(String(url)).toBe(expected.url);
59 expect(init).toEqual(
60 expect.objectContaining({
61 method: expected.method,
62 }),
63 );
64 expect(init.headers).toEqual(expect.objectContaining(expected.headers ?? {}));
65​
66 if ("body" in expected) {
67 const body = init.body;
68 if (typeof body === "string") {
69 expect(body).toBe(expected.body);
70 } else if (body instanceof Uint8Array) {
71 expect(new TextDecoder().decode(body)).toBe(expected.body);
72 } else {
73 throw new Error("Expected fetch request body");
74 }
75 }
76};
77​
78describe("remote environment authorization", () => {
79 it.effect("exchanges managed credentials and admits websocket requests with DPoP", () =>
80 Effect.gen(function* () {
81 const fetch = recordedFetch(
82 Response.json({
83 access_token: "dpop-access-token",
84 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
85 token_type: "DPoP",
86 expires_in: 3600,
87 scope: "orchestration:read orchestration:operate terminal:operate review:write",
88 }),
89 Response.json({
90 ticket: "ws-ticket",
91 expiresAt: "2026-05-01T12:05:00.000Z",
92 }),
93 );
94​
95 const token = yield* exchangeRemoteDpopAccessToken({
96 httpBaseUrl: "https://remote.example.com/",
97 credential: "one-time-credential",
98 dpopProof: "token-proof",
99 clientMetadata: {
100 label: "T3 Code Mobile",
101 deviceType: "mobile",
102 os: "iOS",
103 },
104 }).pipe(provideRemoteHttp(fetch.fetchFn));
105 yield* issueRemoteDpopWebSocketTicket({
106 httpBaseUrl: "https://remote.example.com/",
107 accessToken: token.access_token,
108 dpopProof: "resource-proof",
109 }).pipe(provideRemoteHttp(fetch.fetchFn));
110​
111 expectFetchCall(fetch.calls, 1, {
112 url: "https://remote.example.com/oauth/token",
113 method: "POST",
114 headers: { dpop: "token-proof", "content-type": "application/x-www-form-urlencoded" },
115 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",
116 });
117 expectFetchCall(fetch.calls, 2, {
118 url: "https://remote.example.com/api/auth/websocket-ticket",
119 method: "POST",
120 headers: {
121 authorization: "DPoP dpop-access-token",
122 dpop: "resource-proof",
123 },
124 });
125 }),
126 );
127​
128 it.effect("allows a client to explicitly narrow a pairing grant", () =>
129 Effect.gen(function* () {
130 const fetch = recordedFetch(
131 Response.json(
132 {
133 access_token: "read-only-token",
134 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
135 token_type: "Bearer",
136 expires_in: 3600,
137 scope: "orchestration:read",
138 },
139 { status: 200 },
140 ),
141 );
142​
143 yield* bootstrapRemoteBearerSession({
144 httpBaseUrl: "https://remote.example.com/",
145 credential: "pairing-token",
146 scopes: ["orchestration:read"],
147 }).pipe(provideRemoteHttp(fetch.fetchFn));
148​
149 expectFetchCall(fetch.calls, 1, {
150 url: "https://remote.example.com/oauth/token",
151 method: "POST",
152 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",
153 });
154 }),
155 );
156​
157 it.effect("revives declared typed errors from remote auth failures", () =>
158 Effect.gen(function* () {
159 const fetch = recordedFetch(
160 Response.json(
161 {
162 _tag: "EnvironmentAuthInvalidError",
163 code: "auth_invalid",
164 reason: "missing_credential",
165 traceId: "trace-auth-test",
166 },
167 { status: 401 },
168 ),
169 );
170​
171 const error = yield* issueRemoteWebSocketTicket({
172 httpBaseUrl: "https://remote.example.com/",
173 bearerToken: "expired-token",
174 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
175​
176 expect(isEnvironmentAuthInvalidError(error)).toBe(true);
177 if (isEnvironmentAuthInvalidError(error)) {
178 expect(error.reason).toBe("missing_credential");
179 expect(error.traceId).toBe("trace-auth-test");
180 }
181 }),
182 );
183​
184 it.effect("mints a websocket url that targets the rpc route with a short-lived ticket", () =>
185 Effect.gen(function* () {
186 const fetch = recordedFetch(
187 Response.json(
188 {
189 ticket: "ws-ticket",
190 expiresAt: "2026-05-01T12:05:00.000Z",
191 },
192 { status: 200 },
193 ),
194 );
195​
196 const url = yield* resolveRemoteWebSocketConnectionUrl({
197 wsBaseUrl: "wss://remote.example.com/",
198 httpBaseUrl: "https://remote.example.com/",
199 bearerToken: "bearer-token",
200 clientMetadata: {
201 surface: "mobile",
202 appVersion: "1.2.3",
203 deviceType: "mobile",
204 os: "Android",
205 osMajorVersion: 15,
206 deviceModel: "Pixel 9",
207 },
208 connectionMethod: "relay",
209 }).pipe(provideRemoteHttp(fetch.fetchFn));
210​
211 expect(url).toBe(
212 "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",
213 );
214 }),
215 );
216​
217 it.effect("binds a DPoP client's rpc ticket to its key and proves the upgrade", () =>
218 Effect.gen(function* () {
219 const fetch = recordedFetch(
220 Response.json({ ticket: "ws-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
221 );
222 const proofs: Array<{ method: string; url: string; accessToken: string }> = [];
223​
224 const url = yield* resolveRemoteDpopWebSocketConnectionUrl({
225 wsBaseUrl: "wss://remote.example.com/",
226 httpBaseUrl: "https://remote.example.com/",
227 accessToken: "dpop-access-token",
228 createProof: (input) => {
229 proofs.push(input);
230 return Effect.succeed(`proof-${proofs.length}`);
231 },
232 connectionMethod: "relay",
233 }).pipe(provideRemoteHttp(fetch.fetchFn));
234​
235 expectFetchCall(fetch.calls, 1, {
236 url: "https://remote.example.com/api/auth/websocket-ticket/rpc",
237 method: "POST",
238 headers: { authorization: "DPoP dpop-access-token", dpop: "proof-1" },
239 });
240 expect(proofs).toEqual([
241 {
242 method: "POST",
243 url: "https://remote.example.com/api/auth/websocket-ticket/rpc",
244 accessToken: "dpop-access-token",
245 },
246 { method: "GET", url: "https://remote.example.com/ws", accessToken: "ws-ticket" },
247 ]);
248 expect(url).toBe(
249 "wss://remote.example.com/ws?wsTicket=ws-ticket&dpop=proof-2&connectionMethod=relay",
250 );
251 }),
252 );
253​
254 it.effect("requests the audience route even without a fallback proof", () =>
255 Effect.gen(function* () {
256 const fetch = recordedFetch(
257 Response.json({ ticket: "media-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
258 );
259 yield* issueRemoteDpopWebSocketTicket({
260 httpBaseUrl: "https://remote.example.com/",
261 accessToken: "dpop-access-token",
262 dpopProof: "media-proof",
263 use: "media",
264 }).pipe(provideRemoteHttp(fetch.fetchFn));
265 expectFetchCall(fetch.calls, 1, {
266 url: "https://remote.example.com/api/auth/websocket-ticket/media",
267 method: "POST",
268 headers: { dpop: "media-proof" },
269 });
270 }),
271 );
272​
273 it.effect("falls back to the bare ticket path on a server without the audience route", () =>
274 Effect.gen(function* () {
275 const fetch = recordedFetch(
276 Response.json({ message: "Not Found" }, { status: 404 }),
277 Response.json({ ticket: "old-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
278 );
279 const proofs: Array<{ method: string; url: string; accessToken: string }> = [];
280​
281 const url = yield* resolveRemoteDpopWebSocketConnectionUrl({
282 wsBaseUrl: "wss://remote.example.com/",
283 httpBaseUrl: "https://remote.example.com/",
284 accessToken: "dpop-access-token",
285 createProof: (input) => {
286 proofs.push(input);
287 return Effect.succeed(`proof-${proofs.length}`);
288 },
289 }).pipe(provideRemoteHttp(fetch.fetchFn));
290​
291 expect(fetch.calls.map(([target]) => String(target))).toEqual([
292 "https://remote.example.com/api/auth/websocket-ticket/rpc",
293 "https://remote.example.com/api/auth/websocket-ticket",
294 ]);
295 expect(proofs).toEqual([
296 {
297 method: "POST",
298 url: "https://remote.example.com/api/auth/websocket-ticket/rpc",
299 accessToken: "dpop-access-token",
300 },
301 {
302 method: "POST",
303 url: "https://remote.example.com/api/auth/websocket-ticket",
304 accessToken: "dpop-access-token",
305 },
306 { method: "GET", url: "https://remote.example.com/ws", accessToken: "old-ticket" },
307 ]);
308 expectFetchCall(fetch.calls, 2, {
309 url: "https://remote.example.com/api/auth/websocket-ticket",
310 method: "POST",
311 headers: { dpop: "proof-2" },
312 });
313 expect(new URL(url).searchParams.get("wsTicket")).toBe("old-ticket");
314 expect(new URL(url).searchParams.get("dpop")).toBe("proof-3");
315 }),
316 );
317​
318 it.effect("names the signed-in Connect account and this device by hash only", () =>
319 Effect.gen(function* () {
320 const fetch = recordedFetch(
321 Response.json({ ticket: "ws-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
322 );
323​
324 const url = new URL(
325 yield* resolveRemoteWebSocketConnectionUrl({
326 wsBaseUrl: "wss://remote.example.com/",
327 httpBaseUrl: "https://remote.example.com/",
328 bearerToken: "bearer-token",
329 }).pipe(
330 provideRemoteHttp(fetch.fetchFn),
331 Effect.provideService(
332 ClientCapabilities.CloudSession,
333 ClientCapabilities.CloudSession.of({
334 identity: Effect.succeed(Option.some({ accountId: "user_connect" })),
335 clerkToken: Effect.succeed("clerk-token"),
336 }),
337 ),
338 Effect.provideService(ClientCapabilities.AnalyticsDevice, {
339 id: Effect.succeed(Option.some("device-1")),
340 }),
341 ),
342 );
343​
344 expect(url.searchParams.get("clientOwner")).toBe(hashTelemetryId("user_connect"));
345 expect(url.searchParams.get("clientDevice")).toBe(hashTelemetryId("device-1"));
346 expect(url.toString()).not.toContain("user_connect");
347 expect(url.toString()).not.toContain("device-1");
348 }),
349 );
350});