Open History to see the last commit
1import {
2 AuthAccessTokenType,
3 type AuthClientPresentationMetadata,
4 AuthEnvironmentBootstrapTokenType,
5 AuthTokenExchangeGrantType,
6 type ClientConnectionMethod,
7 type AuthEnvironmentScope,
8} from "@t3tools/contracts";
9import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
10import * as Effect from "effect/Effect";
11import { environmentEndpointUrl } from "../environment/endpoint.ts";
12import {
13 executeEnvironmentHttpRequest,
14 makeEnvironmentHttpApiClient,
15 type RemoteEnvironmentRequestError,
16} from "../rpc/http.ts";
17
18export {
19 RemoteEnvironmentAuthInvalidJsonError,
20 RemoteEnvironmentAuthTimeoutError,
21 RemoteEnvironmentAuthUndeclaredStatusError,
22} from "../rpc/http.ts";
23export type RemoteEnvironmentAuthError = RemoteEnvironmentRequestError;
24
25const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000;
26
27const clientMetadataTokenExchangeFields = (
28 clientMetadata: AuthClientPresentationMetadata | undefined,
29) => {
30 const displayOs = clientMetadata?.os;
31 return {
32 ...(clientMetadata?.label ? { client_label: clientMetadata.label } : {}),
33 ...(clientMetadata?.deviceType ? { client_device_type: clientMetadata.deviceType } : {}),
34 ...(displayOs && displayOs !== "unknown" && displayOs !== "other"
35 ? { client_os: displayOs }
36 : {}),
37 };
38};
39
40// The server reads these off the /ws upgrade URL next to wsTicket. Optional on
41// both ends: old servers ignore unknown params, old clients never send them.
42export const appendClientConnectionParams = (
43 url: URL,
44 clientMetadata: AuthClientPresentationMetadata | undefined,
45 connectionMethod?: ClientConnectionMethod,
46): void => {
47 if (clientMetadata?.surface) {
48 url.searchParams.set("clientSurface", clientMetadata.surface);
49 }
50 if (clientMetadata?.appVersion) {
51 url.searchParams.set("clientAppVersion", clientMetadata.appVersion);
52 }
53 if (clientMetadata?.deviceType) {
54 const deviceType =
55 clientMetadata.deviceType === "mobile"
56 ? "phone"
57 : clientMetadata.deviceType === "desktop" || clientMetadata.deviceType === "tablet"
58 ? clientMetadata.deviceType
59 : "unknown";
60 url.searchParams.set("clientDeviceType", deviceType);
61 }
62 if (clientMetadata?.os) {
63 url.searchParams.set("clientOs", clientMetadata.os);
64 }
65 if (clientMetadata?.surface === "web") {
66 if (clientMetadata.webDeployment) {
67 url.searchParams.set("clientWebDeployment", clientMetadata.webDeployment);
68 }
69 if (clientMetadata.browser) {
70 url.searchParams.set("clientBrowser", clientMetadata.browser);
71 }
72 }
73 if (clientMetadata?.surface === "mobile") {
74 if (clientMetadata.osMajorVersion !== undefined) {
75 url.searchParams.set("clientOsMajorVersion", String(clientMetadata.osMajorVersion));
76 }
77 if (clientMetadata.deviceModel) {
78 url.searchParams.set("clientDeviceModel", clientMetadata.deviceModel);
79 }
80 }
81 if (connectionMethod) {
82 url.searchParams.set("connectionMethod", connectionMethod);
83 }
84};
85
86export const exchangeRemoteDpopAccessToken = Effect.fn(
87 "clientRuntime.authorization.exchangeRemoteDpopAccessToken",
88)(function* (input: {
89 readonly httpBaseUrl: string;
90 readonly credential: string;
91 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
92 readonly clientMetadata?: AuthClientPresentationMetadata;
93 readonly dpopProof: string;
94 readonly timeoutMs?: number;
95}) {
96 const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
97 const response = yield* executeEnvironmentHttpRequest(
98 environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),
99 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
100 client.auth.token({
101 headers: { dpop: input.dpopProof },
102 payload: {
103 grant_type: AuthTokenExchangeGrantType,
104 subject_token: input.credential,
105 subject_token_type: AuthEnvironmentBootstrapTokenType,
106 requested_token_type: AuthAccessTokenType,
107 ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),
108 ...clientMetadataTokenExchangeFields(input.clientMetadata),
109 },
110 }),
111 );
112 return response;
113});
114
115export const bootstrapRemoteBearerSession = Effect.fn(
116 "clientRuntime.authorization.bootstrapRemoteBearerSession",
117)(function* (input: {
118 readonly httpBaseUrl: string;
119 readonly credential: string;
120 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
121 readonly clientMetadata?: AuthClientPresentationMetadata;
122 readonly timeoutMs?: number;
123}) {
124 const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
125 return yield* executeEnvironmentHttpRequest(
126 environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),
127 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
128 client.auth.token({
129 headers: {},
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});
141
142export const fetchRemoteSessionState = Effect.fn(
143 "clientRuntime.authorization.fetchRemoteSessionState",
144)(function* (input: {
145 readonly httpBaseUrl: string;
146 readonly bearerToken: string;
147 readonly timeoutMs?: number;
148}) {
149 const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
150 return yield* executeEnvironmentHttpRequest(
151 environmentEndpointUrl(input.httpBaseUrl, "/api/auth/session"),
152 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
153 client.auth.session({
154 headers: {
155 authorization: `Bearer ${input.bearerToken}`,
156 },
157 }),
158 );
159});
160
161export const fetchRemoteDpopSessionState = Effect.fn(
162 "clientRuntime.authorization.fetchRemoteDpopSessionState",
163)(function* (input: {
164 readonly httpBaseUrl: string;
165 readonly accessToken: string;
166 readonly dpopProof: string;
167 readonly timeoutMs?: number;
168}) {
169 const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
170 return yield* executeEnvironmentHttpRequest(
171 environmentEndpointUrl(input.httpBaseUrl, "/api/auth/session"),
172 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
173 client.auth.session({
174 headers: {
175 authorization: `DPoP ${input.accessToken}`,
176 dpop: input.dpopProof,
177 },
178 }),
179 );
180});
181
182export const issueRemoteWebSocketTicket = Effect.fn(
183 "clientRuntime.authorization.issueRemoteWebSocketTicket",
184)(function* (input: {
185 readonly httpBaseUrl: string;
186 readonly bearerToken: string;
187 readonly timeoutMs?: number;
188}) {
189 const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
190 return yield* executeEnvironmentHttpRequest(
191 environmentEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),
192 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
193 client.auth.webSocketTicket({
194 headers: {
195 authorization: `Bearer ${input.bearerToken}`,
196 },
197 }),
198 );
199});
200
201export const issueRemoteDpopWebSocketTicket = Effect.fn(
202 "clientRuntime.authorization.issueRemoteDpopWebSocketTicket",
203)(function* (input: {
204 readonly httpBaseUrl: string;
205 readonly accessToken: string;
206 readonly dpopProof: string;
207 readonly timeoutMs?: number;
208}) {
209 const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
210 return yield* executeEnvironmentHttpRequest(
211 environmentEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),
212 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
213 client.auth.webSocketTicket({
214 headers: {
215 authorization: `DPoP ${input.accessToken}`,
216 dpop: input.dpopProof,
217 },
218 }),
219 );
220});
221
222export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
223 "clientRuntime.authorization.resolveRemoteWebSocketConnectionUrl",
224)(function* (input: {
225 readonly wsBaseUrl: string;
226 readonly httpBaseUrl: string;
227 readonly bearerToken: string;
228 readonly clientMetadata?: AuthClientPresentationMetadata;
229 readonly connectionMethod?: ClientConnectionMethod;
230 readonly timeoutMs?: number;
231}) {
232 const issued = yield* issueRemoteWebSocketTicket({
233 httpBaseUrl: input.httpBaseUrl,
234 bearerToken: input.bearerToken,
235 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
236 });
237
238 const url = new URL(input.wsBaseUrl);
239 if (url.pathname === "" || url.pathname === "/") {
240 url.pathname = "/ws";
241 }
242 url.searchParams.set("wsTicket", issued.ticket);
243 appendClientConnectionParams(url, input.clientMetadata, input.connectionMethod);
244 return url.toString();
245});
246
247export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn(
248 "clientRuntime.authorization.resolveRemoteDpopWebSocketConnectionUrl",
249)(function* (input: {
250 readonly wsBaseUrl: string;
251 readonly httpBaseUrl: string;
252 readonly accessToken: string;
253 readonly dpopProof: string;
254 readonly clientMetadata?: AuthClientPresentationMetadata;
255 readonly connectionMethod?: ClientConnectionMethod;
256 readonly timeoutMs?: number;
257}) {
258 const issued = yield* issueRemoteDpopWebSocketTicket({
259 httpBaseUrl: input.httpBaseUrl,
260 accessToken: input.accessToken,
261 dpopProof: input.dpopProof,
262 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
263 });
264 const url = new URL(input.wsBaseUrl);
265 if (url.pathname === "" || url.pathname === "/") {
266 url.pathname = "/ws";
267 }
268 url.searchParams.set("wsTicket", issued.ticket);
269 appendClientConnectionParams(url, input.clientMetadata, input.connectionMethod);
270 return url.toString();
271});