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

remote.test.ts

248 lines8.5 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 resolveRemoteWebSocketConnectionUrl,
14} from "./remote.ts";
15import * as ClientCapabilities from "../platform/capabilities.ts";
16import * as RpcHttp from "../rpc/http.ts";
17​
18const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
19​
20type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
21​
22const recordedFetch = (...responses: ReadonlyArray<Response>) => {
23 const calls: Array<FetchCall> = [];
24 let responseIndex = 0;
25 const fetchFn = ((input, init) => {
26 calls.push([input, init ?? {}]);
27 const response = responses[responseIndex++];
28 if (!response) {
29 return Promise.reject(new Error("Unexpected fetch call"));
30 }
31 return Promise.resolve(response);
32 }) satisfies typeof fetch;
33​
34 return { fetchFn, calls };
35};
36​
37const provideRemoteHttp = (fetchFn: typeof fetch) =>
38 Effect.provide(RpcHttp.layerRemoteHttpClient(fetchFn));
39​
40const expectFetchCall = (
41 calls: ReadonlyArray<FetchCall>,
42 index: number,
43 expected: {
44 readonly url: string;
45 readonly method: string;
46 readonly headers?: Record<string, string>;
47 readonly body?: string;
48 },
49): void => {
50 const call = calls[index - 1];
51 expect(call).toBeDefined();
52 if (!call) {
53 return;
54 }
55​
56 const [url, init] = call;
57 expect(String(url)).toBe(expected.url);
58 expect(init).toEqual(
59 expect.objectContaining({
60 method: expected.method,
61 }),
62 );
63 expect(init.headers).toEqual(expect.objectContaining(expected.headers ?? {}));
64​
65 if ("body" in expected) {
66 const body = init.body;
67 if (typeof body === "string") {
68 expect(body).toBe(expected.body);
69 } else if (body instanceof Uint8Array) {
70 expect(new TextDecoder().decode(body)).toBe(expected.body);
71 } else {
72 throw new Error("Expected fetch request body");
73 }
74 }
75};
76​
77describe("remote environment authorization", () => {
78 it.effect("exchanges managed credentials and admits websocket requests with DPoP", () =>
79 Effect.gen(function* () {
80 const fetch = recordedFetch(
81 Response.json({
82 access_token: "dpop-access-token",
83 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
84 token_type: "DPoP",
85 expires_in: 3600,
86 scope: "orchestration:read orchestration:operate terminal:operate review:write",
87 }),
88 Response.json({
89 ticket: "ws-ticket",
90 expiresAt: "2026-05-01T12:05:00.000Z",
91 }),
92 );
93​
94 const token = yield* exchangeRemoteDpopAccessToken({
95 httpBaseUrl: "https://remote.example.com/",
96 credential: "one-time-credential",
97 dpopProof: "token-proof",
98 clientMetadata: {
99 label: "T3 Code Mobile",
100 deviceType: "mobile",
101 os: "iOS",
102 },
103 }).pipe(provideRemoteHttp(fetch.fetchFn));
104 yield* issueRemoteDpopWebSocketTicket({
105 httpBaseUrl: "https://remote.example.com/",
106 accessToken: token.access_token,
107 dpopProof: "resource-proof",
108 }).pipe(provideRemoteHttp(fetch.fetchFn));
109​
110 expectFetchCall(fetch.calls, 1, {
111 url: "https://remote.example.com/oauth/token",
112 method: "POST",
113 headers: { dpop: "token-proof", "content-type": "application/x-www-form-urlencoded" },
114 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",
115 });
116 expectFetchCall(fetch.calls, 2, {
117 url: "https://remote.example.com/api/auth/websocket-ticket",
118 method: "POST",
119 headers: {
120 authorization: "DPoP dpop-access-token",
121 dpop: "resource-proof",
122 },
123 });
124 }),
125 );
126​
127 it.effect("allows a client to explicitly narrow a pairing grant", () =>
128 Effect.gen(function* () {
129 const fetch = recordedFetch(
130 Response.json(
131 {
132 access_token: "read-only-token",
133 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
134 token_type: "Bearer",
135 expires_in: 3600,
136 scope: "orchestration:read",
137 },
138 { status: 200 },
139 ),
140 );
141​
142 yield* bootstrapRemoteBearerSession({
143 httpBaseUrl: "https://remote.example.com/",
144 credential: "pairing-token",
145 scopes: ["orchestration:read"],
146 }).pipe(provideRemoteHttp(fetch.fetchFn));
147​
148 expectFetchCall(fetch.calls, 1, {
149 url: "https://remote.example.com/oauth/token",
150 method: "POST",
151 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",
152 });
153 }),
154 );
155​
156 it.effect("revives declared typed errors from remote auth failures", () =>
157 Effect.gen(function* () {
158 const fetch = recordedFetch(
159 Response.json(
160 {
161 _tag: "EnvironmentAuthInvalidError",
162 code: "auth_invalid",
163 reason: "missing_credential",
164 traceId: "trace-auth-test",
165 },
166 { status: 401 },
167 ),
168 );
169​
170 const error = yield* issueRemoteWebSocketTicket({
171 httpBaseUrl: "https://remote.example.com/",
172 bearerToken: "expired-token",
173 }).pipe(provideRemoteHttp(fetch.fetchFn), Effect.flip);
174​
175 expect(isEnvironmentAuthInvalidError(error)).toBe(true);
176 if (isEnvironmentAuthInvalidError(error)) {
177 expect(error.reason).toBe("missing_credential");
178 expect(error.traceId).toBe("trace-auth-test");
179 }
180 }),
181 );
182​
183 it.effect("mints a websocket url that targets the rpc route with a short-lived ticket", () =>
184 Effect.gen(function* () {
185 const fetch = recordedFetch(
186 Response.json(
187 {
188 ticket: "ws-ticket",
189 expiresAt: "2026-05-01T12:05:00.000Z",
190 },
191 { status: 200 },
192 ),
193 );
194​
195 const url = yield* resolveRemoteWebSocketConnectionUrl({
196 wsBaseUrl: "wss://remote.example.com/",
197 httpBaseUrl: "https://remote.example.com/",
198 bearerToken: "bearer-token",
199 clientMetadata: {
200 surface: "mobile",
201 appVersion: "1.2.3",
202 deviceType: "mobile",
203 os: "Android",
204 osMajorVersion: 15,
205 deviceModel: "Pixel 9",
206 },
207 connectionMethod: "relay",
208 }).pipe(provideRemoteHttp(fetch.fetchFn));
209​
210 expect(url).toBe(
211 "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",
212 );
213 }),
214 );
215​
216 it.effect("names the signed-in Connect account and this device by hash only", () =>
217 Effect.gen(function* () {
218 const fetch = recordedFetch(
219 Response.json({ ticket: "ws-ticket", expiresAt: "2026-05-01T12:05:00.000Z" }),
220 );
221​
222 const url = new URL(
223 yield* resolveRemoteWebSocketConnectionUrl({
224 wsBaseUrl: "wss://remote.example.com/",
225 httpBaseUrl: "https://remote.example.com/",
226 bearerToken: "bearer-token",
227 }).pipe(
228 provideRemoteHttp(fetch.fetchFn),
229 Effect.provideService(
230 ClientCapabilities.CloudSession,
231 ClientCapabilities.CloudSession.of({
232 identity: Effect.succeed(Option.some({ accountId: "user_connect" })),
233 clerkToken: Effect.succeed("clerk-token"),
234 }),
235 ),
236 Effect.provideService(ClientCapabilities.AnalyticsDevice, {
237 id: Effect.succeed(Option.some("device-1")),
238 }),
239 ),
240 );
241​
242 expect(url.searchParams.get("clientOwner")).toBe(hashTelemetryId("user_connect"));
243 expect(url.searchParams.get("clientDevice")).toBe(hashTelemetryId("device-1"));
244 expect(url.toString()).not.toContain("user_connect");
245 expect(url.toString()).not.toContain("device-1");
246 }),
247 );
248});