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

remote.ts

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