@chipmobilesdk/rn-auth 0.4.0 → 0.6.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.
Files changed (180) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +74 -14
  3. package/lib/commonjs/access/accessTier.js +111 -0
  4. package/lib/commonjs/access/accessTier.js.map +1 -0
  5. package/lib/commonjs/app-auth.js +13 -0
  6. package/lib/commonjs/app-auth.js.map +1 -0
  7. package/lib/commonjs/config/types.js +50 -0
  8. package/lib/commonjs/config/types.js.map +1 -0
  9. package/lib/commonjs/config/validateConfig.js +114 -0
  10. package/lib/commonjs/config/validateConfig.js.map +1 -0
  11. package/lib/commonjs/core/authMachine.js +406 -0
  12. package/lib/commonjs/core/authMachine.js.map +1 -0
  13. package/lib/commonjs/core/profile.js +59 -0
  14. package/lib/commonjs/core/profile.js.map +1 -0
  15. package/lib/commonjs/core/session.js +125 -0
  16. package/lib/commonjs/core/session.js.map +1 -0
  17. package/lib/commonjs/diagnostics/errors.js +83 -0
  18. package/lib/commonjs/diagnostics/errors.js.map +1 -0
  19. package/lib/commonjs/diagnostics/messageKeys.js +51 -0
  20. package/lib/commonjs/diagnostics/messageKeys.js.map +1 -0
  21. package/lib/commonjs/index.js +175 -0
  22. package/lib/commonjs/index.js.map +1 -0
  23. package/lib/commonjs/keychain.js +13 -0
  24. package/lib/commonjs/keychain.js.map +1 -0
  25. package/lib/commonjs/oidc/authClient.js +157 -0
  26. package/lib/commonjs/oidc/authClient.js.map +1 -0
  27. package/lib/commonjs/oidc/classifyError.js +65 -0
  28. package/lib/commonjs/oidc/classifyError.js.map +1 -0
  29. package/lib/commonjs/oidc/socialRouting.js +58 -0
  30. package/lib/commonjs/oidc/socialRouting.js.map +1 -0
  31. package/lib/commonjs/package.json +1 -0
  32. package/lib/commonjs/react/AuthProvider.js +37 -0
  33. package/lib/commonjs/react/AuthProvider.js.map +1 -0
  34. package/lib/commonjs/react/hooks.js +122 -0
  35. package/lib/commonjs/react/hooks.js.map +1 -0
  36. package/lib/commonjs/testing/conformance.js +148 -0
  37. package/lib/commonjs/testing/conformance.js.map +1 -0
  38. package/lib/commonjs/testing/index.js +53 -0
  39. package/lib/commonjs/testing/index.js.map +1 -0
  40. package/lib/commonjs/tokens/accessToken.js +165 -0
  41. package/lib/commonjs/tokens/accessToken.js.map +1 -0
  42. package/lib/commonjs/tokens/secureStore.js +60 -0
  43. package/lib/commonjs/tokens/secureStore.js.map +1 -0
  44. package/lib/module/access/accessTier.js +106 -0
  45. package/lib/module/access/accessTier.js.map +1 -0
  46. package/lib/module/app-auth.js +9 -0
  47. package/lib/module/app-auth.js.map +1 -0
  48. package/lib/module/config/types.js +46 -0
  49. package/lib/module/config/types.js.map +1 -0
  50. package/lib/module/config/validateConfig.js +110 -0
  51. package/lib/module/config/validateConfig.js.map +1 -0
  52. package/lib/module/core/authMachine.js +402 -0
  53. package/lib/module/core/authMachine.js.map +1 -0
  54. package/lib/module/core/profile.js +54 -0
  55. package/lib/module/core/profile.js.map +1 -0
  56. package/lib/module/core/session.js +118 -0
  57. package/lib/module/core/session.js.map +1 -0
  58. package/lib/module/diagnostics/errors.js +74 -0
  59. package/lib/module/diagnostics/errors.js.map +1 -0
  60. package/lib/module/diagnostics/messageKeys.js +46 -0
  61. package/lib/module/diagnostics/messageKeys.js.map +1 -0
  62. package/lib/module/index.js +33 -0
  63. package/lib/module/index.js.map +1 -0
  64. package/lib/module/keychain.js +9 -0
  65. package/lib/module/keychain.js.map +1 -0
  66. package/lib/module/oidc/authClient.js +152 -0
  67. package/lib/module/oidc/authClient.js.map +1 -0
  68. package/lib/module/oidc/classifyError.js +60 -0
  69. package/lib/module/oidc/classifyError.js.map +1 -0
  70. package/lib/module/oidc/socialRouting.js +52 -0
  71. package/lib/module/oidc/socialRouting.js.map +1 -0
  72. package/lib/module/package.json +1 -0
  73. package/lib/module/react/AuthProvider.js +31 -0
  74. package/lib/module/react/AuthProvider.js.map +1 -0
  75. package/lib/module/react/hooks.js +111 -0
  76. package/lib/module/react/hooks.js.map +1 -0
  77. package/lib/module/testing/conformance.js +140 -0
  78. package/lib/module/testing/conformance.js.map +1 -0
  79. package/lib/module/testing/index.js +25 -0
  80. package/lib/module/testing/index.js.map +1 -0
  81. package/lib/module/tokens/accessToken.js +161 -0
  82. package/lib/module/tokens/accessToken.js.map +1 -0
  83. package/lib/module/tokens/secureStore.js +56 -0
  84. package/lib/module/tokens/secureStore.js.map +1 -0
  85. package/lib/typescript/commonjs/access/accessTier.d.ts +14 -0
  86. package/lib/typescript/commonjs/access/accessTier.d.ts.map +1 -0
  87. package/lib/typescript/commonjs/app-auth.d.ts +7 -0
  88. package/lib/typescript/commonjs/app-auth.d.ts.map +1 -0
  89. package/lib/typescript/commonjs/config/types.d.ts +171 -0
  90. package/lib/typescript/commonjs/config/types.d.ts.map +1 -0
  91. package/lib/typescript/commonjs/config/validateConfig.d.ts +8 -0
  92. package/lib/typescript/commonjs/config/validateConfig.d.ts.map +1 -0
  93. package/lib/typescript/commonjs/core/authMachine.d.ts +14 -0
  94. package/lib/typescript/commonjs/core/authMachine.d.ts.map +1 -0
  95. package/lib/typescript/commonjs/core/profile.d.ts +15 -0
  96. package/lib/typescript/commonjs/core/profile.d.ts.map +1 -0
  97. package/lib/typescript/commonjs/core/session.d.ts +60 -0
  98. package/lib/typescript/commonjs/core/session.d.ts.map +1 -0
  99. package/lib/typescript/commonjs/diagnostics/errors.d.ts +37 -0
  100. package/lib/typescript/commonjs/diagnostics/errors.d.ts.map +1 -0
  101. package/lib/typescript/commonjs/diagnostics/messageKeys.d.ts +57 -0
  102. package/lib/typescript/commonjs/diagnostics/messageKeys.d.ts.map +1 -0
  103. package/lib/typescript/commonjs/index.d.ts +27 -0
  104. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  105. package/lib/typescript/commonjs/keychain.d.ts +7 -0
  106. package/lib/typescript/commonjs/keychain.d.ts.map +1 -0
  107. package/lib/typescript/commonjs/oidc/authClient.d.ts +75 -0
  108. package/lib/typescript/commonjs/oidc/authClient.d.ts.map +1 -0
  109. package/lib/typescript/commonjs/oidc/classifyError.d.ts +28 -0
  110. package/lib/typescript/commonjs/oidc/classifyError.d.ts.map +1 -0
  111. package/lib/typescript/commonjs/oidc/socialRouting.d.ts +22 -0
  112. package/lib/typescript/commonjs/oidc/socialRouting.d.ts.map +1 -0
  113. package/lib/typescript/commonjs/package.json +1 -0
  114. package/lib/typescript/commonjs/react/AuthProvider.d.ts +17 -0
  115. package/lib/typescript/commonjs/react/AuthProvider.d.ts.map +1 -0
  116. package/lib/typescript/commonjs/react/hooks.d.ts +42 -0
  117. package/lib/typescript/commonjs/react/hooks.d.ts.map +1 -0
  118. package/lib/typescript/commonjs/testing/conformance.d.ts +32 -0
  119. package/lib/typescript/commonjs/testing/conformance.d.ts.map +1 -0
  120. package/lib/typescript/commonjs/testing/index.d.ts +11 -0
  121. package/lib/typescript/commonjs/testing/index.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/tokens/accessToken.d.ts +45 -0
  123. package/lib/typescript/commonjs/tokens/accessToken.d.ts.map +1 -0
  124. package/lib/typescript/commonjs/tokens/secureStore.d.ts +26 -0
  125. package/lib/typescript/commonjs/tokens/secureStore.d.ts.map +1 -0
  126. package/lib/typescript/module/access/accessTier.d.ts +14 -0
  127. package/lib/typescript/module/access/accessTier.d.ts.map +1 -0
  128. package/lib/typescript/module/app-auth.d.ts +7 -0
  129. package/lib/typescript/module/app-auth.d.ts.map +1 -0
  130. package/lib/typescript/module/config/types.d.ts +171 -0
  131. package/lib/typescript/module/config/types.d.ts.map +1 -0
  132. package/lib/typescript/module/config/validateConfig.d.ts +8 -0
  133. package/lib/typescript/module/config/validateConfig.d.ts.map +1 -0
  134. package/lib/typescript/module/core/authMachine.d.ts +14 -0
  135. package/lib/typescript/module/core/authMachine.d.ts.map +1 -0
  136. package/lib/typescript/module/core/profile.d.ts +15 -0
  137. package/lib/typescript/module/core/profile.d.ts.map +1 -0
  138. package/lib/typescript/module/core/session.d.ts +60 -0
  139. package/lib/typescript/module/core/session.d.ts.map +1 -0
  140. package/lib/typescript/module/diagnostics/errors.d.ts +37 -0
  141. package/lib/typescript/module/diagnostics/errors.d.ts.map +1 -0
  142. package/lib/typescript/module/diagnostics/messageKeys.d.ts +57 -0
  143. package/lib/typescript/module/diagnostics/messageKeys.d.ts.map +1 -0
  144. package/lib/typescript/module/index.d.ts +27 -0
  145. package/lib/typescript/module/index.d.ts.map +1 -0
  146. package/lib/typescript/module/keychain.d.ts +7 -0
  147. package/lib/typescript/module/keychain.d.ts.map +1 -0
  148. package/lib/typescript/module/oidc/authClient.d.ts +75 -0
  149. package/lib/typescript/module/oidc/authClient.d.ts.map +1 -0
  150. package/lib/typescript/module/oidc/classifyError.d.ts +28 -0
  151. package/lib/typescript/module/oidc/classifyError.d.ts.map +1 -0
  152. package/lib/typescript/module/oidc/socialRouting.d.ts +22 -0
  153. package/lib/typescript/module/oidc/socialRouting.d.ts.map +1 -0
  154. package/lib/typescript/module/package.json +1 -0
  155. package/lib/typescript/module/react/AuthProvider.d.ts +17 -0
  156. package/lib/typescript/module/react/AuthProvider.d.ts.map +1 -0
  157. package/lib/typescript/module/react/hooks.d.ts +42 -0
  158. package/lib/typescript/module/react/hooks.d.ts.map +1 -0
  159. package/lib/typescript/module/testing/conformance.d.ts +32 -0
  160. package/lib/typescript/module/testing/conformance.d.ts.map +1 -0
  161. package/lib/typescript/module/testing/index.d.ts +11 -0
  162. package/lib/typescript/module/testing/index.d.ts.map +1 -0
  163. package/lib/typescript/module/tokens/accessToken.d.ts +45 -0
  164. package/lib/typescript/module/tokens/accessToken.d.ts.map +1 -0
  165. package/lib/typescript/module/tokens/secureStore.d.ts +26 -0
  166. package/lib/typescript/module/tokens/secureStore.d.ts.map +1 -0
  167. package/package.json +68 -21
  168. package/skills/sdk-rn-auth/SKILL.md +35 -2
  169. package/src/config/types.ts +53 -5
  170. package/src/config/validateConfig.ts +32 -1
  171. package/src/core/authMachine.ts +40 -6
  172. package/src/core/profile.ts +6 -1
  173. package/src/core/session.ts +49 -3
  174. package/src/diagnostics/errors.ts +7 -5
  175. package/src/index.ts +7 -0
  176. package/src/oidc/authClient.ts +19 -1
  177. package/src/oidc/classifyError.ts +2 -1
  178. package/src/oidc/socialRouting.ts +3 -1
  179. package/src/react/hooks.ts +53 -14
  180. package/src/tokens/accessToken.ts +20 -9
