@dloizides/auth-client 1.0.0 → 2.1.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/dist/index.mjs CHANGED
@@ -79,19 +79,141 @@ function parseBaseUrlFromIssuer(issuerUrl) {
79
79
  return issuerUrl.substring(0, idx).replace(/\/$/, "");
80
80
  }
81
81
 
82
+ // src/utils/normalizeTokenResponse.ts
83
+ function asString(value) {
84
+ return typeof value === "string" && value !== "" ? value : void 0;
85
+ }
86
+ function asNumber(value) {
87
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
88
+ }
89
+ function normalizeTokenResponse(raw) {
90
+ const accessToken = asString(raw.access_token);
91
+ if (accessToken === void 0) {
92
+ throw new Error("Token response missing access_token");
93
+ }
94
+ return {
95
+ accessToken,
96
+ refreshToken: asString(raw.refresh_token),
97
+ idToken: asString(raw.id_token),
98
+ expiresIn: asNumber(raw.expires_in),
99
+ tokenType: asString(raw.token_type),
100
+ scope: asString(raw.scope)
101
+ };
102
+ }
103
+ function tokenResponseToAuthTokens(response, now = Date.now()) {
104
+ return {
105
+ accessToken: response.accessToken,
106
+ refreshToken: response.refreshToken,
107
+ idToken: response.idToken,
108
+ expiresAt: computeExpiresAt(response.expiresIn, now)
109
+ };
110
+ }
111
+
112
+ // src/events/AuthEventEmitter.ts
113
+ var AuthEventEmitter = class {
114
+ constructor() {
115
+ this.listeners = /* @__PURE__ */ new Map();
116
+ }
117
+ on(event, listener) {
118
+ let bucket = this.listeners.get(event);
119
+ if (bucket === void 0) {
120
+ bucket = /* @__PURE__ */ new Set();
121
+ this.listeners.set(event, bucket);
122
+ }
123
+ bucket.add(listener);
124
+ return () => {
125
+ const current = this.listeners.get(event);
126
+ if (current !== void 0) {
127
+ current.delete(listener);
128
+ }
129
+ };
130
+ }
131
+ emit(event) {
132
+ const bucket = this.listeners.get(event);
133
+ if (bucket === void 0) {
134
+ return;
135
+ }
136
+ const snapshot = Array.from(bucket);
137
+ for (const listener of snapshot) {
138
+ listener();
139
+ }
140
+ }
141
+ /** Remove all listeners. Useful for `AuthClient.dispose()` and tests. */
142
+ clear() {
143
+ this.listeners.clear();
144
+ }
145
+ };
146
+
82
147
  // src/AuthClient.ts
83
148
  var DEFAULT_SCOPE = "openid profile email";
