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

remote.ts

359 lines12.8 KB

1import {
2 AuthAccessTokenType,
3 type AuthClientPresentationMetadata,
4 AuthEnvironmentBootstrapTokenType,
5 AuthTokenExchangeGrantType,
6 type ClientConnectionMethod,
7 type AuthEnvironmentScope,
8 type AuthWebSocketTicketResult,
9 type AuthWebSocketTicketUse,
10} from "@t3tools/contracts";
11import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
12import { hashTelemetryId } from "@t3tools/shared/telemetryId";
13import * as Effect from "effect/Effect";
14import * as Option from "effect/Option";
15import * as Redacted from "effect/Redacted";
16import * as Schema from "effect/Schema";
17import { environmentEndpointUrl } from "../environment/endpoint.ts";
18import * as ClientCapabilities from "../platform/capabilities.ts";
19import {
20 executeEnvironmentHttpRequest,
21 makeEnvironmentHttpApiGroupClient,
22 RemoteEnvironmentAuthUndeclaredStatusError,
23 type RemoteEnvironmentRequestError,
24} from "../rpc/http.ts";
25​
26export { RemoteEnvironmentAuthUndeclaredStatusError } from "../rpc/http.ts";
27export type RemoteEnvironmentAuthError = RemoteEnvironmentRequestError;
28​
29const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000;
30const isUndeclaredStatusError = Schema.is(RemoteEnvironmentAuthUndeclaredStatusError);
31​
32const clientMetadataTokenExchangeFields = (
33 clientMetadata: AuthClientPresentationMetadata | undefined,
34) => {
35 const displayOs = clientMetadata?.os;
36 return {
37 ...(clientMetadata?.label ? { client_label: clientMetadata.label } : {}),
38 ...(clientMetadata?.deviceType ? { client_device_type: clientMetadata.deviceType } : {}),
39 ...(displayOs && displayOs !== "unknown" && displayOs !== "other"
40 ? { client_os: displayOs }
41 : {}),
42 };
43};
44​
45/** Hashes of who is connecting. Only hashes leave the client. */
46export interface ClientOwnerParams {
47 readonly connect?: string;
48 readonly device?: string;
50​
51/**
52 * Tells the environment, for analytics, which T3 Connect account and device
53 * are connecting, so it can count the environment as theirs.
54 */
55export const readClientOwnerParams = Effect.gen(function* () {
56 const session = yield* Effect.serviceOption(ClientCapabilities.CloudSession);
57 const account = Option.isSome(session) ? yield* session.value.identity : Option.none();
58 const device = yield* (yield* ClientCapabilities.AnalyticsDevice).id;
59 return {
60 ...(Option.isSome(account) ? { connect: hashTelemetryId(account.value.accountId) } : {}),
61 ...(Option.isSome(device) ? { device: hashTelemetryId(device.value) } : {}),
62 } satisfies ClientOwnerParams;
63});
64​
65export const appendClientConnectionParams = (
66 url: URL,
67 clientMetadata: AuthClientPresentationMetadata | undefined,
68 connectionMethod?: ClientConnectionMethod,
69 owners?: ClientOwnerParams,
70): void => {
71 if (clientMetadata?.surface) {
72 url.searchParams.set("clientSurface", clientMetadata.surface);
73 }
74 if (clientMetadata?.appVersion) {
75 url.searchParams.set("clientAppVersion", clientMetadata.appVersion);
76 }
77 if (clientMetadata?.deviceType) {
78 const deviceType =
79 clientMetadata.deviceType === "mobile"
80 ? "phone"
81 : clientMetadata.deviceType === "desktop" || clientMetadata.deviceType === "tablet"
82 ? clientMetadata.deviceType
83 : "unknown";
84 url.searchParams.set("clientDeviceType", deviceType);
85 }
86 if (clientMetadata?.os) {
87 url.searchParams.set("clientOs", clientMetadata.os);
88 }
89 if (clientMetadata?.surface === "web") {
90 if (clientMetadata.webDeployment) {
91 url.searchParams.set("clientWebDeployment", clientMetadata.webDeployment);
92 }
93 if (clientMetadata.browser) {
94 url.searchParams.set("clientBrowser", clientMetadata.browser);
95 }
96 }
97 if (clientMetadata?.surface === "mobile") {
98 if (clientMetadata.osMajorVersion !== undefined) {
99 url.searchParams.set("clientOsMajorVersion", String(clientMetadata.osMajorVersion));
100 }
101 if (clientMetadata.deviceModel) {
102 url.searchParams.set("clientDeviceModel", clientMetadata.deviceModel);
103 }
104 }
105 if (connectionMethod) {
106 url.searchParams.set("connectionMethod", connectionMethod);
107 }
108 if (owners?.connect) {
109 url.searchParams.set("clientOwner", owners.connect);
110 }
111 if (owners?.device) {
112 url.searchParams.set("clientDevice", owners.device);
113 }
114};
115​
116export const exchangeRemoteDpopAccessToken = Effect.fn(
117 "clientRuntime.authorization.exchangeRemoteDpopAccessToken",
118)(function* (input: {
119 readonly httpBaseUrl: string;
120 readonly credential: string;
121 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
122 readonly clientMetadata?: AuthClientPresentationMetadata;
123 readonly dpopProof: string;
124 readonly timeoutMs?: number;
125}) {
126 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
127 const response = yield* executeEnvironmentHttpRequest(
128 environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),
129 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
130 client.token({
131 headers: { dpop: input.dpopProof },
132 payload: {
133 grant_type: AuthTokenExchangeGrantType,
134 subject_token: input.credential,
135 subject_token_type: AuthEnvironmentBootstrapTokenType,
136 requested_token_type: AuthAccessTokenType,
137 ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),
138 ...clientMetadataTokenExchangeFields(input.clientMetadata),
139 },
140 }),
141 );
142 return response;
143});
144​
145export const bootstrapRemoteBearerSession = Effect.fn(
146 "clientRuntime.authorization.bootstrapRemoteBearerSession",
147)(function* (input: {
148 readonly httpBaseUrl: string;
149 readonly credential: string;
150 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
151 readonly clientMetadata?: AuthClientPresentationMetadata;
152 readonly timeoutMs?: number;
153}) {
154 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
155 return yield* executeEnvironmentHttpRequest(
156 environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),
157 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
158 client.token({
159 headers: {},
160 payload: {
161 grant_type: AuthTokenExchangeGrantType,
162 subject_token: input.credential,
163 subject_token_type: AuthEnvironmentBootstrapTokenType,
164 requested_token_type: AuthAccessTokenType,
165 ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),
166 ...clientMetadataTokenExchangeFields(input.clientMetadata),
167 },
168 }),
169 );
170});
171​
172export const fetchRemoteSessionState = Effect.fn(
173 "clientRuntime.authorization.fetchRemoteSessionState",
174)(function* (input: {
175 readonly httpBaseUrl: string;
176 readonly bearerToken: string;
177 readonly timeoutMs?: number;
178}) {
179 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
180 return yield* executeEnvironmentHttpRequest(
181 environmentEndpointUrl(input.httpBaseUrl, "/api/auth/session"),
182 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
183 client.session({
184 headers: {
185 authorization: `Bearer ${input.bearerToken}`,
186 },
187 }),
188 );
189});
190​
191const webSocketTicketPath = (use: AuthWebSocketTicketUse | undefined) =>
192 use === undefined ? "/api/auth/websocket-ticket" : `/api/auth/websocket-ticket/${use}`;
193​
194/**
195 * A server that predates ticket audiences has no `/:use` route and answers 404.
196 * Its tickets are the unbound kind it always issued, so the bare path is the
197 * right request there, not an error.
198 */
199const issueWebSocketTicketWithFallback = <E, R>(
200 use: AuthWebSocketTicketUse | undefined,
201 issue: (
202 use: AuthWebSocketTicketUse | undefined,
203 ) => Effect.Effect<AuthWebSocketTicketResult, E, R>,
204 canFallBack = true,
205) =>
206 use === undefined || !canFallBack
207 ? issue(use)
208 : issue(use).pipe(
209 Effect.catchIf(
210 (error) => isUndeclaredStatusError(error) && error.status === 404,
211 () => issue(undefined),
212 ),
213 );
214​
215export const issueRemoteWebSocketTicket = Effect.fn(
216 "clientRuntime.authorization.issueRemoteWebSocketTicket",
217)(function* (input: {
218 readonly httpBaseUrl: string;
219 readonly bearerToken: string;
220 readonly use?: AuthWebSocketTicketUse;
221 readonly timeoutMs?: number;
222}) {
223 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
224 const headers = { authorization: `Bearer ${input.bearerToken}` };
225 return yield* issueWebSocketTicketWithFallback(input.use, (use) =>
226 executeEnvironmentHttpRequest(
227 environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath(use)),
228 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
229 use === undefined
230 ? client.webSocketTicket({ headers })
231 : client.webSocketTicketFor({ headers, params: { use } }),
232 ),
233 );
234});
235​
236export const issueRemoteDpopWebSocketTicket = Effect.fn(
237 "clientRuntime.authorization.issueRemoteDpopWebSocketTicket",
238)(function* <E = never>(input: {
239 readonly httpBaseUrl: string;
240 readonly accessToken: string;
241 readonly dpopProof: string;
242 readonly use?: AuthWebSocketTicketUse;
243 /** Proof for the bare path, used only when the server lacks the `/:use` route. */
244 readonly fallbackProof?: Effect.Effect<string, E>;
245 readonly timeoutMs?: number;
246}) {
247 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
248 const fallbackProof = input.fallbackProof;
249 return yield* issueWebSocketTicketWithFallback(
250 input.use,
251 (use) =>
252 Effect.gen(function* () {
253 // The proof names the path it signs, so the fallback request needs its own.
254 const dpopProof =
255 use === input.use || fallbackProof === undefined ? input.dpopProof : yield* fallbackProof;
256 const headers = { authorization: `DPoP ${input.accessToken}`, dpop: dpopProof };
257 return yield* executeEnvironmentHttpRequest(
258 environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath(use)),
259 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
260 use === undefined
261 ? client.webSocketTicket({ headers })
262 : client.webSocketTicketFor({ headers, params: { use } }),
263 );
264 }),
265 fallbackProof !== undefined,
266 );
267});
268​
269function rpcSocketUrl(wsBaseUrl: string): URL {
270 const url = new URL(wsBaseUrl);
271 if (url.pathname === "" || url.pathname === "/") {
272 url.pathname = "/ws";
273 }
274 return url;
276​
277export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
278 "clientRuntime.authorization.resolveRemoteWebSocketConnectionUrl",
279)(function* (input: {
280 readonly wsBaseUrl: string;
281 readonly httpBaseUrl: string;
282 readonly bearerToken: string;
283 readonly clientMetadata?: AuthClientPresentationMetadata;
284 readonly connectionMethod?: ClientConnectionMethod;
285 readonly timeoutMs?: number;
286}) {
287 const issued = yield* issueRemoteWebSocketTicket({
288 httpBaseUrl: input.httpBaseUrl,
289 bearerToken: input.bearerToken,
290 use: "rpc",
291 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
292 });
293​
294 const url = rpcSocketUrl(input.wsBaseUrl);
295 url.searchParams.set("wsTicket", Redacted.value(issued.ticket));
296 appendClientConnectionParams(
297 url,
298 input.clientMetadata,
299 input.connectionMethod,
300 yield* readClientOwnerParams,
301 );
302 return url.toString();
303});
304​
305/**
306 * A DPoP client's RPC ticket is bound to its key, so the upgrade carries a
307 * proof too. A WebSocket cannot set headers, so it rides in the `dpop` query
308 * parameter and names the socket URL as the HTTP request the server sees.
309 */
310export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn(
311 "clientRuntime.authorization.resolveRemoteDpopWebSocketConnectionUrl",
312)(function* <E>(input: {
313 readonly wsBaseUrl: string;
314 readonly httpBaseUrl: string;
315 readonly accessToken: string;
316 readonly createProof: (input: {
317 readonly method: "GET" | "POST";
318 readonly url: string;
319 readonly accessToken: string;
320 }) => Effect.Effect<string, E>;
321 readonly clientMetadata?: AuthClientPresentationMetadata;
322 readonly connectionMethod?: ClientConnectionMethod;
323 readonly timeoutMs?: number;
324}) {
325 const ticketProof = yield* input.createProof({
326 method: "POST",
327 url: environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath("rpc")),
328 accessToken: input.accessToken,
329 });
330 const issued = yield* issueRemoteDpopWebSocketTicket({
331 httpBaseUrl: input.httpBaseUrl,
332 accessToken: input.accessToken,
333 dpopProof: ticketProof,
334 use: "rpc",
335 fallbackProof: Effect.suspend(() =>
336 input.createProof({
337 method: "POST",
338 url: environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath(undefined)),
339 accessToken: input.accessToken,
340 }),
341 ),
342 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
343 });
344 const url = rpcSocketUrl(input.wsBaseUrl);
345 const upgradeProof = yield* input.createProof({
346 method: "GET",
347 url: `${url.protocol === "wss:" ? "https:" : "http:"}//${url.host}${url.pathname}`,
348 accessToken: Redacted.value(issued.ticket),
349 });
350 url.searchParams.set("wsTicket", Redacted.value(issued.ticket));
351 url.searchParams.set("dpop", upgradeProof);
352 appendClientConnectionParams(
353 url,
354 input.clientMetadata,
355 input.connectionMethod,
356 yield* readClientOwnerParams,
357 );
358 return url.toString();
359});