@@ -0,0 +1,402 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Auth state machine / orchestrator (FR-005, FR-022, R5, R7). Holds the single
5
+ * active session, wires the OidcAuthClient + SecureTokenStore ports, profile
6
+ * mapping, access-tier evaluation, per-resource tokens, restore, and sign-out.
7
+ *
8
+ * Every operation that starts or ends a session bumps `sessionEpoch`. Work that
9
+ * awaited across such a change — a token refresh, a restore, an authorize —
10
+ * compares the epoch it started with before writing anything back, so a sign-out
11
+ * can never be undone by a request that was already in flight.
12
+ */
13
+
14
+ import { createDiagnosticChannel, createListenerSet, currentPlatform, shallowEqual } from '@chipmobilesdk/rn-core';
15
+ import { resolveMessages } from "../diagnostics/messageKeys.js";
16
+ import { validateConfig } from "../config/validateConfig.js";
17
+ import { createAppAuthClient } from "../oidc/authClient.js";
18
+ import { availableProvidersForPlatform, buildAdditionalParameters, defaultProviderForPlatform, resolveProvider } from "../oidc/socialRouting.js";
19
+ import { mapClaimsToProfile } from "./profile.js";
20
+ import { evaluateAccessTier, failClosedTier } from "../access/accessTier.js";
21
+ import { restoreSession, sameSession, storedProfileFrom } from "./session.js";
22
+ import { AUTH_STORAGE_KEY } from "../tokens/secureStore.js";
23
+ import { createAccessTokenManager } from "../tokens/accessToken.js";
24
+ import { AuthError, toAuthError } from "../diagnostics/errors.js";
25
+ const SIGNED_OUT = {
26
+ status: 'signed-out',
27
+ profile: undefined,
28
+ accessTier: undefined,
29
+ restore: 'unavailable',
30
+ error: undefined
31
+ };
32
+ export function createAuthMachine(config, options = {}) {
33
+ // Throws AuthConfigError before anything else (FR-005, US4 scenario 2).
34
+ validateConfig(config);
35
+
36
+ // rn-core's one platform source (CORE-09). Outside Android and iOS (tests on
37
+ // Node, web) the providers are resolved as for iOS, as before.
38
+ const detected = currentPlatform();
39
+ const platform = options.platform ?? (detected === 'unsupported' ? 'ios' : detected);
40
+ const secureStore = config.secureStore;
41
+ const authClient = config.authClient ?? createAppAuthClient();
42
+ const resources = config.resources ?? [];
43
+ // Declared since 0.1.0 and read by nothing until now (AUTH-15).
44
+ const messages = resolveMessages(config.messages);
45
+ let state = Object.freeze({
46
+ status: 'loading',
47
+ restore: 'pending'
48
+ });
49
+ let refreshToken = null;
50
+ /** Kept for the end-session `id_token_hint`; without it a global sign-out is a no-op. */
51
+ let idToken = null;
52
+ let sessionEpoch = 0;
53
+ const listeners = createListenerSet();
54
+ /**
55
+ * Every Keychain write and delete, in order. A rotation persisted while a
56
+ * sign-out runs must not land after the sign-out's delete and resurrect the
57
+ * session on the next launch.
58
+ */
59
+ let storeQueue = Promise.resolve();
60
+ const enqueueStoreOp = op => {
61
+ const next = storeQueue.then(op);
62
+ // The queue itself never rejects, so one failed write does not poison the
63
+ // writes after it; the caller still sees its own failure through `next`.
64
+ storeQueue = next.catch(() => undefined);
65
+ return next;
66
+ };
67
+
68
+ /** The artifact as last written or read, so an identical write is skipped. */
69
+ let storedSession = null;
70
+ const writeSession = (session, epoch) => enqueueStoreOp(async () => {
71
+ if (epoch !== sessionEpoch) {
72
+ return; // The session this belonged to has already ended.
73
+ }
74
+ const artifact = {
75
+ refreshToken: session.refreshToken,
76
+ profile: storedProfileFrom(session.profile),
77
+ idToken: session.idToken
78
+ };
79
+ // A restore that rotated nothing used to write the Keychain again on
80
+ // every launch, on the startup path (AUTH-23).
81
+ if (storedSession && sameSession(storedSession, artifact)) {
82
+ return;
83
+ }
84
+ await secureStore.setItem(AUTH_STORAGE_KEY, JSON.stringify(artifact));
85
+ storedSession = artifact;
86
+ });
87
+ const tokenManager = createAccessTokenManager({
88
+ authority: config.authority,
89
+ clientId: config.clientId,
90
+ redirectUrl: config.redirectUrl,
91
+ resources,
92
+ authClient,
93
+ getRefreshToken: () => refreshToken,
94
+ sessionEpoch: () => sessionEpoch,
95
+ async onRefreshTokenRotated(token, epoch) {
96
+ if (epoch !== sessionEpoch) {
97
+ return;
98
+ }
99
+ // Live immediately whatever happens to the write: the provider may
100
+ // already have retired the old token, so memory must not keep using it.
101
+ refreshToken = token;
102
+ if (!state.profile) {
103
+ return;
104
+ }
105
+ try {
106
+ await writeSession({
107
+ refreshToken: token,
108
+ profile: state.profile,
109
+ idToken: idToken ?? undefined
110
+ }, epoch);
111
+ } catch {
112
+ // The session stays usable in memory. The stored artifact keeps the
113
+ // previous token until the next successful write; a restart before
114
+ // then restores through it if the provider still accepts it, and
115
+ // otherwise lands on sign-in — never on a corrupted state.
116
+ }
117
+ }
118
+ });
119
+
120
+ /**
121
+ * The current snapshot, the same object until the state changes, so React reads
122
+ * it through `useSyncExternalStore` without re-rendering for nothing (PERF-02).
123
+ * Frozen: a consumer cannot change the machine's state by mutating it.
124
+ */
125
+ function getState() {
126
+ return state;
127
+ }
128
+ function setState(patch) {
129
+ const next = {
130
+ ...state,
131
+ ...patch
132
+ };
133
+ // No change, no new snapshot and no notification.
134
+ if (shallowEqual(state, next)) return;
135
+ state = Object.freeze(next);
136
+ if (patch.error) {
137
+ // The code and audience only; `detail` is already redacted but stays local.
138
+ channel.emit(patch.error.code, patch.error.audience === 'user' ? 'info' : 'warn', {
139
+ status: state.status,
140
+ retryable: patch.error.retryable
141
+ });
142
+ }
143
+ // Isolated: a subscriber that throws neither stops the others nor turns a
144
+ // completed sign-in into an error; rn-core reports it instead (CORE-03).
145
+ listeners.notify(getState());
146
+ }
147
+
148
+ /** Ends the local session: memory, cached access tokens, and the stored artifact. */
149
+ async function clearPersisted() {
150
+ sessionEpoch += 1;
151
+ refreshToken = null;
152
+ idToken = null;
153
+ storedSession = null;
154
+ tokenManager.clear();
155
+ await enqueueStoreOp(() => secureStore.removeItem(AUTH_STORAGE_KEY));
156
+ }
157
+ return {
158
+ getState,
159
+ subscribe: listener => listeners.add(listener),
160
+ async restore() {
161
+ sessionEpoch += 1;
162
+ const epoch = sessionEpoch;
163
+ setState({
164
+ status: 'loading',
165
+ restore: 'pending',
166
+ error: undefined
167
+ });
168
+ let result;
169
+ try {
170
+ result = await restoreSession({
171
+ secureStore,
172
+ authority: config.authority,
173
+ clientId: config.clientId,
174
+ redirectUrl: config.redirectUrl,
175
+ scopes: config.scopes,
176
+ authClient,
177
+ mapping: config.accessTierMapping
178
+ });
179
+ } catch (error) {
180
+ // The store could not be read. Nothing is known, nothing is deleted.
181
+ if (epoch === sessionEpoch) {
182
+ setState({
183
+ ...SIGNED_OUT,
184
+ status: 'error',
185
+ error: toAuthError(error)
186
+ });
187
+ }
188
+ return getState();
189
+ }
190
+ if (epoch !== sessionEpoch) {
191
+ // A sign-in or sign-out ran meanwhile; its outcome stands.
192
+ return getState();
193
+ }
194
+ storedSession = result.persisted ?? null;
195
+ if (result.outcome === 'restored' && result.profile && result.refreshToken) {
196
+ refreshToken = result.refreshToken;
197
+ idToken = result.idToken ?? null;
198
+ try {
199
+ await writeSession({
200
+ refreshToken: result.refreshToken,
201
+ profile: result.profile,
202
+ idToken: result.idToken
203
+ }, epoch);
204
+ } catch {
205
+ // The refresh succeeded, so the user is signed in for this run. Only
206
+ // the next launch is affected, and it falls back to sign-in.
207
+ }
208
+ if (epoch !== sessionEpoch) {
209
+ return getState();
210
+ }
211
+ setState({
212
+ status: 'authenticated',
213
+ profile: result.profile,
214
+ accessTier: result.accessTier,
215
+ restore: 'restored',
216
+ error: undefined
217
+ });
218
+ } else if (result.outcome === 'offline' && result.profile) {
219
+ refreshToken = result.refreshToken ?? null;
220
+ idToken = result.idToken ?? null;
221
+ setState({
222
+ status: 'authenticated',
223
+ profile: result.profile,
224
+ accessTier: result.accessTier ?? failClosedTier(),
225
+ restore: 'offline',
226
+ error: undefined
227
+ });
228
+ } else {
229
+ await clearPersisted();
230
+ setState(SIGNED_OUT);
231
+ }
232
+ return getState();
233
+ },
234
+ async signIn(providerId) {
235
+ sessionEpoch += 1;
236
+ const epoch = sessionEpoch;
237
+ setState({
238
+ status: 'authenticating',
239
+ error: undefined
240
+ });
241
+ let provider;
242
+ try {
243
+ provider = resolveProvider(config, providerId, platform);
244
+ } catch (error) {
245
+ setState({
246
+ status: 'error',
247
+ error: toAuthError(error, 'configuration-error', 'auth.error.configuration')
248
+ });
249
+ return getState();
250
+ }
251
+ try {
252
+ const tokens = await authClient.authorize({
253
+ authority: config.authority,
254
+ clientId: config.clientId,
255
+ redirectUrl: config.redirectUrl,
256
+ scopes: config.scopes,
257
+ additionalParameters: buildAdditionalParameters(provider)
258
+ });
259
+ if (epoch !== sessionEpoch) {
260
+ return getState();
261
+ }
262
+ if (!tokens.refreshToken) {
263
+ // `offline_access` is required by configuration, so its absence is the
264
+ // tenant's doing. Signing in anyway would give a session that silently
265
+ // never survives a restart.
266
+ setState({
267
+ status: 'error',
268
+ error: new AuthError({
269
+ code: 'configuration-error',
270
+ messageKey: 'auth.error.configuration',
271
+ audience: 'developer',
272
+ detail: 'authorize returned no refresh token; check that the app registration grants offline_access'
273
+ })
274
+ });
275
+ return getState();
276
+ }
277
+ const profile = mapClaimsToProfile(tokens.claims, providerId);
278
+ const accessTier = evaluateAccessTier(tokens.claims, config.accessTierMapping);
279
+ // Written first, committed to memory second: a failed write leaves no
280
+ // half-signed-in session holding a refresh token that was never stored.
281
+ await writeSession({
282
+ refreshToken: tokens.refreshToken,
283
+ profile,
284
+ idToken: tokens.idToken
285
+ }, epoch);
286
+ if (epoch !== sessionEpoch) {
287
+ return getState();
288
+ }
289
+ // Single active account: a new sign-in replaces any prior session.
290
+ refreshToken = tokens.refreshToken;
291
+ idToken = tokens.idToken ?? null;
292
+ tokenManager.clear();
293
+ setState({
294
+ status: 'authenticated',
295
+ profile,
296
+ accessTier,
297
+ restore: 'restored',
298
+ error: undefined
299
+ });
300
+ } catch (error) {
301
+ if (epoch !== sessionEpoch) {
302
+ return getState();
303
+ }
304
+ const authError = toAuthError(error);
305
+ if (authError.code === 'provider-cancelled') {
306
+ setState({
307
+ status: 'cancelled',
308
+ error: authError
309
+ });
310
+ } else {
311
+ setState({
312
+ status: 'error',
313
+ error: authError
314
+ });
315
+ }
316
+ }
317
+ return getState();
318
+ },
319
+ async signOut() {
320
+ await clearPersisted();
321
+ setState(SIGNED_OUT);
322
+ },
323
+ async signOutGlobal() {
324
+ let result = {
325
+ global: 'ended'
326
+ };
327
+ try {
328
+ await authClient.endSession({
329
+ authority: config.authority,
330
+ clientId: config.clientId,
331
+ redirectUrl: config.redirectUrl,
332
+ idToken: idToken ?? undefined
333
+ });
334
+ } catch (error) {
335
+ // Reported, not swallowed: the tenant session may still be alive. It
336
+ // still must not block clearing local state.
337
+ result = {
338
+ global: 'failed',
339
+ error: toAuthError(error)
340
+ };
341
+ }
342
+ await clearPersisted();
343
+ setState(SIGNED_OUT);
344
+ return result;
345
+ },
346
+ async requestAccessToken(resourceKey, tokenOptions) {
347
+ const epoch = sessionEpoch;
348
+ // Only a real network refresh is a `token-refreshing` phase; a cache hit
349
+ // would otherwise flash every subscriber twice for nothing.
350
+ const refreshing = state.status === 'authenticated' && (tokenOptions?.forceRefresh === true || !tokenManager.hasFreshToken(resourceKey));
351
+ if (refreshing) {
352
+ setState({
353
+ status: 'token-refreshing'
354
+ });
355
+ }
356
+ const result = await tokenManager.request(resourceKey, tokenOptions);
357
+ // Restored only if nothing else moved the session meanwhile: a sign-out
358
+ // during the refresh used to be overwritten back to `authenticated`.
359
+ if (refreshing && epoch === sessionEpoch && state.status === 'token-refreshing') {
360
+ setState({
361
+ status: 'authenticated'
362
+ });
363
+ }
364
+ return result;
365
+ },
366
+ getAccessTier() {
367
+ return state.accessTier ?? failClosedTier();
368
+ },
369
+ canAccessPremium() {
370
+ const tier = state.accessTier ?? failClosedTier();
371
+ return {
372
+ allowed: tier.tier === 'premium' && tier.verification === 'verified',
373
+ tier
374
+ };
375
+ },
376
+ requirePremium() {
377
+ const tier = state.accessTier ?? failClosedTier();
378
+ const allowed = tier.tier === 'premium' && tier.verification === 'verified';
379
+ if (!allowed) {
380
+ setState({
381
+ status: 'access-denied'
382
+ });
383
+ }
384
+ return {
385
+ allowed,
386
+ tier
387
+ };
388
+ },
389
+ getMessages() {
390
+ return messages;
391
+ },
392
+ getPlatformProvider() {
393
+ return defaultProviderForPlatform(config, platform);
394
+ },
395
+ getPlatformProviders() {
396
+ return availableProvidersForPlatform(config, platform);
397
+ }
398
+ };
399
+ }
400
+ /** Every error the machine lands in also goes to the app's SDK sinks (CORE-08). */
401
+ const channel = createDiagnosticChannel('rn-auth');
402
+ //# sourceMappingURL=authMachine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["createDiagnosticChannel","createListenerSet","currentPlatform","shallowEqual","resolveMessages","validateConfig","createAppAuthClient","availableProvidersForPlatform","buildAdditionalParameters","defaultProviderForPlatform","resolveProvider","mapClaimsToProfile","evaluateAccessTier","failClosedTier","restoreSession","sameSession","storedProfileFrom","AUTH_STORAGE_KEY","createAccessTokenManager","AuthError","toAuthError","SIGNED_OUT","status","profile","undefined","accessTier","restore","error","createAuthMachine","config","options","detected","platform","secureStore","authClient","resources","messages","state","Object","freeze","refreshToken","idToken","sessionEpoch","listeners","storeQueue","Promise","resolve","enqueueStoreOp","op","next","then","catch","storedSession","writeSession","session","epoch","artifact","setItem","JSON","stringify","tokenManager","authority","clientId","redirectUrl","getRefreshToken","onRefreshTokenRotated","token","getState","setState","patch","channel","emit","code","audience","retryable","notify","clearPersisted","clear","removeItem","subscribe","listener","add","result","scopes","mapping","accessTierMapping","persisted","outcome","signIn","providerId","provider","tokens","authorize","additionalParameters","messageKey","detail","claims","authError","signOut","signOutGlobal","global","endSession","requestAccessToken","resourceKey","tokenOptions","refreshing","forceRefresh","hasFreshToken","request","getAccessTier","canAccessPremium","tier","allowed","verification","requirePremium","getMessages","getPlatformProvider","getPlatformProviders"],"sourceRoot":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AO,GAAGtE,uBAAuB,CAAgB,SAAS,CAAC","ignoreList":[]}
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Claims → Profile mapping (FR-006). Tolerant of Apple private-relay emails and
5
+ * missing display name / given name (edge cases).
6
+ */
7
+
8
+ function asString(value) {
9
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
10
+ }
11
+ function looksLikeEmail(value) {
12
+ return !!value && /.+@.+\..+/.test(value);
13
+ }
14
+
15
+ /** Map id-token claims to the app-visible Profile. */
16
+ export function mapClaimsToProfile(claims, providerId) {
17
+ const tenantUserId = asString(claims.oid) ?? asString(claims.sub) ?? asString(claims.unique_name) ?? 'unknown';
18
+ const givenName = asString(claims.given_name);
19
+ const familyName = asString(claims.family_name);
20
+ const composedName = [givenName, familyName].filter(Boolean).join(' ') || undefined;
21
+ const displayName = asString(claims.name) ?? composedName;
22
+ const preferred = asString(claims.preferred_username);
23
+ const email = asString(claims.email) ?? (looksLikeEmail(preferred) ? preferred : undefined);
24
+ const provider = providerId ?? asString(claims.idp) ?? asString(claims.identityProvider) ?? 'unknown';
25
+ return {
26
+ tenantUserId,
27
+ displayName,
28
+ email,
29
+ provider,
30
+ claims
31
+ };
32
+ }
33
+
34
+ /**
35
+ * Describe the external provider identity behind the profile (FR-004 edge
36
+ * cases). `emailBehavior` is what a screen needs to explain an address the user
37
+ * did not choose: Apple's private relay forwards mail and is not the address
38
+ * they type anywhere else.
39
+ */
40
+ export function describeProviderIdentity(claims, providerId) {
41
+ const provider = providerId ?? asString(claims.idp) ?? 'unknown';
42
+ const subject = asString(claims.sub) ?? asString(claims.oid) ?? 'unknown';
43
+ const email = asString(claims.email);
44
+ let emailBehavior = 'none';
45
+ if (email) {
46
+ emailBehavior = email.endsWith('@privaterelay.appleid.com') ? 'private-relay' : 'direct';
47
+ }
48
+ return {
49
+ provider,
50
+ subject,
51
+ emailBehavior
52
+ };
53
+ }
54
+ //# sourceMappingURL=profile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["asString","value","length","undefined","looksLikeEmail","test","mapClaimsToProfile","claims","providerId","tenantUserId","oid","sub","unique_name","givenName","given_name","familyName","family_name","composedName","filter","Boolean","join","displayName","name","preferred","preferred_username","email","provider","idp","identityProvider","describeProviderIdentity","subject","emailBehavior","endsWith"],"sourceRoot":"../../../src","sources":["core/profile.ts"],"mappings":";;AAAA;AACA;AACA;AACA;;AAIA,SAASA,QAAQA,CAACC,KAAc,EAAsB;EACrD,OAAO,OAAOA,KAAK,KAAK,QAAQ,IAAIA,KAAK,CAACC,MAAM,GAAG,CAAC,GAAGD,KAAK,GAAGE,SAAS;AACzE;AAEA,SAASC,cAAcA,CAACH,KAAyB,EAAW;EAC3D,OAAO,CAAC,CAACA,KAAK,IAAI,WAAW,CAACI,IAAI,CAACJ,KAAK,CAAC;AAC1C;;AAEA;AACA,OAAO,SAASK,kBAAkBA,CACjCC,MAA+B,EAC/BC,UAAuB,EACb;EACV,MAAMC,YAAY,GACjBT,QAAQ,CAACO,MAAM,CAACG,GAAG,CAAC,IAAIV,QAAQ,CAACO,MAAM,CAACI,GAAG,CAAC,IAAIX,QAAQ,CAACO,MAAM,CAACK,WAAW,CAAC,IAAI,SAAS;EAE1F,MAAMC,SAAS,GAAGb,QAAQ,CAACO,MAAM,CAACO,UAAU,CAAC;EAC7C,MAAMC,UAAU,GAAGf,QAAQ,CAACO,MAAM,CAACS,WAAW,CAAC;EAC/C,MAAMC,YAAY,GAAG,CAACJ,SAAS,EAAEE,UAAU,CAAC,CAACG,MAAM,CAACC,OAAO,CAAC,CAACC,IAAI,CAAC,GAAG,CAAC,IAAIjB,SAAS;EACnF,MAAMkB,WAAW,GAAGrB,QAAQ,CAACO,MAAM,CAACe,IAAI,CAAC,IAAIL,YAAY;EAEzD,MAAMM,SAAS,GAAGvB,QAAQ,CAACO,MAAM,CAACiB,kBAAkB,CAAC;EACrD,MAAMC,KAAK,GAAGzB,QAAQ,CAACO,MAAM,CAACkB,KAAK,CAAC,KAAKrB,cAAc,CAACmB,SAAS,CAAC,GAAGA,SAAS,GAAGpB,SAAS,CAAC;EAE3F,MAAMuB,QAAQ,GACblB,UAAU,IAAIR,QAAQ,CAACO,MAAM,CAACoB,GAAG,CAAC,IAAI3B,QAAQ,CAACO,MAAM,CAACqB,gBAAgB,CAAC,IAAI,SAAS;EAErF,OAAO;IACNnB,YAAY;IACZY,WAAW;IACXI,KAAK;IACLC,QAAQ;IACRnB;EACD,CAAC;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASsB,wBAAwBA,CACvCtB,MAA+B,EAC/BC,UAAuB,EACJ;EACnB,MAAMkB,QAAQ,GAAGlB,UAAU,IAAIR,QAAQ,CAACO,MAAM,CAACoB,GAAG,CAAC,IAAI,SAAS;EAChE,MAAMG,OAAO,GAAG9B,QAAQ,CAACO,MAAM,CAACI,GAAG,CAAC,IAAIX,QAAQ,CAACO,MAAM,CAACG,GAAG,CAAC,IAAI,SAAS;EACzE,MAAMe,KAAK,GAAGzB,QAAQ,CAACO,MAAM,CAACkB,KAAK,CAAC;EACpC,IAAIM,aAAgD,GAAG,MAAM;EAC7D,IAAIN,KAAK,EAAE;IACVM,aAAa,GAAGN,KAAK,CAACO,QAAQ,CAAC,2BAA2B,CAAC,GAAG,eAAe,GAAG,QAAQ;EACzF;EACA,OAAO;IAAEN,QAAQ;IAAEI,OAAO;IAAEC;EAAc,CAAC;AAC5C","ignoreList":[]}
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Session restoration (FR-008, R5). Reads the persisted artifact, attempts a
5
+ * silent refresh, and classifies the outcome:
6
+ * - restored: fresh tokens + claims → authenticated
7
+ * - offline: the refresh could not complete for any reason other than the
8
+ * session being invalid — no network, a timeout, a 5xx, an error we
9
+ * cannot classify → cached profile read-only, tier unverified (fail
10
+ * closed) — clarify Q3
11
+ * - unavailable: no artifact, or the provider said the refresh token is no
12
+ * longer valid → signed-out reauth
13
+ *
14
+ * Only `unavailable` deletes the stored session, so it is reserved for a verdict
15
+ * the provider actually gave. Treating every unclassified error as expiry signed
16
+ * users out whenever the token endpoint had a bad moment.
17
+ */
18
+
19
+ import { AUTH_STORAGE_KEY } from "../tokens/secureStore.js";
20
+ import { mapClaimsToProfile } from "./profile.js";
21
+ import { evaluateAccessTier, failClosedTier } from "../access/accessTier.js";
22
+ import { isAuthError } from "../diagnostics/errors.js";
23
+
24
+ /**
25
+ * The identity in the stored artifact: who, not what the token said.
26
+ *
27
+ * The whole claim set used to be written to the Keychain on every launch — all
28
+ * of it, groups included — for a value nothing reads back: the access tier is
29
+ * recomputed from fresh claims, and a restore that cannot reach the provider
30
+ * fails closed anyway (AUTH-23).
31
+ */
32
+
33
+ /** The artifact's identity as a profile. Artifacts written before 0.4.0 carry claims; they are kept. */
34
+ export function profileFromStored(stored) {
35
+ return {
36
+ ...stored,
37
+ claims: 'claims' in stored ? stored.claims ?? {} : {}
38
+ };
39
+ }
40
+
41
+ /** What goes to the store: everything but the claims. */
42
+ export function storedProfileFrom(profile) {
43
+ return {
44
+ tenantUserId: profile.tenantUserId,
45
+ displayName: profile.displayName,
46
+ email: profile.email,
47
+ provider: profile.provider
48
+ };
49
+ }
50
+
51
+ /** True when the artifact would be byte-identical, so the write can be skipped. */
52
+ export function sameSession(a, b) {
53
+ return a.refreshToken === b.refreshToken && a.idToken === b.idToken && a.profile.tenantUserId === b.profile.tenantUserId && a.profile.displayName === b.profile.displayName && a.profile.email === b.profile.email && a.profile.provider === b.profile.provider;
54
+ }
55
+ export function parsePersistedSession(raw) {
56
+ if (!raw) {
57
+ return null;
58
+ }
59
+ try {
60
+ const parsed = JSON.parse(raw);
61
+ if (parsed && typeof parsed.refreshToken === 'string' && parsed.profile) {
62
+ return parsed;
63
+ }
64
+ return null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+ export async function restoreSession(deps) {
70
+ const raw = await deps.secureStore.getItem(AUTH_STORAGE_KEY);
71
+ const persisted = parsePersistedSession(raw);
72
+ if (!persisted) {
73
+ return {
74
+ outcome: 'unavailable'
75
+ };
76
+ }
77
+ try {
78
+ const tokens = await deps.authClient.refresh({
79
+ authority: deps.authority,
80
+ clientId: deps.clientId,
81
+ redirectUrl: deps.redirectUrl,
82
+ refreshToken: persisted.refreshToken,
83
+ scopes: deps.scopes
84
+ });
85
+ // A refresh response may carry no id token, and so no claims. The stored
86
+ // profile is then still the best identity there is; an empty one is not.
87
+ const hasClaims = Object.keys(tokens.claims).length > 0;
88
+ return {
89
+ outcome: 'restored',
90
+ persisted,
91
+ // The provider id came from the sign-in and is not in the claims: a
92
+ // refresh answered `idp: 'google.com'`, so a restored profile used to
93
+ // report a different provider than the same session did before (AUTH-10).
94
+ profile: hasClaims ? mapClaimsToProfile(tokens.claims, persisted.profile.provider) : profileFromStored(persisted.profile),
95
+ accessTier: hasClaims ? evaluateAccessTier(tokens.claims, deps.mapping) : failClosedTier(),
96
+ refreshToken: tokens.refreshToken || persisted.refreshToken,
97
+ idToken: tokens.idToken || persisted.idToken
98
+ };
99
+ } catch (error) {
100
+ if (isAuthError(error) && error.code === 'session-expired') {
101
+ // The provider rejected the refresh token: reauthentication is required.
102
+ return {
103
+ outcome: 'unavailable'
104
+ };
105
+ }
106
+ // Anything else is no verdict on the session. Keep the cached identity
107
+ // read-only and fail closed on entitlement; the next restore tries again.
108
+ return {
109
+ outcome: 'offline',
110
+ persisted,
111
+ profile: profileFromStored(persisted.profile),
112
+ accessTier: failClosedTier(),
113
+ refreshToken: persisted.refreshToken,
114
+ idToken: persisted.idToken
115
+ };
116
+ }
117
+ }
118
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["AUTH_STORAGE_KEY","mapClaimsToProfile","evaluateAccessTier","failClosedTier","isAuthError","profileFromStored","stored","claims","storedProfileFrom","profile","tenantUserId","displayName","email","provider","sameSession","a","b","refreshToken","idToken","parsePersistedSession","raw","parsed","JSON","parse","restoreSession","deps","secureStore","getItem","persisted","outcome","tokens","authClient","refresh","authority","clientId","redirectUrl","scopes","hasClaims","Object","keys","length","accessTier","mapping","error","code"],"sourceRoot":"../../../src","sources":["core/session.ts"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA,SAASA,gBAAgB,QAAQ,0BAAuB;AACxD,SAASC,kBAAkB,QAAQ,cAAW;AAC9C,SAASC,kBAAkB,EAAEC,cAAc,QAAQ,yBAAsB;AACzE,SAASC,WAAW,QAAQ,0BAAuB;;AAEnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAUA;AACA,OAAO,SAASC,iBAAiBA,CAACC,MAA+B,EAAW;EAC3E,OAAO;IAAE,GAAGA,MAAM;IAAEC,MAAM,EAAE,QAAQ,IAAID,MAAM,GAAIA,MAAM,CAACC,MAAM,IAAI,CAAC,CAAC,GAAI,CAAC;EAAE,CAAC;AAC9E;;AAEA;AACA,OAAO,SAASC,iBAAiBA,CAACC,OAAgB,EAAiB;EAClE,OAAO;IACNC,YAAY,EAAED,OAAO,CAACC,YAAY;IAClCC,WAAW,EAAEF,OAAO,CAACE,WAAW;IAChCC,KAAK,EAAEH,OAAO,CAACG,KAAK;IACpBC,QAAQ,EAAEJ,OAAO,CAACI;EACnB,CAAC;AACF;;AAEA;AACA,OAAO,SAASC,WAAWA,CAACC,CAAmB,EAAEC,CAAmB,EAAW;EAC9E,OACCD,CAAC,CAACE,YAAY,KAAKD,CAAC,CAACC,YAAY,IACjCF,CAAC,CAACG,OAAO,KAAKF,CAAC,CAACE,OAAO,IACvBH,CAAC,CAACN,OAAO,CAACC,YAAY,KAAKM,CAAC,CAACP,OAAO,CAACC,YAAY,IACjDK,CAAC,CAACN,OAAO,CAACE,WAAW,KAAKK,CAAC,CAACP,OAAO,CAACE,WAAW,IAC/CI,CAAC,CAACN,OAAO,CAACG,KAAK,KAAKI,CAAC,CAACP,OAAO,CAACG,KAAK,IACnCG,CAAC,CAACN,OAAO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