@dloizides/auth-client 1.0.0 → 2.0.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/CHANGELOG.md +113 -0
- package/README.md +138 -42
- package/dist/AuthClient-Dim7HPRz.d.mts +433 -0
- package/dist/AuthClient-Dim7HPRz.d.ts +433 -0
- package/dist/index.d.mts +204 -109
- package/dist/index.d.ts +204 -109
- package/dist/index.js +587 -34
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +580 -35
- package/dist/index.mjs.map +1 -1
- package/dist/react.d.mts +62 -0
- package/dist/react.d.ts +62 -0
- package/dist/react.js +65 -0
- package/dist/react.js.map +1 -0
- package/dist/react.mjs +58 -0
- package/dist/react.mjs.map +1 -0
- package/package.json +43 -5
package/dist/index.mjs
CHANGED
|
@@ -79,19 +79,89 @@ 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
|
};
|
|
94
160
|
this.tokenStorage = storage;
|
|
161
|
+
this.api = collaborators.api;
|
|
162
|
+
this.interceptor = collaborators.interceptor;
|
|
163
|
+
this.inactivityTracker = collaborators.inactivityTracker;
|
|
164
|
+
this.events = collaborators.events ?? new AuthEventEmitter();
|
|
95
165
|
}
|
|
96
166
|
/**
|
|
97
167
|
* Build an {@link AuthClient} from a standalone issuer URL by parsing the
|
|
@@ -100,7 +170,7 @@ var AuthClient = class _AuthClient {
|
|
|
100
170
|
*
|
|
101
171
|
* @throws Error when the issuer URL doesn't match `{base}/realms/{realm}`.
|
|
102
172
|
*/
|
|
103
|
-
static fromIssuerUrl(input, storage) {
|
|
173
|
+
static fromIssuerUrl(input, storage, collaborators = {}) {
|
|
104
174
|
const realm = parseRealmFromIssuer(input.issuerUrl);
|
|
105
175
|
const baseUrl = parseBaseUrlFromIssuer(input.issuerUrl);
|
|
106
176
|
if (realm === null || baseUrl === null || baseUrl === "") {
|
|
@@ -114,7 +184,8 @@ var AuthClient = class _AuthClient {
|
|
|
114
184
|
redirectUri: input.redirectUri,
|
|
115
185
|
scope: input.scope
|
|
116
186
|
},
|
|
117
|
-
storage
|
|
187
|
+
storage,
|
|
188
|
+
collaborators
|
|
118
189
|
);
|
|
119
190
|
}
|
|
120
191
|
static validateConfig(config) {
|
|
@@ -173,7 +244,7 @@ var AuthClient = class _AuthClient {
|
|
|
173
244
|
realm: this.realm,
|
|
174
245
|
clientId: this.clientId,
|
|
175
246
|
redirectUri: this.config.redirectUri,
|
|
176
|
-
scope: this.
|
|
247
|
+
scope: this.resolveScope(input.offlineAccess),
|
|
177
248
|
state: input.state,
|
|
178
249
|
codeChallenge: input.codeChallenge,
|
|
179
250
|
codeChallengeMethod: input.codeChallengeMethod
|
|
@@ -202,6 +273,103 @@ var AuthClient = class _AuthClient {
|
|
|
202
273
|
}
|
|
203
274
|
return tokens.accessToken;
|
|
204
275
|
}
|
|
276
|
+
/** Subscribe to lifecycle events (currently `sessionExpired` only). */
|
|
277
|
+
on(event, listener) {
|
|
278
|
+
return this.events.on(event, listener);
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Boot-time wiring. Checks the inactivity tracker; if expired, clears
|
|
282
|
+
* tokens and emits `sessionExpired`. Returns whether a usable session
|
|
283
|
+
* survived.
|
|
284
|
+
*/
|
|
285
|
+
async init() {
|
|
286
|
+
if (this.inactivityTracker !== void 0) {
|
|
287
|
+
const expired = await this.inactivityTracker.isExpired();
|
|
288
|
+
if (expired) {
|
|
289
|
+
await this.tokenStorage.clear();
|
|
290
|
+
await this.inactivityTracker.clear();
|
|
291
|
+
this.events.emit("sessionExpired");
|
|
292
|
+
return { hasSession: false };
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const tokens = await this.tokenStorage.read();
|
|
296
|
+
return { hasSession: tokens !== null };
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Trigger a refresh via the configured interceptor. Returns the new tokens
|
|
300
|
+
* or `null` when the refresh failed (in which case `sessionExpired` has
|
|
301
|
+
* already fired).
|
|
302
|
+
*
|
|
303
|
+
* @throws Error when no interceptor is configured.
|
|
304
|
+
*/
|
|
305
|
+
async refresh() {
|
|
306
|
+
if (this.interceptor === void 0) {
|
|
307
|
+
throw new Error("AuthClient.refresh: no RefreshInterceptor configured");
|
|
308
|
+
}
|
|
309
|
+
return this.interceptor.refreshTokens();
|
|
310
|
+
}
|
|
311
|
+
async loginWithOtp(input) {
|
|
312
|
+
return this.runLogin(this.requireApi().loginWithOtp({
|
|
313
|
+
email: input.email,
|
|
314
|
+
otp: input.otp,
|
|
315
|
+
tenantId: input.tenantId,
|
|
316
|
+
offlineAccess: input.offlineAccess ?? false
|
|
317
|
+
}));
|
|
318
|
+
}
|
|
319
|
+
async loginWithPassword(input) {
|
|
320
|
+
return this.runLogin(this.requireApi().loginWithPassword({
|
|
321
|
+
email: input.email,
|
|
322
|
+
password: input.password,
|
|
323
|
+
tenantId: input.tenantId,
|
|
324
|
+
offlineAccess: input.offlineAccess ?? false
|
|
325
|
+
}));
|
|
326
|
+
}
|
|
327
|
+
async logout(options = {}) {
|
|
328
|
+
const api = this.requireApi();
|
|
329
|
+
try {
|
|
330
|
+
await api.logout(options.everywhere ?? false);
|
|
331
|
+
} finally {
|
|
332
|
+
await this.tokenStorage.clear();
|
|
333
|
+
if (this.inactivityTracker !== void 0) {
|
|
334
|
+
await this.inactivityTracker.clear();
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
async requestPasswordReset(input) {
|
|
339
|
+
return this.requireApi().forgotPassword({ email: input.email, tenantId: input.tenantId });
|
|
340
|
+
}
|
|
341
|
+
async confirmPasswordReset(input) {
|
|
342
|
+
return this.requireApi().resetPassword({ token: input.token, newPassword: input.newPassword });
|
|
343
|
+
}
|
|
344
|
+
/** Internal: run a login HTTP call, persist tokens, mark inactivity-active. */
|
|
345
|
+
async runLogin(promise) {
|
|
346
|
+
const raw = await promise;
|
|
347
|
+
if (typeof raw.access_token !== "string" || raw.access_token === "") {
|
|
348
|
+
throw new Error("AuthClient: login response missing access_token");
|
|
349
|
+
}
|
|
350
|
+
const normalized = normalizeTokenResponse({ ...raw, access_token: raw.access_token });
|
|
351
|
+
const tokens = tokenResponseToAuthTokens(normalized);
|
|
352
|
+
await this.tokenStorage.write(tokens);
|
|
353
|
+
if (this.inactivityTracker !== void 0) {
|
|
354
|
+
await this.inactivityTracker.markActive();
|
|
355
|
+
}
|
|
356
|
+
return tokens;
|
|
357
|
+
}
|
|
358
|
+
requireApi() {
|
|
359
|
+
if (this.api === void 0) {
|
|
360
|
+
throw new Error("AuthClient: no AuthApiClient configured");
|
|
361
|
+
}
|
|
362
|
+
return this.api;
|
|
363
|
+
}
|
|
364
|
+
resolveScope(offlineAccess) {
|
|
365
|
+
if (offlineAccess !== true) {
|
|
366
|
+
return this.scope;
|
|
367
|
+
}
|
|
368
|
+
if (this.scope.includes(OFFLINE_ACCESS_SCOPE)) {
|
|
369
|
+
return this.scope;
|
|
370
|
+
}
|
|
371
|
+
return `${this.scope} ${OFFLINE_ACCESS_SCOPE}`.trim();
|
|
372
|
+
}
|
|
205
373
|
};
|
|
206
374
|
|
|
207
375
|
// src/types/KeycloakRoles.ts
|
|
@@ -277,6 +445,413 @@ var InMemoryTokenStorage = class {
|
|
|
277
445
|
}
|
|
278
446
|
};
|
|
279
447
|
|
|
448
|
+
// src/storage/CookieTokenStorage.ts
|
|
449
|
+
var CookieTokenStorage = class {
|
|
450
|
+
constructor() {
|
|
451
|
+
this.accessToken = null;
|
|
452
|
+
this.idToken = void 0;
|
|
453
|
+
this.expiresAt = 0;
|
|
454
|
+
}
|
|
455
|
+
read() {
|
|
456
|
+
if (this.accessToken === null) {
|
|
457
|
+
return Promise.resolve(null);
|
|
458
|
+
}
|
|
459
|
+
const tokens = {
|
|
460
|
+
accessToken: this.accessToken,
|
|
461
|
+
idToken: this.idToken,
|
|
462
|
+
expiresAt: this.expiresAt
|
|
463
|
+
};
|
|
464
|
+
return Promise.resolve(tokens);
|
|
465
|
+
}
|
|
466
|
+
write(tokens) {
|
|
467
|
+
this.accessToken = tokens.accessToken;
|
|
468
|
+
this.idToken = tokens.idToken;
|
|
469
|
+
this.expiresAt = tokens.expiresAt;
|
|
470
|
+
return Promise.resolve();
|
|
471
|
+
}
|
|
472
|
+
clear() {
|
|
473
|
+
this.accessToken = null;
|
|
474
|
+
this.idToken = void 0;
|
|
475
|
+
this.expiresAt = 0;
|
|
476
|
+
return Promise.resolve();
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
// src/storage/SecureStoreTokenStorage.ts
|
|
481
|
+
var DEFAULT_PREFIX = "auth";
|
|
482
|
+
var ACCESS_KEY = "access";
|
|
483
|
+
var REFRESH_KEY = "refresh";
|
|
484
|
+
var ID_KEY = "id";
|
|
485
|
+
var EXPIRES_KEY = "expiresAt";
|
|
486
|
+
var SecureStoreTokenStorage = class {
|
|
487
|
+
constructor(options) {
|
|
488
|
+
this.secureStore = options.secureStore;
|
|
489
|
+
this.prefix = options.keyPrefix ?? DEFAULT_PREFIX;
|
|
490
|
+
this.requireAuthentication = options.requireAuthentication ?? false;
|
|
491
|
+
this.biometricGate = options.biometricGate;
|
|
492
|
+
}
|
|
493
|
+
async read() {
|
|
494
|
+
if (this.shouldRunBiometricGate()) {
|
|
495
|
+
await this.biometricGate.unlock();
|
|
496
|
+
}
|
|
497
|
+
const readOptions = this.requireAuthentication ? { requireAuthentication: true } : void 0;
|
|
498
|
+
const accessToken = await this.secureStore.getItemAsync(this.fullKey(ACCESS_KEY), readOptions);
|
|
499
|
+
if (accessToken === null) {
|
|
500
|
+
return null;
|
|
501
|
+
}
|
|
502
|
+
const refreshTokenRaw = await this.secureStore.getItemAsync(this.fullKey(REFRESH_KEY), readOptions);
|
|
503
|
+
const idTokenRaw = await this.secureStore.getItemAsync(this.fullKey(ID_KEY));
|
|
504
|
+
const expiresAtRaw = await this.secureStore.getItemAsync(this.fullKey(EXPIRES_KEY));
|
|
505
|
+
const expiresAt = parseExpiresAt(expiresAtRaw);
|
|
506
|
+
return {
|
|
507
|
+
accessToken,
|
|
508
|
+
refreshToken: refreshTokenRaw === null ? void 0 : refreshTokenRaw,
|
|
509
|
+
idToken: idTokenRaw === null ? void 0 : idTokenRaw,
|
|
510
|
+
expiresAt
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
async write(tokens) {
|
|
514
|
+
await this.secureStore.setItemAsync(this.fullKey(ACCESS_KEY), tokens.accessToken);
|
|
515
|
+
if (tokens.refreshToken !== void 0 && tokens.refreshToken !== "") {
|
|
516
|
+
await this.secureStore.setItemAsync(this.fullKey(REFRESH_KEY), tokens.refreshToken);
|
|
517
|
+
} else {
|
|
518
|
+
await this.secureStore.deleteItemAsync(this.fullKey(REFRESH_KEY));
|
|
519
|
+
}
|
|
520
|
+
if (tokens.idToken !== void 0 && tokens.idToken !== "") {
|
|
521
|
+
await this.secureStore.setItemAsync(this.fullKey(ID_KEY), tokens.idToken);
|
|
522
|
+
} else {
|
|
523
|
+
await this.secureStore.deleteItemAsync(this.fullKey(ID_KEY));
|
|
524
|
+
}
|
|
525
|
+
await this.secureStore.setItemAsync(this.fullKey(EXPIRES_KEY), String(tokens.expiresAt));
|
|
526
|
+
}
|
|
527
|
+
async clear() {
|
|
528
|
+
await this.secureStore.deleteItemAsync(this.fullKey(ACCESS_KEY));
|
|
529
|
+
await this.secureStore.deleteItemAsync(this.fullKey(REFRESH_KEY));
|
|
530
|
+
await this.secureStore.deleteItemAsync(this.fullKey(ID_KEY));
|
|
531
|
+
await this.secureStore.deleteItemAsync(this.fullKey(EXPIRES_KEY));
|
|
532
|
+
}
|
|
533
|
+
shouldRunBiometricGate() {
|
|
534
|
+
return this.biometricGate !== void 0 && this.biometricGate.isEnabled();
|
|
535
|
+
}
|
|
536
|
+
fullKey(slot) {
|
|
537
|
+
return `${this.prefix}.${slot}`;
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
function parseExpiresAt(raw) {
|
|
541
|
+
if (raw === null || raw === "") {
|
|
542
|
+
return 0;
|
|
543
|
+
}
|
|
544
|
+
const parsed = Number(raw);
|
|
545
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// src/biometric/BiometricGate.ts
|
|
549
|
+
var DEFAULT_PROMPT = "Unlock to continue";
|
|
550
|
+
var DEFAULT_MAX_FAILURES = 3;
|
|
551
|
+
var BiometricGate = class {
|
|
552
|
+
constructor(options) {
|
|
553
|
+
this.enabled = false;
|
|
554
|
+
this.failureCount = 0;
|
|
555
|
+
this.hydrated = false;
|
|
556
|
+
this.localAuth = options.localAuth;
|
|
557
|
+
this.flagStore = options.flagStore;
|
|
558
|
+
this.promptMessage = options.promptMessage ?? DEFAULT_PROMPT;
|
|
559
|
+
this.maxFailures = options.maxFailures ?? DEFAULT_MAX_FAILURES;
|
|
560
|
+
}
|
|
561
|
+
/** Hardware present AND a fingerprint/face ID is enrolled. */
|
|
562
|
+
async isAvailable() {
|
|
563
|
+
const hasHardware = await this.localAuth.hasHardwareAsync();
|
|
564
|
+
if (!hasHardware) {
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
567
|
+
return this.localAuth.isEnrolledAsync();
|
|
568
|
+
}
|
|
569
|
+
/** Synchronous read of the current enabled flag (post-hydration). */
|
|
570
|
+
isEnabled() {
|
|
571
|
+
return this.enabled;
|
|
572
|
+
}
|
|
573
|
+
/** Read the persisted opt-in flag once at app boot. Idempotent. */
|
|
574
|
+
async hydrate() {
|
|
575
|
+
if (this.hydrated) {
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
this.hydrated = true;
|
|
579
|
+
if (this.flagStore !== void 0) {
|
|
580
|
+
this.enabled = await this.flagStore.read();
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Toggle biometric requirement. Persists via {@link BiometricFlagStore} when
|
|
585
|
+
* configured. Resets the failure counter so a re-enable starts fresh.
|
|
586
|
+
*/
|
|
587
|
+
async setEnabled(enabled) {
|
|
588
|
+
this.enabled = enabled;
|
|
589
|
+
this.failureCount = 0;
|
|
590
|
+
if (this.flagStore !== void 0) {
|
|
591
|
+
await this.flagStore.write(enabled);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
/** Reset the failure counter. Tests + consumer recovery flows. */
|
|
595
|
+
resetFailures() {
|
|
596
|
+
this.failureCount = 0;
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* One-shot biometric prompt. Returns `true` on success. Does NOT throw on
|
|
600
|
+
* failure or update the failure counter — useful for action confirmation.
|
|
601
|
+
*/
|
|
602
|
+
async prompt() {
|
|
603
|
+
const result = await this.localAuth.authenticateAsync({
|
|
604
|
+
promptMessage: this.promptMessage
|
|
605
|
+
});
|
|
606
|
+
return result.success;
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Required pre-condition for sensitive token reads. No-op when disabled.
|
|
610
|
+
*
|
|
611
|
+
* @throws Error after {@link maxFailures} consecutive failures.
|
|
612
|
+
* @throws Error on a single failure (lower in the count, but still throws so
|
|
613
|
+
* `SecureStoreTokenStorage.read()` short-circuits).
|
|
614
|
+
*/
|
|
615
|
+
async unlock() {
|
|
616
|
+
if (!this.enabled) {
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
const result = await this.localAuth.authenticateAsync({
|
|
620
|
+
promptMessage: this.promptMessage
|
|
621
|
+
});
|
|
622
|
+
if (result.success) {
|
|
623
|
+
this.failureCount = 0;
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
this.failureCount += 1;
|
|
627
|
+
if (this.failureCount >= this.maxFailures) {
|
|
628
|
+
throw new Error("Biometric authentication failed; locked out");
|
|
629
|
+
}
|
|
630
|
+
throw new Error("Biometric authentication failed");
|
|
631
|
+
}
|
|
632
|
+
};
|
|
633
|
+
|
|
634
|
+
// src/interceptor/RefreshInterceptor.ts
|
|
635
|
+
var RefreshInterceptor = class {
|
|
636
|
+
constructor(options) {
|
|
637
|
+
this.inflight = null;
|
|
638
|
+
this.storage = options.storage;
|
|
639
|
+
this.refresh = options.refresh;
|
|
640
|
+
this.events = options.events;
|
|
641
|
+
this.onRefreshSuccess = options.onRefreshSuccess;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Trigger (or join) a refresh. Returns the new tokens, or `null` if the
|
|
645
|
+
* refresh failed — in which case storage has already been cleared and
|
|
646
|
+
* `sessionExpired` already fired.
|
|
647
|
+
*/
|
|
648
|
+
async refreshTokens() {
|
|
649
|
+
if (this.inflight !== null) {
|
|
650
|
+
return this.inflight;
|
|
651
|
+
}
|
|
652
|
+
this.inflight = this.runRefresh();
|
|
653
|
+
try {
|
|
654
|
+
return await this.inflight;
|
|
655
|
+
} finally {
|
|
656
|
+
this.inflight = null;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* Whether a refresh is currently in flight. Exposed for tests / debug.
|
|
661
|
+
*/
|
|
662
|
+
get isRefreshing() {
|
|
663
|
+
return this.inflight !== null;
|
|
664
|
+
}
|
|
665
|
+
async runRefresh() {
|
|
666
|
+
const current = await this.storage.read();
|
|
667
|
+
let next;
|
|
668
|
+
try {
|
|
669
|
+
next = await this.refresh(current);
|
|
670
|
+
} catch {
|
|
671
|
+
await this.failHard();
|
|
672
|
+
return null;
|
|
673
|
+
}
|
|
674
|
+
if (next === null) {
|
|
675
|
+
await this.failHard();
|
|
676
|
+
return null;
|
|
677
|
+
}
|
|
678
|
+
await this.storage.write(next);
|
|
679
|
+
if (this.onRefreshSuccess !== void 0) {
|
|
680
|
+
await this.onRefreshSuccess(next);
|
|
681
|
+
}
|
|
682
|
+
return next;
|
|
683
|
+
}
|
|
684
|
+
async failHard() {
|
|
685
|
+
await this.storage.clear();
|
|
686
|
+
this.events.emit("sessionExpired");
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
|
|
690
|
+
// src/inactivity/InactivityTracker.ts
|
|
691
|
+
var DEFAULT_MAX_DAYS = 90;
|
|
692
|
+
var MS_PER_DAY = 24 * 60 * 60 * 1e3;
|
|
693
|
+
var InactivityTracker = class {
|
|
694
|
+
constructor(options) {
|
|
695
|
+
this.store = options.store;
|
|
696
|
+
const days = options.maxInactivityDays ?? DEFAULT_MAX_DAYS;
|
|
697
|
+
this.maxInactivityMs = days * MS_PER_DAY;
|
|
698
|
+
this.now = options.now ?? Date.now;
|
|
699
|
+
}
|
|
700
|
+
async markActive(timestamp) {
|
|
701
|
+
await this.store.write(timestamp ?? this.now());
|
|
702
|
+
}
|
|
703
|
+
async getLastActive() {
|
|
704
|
+
return this.store.read();
|
|
705
|
+
}
|
|
706
|
+
async isExpired() {
|
|
707
|
+
const last = await this.store.read();
|
|
708
|
+
if (last === null) {
|
|
709
|
+
return false;
|
|
710
|
+
}
|
|
711
|
+
return this.now() - last > this.maxInactivityMs;
|
|
712
|
+
}
|
|
713
|
+
async clear() {
|
|
714
|
+
await this.store.clear();
|
|
715
|
+
}
|
|
716
|
+
};
|
|
717
|
+
|
|
718
|
+
// src/http/HttpClient.ts
|
|
719
|
+
function createFetchHttpClient(fetchImpl) {
|
|
720
|
+
return async (request) => {
|
|
721
|
+
const init = {
|
|
722
|
+
method: request.method,
|
|
723
|
+
headers: request.headers,
|
|
724
|
+
body: request.body
|
|
725
|
+
};
|
|
726
|
+
if (request.credentials !== void 0) {
|
|
727
|
+
init.credentials = request.credentials;
|
|
728
|
+
}
|
|
729
|
+
const response = await fetchImpl(request.url, init);
|
|
730
|
+
let data;
|
|
731
|
+
if (response.status !== 204) {
|
|
732
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
733
|
+
if (contentType.includes("application/json")) {
|
|
734
|
+
data = await response.json();
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
return {
|
|
738
|
+
status: response.status,
|
|
739
|
+
ok: response.ok,
|
|
740
|
+
data
|
|
741
|
+
};
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// src/api/AuthApiClient.ts
|
|
746
|
+
var AuthApiClient = class {
|
|
747
|
+
constructor(options) {
|
|
748
|
+
this.http = options.http;
|
|
749
|
+
this.baseUrl = options.baseUrl.replace(/\/$/, "");
|
|
750
|
+
this.getAccessToken = options.getAccessToken;
|
|
751
|
+
this.useCredentials = options.useCredentials ?? false;
|
|
752
|
+
}
|
|
753
|
+
loginWithOtp(request) {
|
|
754
|
+
return this.postLogin("/auth/verify-otp", request);
|
|
755
|
+
}
|
|
756
|
+
loginWithPassword(request) {
|
|
757
|
+
return this.postLogin("/auth/login", request);
|
|
758
|
+
}
|
|
759
|
+
/** Web cookie-flow refresh. Sends no body; cookie travels via `credentials`. */
|
|
760
|
+
async refreshCookie() {
|
|
761
|
+
const response = await this.http({
|
|
762
|
+
url: `${this.baseUrl}/auth/refresh-cookie`,
|
|
763
|
+
method: "POST",
|
|
764
|
+
headers: { "content-type": "application/json" },
|
|
765
|
+
credentials: this.useCredentials ? "include" : void 0
|
|
766
|
+
});
|
|
767
|
+
if (!response.ok) {
|
|
768
|
+
throw new Error(`refresh-cookie failed with status ${response.status}`);
|
|
769
|
+
}
|
|
770
|
+
return response.data ?? {};
|
|
771
|
+
}
|
|
772
|
+
async logout(everywhere = false) {
|
|
773
|
+
const url = everywhere ? `${this.baseUrl}/auth/logout?everywhere=true` : `${this.baseUrl}/auth/logout`;
|
|
774
|
+
const response = await this.http({
|
|
775
|
+
url,
|
|
776
|
+
method: "POST",
|
|
777
|
+
headers: await this.authHeaders(),
|
|
778
|
+
credentials: this.useCredentials ? "include" : void 0
|
|
779
|
+
});
|
|
780
|
+
if (!response.ok) {
|
|
781
|
+
throw new Error(`logout failed with status ${response.status}`);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
async forgotPassword(request) {
|
|
785
|
+
const response = await this.http({
|
|
786
|
+
url: `${this.baseUrl}/auth/forgot-password`,
|
|
787
|
+
method: "POST",
|
|
788
|
+
headers: { "content-type": "application/json" },
|
|
789
|
+
body: JSON.stringify(request)
|
|
790
|
+
});
|
|
791
|
+
if (!response.ok) {
|
|
792
|
+
throw new Error(`forgot-password failed with status ${response.status}`);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
async resetPassword(request) {
|
|
796
|
+
const response = await this.http({
|
|
797
|
+
url: `${this.baseUrl}/auth/reset-password`,
|
|
798
|
+
method: "POST",
|
|
799
|
+
headers: { "content-type": "application/json" },
|
|
800
|
+
body: JSON.stringify(request)
|
|
801
|
+
});
|
|
802
|
+
if (!response.ok) {
|
|
803
|
+
throw new Error(`reset-password failed with status ${response.status}`);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
async listSessions() {
|
|
807
|
+
const response = await this.http({
|
|
808
|
+
url: `${this.baseUrl}/me/sessions`,
|
|
809
|
+
method: "GET",
|
|
810
|
+
headers: await this.authHeaders(),
|
|
811
|
+
credentials: this.useCredentials ? "include" : void 0
|
|
812
|
+
});
|
|
813
|
+
if (!response.ok) {
|
|
814
|
+
throw new Error(`listSessions failed with status ${response.status}`);
|
|
815
|
+
}
|
|
816
|
+
return Array.isArray(response.data) ? response.data : [];
|
|
817
|
+
}
|
|
818
|
+
async revokeSession(sessionId) {
|
|
819
|
+
const response = await this.http({
|
|
820
|
+
url: `${this.baseUrl}/me/sessions/${encodeURIComponent(sessionId)}/revoke`,
|
|
821
|
+
method: "POST",
|
|
822
|
+
headers: await this.authHeaders(),
|
|
823
|
+
credentials: this.useCredentials ? "include" : void 0
|
|
824
|
+
});
|
|
825
|
+
if (!response.ok) {
|
|
826
|
+
throw new Error(`revokeSession failed with status ${response.status}`);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
async postLogin(path, body) {
|
|
830
|
+
const response = await this.http({
|
|
831
|
+
url: `${this.baseUrl}${path}`,
|
|
832
|
+
method: "POST",
|
|
833
|
+
headers: { "content-type": "application/json" },
|
|
834
|
+
body: JSON.stringify(body),
|
|
835
|
+
credentials: this.useCredentials ? "include" : void 0
|
|
836
|
+
});
|
|
837
|
+
if (!response.ok) {
|
|
838
|
+
throw new Error(`login failed with status ${response.status}`);
|
|
839
|
+
}
|
|
840
|
+
return response.data ?? {};
|
|
841
|
+
}
|
|
842
|
+
async authHeaders() {
|
|
843
|
+
const headers = { "content-type": "application/json" };
|
|
844
|
+
if (this.getAccessToken === void 0) {
|
|
845
|
+
return headers;
|
|
846
|
+
}
|
|
847
|
+
const token = await this.getAccessToken();
|
|
848
|
+
if (token !== null && token !== "") {
|
|
849
|
+
headers.authorization = `Bearer ${token}`;
|
|
850
|
+
}
|
|
851
|
+
return headers;
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
|
|
280
855
|
// src/utils/normalizeKeycloakUser.ts
|
|
281
856
|
function isNonEmptyString(value) {
|
|
282
857
|
return typeof value === "string" && value !== "";
|
|
@@ -405,36 +980,6 @@ function decodeUtf8(binary) {
|
|
|
405
980
|
return new TextDecoder("utf-8").decode(bytes);
|
|
406
981
|
}
|
|
407
982
|
|
|
408
|
-
|
|
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 };
|
|
983
|
+
export { AuthApiClient, AuthClient, AuthEventEmitter, BiometricGate, BrowserStorageTokenStorage, CookieTokenStorage, InMemoryTokenStorage, InactivityTracker, KeycloakRoles, RefreshInterceptor, SecureStoreTokenStorage, buildAuthorizationCodeBody, buildAuthorizationEndpoint, buildAuthorizationUrl, buildIssuerUrl, buildLogoutEndpoint, buildRefreshTokenBody, buildTokenEndpoint, buildUserInfoEndpoint, computeExpiresAt, createFetchHttpClient, decodeJwt, extractAuthCode, isKeycloakRole, isTokenExpired, normalizeKeycloakUser, normalizeTokenResponse, parseBaseUrlFromIssuer, parseRealmFromIssuer, tokenResponseToAuthTokens };
|
|
439
984
|
//# sourceMappingURL=index.mjs.map
|
|
440
985
|
//# sourceMappingURL=index.mjs.map
|