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