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 makeEnvironmentHttpApiGroupClient,
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* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
97 const response = yield* executeEnvironmentHttpRequest(
98 environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),
99 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
100 client.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* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
125 return yield* executeEnvironmentHttpRequest(
126 environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),
127 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
128 client.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* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
150 return yield* executeEnvironmentHttpRequest(
151 environmentEndpointUrl(input.httpBaseUrl, "/api/auth/session"),
152 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
153 client.session({
154 headers: {
155 authorization: `Bearer ${input.bearerToken}`,
156 },
157 }),
158 );
159});
160
161export const issueRemoteWebSocketTicket = Effect.fn(
162 "clientRuntime.authorization.issueRemoteWebSocketTicket",
163)(function* (input: {
164 readonly httpBaseUrl: string;
165 readonly bearerToken: string;
166 readonly timeoutMs?: number;
167}) {
168 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
169 return yield* executeEnvironmentHttpRequest(
170 environmentEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),
171 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
172 client.webSocketTicket({
173 headers: {
174 authorization: `Bearer ${input.bearerToken}`,
175 },
176 }),
177 );
178});
179
180export const issueRemoteDpopWebSocketTicket = Effect.fn(
181 "clientRuntime.authorization.issueRemoteDpopWebSocketTicket",
182)(function* (input: {
183 readonly httpBaseUrl: string;
184 readonly accessToken: string;
185 readonly dpopProof: string;
186 readonly timeoutMs?: number;
187}) {
188 const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth");
189 return yield* executeEnvironmentHttpRequest(
190 environmentEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),
191 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
192 client.webSocketTicket({
193 headers: {
194 authorization: `DPoP ${input.accessToken}`,
195 dpop: input.dpopProof,
196 },
197 }),
198 );
199});
200
201export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
202 "clientRuntime.authorization.resolveRemoteWebSocketConnectionUrl",
203)(function* (input: {
204 readonly wsBaseUrl: string;
205 readonly httpBaseUrl: string;
206 readonly bearerToken: string;
207 readonly clientMetadata?: AuthClientPresentationMetadata;
208 readonly connectionMethod?: ClientConnectionMethod;
209 readonly timeoutMs?: number;
210}) {
211 const issued = yield* issueRemoteWebSocketTicket({
212 httpBaseUrl: input.httpBaseUrl,
213 bearerToken: input.bearerToken,
214 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
215 });
216
217 const url = new URL(input.wsBaseUrl);
218 if (url.pathname === "" || url.pathname === "/") {
219 url.pathname = "/ws";
220 }
221 url.searchParams.set("wsTicket", issued.ticket);
222 appendClientConnectionParams(url, input.clientMetadata, input.connectionMethod);
223 return url.toString();
224});
225
226export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn(
227 "clientRuntime.authorization.resolveRemoteDpopWebSocketConnectionUrl",
228)(function* (input: {
229 readonly wsBaseUrl: string;
230 readonly httpBaseUrl: string;
231 readonly accessToken: string;
232 readonly dpopProof: string;
233 readonly clientMetadata?: AuthClientPresentationMetadata;
234 readonly connectionMethod?: ClientConnectionMethod;
235 readonly timeoutMs?: number;
236}) {
237 const issued = yield* issueRemoteDpopWebSocketTicket({
238 httpBaseUrl: input.httpBaseUrl,
239 accessToken: input.accessToken,
240 dpopProof: input.dpopProof,
241 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
242 });
243 const url = new URL(input.wsBaseUrl);
244 if (url.pathname === "" || url.pathname === "/") {
245 url.pathname = "/ws";
246 }
247 url.searchParams.set("wsTicket", issued.ticket);
248 appendClientConnectionParams(url, input.clientMetadata, input.connectionMethod);
249 return url.toString();
250});