@baukit/auth-native 0.18.3 → 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.
package/src/index.ts CHANGED
@@ -1,3 +1,20 @@
1
+ import { OidcError } from './oidc-errors.js';
2
+ import {
3
+ discoverProvider,
4
+ fetchSubject,
5
+ normalizeConfig,
6
+ refreshWindowMs,
7
+ makeSession,
8
+ readProviderError,
9
+ isTerminalRefreshRejection,
10
+ isTerminalRefreshError,
11
+ transientRefreshError,
12
+ parseSession,
13
+ isTokenResponse,
14
+ type NormalizedConfig,
15
+ type ReceivedTokenResponse,
16
+ } from './oidc-support.js';
17
+
1
18
  export {
2
19
  AUTHORIZATION_STATE_ENTROPY_BYTES,
3
20
  appearanceStateDecoration,
@@ -5,54 +22,8 @@ export {
5
22
  type AppearanceMode,
6
23
  type AppearanceState,
7
24
  } from './authorization-state.js';
8
-
9
- export type OidcErrorCode =
10
- | 'authorization_failed'
11
- | 'callback_state_mismatch'
12
- | 'discovery_failed'
13
- | 'invalid_discovery_document'
14
- | 'invalid_token_response'
15
- | 'invalid_userinfo_response'
16
- | 'issuer_mismatch'
17
- | 'pkce_verifier_missing'
18
- | 'refresh_failed'
19
- | 'storage_failed'
20
- | 'token_exchange_failed'
21
- | 'userinfo_failed';
22
-
23
- const SAFE_ERROR_MESSAGES = {
24
- authorization_failed: 'OIDC authorization failed.',
25
- callback_state_mismatch: 'OIDC callback state did not match the login transaction.',
26
- discovery_failed: 'OIDC provider discovery failed.',
27
- invalid_discovery_document: 'OIDC provider returned invalid discovery metadata.',
28
- invalid_token_response: 'OIDC token endpoint returned an invalid response.',
29
- invalid_userinfo_response: 'OIDC UserInfo endpoint returned an invalid response.',
30
- issuer_mismatch: 'OIDC provider issuer did not match the configured issuer.',
31
- pkce_verifier_missing: 'OIDC login did not produce a PKCE verifier.',
32
- refresh_failed: 'OIDC token refresh failed.',
33
- storage_failed: 'Secure authentication storage failed.',
34
- token_exchange_failed: 'OIDC token exchange failed.',
35
- userinfo_failed: 'OIDC UserInfo request failed.',
36
- } as const satisfies Record<OidcErrorCode, string>;
37
-
38
- /** An authentication failure whose message is safe to display or log. */
39
- export class OidcError extends Error {
40
- public readonly code: OidcErrorCode;
41
- public readonly status: number | undefined;
42
- /** True only when retrying the failed operation may succeed without signing in again. */
43
- public readonly retryable: boolean;
44
-
45
- public constructor(
46
- code: OidcErrorCode,
47
- options: { readonly retryable?: boolean; readonly status?: number } = {},
48
- ) {
49
- super(SAFE_ERROR_MESSAGES[code]);
50
- this.name = 'OidcError';
51
- this.code = code;
52
- this.status = options.status;
53
- this.retryable = options.retryable ?? false;
54
- }
55
- }
25
+ export { OidcError, safeAuthErrorMessage, type OidcErrorCode } from './oidc-errors.js';
26
+ export { normalizeIssuer } from './oidc-support.js';
56
27
 
57
28
  export interface NativeOidcConfig {
58
29
  readonly issuer: string;
@@ -175,38 +146,6 @@ export interface NativeOidcEnvironment {
175
146
  readonly now: () => number;
176
147
  }
177
148
 
178
- interface NormalizedConfig {
179
- readonly issuer: string;
180
- readonly clientId: string;
181
- readonly redirectUri: string;
182
- readonly audience?: string;
183
- readonly resource?: string;
184
- readonly scopes: readonly string[];
185
- readonly postLogoutRedirectUri: string;
186
- readonly refreshLeewayMs: number;
187
- readonly refreshOnRestore: boolean;
188
- readonly storageKeyPrefix: string;
189
- }
190
-
191
- interface RawProviderMetadata {
192
- readonly issuer: string;
193
- readonly authorization_endpoint: string;
194
- readonly token_endpoint: string;
195
- readonly userinfo_endpoint: string;
196
- readonly end_session_endpoint?: string;
197
- }
198
-
199
- interface TokenResponse {
200
- readonly access_token: string;
201
- readonly expires_in: number;
202
- readonly refresh_token?: string;
203
- readonly id_token?: string;
204
- }
205
-
206
- interface ReceivedTokenResponse extends TokenResponse {
207
- readonly receivedAt: number;
208
- }
209
-
210
149
  type SessionListener = (session: OidcSession | undefined) => void;
211
150
  type SessionExpiredListener = (event: SessionExpiredEvent) => void;
212
151
 
@@ -292,15 +231,7 @@ export class NativeOidcClient {
292
231
  if (result.type === 'cancel' || result.type === 'dismiss') {
293
232
  return { status: 'cancelled', reason: result.type };
294
233
  }
295
- if (result.type === 'error' || result.code.length === 0) {
296
- throw new OidcError('authorization_failed');
297
- }
298
- if (result.state.length === 0 || result.state !== result.expectedState) {
299
- throw new OidcError('callback_state_mismatch');
300
- }
301
- if (result.codeVerifier.length === 0) {
302
- throw new OidcError('pkce_verifier_missing');
303
- }
234
+ assertAuthorizationSucceeded(result);
304
235
 
305
236
  const tokens = await this.exchange(
306
237
  metadata.tokenEndpoint,
@@ -596,294 +527,16 @@ export class NativeOidcClient {
596
527
  }
597
528
  }
598
529
 
599
- /** Removes trailing issuer slashes while rejecting query strings and fragments. */
600
- export function normalizeIssuer(issuer: string): string {
601
- const trimmed = issuer.trim();
602
- if (trimmed.length === 0) {
603
- throw new TypeError('OIDC issuer must not be empty.');
604
- }
605
- const url = new URL(trimmed);
606
- if (url.search.length !== 0 || url.hash.length !== 0) {
607
- throw new TypeError('OIDC issuer must not include a query string or fragment.');
608
- }
609
- return url.toString().replace(/\/+$/u, '');
610
- }
611
-
612
- /** Returns an allowlisted message without reflecting untrusted error content. */
613
- export function safeAuthErrorMessage(cause: unknown): string {
614
- return cause instanceof OidcError ? SAFE_ERROR_MESSAGES[cause.code] : 'OIDC login failed.';
615
- }
616
-
617
- async function discoverProvider(
618
- issuer: string,
619
- fetchImplementation: FetchPort,
620
- ): Promise<OidcProviderMetadata> {
621
- let response: Response;
622
- try {
623
- response = await fetchImplementation(`${issuer}/.well-known/openid-configuration`);
624
- } catch {
625
- throw new OidcError('discovery_failed');
626
- }
627
- if (!response.ok) {
628
- throw new OidcError('discovery_failed', { status: response.status });
629
- }
630
- let value: unknown;
631
- try {
632
- value = await response.json();
633
- } catch {
634
- throw new OidcError('invalid_discovery_document');
635
- }
636
- if (!isProviderMetadata(value)) {
637
- throw new OidcError('invalid_discovery_document');
638
- }
639
- if (normalizeIssuer(value.issuer) !== issuer) {
640
- throw new OidcError('issuer_mismatch');
641
- }
642
- return Object.freeze({
643
- issuer,
644
- authorizationEndpoint: value.authorization_endpoint,
645
- tokenEndpoint: value.token_endpoint,
646
- userInfoEndpoint: value.userinfo_endpoint,
647
- ...(value.end_session_endpoint === undefined
648
- ? {}
649
- : { endSessionEndpoint: value.end_session_endpoint }),
650
- });
651
- }
652
-
653
- async function fetchSubject(
654
- endpoint: string,
655
- accessToken: string,
656
- fetchImplementation: FetchPort,
657
- ): Promise<string> {
658
- let response: Response;
659
- try {
660
- response = await fetchImplementation(endpoint, {
661
- headers: { authorization: `Bearer ${accessToken}` },
662
- });
663
- } catch {
664
- throw new OidcError('userinfo_failed');
530
+ function assertAuthorizationSucceeded(
531
+ result: AuthorizationResult,
532
+ ): asserts result is Extract<AuthorizationResult, { readonly type: 'success' }> {
533
+ if (result.type !== 'success' || result.code.length === 0) {
534
+ throw new OidcError('authorization_failed');
665
535
  }
666
- if (!response.ok) {
667
- throw new OidcError('userinfo_failed', { status: response.status });
536
+ if (result.state.length === 0 || result.state !== result.expectedState) {
537
+ throw new OidcError('callback_state_mismatch');
668
538
  }
669
- let value: unknown;
670
- try {
671
- value = await response.json();
672
- } catch {
673
- throw new OidcError('invalid_userinfo_response');
539
+ if (result.codeVerifier.length === 0) {
540
+ throw new OidcError('pkce_verifier_missing');
674
541
  }
675
- if (!isObject(value) || typeof value['sub'] !== 'string' || value['sub'].length === 0) {
676
- throw new OidcError('invalid_userinfo_response');
677
- }
678
- return value['sub'];
679
- }
680
-
681
- function normalizeConfig(config: NativeOidcConfig): NormalizedConfig {
682
- const issuer = normalizeIssuer(config.issuer);
683
- const clientId = requiredText(config.clientId, 'OIDC client ID');
684
- const redirectUri = requiredUrl(config.redirectUri, 'OIDC redirect URI');
685
- const refreshLeewaySeconds = config.refreshLeewaySeconds ?? 30;
686
- if (!Number.isFinite(refreshLeewaySeconds) || refreshLeewaySeconds < 0) {
687
- throw new RangeError('OIDC refresh leeway must be a non-negative number.');
688
- }
689
- const storageKeyPrefix =
690
- config.storageKeyPrefix ??
691
- `baukit.auth-native.${storageKeyPart(issuer)}.${storageKeyPart(clientId)}`;
692
- if (storageKeyPrefix.length === 0) {
693
- throw new TypeError('OIDC storage key prefix must not be empty.');
694
- }
695
- if (!/^[A-Za-z0-9._-]+$/u.test(storageKeyPrefix)) {
696
- throw new TypeError(
697
- "OIDC storage key prefix must contain only ASCII letters, digits, '.', '-' and '_'.",
698
- );
699
- }
700
- return {
701
- issuer,
702
- clientId,
703
- redirectUri,
704
- ...(config.audience === undefined
705
- ? {}
706
- : { audience: requiredText(config.audience, 'OIDC audience') }),
707
- ...(config.resource === undefined
708
- ? {}
709
- : { resource: requiredText(config.resource, 'OIDC resource') }),
710
- scopes: normalizeScopes(config.scopes, config.offlineAccess),
711
- postLogoutRedirectUri: requiredUrl(
712
- config.postLogoutRedirectUri ?? redirectUri,
713
- 'OIDC post-logout redirect URI',
714
- ),
715
- refreshLeewayMs: refreshLeewaySeconds * 1000,
716
- refreshOnRestore: config.refreshOnRestore ?? false,
717
- storageKeyPrefix,
718
- };
719
- }
720
-
721
- function storageKeyPart(value: string): string {
722
- return encodeURIComponent(value).replace(
723
- /[!'()*_.~%]/gu,
724
- (character) => `_${character.charCodeAt(0).toString(16)}`,
725
- );
726
- }
727
-
728
- function normalizeScopes(scopes: readonly string[] | undefined, offlineAccess = false): string[] {
729
- const requested = scopes ?? ['openid', 'profile', 'email'];
730
- const normalized: string[] = [];
731
- for (const scope of ['openid', ...requested, ...(offlineAccess ? ['offline_access'] : [])]) {
732
- const trimmed = scope.trim();
733
- if (trimmed.length === 0 || /\s/u.test(trimmed)) {
734
- throw new TypeError('OIDC scopes must be non-empty and contain no whitespace.');
735
- }
736
- if (!normalized.includes(trimmed)) {
737
- normalized.push(trimmed);
738
- }
739
- }
740
- return normalized;
741
- }
742
-
743
- function requiredText(value: string, label: string): string {
744
- const trimmed = value.trim();
745
- if (trimmed.length === 0) {
746
- throw new TypeError(`${label} must not be empty.`);
747
- }
748
- return trimmed;
749
- }
750
-
751
- function requiredUrl(value: string, label: string): string {
752
- const trimmed = requiredText(value, label);
753
- try {
754
- return new URL(trimmed).toString();
755
- } catch {
756
- throw new TypeError(`${label} must be an absolute URL.`);
757
- }
758
- }
759
-
760
- function refreshWindowMs(issuedAt: number, expiresAt: number, configuredLeewayMs: number): number {
761
- return Math.min(configuredLeewayMs, (expiresAt - issuedAt) / 2);
762
- }
763
-
764
- function makeSession(
765
- tokens: ReceivedTokenResponse,
766
- subject: string,
767
- previous?: OidcSession,
768
- ): OidcSession {
769
- const refreshToken = tokens.refresh_token ?? previous?.refreshToken;
770
- const idToken = tokens.id_token ?? previous?.idToken;
771
- return Object.freeze({
772
- subject,
773
- accessToken: tokens.access_token,
774
- issuedAt: tokens.receivedAt,
775
- expiresAt: tokens.receivedAt + tokens.expires_in * 1000,
776
- ...(refreshToken === undefined ? {} : { refreshToken }),
777
- ...(idToken === undefined ? {} : { idToken }),
778
- });
779
- }
780
-
781
- async function readProviderError(response: Response): Promise<string | undefined> {
782
- try {
783
- const value: unknown = await response.json();
784
- return isObject(value) && typeof value['error'] === 'string' ? value['error'] : undefined;
785
- } catch {
786
- return undefined;
787
- }
788
- }
789
-
790
- function isTerminalRefreshRejection(status: number, providerError: string | undefined): boolean {
791
- return (
792
- status === 400 ||
793
- status === 401 ||
794
- providerError === 'invalid_grant' ||
795
- providerError === 'invalid_token'
796
- );
797
- }
798
-
799
- function isTerminalRefreshError(cause: unknown): boolean {
800
- return cause instanceof OidcError && cause.code === 'refresh_failed' && !cause.retryable;
801
- }
802
-
803
- function transientRefreshError(cause: unknown): OidcError {
804
- if (cause instanceof OidcError && cause.code === 'refresh_failed' && cause.retryable) {
805
- return cause;
806
- }
807
- return new OidcError('refresh_failed', {
808
- retryable: true,
809
- ...(cause instanceof OidcError && cause.status !== undefined ? { status: cause.status } : {}),
810
- });
811
- }
812
-
813
- function parseSession(raw: string | null): OidcSession | undefined {
814
- if (raw === null) {
815
- return undefined;
816
- }
817
- try {
818
- const value: unknown = JSON.parse(raw);
819
- if (isSession(value)) {
820
- return Object.freeze({ ...value });
821
- }
822
- } catch {
823
- // Corrupt state is discarded by the caller without reflecting its content.
824
- }
825
- return undefined;
826
- }
827
-
828
- function isSession(value: unknown): value is OidcSession {
829
- return (
830
- isObject(value) &&
831
- typeof value['subject'] === 'string' &&
832
- value['subject'].length > 0 &&
833
- typeof value['accessToken'] === 'string' &&
834
- value['accessToken'].length > 0 &&
835
- typeof value['issuedAt'] === 'number' &&
836
- Number.isFinite(value['issuedAt']) &&
837
- typeof value['expiresAt'] === 'number' &&
838
- Number.isFinite(value['expiresAt']) &&
839
- (value['refreshToken'] === undefined ||
840
- (typeof value['refreshToken'] === 'string' && value['refreshToken'].length > 0)) &&
841
- (value['idToken'] === undefined ||
842
- (typeof value['idToken'] === 'string' && value['idToken'].length > 0))
843
- );
844
- }
845
-
846
- function isTokenResponse(value: unknown): value is TokenResponse {
847
- return (
848
- isObject(value) &&
849
- typeof value['access_token'] === 'string' &&
850
- value['access_token'].length > 0 &&
851
- typeof value['expires_in'] === 'number' &&
852
- Number.isFinite(value['expires_in']) &&
853
- value['expires_in'] > 0 &&
854
- (value['refresh_token'] === undefined ||
855
- (typeof value['refresh_token'] === 'string' && value['refresh_token'].length > 0)) &&
856
- (value['id_token'] === undefined ||
857
- (typeof value['id_token'] === 'string' && value['id_token'].length > 0))
858
- );
859
- }
860
-
861
- function isProviderMetadata(value: unknown): value is RawProviderMetadata {
862
- if (
863
- !isObject(value) ||
864
- typeof value['issuer'] !== 'string' ||
865
- typeof value['authorization_endpoint'] !== 'string' ||
866
- typeof value['token_endpoint'] !== 'string' ||
867
- typeof value['userinfo_endpoint'] !== 'string' ||
868
- (value['end_session_endpoint'] !== undefined &&
869
- typeof value['end_session_endpoint'] !== 'string')
870
- ) {
871
- return false;
872
- }
873
- try {
874
- normalizeIssuer(value['issuer']);
875
- requiredUrl(value['authorization_endpoint'], 'OIDC authorization endpoint');
876
- requiredUrl(value['token_endpoint'], 'OIDC token endpoint');
877
- requiredUrl(value['userinfo_endpoint'], 'OIDC UserInfo endpoint');
878
- if (value['end_session_endpoint'] !== undefined) {
879
- requiredUrl(value['end_session_endpoint'], 'OIDC end-session endpoint');
880
- }
881
- return true;
882
- } catch {
883
- return false;
884
- }
885
- }
886
-
887
- function isObject(value: unknown): value is Record<string, unknown> {
888
- return typeof value === 'object' && value !== null;
889
542
  }
@@ -0,0 +1,52 @@
1
+ export type OidcErrorCode =
2
+ | 'authorization_failed'
3
+ | 'callback_state_mismatch'
4
+ | 'discovery_failed'
5
+ | 'invalid_discovery_document'
6
+ | 'invalid_token_response'
7
+ | 'invalid_userinfo_response'
8
+ | 'issuer_mismatch'
9
+ | 'pkce_verifier_missing'
10
+ | 'refresh_failed'
11
+ | 'storage_failed'
12
+ | 'token_exchange_failed'
13
+ | 'userinfo_failed';
14
+
15
+ const SAFE_ERROR_MESSAGES = {
16
+ authorization_failed: 'OIDC authorization failed.',
17
+ callback_state_mismatch: 'OIDC callback state did not match the login transaction.',
18
+ discovery_failed: 'OIDC provider discovery failed.',
19
+ invalid_discovery_document: 'OIDC provider returned invalid discovery metadata.',
20
+ invalid_token_response: 'OIDC token endpoint returned an invalid response.',
21
+ invalid_userinfo_response: 'OIDC UserInfo endpoint returned an invalid response.',
22
+ issuer_mismatch: 'OIDC provider issuer did not match the configured issuer.',
23
+ pkce_verifier_missing: 'OIDC login did not produce a PKCE verifier.',
24
+ refresh_failed: 'OIDC token refresh failed.',
25
+ storage_failed: 'Secure authentication storage failed.',
26
+ token_exchange_failed: 'OIDC token exchange failed.',
27
+ userinfo_failed: 'OIDC UserInfo request failed.',
28
+ } as const satisfies Record<OidcErrorCode, string>;
29
+
30
+ /** An authentication failure whose message is safe to display or log. */
31
+ export class OidcError extends Error {
32
+ public readonly code: OidcErrorCode;
33
+ public readonly status: number | undefined;
34
+ /** True only when retrying the failed operation may succeed without signing in again. */
35
+ public readonly retryable: boolean;
36
+
37
+ public constructor(
38
+ code: OidcErrorCode,
39
+ options: { readonly retryable?: boolean; readonly status?: number } = {},
40
+ ) {
41
+ super(SAFE_ERROR_MESSAGES[code]);
42
+ this.name = 'OidcError';
43
+ this.code = code;
44
+ this.status = options.status;
45
+ this.retryable = options.retryable ?? false;
46
+ }
47
+ }
48
+
49
+ /** Returns an allowlisted message without reflecting untrusted error content. */
50
+ export function safeAuthErrorMessage(cause: unknown): string {
51
+ return cause instanceof OidcError ? SAFE_ERROR_MESSAGES[cause.code] : 'OIDC login failed.';
52
+ }