149
+ var OFFLINE_ACCESS_SCOPE = "offline_access";
84
150
  var AuthClient = class _AuthClient {
85
151
  /**
86
152
  * @throws Error when `baseUrl`, `realm`, or `clientId` is missing or empty.
87
153
  */
88
- constructor(config, storage) {
154
+ constructor(config, storage, collaborators = {}) {
89
155
  _AuthClient.validateConfig(config);
90
156
  this.config = {
91
157
  ...config,
92
158
  scope: config.scope ?? DEFAULT_SCOPE
93
159
  };
160
+ this.directKcAuth = config.useDirectKcAuth === true;
94
161
  this.tokenStorage = storage;
162
+ this.api = collaborators.api;
163
+ this.interceptor = collaborators.interceptor;
164
+ this.inactivityTracker = collaborators.inactivityTracker;
165
+ this.events = collaborators.events ?? new AuthEventEmitter();
166
+ this.onTokenAcquired = collaborators.onTokenAcquired;
167
+ this.onTokenRefreshed = collaborators.onTokenRefreshed;
168
+ }
169
+ /**
170
+ * Whether this client is configured to route auth flows directly to
171
+ * Keycloak (v2.1.0 direct-KC path) instead of through the proxied
172
+ * identity-api `/auth/*` endpoints.
173
+ *
174
+ * Apps can render conditionally on this — e.g. to swap a login form for
175
+ * a "Sign in with Keycloak" redirect button.
176
+ */
177
+ isDirectMode() {
178
+ return this.directKcAuth;
179
+ }
180
+ /**
181
+ * Persist a token bundle produced by an external flow (e.g. the
182
+ * app-side `useKeycloakExchange` hook that consumes the shared
183
+ * `exchangeAuthorizationCode` primitive). Fires `onTokenAcquired` after
184
+ * persistence and marks the inactivity tracker active.
185
+ *
186
+ * Designed for the v2.1.0 direct-KC path where the PKCE code exchange
187
+ * happens in the app's React-Query hook (which needs `useDispatch`/etc.)
188
+ * but the token persistence + observability should still flow through
189
+ * the shared client.
190
+ */
191
+ async acceptDirectKcTokens(response) {
192
+ const tokens = tokenResponseToAuthTokens(response);
193
+ await this.tokenStorage.write(tokens);
194
+ if (this.inactivityTracker !== void 0) {
195
+ await this.inactivityTracker.markActive();
196
+ }
197
+ if (this.onTokenAcquired !== void 0) {
198
+ this.onTokenAcquired(tokens);
199
+ }
200
+ return tokens;
201
+ }
202
+ /**
203
+ * Same as {@link acceptDirectKcTokens} but fires `onTokenRefreshed`.
204
+ * Use after a `refreshAccessToken()` swap to keep observability counts
205
+ * separated between "fresh login" and "silent refresh".
206
+ */
207
+ async acceptDirectKcRefresh(response) {
208
+ const tokens = tokenResponseToAuthTokens(response);
209
+ await this.tokenStorage.write(tokens);
210
+ if (this.inactivityTracker !== void 0) {
211
+ await this.inactivityTracker.markActive();
212
+ }
213
+ if (this.onTokenRefreshed !== void 0) {
214
+ this.onTokenRefreshed(tokens);
215
+ }
216
+ return tokens;
95
217
  }
96
218
  /**
97
219
  * Build an {@link AuthClient} from a standalone issuer URL by parsing the
@@ -100,7 +222,7 @@ var AuthClient = class _AuthClient {
100
222
  *
101
223
  * @throws Error when the issuer URL doesn't match `{base}/realms/{realm}`.
102
224
  */
103
- static fromIssuerUrl(input, storage) {
225
+ static fromIssuerUrl(input, storage, collaborators = {}) {
104
226
  const realm = parseRealmFromIssuer(input.issuerUrl);
105
227
  const baseUrl = parseBaseUrlFromIssuer(input.issuerUrl);
106
228
  if (realm === null || baseUrl === null || baseUrl === "") {
@@ -114,7 +236,8 @@ var AuthClient = class _AuthClient {
114
236
  redirectUri: input.redirectUri,
115
237
  scope: input.scope
116
238
  },
117
- storage
239
+ storage,
240
+ collaborators
118
241
  );
119
242
  }
120
243
  static validateConfig(config) {
@@ -173,7 +296,7 @@ var AuthClient = class _AuthClient {
173
296
  realm: this.realm,
174
297
  clientId: this.clientId,
175
298
  redirectUri: this.config.redirectUri,
176
- scope: this.scope,
299
+ scope: this.resolveScope(input.offlineAccess),
177
300
  state: input.state,
178
301
  codeChallenge: input.codeChallenge,
179
302
  codeChallengeMethod: input.codeChallengeMethod
@@ -202,8 +325,258 @@ var AuthClient = class _AuthClient {
202
325
  }
203
326
  return tokens.accessToken;
204
327
  }
328
+ /** Subscribe to lifecycle events (currently `sessionExpired` only). */
329
+ on(event, listener) {
330
+ return this.events.on(event, listener);
331
+ }
332
+ /**
333
+ * Boot-time wiring. Checks the inactivity tracker; if expired, clears
334
+ * tokens and emits `sessionExpired`. Returns whether a usable session
335
+ * survived.
336
+ */
337
+ async init() {
338
+ if (this.inactivityTracker !== void 0) {
339
+ const expired = await this.inactivityTracker.isExpired();
340
+ if (expired) {
341
+ await this.tokenStorage.clear();
342
+ await this.inactivityTracker.clear();
343
+ this.events.emit("sessionExpired");
344
+ return { hasSession: false };
345
+ }
346
+ }
347
+ const tokens = await this.tokenStorage.read();
348
+ return { hasSession: tokens !== null };
349
+ }
350
+ /**
351
+ * Trigger a refresh via the configured interceptor. Returns the new tokens
352
+ * or `null` when the refresh failed (in which case `sessionExpired` has
353
+ * already fired).
354
+ *
355
+ * @throws Error when no interceptor is configured.
356
+ */
357
+ async refresh() {
358
+ if (this.interceptor === void 0) {
359
+ throw new Error("AuthClient.refresh: no RefreshInterceptor configured");
360
+ }
361
+ const tokens = await this.interceptor.refreshTokens();
362
+ if (tokens !== null && this.onTokenRefreshed !== void 0) {
363
+ this.onTokenRefreshed(tokens);
364
+ }
365
+ return tokens;
366
+ }
367
+ async loginWithOtp(input) {
368
+ return this.runLogin(this.requireApi().loginWithOtp({
369
+ email: input.email,
370
+ otp: input.otp,
371
+ tenantId: input.tenantId,
372
+ offlineAccess: input.offlineAccess ?? false
373
+ }));
374
+ }
375
+ async loginWithPassword(input) {
376
+ return this.runLogin(this.requireApi().loginWithPassword({
377
+ email: input.email,
378
+ password: input.password,
379
+ tenantId: input.tenantId,
380
+ offlineAccess: input.offlineAccess ?? false
381
+ }));
382
+ }
383
+ async logout(options = {}) {
384
+ const api = this.requireApi();
385
+ try {
386
+ await api.logout(options.everywhere ?? false);
387
+ } finally {
388
+ await this.tokenStorage.clear();
389
+ if (this.inactivityTracker !== void 0) {
390
+ await this.inactivityTracker.clear();
391
+ }
392
+ }
393
+ }
394
+ async requestPasswordReset(input) {
395
+ return this.requireApi().forgotPassword({ email: input.email, tenantId: input.tenantId });
396
+ }
397
+ async confirmPasswordReset(input) {
398
+ return this.requireApi().resetPassword({ token: input.token, newPassword: input.newPassword });
399
+ }
400
+ /** Internal: run a login HTTP call, persist tokens, mark inactivity-active. */
401
+ async runLogin(promise) {
402
+ const raw = await promise;
403
+ if (typeof raw.access_token !== "string" || raw.access_token === "") {
404
+ throw new Error("AuthClient: login response missing access_token");
405
+ }
406
+ const normalized = normalizeTokenResponse({ ...raw, access_token: raw.access_token });
407
+ const tokens = tokenResponseToAuthTokens(normalized);
408
+ await this.tokenStorage.write(tokens);
409
+ if (this.inactivityTracker !== void 0) {
410
+ await this.inactivityTracker.markActive();
411
+ }
412
+ if (this.onTokenAcquired !== void 0) {
413
+ this.onTokenAcquired(tokens);
414
+ }
415
+ return tokens;
416
+ }
417
+ requireApi() {
418
+ if (this.api === void 0) {
419
+ throw new Error("AuthClient: no AuthApiClient configured");
420
+ }
421
+ return this.api;
422
+ }
423
+ resolveScope(offlineAccess) {
424
+ if (offlineAccess !== true) {
425
+ return this.scope;
426
+ }
427
+ if (this.scope.includes(OFFLINE_ACCESS_SCOPE)) {
428
+ return this.scope;
429
+ }
430
+ return `${this.scope} ${OFFLINE_ACCESS_SCOPE}`.trim();
431
+ }
205
432
  };
206
433
 
434
+ // src/oidc/discovery.ts
435
+ var cache = /* @__PURE__ */ new Map();
436
+ function normalizeIssuer(issuerUrl) {
437
+ return issuerUrl.replace(/\/$/, "");
438
+ }
439
+ function isOidcDiscoveryDocument(data) {
440
+ if (data === null || typeof data !== "object") {
441
+ return false;
442
+ }
443
+ const d = data;
444
+ return typeof d.issuer === "string" && d.issuer !== "" && typeof d.authorization_endpoint === "string" && d.authorization_endpoint !== "" && typeof d.token_endpoint === "string" && d.token_endpoint !== "";
445
+ }
446
+ async function fetchDiscoveryDocument(input) {
447
+ const key = normalizeIssuer(input.issuerUrl);
448
+ const cached = cache.get(key);
449
+ if (cached !== void 0) {
450
+ return cached;
451
+ }
452
+ const response = await input.http({
453
+ url: `${key}/.well-known/openid-configuration`,
454
+ method: "GET"
455
+ });
456
+ if (!response.ok) {
457
+ throw new Error(
458
+ `OIDC discovery failed: ${String(response.status)} for ${key}`
459
+ );
460
+ }
461
+ if (!isOidcDiscoveryDocument(response.data)) {
462
+ throw new Error(`OIDC discovery returned invalid metadata for ${key}`);
463
+ }
464
+ cache.set(key, response.data);
465
+ return response.data;
466
+ }
467
+ function clearDiscoveryCache() {
468
+ cache.clear();
469
+ }
470
+
471
+ // src/oidc/pkce.ts
472
+ var VERIFIER_MIN_LENGTH = 43;
473
+ var VERIFIER_MAX_LENGTH = 128;
474
+ var DEFAULT_VERIFIER_LENGTH = 64;
475
+ var RANDOM_BYTES_PER_CHAR = 1;
476
+ var UNRESERVED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
477
+ function getCrypto() {
478
+ const c = globalThis.crypto;
479
+ if (c === void 0 || c.subtle === void 0) {
480
+ throw new Error("pkce: globalThis.crypto.subtle is required (Node 16+ / modern browser)");
481
+ }
482
+ return c;
483
+ }
484
+ function assertVerifierLength(length) {
485
+ if (length < VERIFIER_MIN_LENGTH || length > VERIFIER_MAX_LENGTH) {
486
+ throw new Error(`pkce: code_verifier length must be ${String(VERIFIER_MIN_LENGTH)}-${String(VERIFIER_MAX_LENGTH)} chars (RFC 7636)`);
487
+ }
488
+ }
489
+ function base64UrlEncode(buffer) {
490
+ const bytes = new Uint8Array(buffer);
491
+ let binary = "";
492
+ for (let i = 0; i < bytes.length; i++) {
493
+ binary += String.fromCharCode(bytes[i]);
494
+ }
495
+ const b64 = globalThis.btoa?.(binary) ?? Buffer.from(binary, "binary").toString("base64");
496
+ let end = b64.length;
497
+ while (end > 0 && b64.charCodeAt(end - 1) === "=".charCodeAt(0)) {
498
+ end -= 1;
499
+ }
500
+ return b64.slice(0, end).replace(/\+/g, "-").replace(/\//g, "_");
501
+ }
502
+ function generateCodeVerifier(length = DEFAULT_VERIFIER_LENGTH) {
503
+ assertVerifierLength(length);
504
+ const crypto = getCrypto();
505
+ const bytes = new Uint8Array(length * RANDOM_BYTES_PER_CHAR);
506
+ crypto.getRandomValues(bytes);
507
+ let out = "";
508
+ for (let i = 0; i < length; i++) {
509
+ const byte = bytes[i];
510
+ out += UNRESERVED_CHARS[byte % UNRESERVED_CHARS.length];
511
+ }
512
+ return out;
513
+ }
514
+ async function deriveCodeChallenge(verifier) {
515
+ assertVerifierLength(verifier.length);
516
+ const crypto = getCrypto();
517
+ const data = new TextEncoder().encode(verifier);
518
+ const digest = await crypto.subtle.digest("SHA-256", data);
519
+ return base64UrlEncode(digest);
520
+ }
521
+ async function generatePkcePair(length) {
522
+ const codeVerifier = generateCodeVerifier(length);
523
+ const codeChallenge = await deriveCodeChallenge(codeVerifier);
524
+ return { codeVerifier, codeChallenge, codeChallengeMethod: "S256" };
525
+ }
526
+
527
+ // src/utils/buildTokenRequestBody.ts
528
+ function buildAuthorizationCodeBody(input) {
529
+ return new URLSearchParams({
530
+ client_id: input.clientId,
531
+ grant_type: "authorization_code",
532
+ code: input.code,
533
+ redirect_uri: input.redirectUri,
534
+ code_verifier: input.codeVerifier
535
+ }).toString();
536
+ }
537
+ function buildRefreshTokenBody(input) {
538
+ return new URLSearchParams({
539
+ client_id: input.clientId,
540
+ grant_type: "refresh_token",
541
+ refresh_token: input.refreshToken
542
+ }).toString();
543
+ }
544
+
545
+ // src/oidc/tokenExchange.ts
546
+ var FORM_HEADERS = {
547
+ "Content-Type": "application/x-www-form-urlencoded"
548
+ };
549
+ async function postTokenEndpoint(http, url, body) {
550
+ const response = await http({
551
+ url,
552
+ method: "POST",
553
+ headers: FORM_HEADERS,
554
+ body
555
+ });
556
+ if (!response.ok) {
557
+ throw new Error(`token endpoint POST failed: ${String(response.status)}`);
558
+ }
559
+ return normalizeTokenResponse(response.data);
560
+ }
561
+ async function exchangeAuthorizationCode(input) {
562
+ const url = buildTokenEndpoint(input.baseUrl, input.realm);
563
+ const body = buildAuthorizationCodeBody({
564
+ clientId: input.clientId,
565
+ code: input.code,
566
+ redirectUri: input.redirectUri,
567
+ codeVerifier: input.codeVerifier
568
+ });
569
+ return postTokenEndpoint(input.http, url, body);
570
+ }
571
+ async function refreshAccessToken(input) {
572
+ const url = buildTokenEndpoint(input.baseUrl, input.realm);
573
+ const body = buildRefreshTokenBody({
574
+ clientId: input.clientId,
575
+ refreshToken: input.refreshToken
576
+ });
577
+ return postTokenEndpoint(input.http, url, body);
578
+ }
579
+
207
580
  // src/types/KeycloakRoles.ts
208
581
  var KeycloakRoles = /* @__PURE__ */ ((KeycloakRoles2) => {
209
582
  KeycloakRoles2["SuperUser"] = "superUser";
@@ -277,6 +650,413 @@ var InMemoryTokenStorage = class {
277
650
  }
278
651
  };
279
652
 
653
+ // src/storage/CookieTokenStorage.ts
654
+ var CookieTokenStorage = class {
655
+ constructor() {
656
+ this.accessToken = null;
657
+ this.idToken = void 0;
658
+ this.expiresAt = 0;
659
+ }
660
+ read() {
661
+ if (this.accessToken === null) {
662
+ return Promise.resolve(null);
663
+ }
664
+ const tokens = {
665
+ accessToken: this.accessToken,
666
+ idToken: this.idToken,
667
+ expiresAt: this.expiresAt
668
+ };
669
+ return Promise.resolve(tokens);
670
+ }
671
+ write(tokens) {
672
+ this.accessToken = tokens.accessToken;
673
+ this.idToken = tokens.idToken;
674
+ this.expiresAt = tokens.expiresAt;
675
+ return Promise.resolve();
676
+ }
677
+ clear() {
678
+ this.accessToken = null;
679
+ this.idToken = void 0;
680
+ this.expiresAt = 0;
681
+ return Promise.resolve();
682
+ }
683
+ };
684
+
685
+ // src/storage/SecureStoreTokenStorage.ts
686
+ var DEFAULT_PREFIX = "auth";
687
+ var ACCESS_KEY = "access";
688
+ var REFRESH_KEY = "refresh";
689
+ var ID_KEY = "id";
690
+ var EXPIRES_KEY = "expiresAt";
691
+ var SecureStoreTokenStorage = class {
692
+ constructor(options) {
693
+ this.secureStore = options.secureStore;
694
+ this.prefix = options.keyPrefix ?? DEFAULT_PREFIX;
695
+ this.requireAuthentication = options.requireAuthentication ?? false;
696
+ this.biometricGate = options.biometricGate;
697
+ }
698
+ async read() {
699
+ if (this.shouldRunBiometricGate()) {
700
+ await this.biometricGate.unlock();
701
+ }
702
+ const readOptions = this.requireAuthentication ? { requireAuthentication: true } : void 0;
703
+ const accessToken = await this.secureStore.getItemAsync(this.fullKey(ACCESS_KEY), readOptions);
704
+ if (accessToken === null) {
705
+ return null;
706
+ }
707
+ const refreshTokenRaw = await this.secureStore.getItemAsync(this.fullKey(REFRESH_KEY), readOptions);
708
+ const idTokenRaw = await this.secureStore.getItemAsync(this.fullKey(ID_KEY));
709
+ const expiresAtRaw = await this.secureStore.getItemAsync(this.fullKey(EXPIRES_KEY));
710
+ const expiresAt = parseExpiresAt(expiresAtRaw);
711
+ return {
712
+ accessToken,
713
+ refreshToken: refreshTokenRaw === null ? void 0 : refreshTokenRaw,
714
+ idToken: idTokenRaw === null ? void 0 : idTokenRaw,
715
+ expiresAt
716
+ };
717
+ }
718
+ async write(tokens) {
719
+ await this.secureStore.setItemAsync(this.fullKey(ACCESS_KEY), tokens.accessToken);
720
+ if (tokens.refreshToken !== void 0 && tokens.refreshToken !== "") {
721
+ await this.secureStore.setItemAsync(this.fullKey(REFRESH_KEY), tokens.refreshToken);
722
+ } else {
723
+ await this.secureStore.deleteItemAsync(this.fullKey(REFRESH_KEY));
724
+ }
725
+ if (tokens.idToken !== void 0 && tokens.idToken !== "") {
726
+ await this.secureStore.setItemAsync(this.fullKey(ID_KEY), tokens.idToken);
727
+ } else {
728
+ await this.secureStore.deleteItemAsync(this.fullKey(ID_KEY));
729
+ }
730
+ await this.secureStore.setItemAsync(this.fullKey(EXPIRES_KEY), String(tokens.expiresAt));
731
+ }
732
+ async clear() {
733
+ await this.secureStore.deleteItemAsync(this.fullKey(ACCESS_KEY));
734
+ await this.secureStore.deleteItemAsync(this.fullKey(REFRESH_KEY));
735
+ await this.secureStore.deleteItemAsync(this.fullKey(ID_KEY));
736
+ await this.secureStore.deleteItemAsync(this.fullKey(EXPIRES_KEY));
737
+ }
738
+ shouldRunBiometricGate() {
739
+ return this.biometricGate !== void 0 && this.biometricGate.isEnabled();
740
+ }
741
+ fullKey(slot) {
742
+ return `${this.prefix}.${slot}`;
743
+ }
744
+ };
745
+ function parseExpiresAt(raw) {
746
+ if (raw === null || raw === "") {
747
+ return 0;
748
+ }
749
+ const parsed = Number(raw);
750
+ return Number.isFinite(parsed) ? parsed : 0;
751
+ }
752
+
753
+ // src/biometric/BiometricGate.ts
754
+ var DEFAULT_PROMPT = "Unlock to continue";
755
+ var DEFAULT_MAX_FAILURES = 3;
756
+ var BiometricGate = class {
757
+ constructor(options) {
758
+ this.enabled = false;
759
+ this.failureCount = 0;
760
+ this.hydrated = false;
761
+ this.localAuth = options.localAuth;
762
+ this.flagStore = options.flagStore;
763
+ this.promptMessage = options.promptMessage ?? DEFAULT_PROMPT;
764
+ this.maxFailures = options.maxFailures ?? DEFAULT_MAX_FAILURES;
765
+ }
766
+ /** Hardware present AND a fingerprint/face ID is enrolled. */
767
+ async isAvailable() {
768
+ const hasHardware = await this.localAuth.hasHardwareAsync();
769
+ if (!hasHardware) {
770
+ return false;
771
+ }
772
+ return this.localAuth.isEnrolledAsync();
773
+ }
774
+ /** Synchronous read of the current enabled flag (post-hydration). */
775
+ isEnabled() {
776
+ return this.enabled;
777
+ }
778
+ /** Read the persisted opt-in flag once at app boot. Idempotent. */
779
+ async hydrate() {
780
+ if (this.hydrated) {
781
+ return;
782
+ }
783
+ this.hydrated = true;
784
+ if (this.flagStore !== void 0) {
785
+ this.enabled = await this.flagStore.read();
786
+ }
787
+ }
788
+ /**
789
+ * Toggle biometric requirement. Persists via {@link BiometricFlagStore} when
790
+ * configured. Resets the failure counter so a re-enable starts fresh.
791
+ */
792
+ async setEnabled(enabled) {
793
+ this.enabled = enabled;
794
+ this.failureCount = 0;
795
+ if (this.flagStore !== void 0) {
796
+ await this.flagStore.write(enabled);
797
+ }
798
+ }
799
+ /** Reset the failure counter. Tests + consumer recovery flows. */
800
+ resetFailures() {
801
+ this.failureCount = 0;
802
+ }
803
+ /**
804
+ * One-shot biometric prompt. Returns `true` on success. Does NOT throw on
805
+ * failure or update the failure counter — useful for action confirmation.
806
+ */
807
+ async prompt() {
808
+ const result = await this.localAuth.authenticateAsync({
809
+ promptMessage: this.promptMessage
810
+ });
811
+ return result.success;
812
+ }
813
+ /**
814
+ * Required pre-condition for sensitive token reads. No-op when disabled.
815
+ *
816
+ * @throws Error after {@link maxFailures} consecutive failures.
817
+ * @throws Error on a single failure (lower in the count, but still throws so
818
+ * `SecureStoreTokenStorage.read()` short-circuits).
819
+ */
820
+ async unlock() {
821
+ if (!this.enabled) {
822
+ return;
823
+ }
824
+ const result = await this.localAuth.authenticateAsync({
825
+ promptMessage: this.promptMessage
826
+ });
827
+ if (result.success) {
828
+ this.failureCount = 0;
829
+ return;
830
+ }
831
+ this.failureCount += 1;
832
+ if (this.failureCount >= this.maxFailures) {
833
+ throw new Error("Biometric authentication failed; locked out");
834
+ }
835
+ throw new Error("Biometric authentication failed");
836
+ }
837
+ };
838
+
839
+ // src/interceptor/RefreshInterceptor.ts
840
+ var RefreshInterceptor = class {
841
+ constructor(options) {
842
+ this.inflight = null;
843
+ this.storage = options.storage;
844
+ this.refresh = options.refresh;
845
+ this.events = options.events;
846
+ this.onRefreshSuccess = options.onRefreshSuccess;
847
+ }
848
+ /**
849
+ * Trigger (or join) a refresh. Returns the new tokens, or `null` if the
850
+ * refresh failed — in which case storage has already been cleared and
851
+ * `sessionExpired` already fired.
852
+ */
853
+ async refreshTokens() {
854
+ if (this.inflight !== null) {
855
+ return this.inflight;
856
+ }
857
+ this.inflight = this.runRefresh();
858
+ try {
859
+ return await this.inflight;
860
+ } finally {
861
+ this.inflight = null;
862
+ }
863
+ }
864
+ /**
865
+ * Whether a refresh is currently in flight. Exposed for tests / debug.
866
+ */
867
+ get isRefreshing() {
868
+ return this.inflight !== null;
869
+ }
870
+ async runRefresh() {
871
+ const current = await this.storage.read();
872
+ let next;
873
+ try {
874
+ next = await this.refresh(current);
875
+ } catch {
876
+ await this.failHard();
877
+ return null;
878
+ }
879
+ if (next === null) {
880
+ await this.failHard();
881
+ return null;
882
+ }
883
+ await this.storage.write(next);
884
+ if (this.onRefreshSuccess !== void 0) {
885
+ await this.onRefreshSuccess(next);
886
+ }
887
+ return next;
888
+ }
889
+ async failHard() {
890
+ await this.storage.clear();
891
+ this.events.emit("sessionExpired");
892
+ }
893
+ };
894
+
895
+ // src/inactivity/InactivityTracker.ts
896
+ var DEFAULT_MAX_DAYS = 90;
897
+ var MS_PER_DAY = 24 * 60 * 60 * 1e3;
898
+ var InactivityTracker = class {
899
+ constructor(options) {
900
+ this.store = options.store;
901
+ const days = options.maxInactivityDays ?? DEFAULT_MAX_DAYS;
902
+ this.maxInactivityMs = days * MS_PER_DAY;
903
+ this.now = options.now ?? Date.now;
904
+ }
905
+ async markActive(timestamp) {
906
+ await this.store.write(timestamp ?? this.now());
907
+ }
908
+ async getLastActive() {
909
+ return this.store.read();
910
+ }
911
+ async isExpired() {
912
+ const last = await this.store.read();
913
+ if (last === null) {
914
+ return false;
915
+ }
916
+ return this.now() - last > this.maxInactivityMs;
917
+ }
918
+ async clear() {
919
+ await this.store.clear();
920
+ }
921
+ };
922
+
923
+ // src/http/HttpClient.ts
924
+ function createFetchHttpClient(fetchImpl) {
925
+ return async (request) => {
926
+ const init = {
927
+ method: request.method,
928
+ headers: request.headers,
929
+ body: request.body
930
+ };
931
+ if (request.credentials !== void 0) {
932
+ init.credentials = request.credentials;
933
+ }
934
+ const response = await fetchImpl(request.url, init);
935
+ let data;
936
+ if (response.status !== 204) {
937
+ const contentType = response.headers.get("content-type") ?? "";
938
+ if (contentType.includes("application/json")) {
939
+ data = await response.json();
940
+ }
941
+ }
942
+ return {
943
+ status: response.status,
944
+ ok: response.ok,
945
+ data
946
+ };
947
+ };
948
+ }
949
+
950
+ // src/api/AuthApiClient.ts
951
+ var AuthApiClient = class {
952
+ constructor(options) {
953
+ this.http = options.http;
954
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
955
+ this.getAccessToken = options.getAccessToken;
956
+ this.useCredentials = options.useCredentials ?? false;
957
+ }
958
+ loginWithOtp(request) {
959
+ return this.postLogin("/auth/verify-otp", request);
960
+ }
961
+ loginWithPassword(request) {
962
+ return this.postLogin("/auth/login", request);
963
+ }
964
+ /** Web cookie-flow refresh. Sends no body; cookie travels via `credentials`. */
965
+ async refreshCookie() {
966
+ const response = await this.http({
967
+ url: `${this.baseUrl}/auth/refresh-cookie`,
968
+ method: "POST",
969
+ headers: { "content-type": "application/json" },
970
+ credentials: this.useCredentials ? "include" : void 0
971
+ });
972
+ if (!response.ok) {
973
+ throw new Error(`refresh-cookie failed with status ${response.status}`);
974
+ }
975
+ return response.data ?? {};
976
+ }
977
+ async logout(everywhere = false) {
978
+ const url = everywhere ? `${this.baseUrl}/auth/logout?everywhere=true` : `${this.baseUrl}/auth/logout`;
979
+ const response = await this.http({
980
+ url,
981
+ method: "POST",
982
+ headers: await this.authHeaders(),
983
+ credentials: this.useCredentials ? "include" : void 0
984
+ });
985
+ if (!response.ok) {
986
+ throw new Error(`logout failed with status ${response.status}`);
987
+ }
988
+ }
989
+ async forgotPassword(request) {
990
+ const response = await this.http({
991
+ url: `${this.baseUrl}/auth/forgot-password`,
992
+ method: "POST",
993
+ headers: { "content-type": "application/json" },
994
+ body: JSON.stringify(request)
995
+ });
996
+ if (!response.ok) {
997
+ throw new Error(`forgot-password failed with status ${response.status}`);
998
+ }
999
+ }
1000
+ async resetPassword(request) {
1001
+ const response = await this.http({
1002
+ url: `${this.baseUrl}/auth/reset-password`,
1003
+ method: "POST",
1004
+ headers: { "content-type": "application/json" },
1005
+ body: JSON.stringify(request)
1006
+ });
1007
+ if (!response.ok) {
1008
+ throw new Error(`reset-password failed with status ${response.status}`);
1009
+ }
1010
+ }
1011
+ async listSessions() {
1012
+ const response = await this.http({
1013
+ url: `${this.baseUrl}/me/sessions`,
1014
+ method: "GET",
1015
+ headers: await this.authHeaders(),
1016
+ credentials: this.useCredentials ? "include" : void 0
1017
+ });
1018
+ if (!response.ok) {
1019
+ throw new Error(`listSessions failed with status ${response.status}`);
1020
+ }
1021
+ return Array.isArray(response.data) ? response.data : [];
1022
+ }
1023
+ async revokeSession(sessionId) {
1024
+ const response = await this.http({
1025
+ url: `${this.baseUrl}/me/sessions/${encodeURIComponent(sessionId)}/revoke`,
1026
+ method: "POST",
1027
+ headers: await this.authHeaders(),
1028
+ credentials: this.useCredentials ? "include" : void 0
1029
+ });
1030
+ if (!response.ok) {
1031
+ throw new Error(`revokeSession failed with status ${response.status}`);
1032
+ }
1033
+ }
1034
+ async postLogin(path, body) {
1035
+ const response = await this.http({
1036
+ url: `${this.baseUrl}${path}`,
1037
+ method: "POST",
1038
+ headers: { "content-type": "application/json" },
1039
+ body: JSON.stringify(body),
1040
+ credentials: this.useCredentials ? "include" : void 0
1041
+ });
1042
+ if (!response.ok) {
1043
+ throw new Error(`login failed with status ${response.status}`);
1044
+ }
1045
+ return response.data ?? {};
1046
+ }
1047
+ async authHeaders() {
1048
+ const headers = { "content-type": "application/json" };
1049
+ if (this.getAccessToken === void 0) {
1050
+ return headers;
1051
+ }
1052
+ const token = await this.getAccessToken();
1053
+ if (token !== null && token !== "") {
1054
+ headers.authorization = `Bearer ${token}`;
1055
+ }
1056
+ return headers;
1057
+ }
1058
+ };
1059
+
280
1060
  // src/utils/normalizeKeycloakUser.ts
281
1061
  function isNonEmptyString(value) {
282
1062
  return typeof value === "string" && value !== "";
@@ -327,24 +1107,6 @@ function normalizeKeycloakUser(u) {
327
1107
  };
328
1108
  }
329
1109
 
330
- // src/utils/buildTokenRequestBody.ts
331
- function buildAuthorizationCodeBody(input) {
332
- return new URLSearchParams({
333
- client_id: input.clientId,
334
- grant_type: "authorization_code",
335
- code: input.code,
336
- redirect_uri: input.redirectUri,
337
- code_verifier: input.codeVerifier
338
- }).toString();
339
- }
340
- function buildRefreshTokenBody(input) {
341
- return new URLSearchParams({
342
- client_id: input.clientId,
343
- grant_type: "refresh_token",
344
- refresh_token: input.refreshToken
345
- }).toString();
346
- }
347
-
348
1110
  // src/utils/extractAuthCode.ts
349
1111
  function extractAuthCode(response) {
350
1112
  if (!response) {
@@ -405,36 +1167,6 @@ function decodeUtf8(binary) {
405
1167
  return new TextDecoder("utf-8").decode(bytes);
406
1168
  }
407
1169
 
408
- // src/utils/normalizeTokenResponse.ts
409
- function asString(value) {
410
- return typeof value === "string" && value !== "" ? value : void 0;
411
- }
412
- function asNumber(value) {
413
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
414
- }
415
- function normalizeTokenResponse(raw) {
416
- const accessToken = asString(raw.access_token);
417
- if (accessToken === void 0) {
418
- throw new Error("Token response missing access_token");
419
- }
420
- return {
421
- accessToken,
422
- refreshToken: asString(raw.refresh_token),
423
- idToken: asString(raw.id_token),
424
- expiresIn: asNumber(raw.expires_in),
425
- tokenType: asString(raw.token_type),
426
- scope: asString(raw.scope)
427
- };
428
- }
429
- function tokenResponseToAuthTokens(response, now = Date.now()) {
430
- return {
431
- accessToken: response.accessToken,
432
- refreshToken: response.refreshToken,
433
- idToken: response.idToken,
434
- expiresAt: computeExpiresAt(response.expiresIn, now)
435
- };
436
- }
437
-
438
- export { AuthClient, BrowserStorageTokenStorage, InMemoryTokenStorage, KeycloakRoles, buildAuthorizationCodeBody, buildAuthorizationEndpoint, buildAuthorizationUrl, buildIssuerUrl, buildLogoutEndpoint, buildRefreshTokenBody, buildTokenEndpoint, buildUserInfoEndpoint, computeExpiresAt, decodeJwt, extractAuthCode, isKeycloakRole, isTokenExpired, normalizeKeycloakUser, normalizeTokenResponse, parseBaseUrlFromIssuer, parseRealmFromIssuer, tokenResponseToAuthTokens };
1170
+ export { AuthApiClient, AuthClient, AuthEventEmitter, BiometricGate, BrowserStorageTokenStorage, CookieTokenStorage, InMemoryTokenStorage, InactivityTracker, KeycloakRoles, RefreshInterceptor, SecureStoreTokenStorage, buildAuthorizationCodeBody, buildAuthorizationEndpoint, buildAuthorizationUrl, buildIssuerUrl, buildLogoutEndpoint, buildRefreshTokenBody, buildTokenEndpoint, buildUserInfoEndpoint, clearDiscoveryCache, computeExpiresAt, createFetchHttpClient, decodeJwt, deriveCodeChallenge, exchangeAuthorizationCode, extractAuthCode, fetchDiscoveryDocument, generateCodeVerifier, generatePkcePair, isKeycloakRole, isTokenExpired, normalizeKeycloakUser, normalizeTokenResponse, parseBaseUrlFromIssuer, parseRealmFromIssuer, refreshAccessToken, tokenResponseToAuthTokens };
439
1171
  //# sourceMappingURL=index.mjs.map
440
1172
  //# sourceMappingURL=index.mjs.map