@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.
@@ -1,364 +1,364 @@
1
- /**
2
- * Auth state machine / orchestrator (FR-005, FR-022, R5, R7). Holds the single
3
- * active session, wires the OidcAuthClient + SecureTokenStore ports, profile
4
- * mapping, access-tier evaluation, per-resource tokens, restore, and sign-out.
5
- *
6
- * Every operation that starts or ends a session bumps `sessionEpoch`. Work that
7
- * awaited across such a change — a token refresh, a restore, an authorize —
8
- * compares the epoch it started with before writing anything back, so a sign-out
9
- * can never be undone by a request that was already in flight.
10
- */
11
-
12
- import { Platform } from 'react-native';
13
- import type {
14
- Auth,
15
- AuthConfig,
16
- AuthState,
17
- CreateAuthOptions,
18
- DevicePlatform,
19
- GlobalSignOutResult,
20
- PremiumGateResult,
21
- Profile,
22
- ProviderId,
23
- } from '../config/types';
24
- import { validateConfig } from '../config/validateConfig';
25
- import { createAppAuthClient } from '../oidc/authClient';
26
- import {
27
- availableProvidersForPlatform,
28
- buildAdditionalParameters,
29
- defaultProviderForPlatform,
30
- resolveProvider,
31
- } from '../oidc/socialRouting';
32
- import { mapClaimsToProfile } from './profile';
33
- import { evaluateAccessTier, failClosedTier } from '../access/accessTier';
34
- import { restoreSession, type PersistedSession } from './session';
35
- import { AUTH_STORAGE_KEY } from '../tokens/secureStore';
36
- import { createAccessTokenManager } from '../tokens/accessToken';
37
- import { AuthError, toAuthError } from '../diagnostics/errors';
38
-
39
- const SIGNED_OUT: Partial<AuthState> = {
40
- status: 'signed-out',
41
- profile: undefined,
42
- accessTier: undefined,
43
- restore: 'unavailable',
44
- error: undefined,
45
- };
46
-
47
- export function createAuthMachine(
48
- config: AuthConfig,
49
- options: CreateAuthOptions = {},
50
- ): Auth {
51
- // Throws AuthConfigError before anything else (FR-005, US4 scenario 2).
52
- validateConfig(config);
53
-
54
- const platform: DevicePlatform =
55
- options.platform ?? ((Platform?.OS as DevicePlatform) ?? 'ios');
56
- const secureStore = config.secureStore;
57
- const authClient = config.authClient ?? createAppAuthClient();
58
- const resources = config.resources ?? [];
59
-
60
- let state: AuthState = { status: 'loading', restore: 'pending' };
61
- let refreshToken: string | null = null;
62
- /** Kept for the end-session `id_token_hint`; without it a global sign-out is a no-op. */
63
- let idToken: string | null = null;
64
- let sessionEpoch = 0;
65
- const listeners = new Set<(state: AuthState) => void>();
66
- /**
67
- * Every Keychain write and delete, in order. A rotation persisted while a
68
- * sign-out runs must not land after the sign-out's delete and resurrect the
69
- * session on the next launch.
70
- */
71
- let storeQueue: Promise<void> = Promise.resolve();
72
-
73
- const enqueueStoreOp = (op: () => Promise<void>): Promise<void> => {
74
- const next = storeQueue.then(op);
75
- // The queue itself never rejects, so one failed write does not poison the
76
- // writes after it; the caller still sees its own failure through `next`.
77
- storeQueue = next.catch(() => undefined);
78
- return next;
79
- };
80
-
81
- const writeSession = (session: PersistedSession, epoch: number): Promise<void> =>
82
- enqueueStoreOp(async () => {
83
- if (epoch !== sessionEpoch) {
84
- return; // The session this belonged to has already ended.
85
- }
86
- await secureStore.setItem(AUTH_STORAGE_KEY, JSON.stringify(session));
87
- });
88
-
89
- const tokenManager = createAccessTokenManager({
90
- authority: config.authority,
91
- clientId: config.clientId,
92
- redirectUrl: config.redirectUrl,
93
- resources,
94
- authClient,
95
- getRefreshToken: () => refreshToken,
96
- sessionEpoch: () => sessionEpoch,
97
- async onRefreshTokenRotated(token, epoch) {
98
- if (epoch !== sessionEpoch) {
99
- return;
100
- }
101
- // Live immediately whatever happens to the write: the provider may
102
- // already have retired the old token, so memory must not keep using it.
103
- refreshToken = token;
104
- if (!state.profile) {
105
- return;
106
- }
107
- try {
108
- await writeSession(
109
- { refreshToken: token, profile: state.profile, idToken: idToken ?? undefined },
110
- epoch,
111
- );
112
- } catch {
113
- // The session stays usable in memory. The stored artifact keeps the
114
- // previous token until the next successful write; a restart before
115
- // then restores through it if the provider still accepts it, and
116
- // otherwise lands on sign-in — never on a corrupted state.
117
- }
118
- },
119
- });
120
-
121
- function getState(): AuthState {
122
- return { ...state };
123
- }
124
-
125
- function setState(patch: Partial<AuthState>): void {
126
- state = { ...state, ...patch };
127
- // Snapshot, and isolate each listener: a subscriber that throws must not
128
- // stop the others or turn a completed sign-in into an error (CORE-03).
129
- for (const listener of [...listeners]) {
130
- try {
131
- listener(getState());
132
- } catch {
133
- /* consumer bug; the state transition itself already happened */
134
- }
135
- }
136
- }
137
-
138
- /** Ends the local session: memory, cached access tokens, and the stored artifact. */
139
- async function clearPersisted(): Promise<void> {
140
- sessionEpoch += 1;
141
- refreshToken = null;
142
- idToken = null;
143
- tokenManager.clear();
144
- await enqueueStoreOp(() => secureStore.removeItem(AUTH_STORAGE_KEY));
145
- }
146
-
147
- return {
148
- getState,
149
-
150
- subscribe(listener) {
151
- listeners.add(listener);
152
- return () => {
153
- listeners.delete(listener);
154
- };
155
- },
156
-
157
- async restore() {
158
- sessionEpoch += 1;
159
- const epoch = sessionEpoch;
160
- setState({ status: 'loading', restore: 'pending', error: undefined });
161
-
162
- let result;
163
- try {
164
- result = await restoreSession({
165
- secureStore,
166
- authority: config.authority,
167
- clientId: config.clientId,
168
- redirectUrl: config.redirectUrl,
169
- scopes: config.scopes,
170
- authClient,
171
- mapping: config.accessTierMapping,
172
- });
173
- } catch (error) {
174
- // The store could not be read. Nothing is known, nothing is deleted.
175
- if (epoch === sessionEpoch) {
176
- setState({ ...SIGNED_OUT, status: 'error', error: toAuthError(error) });
177
- }
178
- return getState();
179
- }
180
-
181
- if (epoch !== sessionEpoch) {
182
- // A sign-in or sign-out ran meanwhile; its outcome stands.
183
- return getState();
184
- }
185
-
186
- if (result.outcome === 'restored' && result.profile && result.refreshToken) {
187
- refreshToken = result.refreshToken;
188
- idToken = result.idToken ?? null;
189
- try {
190
- await writeSession(
191
- { refreshToken: result.refreshToken, profile: result.profile, idToken: result.idToken },
192
- epoch,
193
- );
194
- } catch {
195
- // The refresh succeeded, so the user is signed in for this run. Only
196
- // the next launch is affected, and it falls back to sign-in.
197
- }
198
- if (epoch !== sessionEpoch) {
199
- return getState();
200
- }
201
- setState({
202
- status: 'authenticated',
203
- profile: result.profile,
204
- accessTier: result.accessTier,
205
- restore: 'restored',
206
- error: undefined,
207
- });
208
- } else if (result.outcome === 'offline' && result.profile) {
209
- refreshToken = result.refreshToken ?? null;
210
- idToken = result.idToken ?? null;
211
- setState({
212
- status: 'authenticated',
213
- profile: result.profile,
214
- accessTier: result.accessTier ?? failClosedTier(),
215
- restore: 'offline',
216
- error: undefined,
217
- });
218
- } else {
219
- await clearPersisted();
220
- setState(SIGNED_OUT);
221
- }
222
- return getState();
223
- },
224
-
225
- async signIn(providerId: ProviderId) {
226
- sessionEpoch += 1;
227
- const epoch = sessionEpoch;
228
- setState({ status: 'authenticating', error: undefined });
229
- let provider;
230
- try {
231
- provider = resolveProvider(config, providerId, platform);
232
- } catch (error) {
233
- setState({ status: 'error', error: toAuthError(error, 'configuration-error', 'auth.error.configuration') });
234
- return getState();
235
- }
236
-
237
- try {
238
- const tokens = await authClient.authorize({
239
- authority: config.authority,
240
- clientId: config.clientId,
241
- redirectUrl: config.redirectUrl,
242
- scopes: config.scopes,
243
- additionalParameters: buildAdditionalParameters(provider),
244
- });
245
- if (epoch !== sessionEpoch) {
246
- return getState();
247
- }
248
- if (!tokens.refreshToken) {
249
- // `offline_access` is required by configuration, so its absence is the
250
- // tenant's doing. Signing in anyway would give a session that silently
251
- // never survives a restart.
252
- setState({
253
- status: 'error',
254
- error: new AuthError({
255
- code: 'configuration-error',
256
- messageKey: 'auth.error.configuration',
257
- audience: 'developer',
258
- detail: 'authorize returned no refresh token; check that the app registration grants offline_access',
259
- }),
260
- });
261
- return getState();
262
- }
263
- const profile = mapClaimsToProfile(tokens.claims, providerId);
264
- const accessTier = evaluateAccessTier(tokens.claims, config.accessTierMapping);
265
- // Written first, committed to memory second: a failed write leaves no
266
- // half-signed-in session holding a refresh token that was never stored.
267
- await writeSession(
268
- { refreshToken: tokens.refreshToken, profile, idToken: tokens.idToken },
269
- epoch,
270
- );
271
- if (epoch !== sessionEpoch) {
272
- return getState();
273
- }
274
- // Single active account: a new sign-in replaces any prior session.
275
- refreshToken = tokens.refreshToken;
276
- idToken = tokens.idToken ?? null;
277
- tokenManager.clear();
278
- setState({
279
- status: 'authenticated',
280
- profile,
281
- accessTier,
282
- restore: 'restored',
283
- error: undefined,
284
- });
285
- } catch (error) {
286
- if (epoch !== sessionEpoch) {
287
- return getState();
288
- }
289
- const authError = toAuthError(error);
290
- if (authError.code === 'provider-cancelled') {
291
- setState({ status: 'cancelled', error: authError });
292
- } else {
293
- setState({ status: 'error', error: authError });
294
- }
295
- }
296
- return getState();
297
- },
298
-
299
- async signOut() {
300
- await clearPersisted();
301
- setState(SIGNED_OUT);
302
- },
303
-
304
- async signOutGlobal(): Promise<GlobalSignOutResult> {
305
- let result: GlobalSignOutResult = { global: 'ended' };
306
- try {
307
- await authClient.endSession({
308
- authority: config.authority,
309
- clientId: config.clientId,
310
- redirectUrl: config.redirectUrl,
311
- idToken: idToken ?? undefined,
312
- });
313
- } catch (error) {
314
- // Reported, not swallowed: the tenant session may still be alive. It
315
- // still must not block clearing local state.
316
- result = { global: 'failed', error: toAuthError(error) };
317
- }
318
- await clearPersisted();
319
- setState(SIGNED_OUT);
320
- return result;
321
- },
322
-
323
- async requestAccessToken(resourceKey) {
324
- const epoch = sessionEpoch;
325
- // Only a real network refresh is a `token-refreshing` phase; a cache hit
326
- // would otherwise flash every subscriber twice for nothing.
327
- const refreshing =
328
- state.status === 'authenticated' && !tokenManager.hasFreshToken(resourceKey);
329
- if (refreshing) {
330
- setState({ status: 'token-refreshing' });
331
- }
332
- const result = await tokenManager.request(resourceKey);
333
- // Restored only if nothing else moved the session meanwhile: a sign-out
334
- // during the refresh used to be overwritten back to `authenticated`.
335
- if (refreshing && epoch === sessionEpoch && state.status === 'token-refreshing') {
336
- setState({ status: 'authenticated' });
337
- }
338
- return result;
339
- },
340
-
341
- getAccessTier() {
342
- return state.accessTier ?? failClosedTier();
343
- },
344
-
345
- requirePremium(): PremiumGateResult {
346
- const tier = state.accessTier ?? failClosedTier();
347
- const allowed = tier.tier === 'premium' && tier.verification === 'verified';
348
- if (!allowed) {
349
- setState({ status: 'access-denied' });
350
- }
351
- return { allowed, tier };
352
- },
353
-
354
- getPlatformProvider() {
355
- return defaultProviderForPlatform(config, platform);
356
- },
357
-
358
- getPlatformProviders() {
359
- return availableProvidersForPlatform(config, platform);
360
- },
361
- };
362
- }
363
-
364
- export type { Profile };
1
+ /**
2
+ * Auth state machine / orchestrator (FR-005, FR-022, R5, R7). Holds the single
3
+ * active session, wires the OidcAuthClient + SecureTokenStore ports, profile
4
+ * mapping, access-tier evaluation, per-resource tokens, restore, and sign-out.
5
+ *
6
+ * Every operation that starts or ends a session bumps `sessionEpoch`. Work that
7
+ * awaited across such a change — a token refresh, a restore, an authorize —
8
+ * compares the epoch it started with before writing anything back, so a sign-out
9
+ * can never be undone by a request that was already in flight.
10
+ */
11
+
12
+ import { Platform } from 'react-native';
13
+ import type {
14
+ Auth,
15
+ AuthConfig,
16
+ AuthState,
17
+ CreateAuthOptions,
18
+ DevicePlatform,
19
+ GlobalSignOutResult,
20
+ PremiumGateResult,
21
+ Profile,
22
+ ProviderId,
23
+ } from '../config/types';
24
+ import { validateConfig } from '../config/validateConfig';
25
+ import { createAppAuthClient } from '../oidc/authClient';
26
+ import {
27
+ availableProvidersForPlatform,
28
+ buildAdditionalParameters,
29
+ defaultProviderForPlatform,
30
+ resolveProvider,
31
+ } from '../oidc/socialRouting';
32
+ import { mapClaimsToProfile } from './profile';
33
+ import { evaluateAccessTier, failClosedTier } from '../access/accessTier';
34
+ import { restoreSession, type PersistedSession } from './session';
35
+ import { AUTH_STORAGE_KEY } from '../tokens/secureStore';
36
+ import { createAccessTokenManager } from '../tokens/accessToken';
37
+ import { AuthError, toAuthError } from '../diagnostics/errors';
38
+
39
+ const SIGNED_OUT: Partial<AuthState> = {
40
+ status: 'signed-out',
41
+ profile: undefined,
42
+ accessTier: undefined,
43
+ restore: 'unavailable',
44
+ error: undefined,
45
+ };
46
+
47
+ export function createAuthMachine(config: AuthConfig, options: CreateAuthOptions = {}): Auth {
48
+ // Throws AuthConfigError before anything else (FR-005, US4 scenario 2).
49
+ validateConfig(config);
50
+
51
+ const platform: DevicePlatform = options.platform ?? (Platform?.OS as DevicePlatform) ?? 'ios';
52
+ const secureStore = config.secureStore;
53
+ const authClient = config.authClient ?? createAppAuthClient();
54
+ const resources = config.resources ?? [];
55
+
56
+ let state: AuthState = { status: 'loading', restore: 'pending' };
57
+ let refreshToken: string | null = null;
58
+ /** Kept for the end-session `id_token_hint`; without it a global sign-out is a no-op. */
59
+ let idToken: string | null = null;
60
+ let sessionEpoch = 0;
61
+ const listeners = new Set<(state: AuthState) => void>();
62
+ /**
63
+ * Every Keychain write and delete, in order. A rotation persisted while a
64
+ * sign-out runs must not land after the sign-out's delete and resurrect the
65
+ * session on the next launch.
66
+ */
67
+ let storeQueue: Promise<void> = Promise.resolve();
68
+
69
+ const enqueueStoreOp = (op: () => Promise<void>): Promise<void> => {
70
+ const next = storeQueue.then(op);
71
+ // The queue itself never rejects, so one failed write does not poison the
72
+ // writes after it; the caller still sees its own failure through `next`.
73
+ storeQueue = next.catch(() => undefined);
74
+ return next;
75
+ };
76
+
77
+ const writeSession = (session: PersistedSession, epoch: number): Promise<void> =>
78
+ enqueueStoreOp(async () => {
79
+ if (epoch !== sessionEpoch) {
80
+ return; // The session this belonged to has already ended.
81
+ }
82
+ await secureStore.setItem(AUTH_STORAGE_KEY, JSON.stringify(session));
83
+ });
84
+
85
+ const tokenManager = createAccessTokenManager({
86
+ authority: config.authority,
87
+ clientId: config.clientId,
88
+ redirectUrl: config.redirectUrl,
89
+ resources,
90
+ authClient,
91
+ getRefreshToken: () => refreshToken,
92
+ sessionEpoch: () => sessionEpoch,
93
+ async onRefreshTokenRotated(token, epoch) {
94
+ if (epoch !== sessionEpoch) {
95
+ return;
96
+ }
97
+ // Live immediately whatever happens to the write: the provider may
98
+ // already have retired the old token, so memory must not keep using it.
99
+ refreshToken = token;
100
+ if (!state.profile) {
101
+ return;
102
+ }
103
+ try {
104
+ await writeSession(
105
+ { refreshToken: token, profile: state.profile, idToken: idToken ?? undefined },
106
+ epoch,
107
+ );
108
+ } catch {
109
+ // The session stays usable in memory. The stored artifact keeps the
110
+ // previous token until the next successful write; a restart before
111
+ // then restores through it if the provider still accepts it, and
112
+ // otherwise lands on sign-in — never on a corrupted state.
113
+ }
114
+ },
115
+ });
116
+
117
+ function getState(): AuthState {
118
+ return { ...state };
119
+ }
120
+
121
+ function setState(patch: Partial<AuthState>): void {
122
+ state = { ...state, ...patch };
123
+ // Snapshot, and isolate each listener: a subscriber that throws must not
124
+ // stop the others or turn a completed sign-in into an error (CORE-03).
125
+ for (const listener of [...listeners]) {
126
+ try {
127
+ listener(getState());
128
+ } catch {
129
+ /* consumer bug; the state transition itself already happened */
130
+ }
131
+ }
132
+ }
133
+
134
+ /** Ends the local session: memory, cached access tokens, and the stored artifact. */
135
+ async function clearPersisted(): Promise<void> {
136
+ sessionEpoch += 1;
137
+ refreshToken = null;
138
+ idToken = null;
139
+ tokenManager.clear();
140
+ await enqueueStoreOp(() => secureStore.removeItem(AUTH_STORAGE_KEY));
141
+ }
142
+
143
+ return {
144
+ getState,
145
+
146
+ subscribe(listener) {
147
+ listeners.add(listener);
148
+ return () => {
149
+ listeners.delete(listener);
150
+ };
151
+ },
152
+
153
+ async restore() {
154
+ sessionEpoch += 1;
155
+ const epoch = sessionEpoch;
156
+ setState({ status: 'loading', restore: 'pending', error: undefined });
157
+
158
+ let result;
159
+ try {
160
+ result = await restoreSession({
161
+ secureStore,
162
+ authority: config.authority,
163
+ clientId: config.clientId,
164
+ redirectUrl: config.redirectUrl,
165
+ scopes: config.scopes,
166
+ authClient,
167
+ mapping: config.accessTierMapping,
168
+ });
169
+ } catch (error) {
170
+ // The store could not be read. Nothing is known, nothing is deleted.
171
+ if (epoch === sessionEpoch) {
172
+ setState({ ...SIGNED_OUT, status: 'error', error: toAuthError(error) });
173
+ }
174
+ return getState();
175
+ }
176
+
177
+ if (epoch !== sessionEpoch) {
178
+ // A sign-in or sign-out ran meanwhile; its outcome stands.
179
+ return getState();
180
+ }
181
+
182
+ if (result.outcome === 'restored' && result.profile && result.refreshToken) {
183
+ refreshToken = result.refreshToken;
184
+ idToken = result.idToken ?? null;
185
+ try {
186
+ await writeSession(
187
+ { refreshToken: result.refreshToken, profile: result.profile, idToken: result.idToken },
188
+ epoch,
189
+ );
190
+ } catch {
191
+ // The refresh succeeded, so the user is signed in for this run. Only
192
+ // the next launch is affected, and it falls back to sign-in.
193
+ }
194
+ if (epoch !== sessionEpoch) {
195
+ return getState();
196
+ }
197
+ setState({
198
+ status: 'authenticated',
199
+ profile: result.profile,
200
+ accessTier: result.accessTier,
201
+ restore: 'restored',
202
+ error: undefined,
203
+ });
204
+ } else if (result.outcome === 'offline' && result.profile) {
205
+ refreshToken = result.refreshToken ?? null;
206
+ idToken = result.idToken ?? null;
207
+ setState({
208
+ status: 'authenticated',
209
+ profile: result.profile,
210
+ accessTier: result.accessTier ?? failClosedTier(),
211
+ restore: 'offline',
212
+ error: undefined,
213
+ });
214
+ } else {
215
+ await clearPersisted();
216
+ setState(SIGNED_OUT);
217
+ }
218
+ return getState();
219
+ },
220
+
221
+ async signIn(providerId: ProviderId) {
222
+ sessionEpoch += 1;
223
+ const epoch = sessionEpoch;
224
+ setState({ status: 'authenticating', error: undefined });
225
+ let provider;
226
+ try {
227
+ provider = resolveProvider(config, providerId, platform);
228
+ } catch (error) {
229
+ setState({
230
+ status: 'error',
231
+ error: toAuthError(error, 'configuration-error', 'auth.error.configuration'),
232
+ });
233
+ return getState();
234
+ }
235
+
236
+ try {
237
+ const tokens = await authClient.authorize({
238
+ authority: config.authority,
239
+ clientId: config.clientId,
240
+ redirectUrl: config.redirectUrl,
241
+ scopes: config.scopes,
242
+ additionalParameters: buildAdditionalParameters(provider),
243
+ });
244
+ if (epoch !== sessionEpoch) {
245
+ return getState();
246
+ }
247
+ if (!tokens.refreshToken) {
248
+ // `offline_access` is required by configuration, so its absence is the
249
+ // tenant's doing. Signing in anyway would give a session that silently
250
+ // never survives a restart.
251
+ setState({
252
+ status: 'error',
253
+ error: new AuthError({
254
+ code: 'configuration-error',
255
+ messageKey: 'auth.error.configuration',
256
+ audience: 'developer',
257
+ detail:
258
+ 'authorize returned no refresh token; check that the app registration grants offline_access',
259
+ }),
260
+ });
261
+ return getState();
262
+ }
263
+ const profile = mapClaimsToProfile(tokens.claims, providerId);
264
+ const accessTier = evaluateAccessTier(tokens.claims, config.accessTierMapping);
265
+ // Written first, committed to memory second: a failed write leaves no
266
+ // half-signed-in session holding a refresh token that was never stored.
267
+ await writeSession(
268
+ { refreshToken: tokens.refreshToken, profile, idToken: tokens.idToken },
269
+ epoch,
270
+ );
271
+ if (epoch !== sessionEpoch) {
272
+ return getState();
273
+ }
274
+ // Single active account: a new sign-in replaces any prior session.
275
+ refreshToken = tokens.refreshToken;
276
+ idToken = tokens.idToken ?? null;
277
+ tokenManager.clear();
278
+ setState({
279
+ status: 'authenticated',
280
+ profile,
281
+ accessTier,
282
+ restore: 'restored',
283
+ error: undefined,
284
+ });
285
+ } catch (error) {
286
+ if (epoch !== sessionEpoch) {
287
+ return getState();
288
+ }
289
+ const authError = toAuthError(error);
290
+ if (authError.code === 'provider-cancelled') {
291
+ setState({ status: 'cancelled', error: authError });
292
+ } else {
293
+ setState({ status: 'error', error: authError });
294
+ }
295
+ }
296
+ return getState();
297
+ },
298
+
299
+ async signOut() {
300
+ await clearPersisted();
301
+ setState(SIGNED_OUT);
302
+ },
303
+
304
+ async signOutGlobal(): Promise<GlobalSignOutResult> {
305
+ let result: GlobalSignOutResult = { global: 'ended' };
306
+ try {
307
+ await authClient.endSession({
308
+ authority: config.authority,
309
+ clientId: config.clientId,
310
+ redirectUrl: config.redirectUrl,
311
+ idToken: idToken ?? undefined,
312
+ });
313
+ } catch (error) {
314
+ // Reported, not swallowed: the tenant session may still be alive. It
315
+ // still must not block clearing local state.
316
+ result = { global: 'failed', error: toAuthError(error) };
317
+ }
318
+ await clearPersisted();
319
+ setState(SIGNED_OUT);
320
+ return result;
321
+ },
322
+
323
+ async requestAccessToken(resourceKey) {
324
+ const epoch = sessionEpoch;
325
+ // Only a real network refresh is a `token-refreshing` phase; a cache hit
326
+ // would otherwise flash every subscriber twice for nothing.
327
+ const refreshing =
328
+ state.status === 'authenticated' && !tokenManager.hasFreshToken(resourceKey);
329
+ if (refreshing) {
330
+ setState({ status: 'token-refreshing' });
331
+ }
332
+ const result = await tokenManager.request(resourceKey);
333
+ // Restored only if nothing else moved the session meanwhile: a sign-out
334
+ // during the refresh used to be overwritten back to `authenticated`.
335
+ if (refreshing && epoch === sessionEpoch && state.status === 'token-refreshing') {
336
+ setState({ status: 'authenticated' });
337
+ }
338
+ return result;
339
+ },
340
+
341
+ getAccessTier() {
342
+ return state.accessTier ?? failClosedTier();
343
+ },
344
+
345
+ requirePremium(): PremiumGateResult {
346
+ const tier = state.accessTier ?? failClosedTier();
347
+ const allowed = tier.tier === 'premium' && tier.verification === 'verified';
348
+ if (!allowed) {
349
+ setState({ status: 'access-denied' });
350
+ }
351
+ return { allowed, tier };
352
+ },
353
+
354
+ getPlatformProvider() {
355
+ return defaultProviderForPlatform(config, platform);
356
+ },
357
+
358
+ getPlatformProviders() {
359
+ return availableProvidersForPlatform(config, platform);
360
+ },
361
+ };
362
+ }
363
+
364
+ export type { Profile };