@chipmobilesdk/rn-auth 0.3.0 → 0.3.1

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,83 +1,71 @@
1
- /**
2
- * @chipmobilesdk/rn-auth — reusable Microsoft Entra External ID authentication
3
- * for ChipMobileSdk-family React Native apps (public OIDC/PKCE client, no
4
- * backend). This is the single public entrypoint (LIB-003); modules under
5
- * `core/`, `tokens/`, `oidc/`, `access/`, and `diagnostics/` are private.
6
- */
7
-
8
- import { createAuthMachine } from './core/authMachine';
9
- import type { Auth, AuthConfig, CreateAuthOptions } from './config/types';
10
-
11
- /** Create the auth controller. Throws AuthConfigError on invalid config (FR-005). */
12
- export function createAuth(config: AuthConfig, options?: CreateAuthOptions): Auth {
13
- return createAuthMachine(config, options);
14
- }
15
-
16
- // Public types
17
- export type {
18
- Auth,
19
- AuthConfig,
20
- CreateAuthOptions,
21
- AuthState,
22
- AuthStatus,
23
- RestoreStatus,
24
- Profile,
25
- ProviderIdentity,
26
- ProviderConfig,
27
- ProviderId,
28
- DevicePlatform,
29
- ResourceConfig,
30
- ClaimMatcher,
31
- AccessTierMapping,
32
- AccessTier,
33
- AccessTokenResult,
34
- AccessTokenStatus,
35
- PremiumGateResult,
36
- GlobalSignOutResult,
37
- } from './config/types';
38
-
39
- // Ports + default adapters
40
- export type { SecureTokenStore } from './tokens/secureStore';
41
- export { createKeychainSecureStore, AUTH_STORAGE_KEY } from './tokens/secureStore';
42
- export type {
43
- OidcAuthClient,
44
- OidcTokens,
45
- AuthorizeParams,
46
- RefreshParams,
47
- EndSessionParams,
48
- } from './oidc/authClient';
49
- export { createAppAuthClient } from './oidc/authClient';
50
-
51
- // Access-tier evaluation (also exported for app-side reuse/testing)
52
- export { evaluateAccessTier, failClosedTier } from './access/accessTier';
53
-
54
- // Diagnostics
55
- export {
56
- AuthError,
57
- AuthConfigError,
58
- isAuthError,
59
- redact,
60
- } from './diagnostics/errors';
61
- export type { AuthErrorCode, AuthErrorAudience } from './diagnostics/errors';
62
- export {
63
- DEFAULT_MESSAGES,
64
- resolveMessages,
65
- } from './diagnostics/messageKeys';
66
- export type { AuthMessageMap, AuthMessageKey } from './diagnostics/messageKeys';
67
-
68
- // React bindings
69
- export { AuthProvider } from './react/AuthProvider';
70
- export type { AuthProviderProps } from './react/AuthProvider';
71
- export {
72
- useAuth,
73
- useProfile,
74
- useAccessTier,
75
- useAccessToken,
76
- useSignInProvider,
77
- useSignInProviders,
78
- } from './react/hooks';
79
- export type {
80
- UseAuthResult,
81
- UseAccessTokenResult,
82
- UseAccessTokenStatus,
83
- } from './react/hooks';
1
+ /**
2
+ * @chipmobilesdk/rn-auth — reusable Microsoft Entra External ID authentication
3
+ * for ChipMobileSdk-family React Native apps (public OIDC/PKCE client, no
4
+ * backend). This is the single public entrypoint (LIB-003); modules under
5
+ * `core/`, `tokens/`, `oidc/`, `access/`, and `diagnostics/` are private.
6
+ */
7
+
8
+ import { createAuthMachine } from './core/authMachine';
9
+ import type { Auth, AuthConfig, CreateAuthOptions } from './config/types';
10
+
11
+ /** Create the auth controller. Throws AuthConfigError on invalid config (FR-005). */
12
+ export function createAuth(config: AuthConfig, options?: CreateAuthOptions): Auth {
13
+ return createAuthMachine(config, options);
14
+ }
15
+
16
+ // Public types
17
+ export type {
18
+ Auth,
19
+ AuthConfig,
20
+ CreateAuthOptions,
21
+ AuthState,
22
+ AuthStatus,
23
+ RestoreStatus,
24
+ Profile,
25
+ ProviderIdentity,
26
+ ProviderConfig,
27
+ ProviderId,
28
+ DevicePlatform,
29
+ ResourceConfig,
30
+ ClaimMatcher,
31
+ AccessTierMapping,
32
+ AccessTier,
33
+ AccessTokenResult,
34
+ AccessTokenStatus,
35
+ PremiumGateResult,
36
+ GlobalSignOutResult,
37
+ } from './config/types';
38
+
39
+ // Ports + default adapters
40
+ export type { SecureTokenStore } from './tokens/secureStore';
41
+ export { createKeychainSecureStore, AUTH_STORAGE_KEY } from './tokens/secureStore';
42
+ export type {
43
+ OidcAuthClient,
44
+ OidcTokens,
45
+ AuthorizeParams,
46
+ RefreshParams,
47
+ EndSessionParams,
48
+ } from './oidc/authClient';
49
+ export { createAppAuthClient } from './oidc/authClient';
50
+
51
+ // Access-tier evaluation (also exported for app-side reuse/testing)
52
+ export { evaluateAccessTier, failClosedTier } from './access/accessTier';
53
+
54
+ // Diagnostics
55
+ export { AuthError, AuthConfigError, isAuthError, redact } from './diagnostics/errors';
56
+ export type { AuthErrorCode, AuthErrorAudience } from './diagnostics/errors';
57
+ export { DEFAULT_MESSAGES, resolveMessages } from './diagnostics/messageKeys';
58
+ export type { AuthMessageMap, AuthMessageKey } from './diagnostics/messageKeys';
59
+
60
+ // React bindings
61
+ export { AuthProvider } from './react/AuthProvider';
62
+ export type { AuthProviderProps } from './react/AuthProvider';
63
+ export {
64
+ useAuth,
65
+ useProfile,
66
+ useAccessTier,
67
+ useAccessToken,
68
+ useSignInProvider,
69
+ useSignInProviders,
70
+ } from './react/hooks';
71
+ export type { UseAuthResult, UseAccessTokenResult, UseAccessTokenStatus } from './react/hooks';
@@ -1,199 +1,195 @@
1
- /**
2
- * OidcAuthClient port + default react-native-app-auth adapter (R1).
3
- *
4
- * The port abstracts the Authorization Code + PKCE public-client flow so the
5
- * auth engine is testable without native code. The default adapter lazily
6
- * requires react-native-app-auth and is validated on device.
7
- */
8
-
9
- import { classifyAppAuthError } from './classifyError';
10
-
11
- export interface OidcTokens {
12
- /** Resource/audience access token (present for authorize and resource refresh). */
13
- accessToken?: string;
14
- /**
15
- * Refresh token used for silent acquisition and restore. Absent when the
16
- * provider issued none — a refresh that does not rotate, or an authorize the
17
- * tenant answered without `offline_access`.
18
- */
19
- refreshToken?: string;
20
- /** Raw id token (JWT). Absent from a refresh requested without `openid`. */
21
- idToken?: string;
22
- /** Decoded id-token (or access-token) claims used for profile + access tier. */
23
- claims: Record<string, unknown>;
24
- /** Access-token expiry in epoch milliseconds, when available. */
25
- accessTokenExpiresAt?: number;
26
- }
27
-
28
- export interface AuthorizeParams {
29
- authority: string;
30
- clientId: string;
31
- redirectUrl: string;
32
- scopes: string[];
33
- /** Additional OIDC parameters, e.g. `domain_hint` for social routing. */
34
- additionalParameters?: Record<string, string>;
35
- }
36
-
37
- export interface RefreshParams {
38
- authority: string;
39
- clientId: string;
40
- redirectUrl: string;
41
- refreshToken: string;
42
- scopes: string[];
43
- }
44
-
45
- export interface EndSessionParams {
46
- authority: string;
47
- clientId: string;
48
- redirectUrl: string;
49
- idToken?: string;
50
- }
51
-
52
- export interface OidcAuthClient {
53
- authorize(params: AuthorizeParams): Promise<OidcTokens>;
54
- refresh(params: RefreshParams): Promise<OidcTokens>;
55
- endSession(params: EndSessionParams): Promise<void>;
56
- }
57
-
58
- /** Decode the payload segment of a JWT without any dependency (device-safe). */
59
- export function decodeJwtClaims(jwt: string | null | undefined): Record<string, unknown> {
60
- if (typeof jwt !== 'string') {
61
- return {};
62
- }
63
- const parts = jwt.split('.');
64
- if (parts.length < 2) {
65
- return {};
66
- }
67
- try {
68
- const json = base64UrlDecode(parts[1]);
69
- return JSON.parse(json) as Record<string, unknown>;
70
- } catch {
71
- return {};
72
- }
73
- }
74
-
75
- const BASE64_CHARS =
76
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
77
-
78
- function base64UrlDecode(input: string): string {
79
- let base64 = input.replace(/-/g, '+').replace(/_/g, '/');
80
- while (base64.length % 4 !== 0) {
81
- base64 += '=';
82
- }
83
- let bytes = '';
84
- let buffer = 0;
85
- let bits = 0;
86
- for (const char of base64) {
87
- if (char === '=') {
88
- break;
89
- }
90
- const index = BASE64_CHARS.indexOf(char);
91
- if (index === -1) {
92
- continue;
93
- }
94
- // Standard base64 bit assembly; bitwise ops are intentional here.
95
- // eslint-disable-next-line no-bitwise
96
- buffer = (buffer << 6) | index;
97
- bits += 6;
98
- if (bits >= 8) {
99
- bits -= 8;
100
- // eslint-disable-next-line no-bitwise
101
- bytes += String.fromCharCode((buffer >> bits) & 0xff);
102
- }
103
- }
104
- // Interpret the byte string (each char is a 0–255 byte) as UTF-8 without
105
- // relying on the deprecated global `escape`.
106
- try {
107
- const percentEncoded = Array.from(bytes)
108
- .map(char => '%' + char.charCodeAt(0).toString(16).padStart(2, '0'))
109
- .join('');
110
- return decodeURIComponent(percentEncoded);
111
- } catch {
112
- return bytes;
113
- }
114
- }
115
-
116
-
117
- export interface AppAuthClientOptions {
118
- /** When true, the OIDC discovery document is fetched from `${authority}`. */
119
- useDiscovery?: boolean;
120
- }
121
-
122
- /**
123
- * Default OidcAuthClient adapter wrapping react-native-app-auth (PKCE public
124
- * client). Lazily requires the native module. Validated on device (R8).
125
- */
126
- export function createAppAuthClient(
127
- options: AppAuthClientOptions = {},
128
- ): OidcAuthClient {
129
- // Lazy require so injecting a fake client never loads native code.
130
- const AppAuth = require('react-native-app-auth');
131
- const useDiscovery = options.useDiscovery ?? true;
132
-
133
- const baseConfig = (
134
- authority: string,
135
- clientId: string,
136
- redirectUrl: string,
137
- scopes: string[],
138
- ) => ({
139
- issuer: useDiscovery ? authority : undefined,
140
- clientId,
141
- redirectUrl,
142
- scopes,
143
- });
144
-
145
- const toTokens = (result: {
146
- accessToken?: string;
147
- refreshToken?: string | null;
148
- idToken?: string | null;
149
- accessTokenExpirationDate?: string;
150
- }): OidcTokens => ({
151
- accessToken: result.accessToken,
152
- // Absent stays absent: an empty string was indistinguishable from a real
153
- // token by type, and silently disabled session persistence.
154
- refreshToken: result.refreshToken || undefined,
155
- idToken: result.idToken || undefined,
156
- claims: decodeJwtClaims(result.idToken),
157
- accessTokenExpiresAt: result.accessTokenExpirationDate
158
- ? new Date(result.accessTokenExpirationDate).getTime()
159
- : undefined,
160
- });
161
-
162
- return {
163
- async authorize(params) {
164
- try {
165
- const result = await AppAuth.authorize({
166
- ...baseConfig(params.authority, params.clientId, params.redirectUrl, params.scopes),
167
- additionalParameters: params.additionalParameters,
168
- });
169
- return toTokens(result);
170
- } catch (error) {
171
- throw classifyAppAuthError(error);
172
- }
173
- },
174
- async refresh(params) {
175
- try {
176
- const result = await AppAuth.refresh(
177
- baseConfig(params.authority, params.clientId, params.redirectUrl, params.scopes),
178
- { refreshToken: params.refreshToken },
179
- );
180
- return toTokens(result);
181
- } catch (error) {
182
- throw classifyAppAuthError(error);
183
- }
184
- },
185
- async endSession(params) {
186
- try {
187
- await AppAuth.logout(
188
- baseConfig(params.authority, params.clientId, params.redirectUrl, []),
189
- {
190
- idToken: params.idToken ?? '',
191
- postLogoutRedirectUrl: params.redirectUrl,
192
- },
193
- );
194
- } catch (error) {
195
- throw classifyAppAuthError(error);
196
- }
197
- },
198
- };
199
- }
1
+ /**
2
+ * OidcAuthClient port + default react-native-app-auth adapter (R1).
3
+ *
4
+ * The port abstracts the Authorization Code + PKCE public-client flow so the
5
+ * auth engine is testable without native code. The default adapter lazily
6
+ * requires react-native-app-auth and is validated on device.
7
+ */
8
+
9
+ import { classifyAppAuthError } from './classifyError';
10
+
11
+ export interface OidcTokens {
12
+ /** Resource/audience access token (present for authorize and resource refresh). */
13
+ accessToken?: string;
14
+ /**
15
+ * Refresh token used for silent acquisition and restore. Absent when the
16
+ * provider issued none — a refresh that does not rotate, or an authorize the
17
+ * tenant answered without `offline_access`.
18
+ */
19
+ refreshToken?: string;
20
+ /** Raw id token (JWT). Absent from a refresh requested without `openid`. */
21
+ idToken?: string;
22
+ /** Decoded id-token (or access-token) claims used for profile + access tier. */
23
+ claims: Record<string, unknown>;
24
+ /** Access-token expiry in epoch milliseconds, when available. */
25
+ accessTokenExpiresAt?: number;
26
+ }
27
+
28
+ export interface AuthorizeParams {
29
+ authority: string;
30
+ clientId: string;
31
+ redirectUrl: string;
32
+ scopes: string[];
33
+ /** Additional OIDC parameters, e.g. `domain_hint` for social routing. */
34
+ additionalParameters?: Record<string, string>;
35
+ }
36
+
37
+ export interface RefreshParams {
38
+ authority: string;
39
+ clientId: string;
40
+ redirectUrl: string;
41
+ refreshToken: string;
42
+ scopes: string[];
43
+ }
44
+
45
+ export interface EndSessionParams {
46
+ authority: string;
47
+ clientId: string;
48
+ redirectUrl: string;
49
+ idToken?: string;
50
+ }
51
+
52
+ export interface OidcAuthClient {
53
+ authorize(params: AuthorizeParams): Promise<OidcTokens>;
54
+ refresh(params: RefreshParams): Promise<OidcTokens>;
55
+ endSession(params: EndSessionParams): Promise<void>;
56
+ }
57
+
58
+ /** Decode the payload segment of a JWT without any dependency (device-safe). */
59
+ export function decodeJwtClaims(jwt: string | null | undefined): Record<string, unknown> {
60
+ if (typeof jwt !== 'string') {
61
+ return {};
62
+ }
63
+ const parts = jwt.split('.');
64
+ if (parts.length < 2) {
65
+ return {};
66
+ }
67
+ try {
68
+ const json = base64UrlDecode(parts[1]);
69
+ return JSON.parse(json) as Record<string, unknown>;
70
+ } catch {
71
+ return {};
72
+ }
73
+ }
74
+
75
+ const BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
76
+
77
+ function base64UrlDecode(input: string): string {
78
+ let base64 = input.replace(/-/g, '+').replace(/_/g, '/');
79
+ while (base64.length % 4 !== 0) {
80
+ base64 += '=';
81
+ }
82
+ let bytes = '';
83
+ let buffer = 0;
84
+ let bits = 0;
85
+ for (const char of base64) {
86
+ if (char === '=') {
87
+ break;
88
+ }
89
+ const index = BASE64_CHARS.indexOf(char);
90
+ if (index === -1) {
91
+ continue;
92
+ }
93
+ // Standard base64 bit assembly; bitwise ops are intentional here.
94
+ // eslint-disable-next-line no-bitwise
95
+ buffer = (buffer << 6) | index;
96
+ bits += 6;
97
+ if (bits >= 8) {
98
+ bits -= 8;
99
+ // eslint-disable-next-line no-bitwise
100
+ bytes += String.fromCharCode((buffer >> bits) & 0xff);
101
+ }
102
+ }
103
+ // Interpret the byte string (each char is a 0–255 byte) as UTF-8 without
104
+ // relying on the deprecated global `escape`.
105
+ try {
106
+ const percentEncoded = Array.from(bytes)
107
+ .map(char => '%' + char.charCodeAt(0).toString(16).padStart(2, '0'))
108
+ .join('');
109
+ return decodeURIComponent(percentEncoded);
110
+ } catch {
111
+ return bytes;
112
+ }
113
+ }
114
+
115
+ export interface AppAuthClientOptions {
116
+ /** When true, the OIDC discovery document is fetched from `${authority}`. */
117
+ useDiscovery?: boolean;
118
+ }
119
+
120
+ /**
121
+ * Default OidcAuthClient adapter wrapping react-native-app-auth (PKCE public
122
+ * client). Lazily requires the native module. Validated on device (R8).
123
+ */
124
+ export function createAppAuthClient(options: AppAuthClientOptions = {}): OidcAuthClient {
125
+ // Lazy require so injecting a fake client never loads native code.
126
+ const AppAuth = require('react-native-app-auth');
127
+ const useDiscovery = options.useDiscovery ?? true;
128
+
129
+ const baseConfig = (
130
+ authority: string,
131
+ clientId: string,
132
+ redirectUrl: string,
133
+ scopes: string[],
134
+ ) => ({
135
+ issuer: useDiscovery ? authority : undefined,
136
+ clientId,
137
+ redirectUrl,
138
+ scopes,
139
+ });
140
+
141
+ const toTokens = (result: {
142
+ accessToken?: string;
143
+ refreshToken?: string | null;
144
+ idToken?: string | null;
145
+ accessTokenExpirationDate?: string;
146
+ }): OidcTokens => ({
147
+ accessToken: result.accessToken,
148
+ // Absent stays absent: an empty string was indistinguishable from a real
149
+ // token by type, and silently disabled session persistence.
150
+ refreshToken: result.refreshToken || undefined,
151
+ idToken: result.idToken || undefined,
152
+ claims: decodeJwtClaims(result.idToken),
153
+ accessTokenExpiresAt: result.accessTokenExpirationDate
154
+ ? new Date(result.accessTokenExpirationDate).getTime()
155
+ : undefined,
156
+ });
157
+
158
+ return {
159
+ async authorize(params) {
160
+ try {
161
+ const result = await AppAuth.authorize({
162
+ ...baseConfig(params.authority, params.clientId, params.redirectUrl, params.scopes),
163
+ additionalParameters: params.additionalParameters,
164
+ });
165
+ return toTokens(result);
166
+ } catch (error) {
167
+ throw classifyAppAuthError(error);
168
+ }
169
+ },
170
+ async refresh(params) {
171
+ try {
172
+ const result = await AppAuth.refresh(
173
+ baseConfig(params.authority, params.clientId, params.redirectUrl, params.scopes),
174
+ { refreshToken: params.refreshToken },
175
+ );
176
+ return toTokens(result);
177
+ } catch (error) {
178
+ throw classifyAppAuthError(error);
179
+ }
180
+ },
181
+ async endSession(params) {
182
+ try {
183
+ await AppAuth.logout(
184
+ baseConfig(params.authority, params.clientId, params.redirectUrl, []),
185
+ {
186
+ idToken: params.idToken ?? '',
187
+ postLogoutRedirectUrl: params.redirectUrl,
188
+ },
189
+ );
190
+ } catch (error) {
191
+ throw classifyAppAuthError(error);
192
+ }
193
+ },
194
+ };
195
+ }