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