@baukit/auth-native 0.18.2 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,329 @@
1
+ import { isRecord } from '@baukit/type-guards';
2
+
3
+ import type { FetchPort, NativeOidcConfig, OidcProviderMetadata, OidcSession } from './index.js';
4
+ import { OidcError } from './oidc-errors.js';
5
+
6
+ export interface NormalizedConfig {
7
+ readonly issuer: string;
8
+ readonly clientId: string;
9
+ readonly redirectUri: string;
10
+ readonly audience?: string;
11
+ readonly resource?: string;
12
+ readonly scopes: readonly string[];
13
+ readonly postLogoutRedirectUri: string;
14
+ readonly refreshLeewayMs: number;
15
+ readonly refreshOnRestore: boolean;
16
+ readonly storageKeyPrefix: string;
17
+ }
18
+
19
+ export interface RawProviderMetadata {
20
+ readonly issuer: string;
21
+ readonly authorization_endpoint: string;
22
+ readonly token_endpoint: string;
23
+ readonly userinfo_endpoint: string;
24
+ readonly end_session_endpoint?: string;
25
+ }
26
+
27
+ export interface TokenResponse {
28
+ readonly access_token: string;
29
+ readonly expires_in: number;
30
+ readonly refresh_token?: string;
31
+ readonly id_token?: string;
32
+ }
33
+
34
+ export interface ReceivedTokenResponse extends TokenResponse {
35
+ readonly receivedAt: number;
36
+ }
37
+
38
+ /** Removes trailing issuer slashes while rejecting query strings and fragments. */
39
+ export function normalizeIssuer(issuer: string): string {
40
+ const trimmed = issuer.trim();
41
+ if (trimmed.length === 0) {
42
+ throw new TypeError('OIDC issuer must not be empty.');
43
+ }
44
+ const url = new URL(trimmed);
45
+ if (url.search.length !== 0 || url.hash.length !== 0) {
46
+ throw new TypeError('OIDC issuer must not include a query string or fragment.');
47
+ }
48
+ return url.toString().replace(/\/+$/u, '');
49
+ }
50
+
51
+ export async function discoverProvider(
52
+ issuer: string,
53
+ fetchImplementation: FetchPort,
54
+ ): Promise<OidcProviderMetadata> {
55
+ let response: Response;
56
+ try {
57
+ response = await fetchImplementation(`${issuer}/.well-known/openid-configuration`);
58
+ } catch {
59
+ throw new OidcError('discovery_failed');
60
+ }
61
+ if (!response.ok) {
62
+ throw new OidcError('discovery_failed', { status: response.status });
63
+ }
64
+ let value: unknown;
65
+ try {
66
+ value = await response.json();
67
+ } catch {
68
+ throw new OidcError('invalid_discovery_document');
69
+ }
70
+ if (!isProviderMetadata(value)) {
71
+ throw new OidcError('invalid_discovery_document');
72
+ }
73
+ if (normalizeIssuer(value.issuer) !== issuer) {
74
+ throw new OidcError('issuer_mismatch');
75
+ }
76
+ return Object.freeze({
77
+ issuer,
78
+ authorizationEndpoint: value.authorization_endpoint,
79
+ tokenEndpoint: value.token_endpoint,
80
+ userInfoEndpoint: value.userinfo_endpoint,
81
+ ...(value.end_session_endpoint === undefined
82
+ ? {}
83
+ : { endSessionEndpoint: value.end_session_endpoint }),
84
+ });
85
+ }
86
+
87
+ export async function fetchSubject(
88
+ endpoint: string,
89
+ accessToken: string,
90
+ fetchImplementation: FetchPort,
91
+ ): Promise<string> {
92
+ let response: Response;
93
+ try {
94
+ response = await fetchImplementation(endpoint, {
95
+ headers: { authorization: `Bearer ${accessToken}` },
96
+ });
97
+ } catch {
98
+ throw new OidcError('userinfo_failed');
99
+ }
100
+ if (!response.ok) {
101
+ throw new OidcError('userinfo_failed', { status: response.status });
102
+ }
103
+ let value: unknown;
104
+ try {
105
+ value = await response.json();
106
+ } catch {
107
+ throw new OidcError('invalid_userinfo_response');
108
+ }
109
+ if (!isRecord(value) || typeof value['sub'] !== 'string' || value['sub'].length === 0) {
110
+ throw new OidcError('invalid_userinfo_response');
111
+ }
112
+ return value['sub'];
113
+ }
114
+
115
+ export function normalizeConfig(config: NativeOidcConfig): NormalizedConfig {
116
+ const issuer = normalizeIssuer(config.issuer);
117
+ const clientId = requiredText(config.clientId, 'OIDC client ID');
118
+ const redirectUri = requiredUrl(config.redirectUri, 'OIDC redirect URI');
119
+ const refreshLeewaySeconds = config.refreshLeewaySeconds ?? 30;
120
+ if (!Number.isFinite(refreshLeewaySeconds) || refreshLeewaySeconds < 0) {
121
+ throw new RangeError('OIDC refresh leeway must be a non-negative number.');
122
+ }
123
+ const storageKeyPrefix =
124
+ config.storageKeyPrefix ??
125
+ `baukit.auth-native.${storageKeyPart(issuer)}.${storageKeyPart(clientId)}`;
126
+ if (storageKeyPrefix.length === 0) {
127
+ throw new TypeError('OIDC storage key prefix must not be empty.');
128
+ }
129
+ if (!/^[A-Za-z0-9._-]+$/u.test(storageKeyPrefix)) {
130
+ throw new TypeError(
131
+ "OIDC storage key prefix must contain only ASCII letters, digits, '.', '-' and '_'.",
132
+ );
133
+ }
134
+ return {
135
+ issuer,
136
+ clientId,
137
+ redirectUri,
138
+ ...(config.audience === undefined
139
+ ? {}
140
+ : { audience: requiredText(config.audience, 'OIDC audience') }),
141
+ ...(config.resource === undefined
142
+ ? {}
143
+ : { resource: requiredText(config.resource, 'OIDC resource') }),
144
+ scopes: normalizeScopes(config.scopes, config.offlineAccess),
145
+ postLogoutRedirectUri: requiredUrl(
146
+ config.postLogoutRedirectUri ?? redirectUri,
147
+ 'OIDC post-logout redirect URI',
148
+ ),
149
+ refreshLeewayMs: refreshLeewaySeconds * 1000,
150
+ refreshOnRestore: config.refreshOnRestore ?? false,
151
+ storageKeyPrefix,
152
+ };
153
+ }
154
+
155
+ export function storageKeyPart(value: string): string {
156
+ return encodeURIComponent(value).replace(
157
+ /[!'()*_.~%]/gu,
158
+ (character) => `_${character.charCodeAt(0).toString(16)}`,
159
+ );
160
+ }
161
+
162
+ export function normalizeScopes(
163
+ scopes: readonly string[] | undefined,
164
+ offlineAccess = false,
165
+ ): string[] {
166
+ const requested = scopes ?? ['openid', 'profile', 'email'];
167
+ const normalized: string[] = [];
168
+ for (const scope of ['openid', ...requested, ...(offlineAccess ? ['offline_access'] : [])]) {
169
+ const trimmed = scope.trim();
170
+ if (trimmed.length === 0 || /\s/u.test(trimmed)) {
171
+ throw new TypeError('OIDC scopes must be non-empty and contain no whitespace.');
172
+ }
173
+ if (!normalized.includes(trimmed)) {
174
+ normalized.push(trimmed);
175
+ }
176
+ }
177
+ return normalized;
178
+ }
179
+
180
+ export function requiredText(value: string, label: string): string {
181
+ const trimmed = value.trim();
182
+ if (trimmed.length === 0) {
183
+ throw new TypeError(`${label} must not be empty.`);
184
+ }
185
+ return trimmed;
186
+ }
187
+
188
+ export function requiredUrl(value: string, label: string): string {
189
+ const trimmed = requiredText(value, label);
190
+ try {
191
+ return new URL(trimmed).toString();
192
+ } catch {
193
+ throw new TypeError(`${label} must be an absolute URL.`);
194
+ }
195
+ }
196
+
197
+ export function refreshWindowMs(
198
+ issuedAt: number,
199
+ expiresAt: number,
200
+ configuredLeewayMs: number,
201
+ ): number {
202
+ return Math.min(configuredLeewayMs, (expiresAt - issuedAt) / 2);
203
+ }
204
+
205
+ export function makeSession(
206
+ tokens: ReceivedTokenResponse,
207
+ subject: string,
208
+ previous?: OidcSession,
209
+ ): OidcSession {
210
+ const refreshToken = tokens.refresh_token ?? previous?.refreshToken;
211
+ const idToken = tokens.id_token ?? previous?.idToken;
212
+ return Object.freeze({
213
+ subject,
214
+ accessToken: tokens.access_token,
215
+ issuedAt: tokens.receivedAt,
216
+ expiresAt: tokens.receivedAt + tokens.expires_in * 1000,
217
+ ...(refreshToken === undefined ? {} : { refreshToken }),
218
+ ...(idToken === undefined ? {} : { idToken }),
219
+ });
220
+ }
221
+
222
+ export async function readProviderError(response: Response): Promise<string | undefined> {
223
+ try {
224
+ const value: unknown = await response.json();
225
+ return isRecord(value) && typeof value['error'] === 'string' ? value['error'] : undefined;
226
+ } catch {
227
+ return undefined;
228
+ }
229
+ }
230
+
231
+ export function isTerminalRefreshRejection(
232
+ status: number,
233
+ providerError: string | undefined,
234
+ ): boolean {
235
+ return (
236
+ status === 400 ||
237
+ status === 401 ||
238
+ providerError === 'invalid_grant' ||
239
+ providerError === 'invalid_token'
240
+ );
241
+ }
242
+
243
+ export function isTerminalRefreshError(cause: unknown): boolean {
244
+ return cause instanceof OidcError && cause.code === 'refresh_failed' && !cause.retryable;
245
+ }
246
+
247
+ export function transientRefreshError(cause: unknown): OidcError {
248
+ if (cause instanceof OidcError && cause.code === 'refresh_failed' && cause.retryable) {
249
+ return cause;
250
+ }
251
+ return new OidcError('refresh_failed', {
252
+ retryable: true,
253
+ ...(cause instanceof OidcError && cause.status !== undefined ? { status: cause.status } : {}),
254
+ });
255
+ }
256
+
257
+ export function parseSession(raw: string | null): OidcSession | undefined {
258
+ if (raw === null) {
259
+ return undefined;
260
+ }
261
+ try {
262
+ const value: unknown = JSON.parse(raw);
263
+ if (isSession(value)) {
264
+ return Object.freeze({ ...value });
265
+ }
266
+ } catch {
267
+ // Corrupt state is discarded by the caller without reflecting its content.
268
+ }
269
+ return undefined;
270
+ }
271
+
272
+ export function isSession(value: unknown): value is OidcSession {
273
+ return (
274
+ isRecord(value) &&
275
+ typeof value['subject'] === 'string' &&
276
+ value['subject'].length > 0 &&
277
+ typeof value['accessToken'] === 'string' &&
278
+ value['accessToken'].length > 0 &&
279
+ typeof value['issuedAt'] === 'number' &&
280
+ Number.isFinite(value['issuedAt']) &&
281
+ typeof value['expiresAt'] === 'number' &&
282
+ Number.isFinite(value['expiresAt']) &&
283
+ (value['refreshToken'] === undefined ||
284
+ (typeof value['refreshToken'] === 'string' && value['refreshToken'].length > 0)) &&
285
+ (value['idToken'] === undefined ||
286
+ (typeof value['idToken'] === 'string' && value['idToken'].length > 0))
287
+ );
288
+ }
289
+
290
+ export function isTokenResponse(value: unknown): value is TokenResponse {
291
+ return (
292
+ isRecord(value) &&
293
+ typeof value['access_token'] === 'string' &&
294
+ value['access_token'].length > 0 &&
295
+ typeof value['expires_in'] === 'number' &&
296
+ Number.isFinite(value['expires_in']) &&
297
+ value['expires_in'] > 0 &&
298
+ (value['refresh_token'] === undefined ||
299
+ (typeof value['refresh_token'] === 'string' && value['refresh_token'].length > 0)) &&
300
+ (value['id_token'] === undefined ||
301
+ (typeof value['id_token'] === 'string' && value['id_token'].length > 0))
302
+ );
303
+ }
304
+
305
+ export function isProviderMetadata(value: unknown): value is RawProviderMetadata {
306
+ if (
307
+ !isRecord(value) ||
308
+ typeof value['issuer'] !== 'string' ||
309
+ typeof value['authorization_endpoint'] !== 'string' ||
310
+ typeof value['token_endpoint'] !== 'string' ||
311
+ typeof value['userinfo_endpoint'] !== 'string' ||
312
+ (value['end_session_endpoint'] !== undefined &&
313
+ typeof value['end_session_endpoint'] !== 'string')
314
+ ) {
315
+ return false;
316
+ }
317
+ try {
318
+ normalizeIssuer(value['issuer']);
319
+ requiredUrl(value['authorization_endpoint'], 'OIDC authorization endpoint');
320
+ requiredUrl(value['token_endpoint'], 'OIDC token endpoint');
321
+ requiredUrl(value['userinfo_endpoint'], 'OIDC UserInfo endpoint');
322
+ if (value['end_session_endpoint'] !== undefined) {
323
+ requiredUrl(value['end_session_endpoint'], 'OIDC end-session endpoint');
324
+ }
325
+ return true;
326
+ } catch {
327
+ return false;
328
+ }
329
+ }