@udibo/oauth2 0.46.0 → 0.47.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/client/direct-client.d.ts +15 -0
- package/dist/client/direct-client.js +92 -34
- package/dist/identity/lockout.d.ts +38 -6
- package/dist/identity/lockout.js +12 -1
- package/dist/identity/service.d.ts +4 -1
- package/dist/identity/service.js +55 -9
- package/dist/react/context.d.ts +4 -1
- package/dist/react/provider.js +8 -2
- package/dist/testing/contract/lockout-store.d.ts +5 -4
- package/dist/testing/contract/lockout-store.js +15 -6
- package/package.json +1 -1
|
@@ -577,6 +577,15 @@ export declare class DirectClient extends OAuth2ClientBase {
|
|
|
577
577
|
* If the refresh fails with `invalid_grant` (the token was revoked or, under
|
|
578
578
|
* rotation, already consumed), all local token state is cleared and
|
|
579
579
|
* `logged_out` is emitted so the framework adapter can redirect to login.
|
|
580
|
+
* The exception is a refresh-token storage shared with another client (a
|
|
581
|
+
* second tab on `IndexedDBRefreshTokenStorage`) that now holds a different
|
|
582
|
+
* token, because the other client rotated it first: storage is left alone
|
|
583
|
+
* and the refresh retries once with the newer token.
|
|
584
|
+
*
|
|
585
|
+
* A refresh that revives a session with no stored token bundle (a reload
|
|
586
|
+
* that kept only the refresh token) emits `authenticated` after
|
|
587
|
+
* `token_refreshed`, because it is the first time this client holds the
|
|
588
|
+
* user's claims.
|
|
580
589
|
*
|
|
581
590
|
* Single-flight has one consequence worth knowing: a call that **joins** a
|
|
582
591
|
* refresh already started by {@link renewSession} inherits that call's quiet
|
|
@@ -756,6 +765,9 @@ export declare class DirectClient extends OAuth2ClientBase {
|
|
|
756
765
|
* state, emits `logged_out`, and returns the OIDC end-session URL when the
|
|
757
766
|
* server advertises one.
|
|
758
767
|
*
|
|
768
|
+
* The revocation is attempted even when clearing local storage fails, in
|
|
769
|
+
* which case `logout` rejects with the storage's error and emits nothing.
|
|
770
|
+
*
|
|
759
771
|
* Best effort covers the reads too: a refresh-token store that cannot be
|
|
760
772
|
* read skips the revocation, and a token store that cannot be read omits
|
|
761
773
|
* `id_token_hint`, rather than failing the sign-out, because a client that
|
|
@@ -797,6 +809,9 @@ export declare class DirectClient extends OAuth2ClientBase {
|
|
|
797
809
|
* out rather than leaving the UI authenticated over a dead token. An expired
|
|
798
810
|
* bundle that a stored refresh token could still revive also reads as signed
|
|
799
811
|
* in, with `sessionExpiresIn: 0` — call {@link renewSession} to revive it.
|
|
812
|
+
* So does a stored refresh token with no bundle at all, as after a reload
|
|
813
|
+
* with `IndexedDBRefreshTokenStorage` and an in-memory access token; `user`
|
|
814
|
+
* is `null` until the renewal stores a bundle.
|
|
800
815
|
*
|
|
801
816
|
* `logoutUrl` is always `null`: sign-out runs through {@link logout}, which
|
|
802
817
|
* revokes and clears locally rather than sending the browser somewhere.
|
|
@@ -649,6 +649,15 @@ export class DirectClient extends OAuth2ClientBase {
|
|
|
649
649
|
* If the refresh fails with `invalid_grant` (the token was revoked or, under
|
|
650
650
|
* rotation, already consumed), all local token state is cleared and
|
|
651
651
|
* `logged_out` is emitted so the framework adapter can redirect to login.
|
|
652
|
+
* The exception is a refresh-token storage shared with another client (a
|
|
653
|
+
* second tab on `IndexedDBRefreshTokenStorage`) that now holds a different
|
|
654
|
+
* token, because the other client rotated it first: storage is left alone
|
|
655
|
+
* and the refresh retries once with the newer token.
|
|
656
|
+
*
|
|
657
|
+
* A refresh that revives a session with no stored token bundle (a reload
|
|
658
|
+
* that kept only the refresh token) emits `authenticated` after
|
|
659
|
+
* `token_refreshed`, because it is the first time this client holds the
|
|
660
|
+
* user's claims.
|
|
652
661
|
*
|
|
653
662
|
* Single-flight has one consequence worth knowing: a call that **joins** a
|
|
654
663
|
* refresh already started by {@link renewSession} inherits that call's quiet
|
|
@@ -692,11 +701,16 @@ export class DirectClient extends OAuth2ClientBase {
|
|
|
692
701
|
return promise;
|
|
693
702
|
}
|
|
694
703
|
async #doRefresh(reportTransient, snapshot) {
|
|
695
|
-
const { version, refreshToken } = await this.#mutateSession(async () => {
|
|
704
|
+
const { version, refreshToken, revivesEmptyBundle } = await this.#mutateSession(async () => {
|
|
696
705
|
const version = (snapshot.version = this.#sessionVersion);
|
|
706
|
+
const refreshToken = await this.#readRefreshToken(reportTransient);
|
|
707
|
+
const bundle = await Promise.resolve()
|
|
708
|
+
.then(() => this.#tokenStorage.get())
|
|
709
|
+
.catch(() => undefined);
|
|
697
710
|
return {
|
|
698
711
|
version,
|
|
699
|
-
refreshToken
|
|
712
|
+
refreshToken,
|
|
713
|
+
revivesEmptyBundle: bundle === null || bundle?.accessToken === "",
|
|
700
714
|
};
|
|
701
715
|
});
|
|
702
716
|
if (version !== this.#sessionVersion) {
|
|
@@ -705,27 +719,41 @@ export class DirectClient extends OAuth2ClientBase {
|
|
|
705
719
|
if (!refreshToken) {
|
|
706
720
|
throw new InvalidGrantError("no refresh token available");
|
|
707
721
|
}
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
}
|
|
721
|
-
if (isOAuth2ErrorCode(error, "invalid_grant")) {
|
|
722
|
-
await this.#clearSession();
|
|
723
|
-
this.emit({ type: "logged_out", reason: "invalid_grant" });
|
|
722
|
+
let presented = refreshToken;
|
|
723
|
+
for (let attempt = 0;; attempt++) {
|
|
724
|
+
try {
|
|
725
|
+
const response = await this.#postToken(new URLSearchParams({
|
|
726
|
+
grant_type: "refresh_token",
|
|
727
|
+
refresh_token: presented,
|
|
728
|
+
}));
|
|
729
|
+
const tokens = await this.#saveTokens(response, version, true);
|
|
730
|
+
this.emit({ type: "token_refreshed", tokens });
|
|
731
|
+
if (revivesEmptyBundle)
|
|
732
|
+
this.emit({ type: "authenticated", tokens });
|
|
733
|
+
return tokens.accessToken;
|
|
724
734
|
}
|
|
725
|
-
|
|
726
|
-
|
|
735
|
+
catch (error) {
|
|
736
|
+
if (version !== this.#sessionVersion) {
|
|
737
|
+
throw new InvalidGrantError("session changed during refresh");
|
|
738
|
+
}
|
|
739
|
+
if (isOAuth2ErrorCode(error, "invalid_grant")) {
|
|
740
|
+
const outcome = await this.#clearSessionUnlessReplaced(presented, version);
|
|
741
|
+
if (outcome.superseded) {
|
|
742
|
+
throw new InvalidGrantError("session changed during refresh");
|
|
743
|
+
}
|
|
744
|
+
if (outcome.replacement === undefined) {
|
|
745
|
+
this.emit({ type: "logged_out", reason: "invalid_grant" });
|
|
746
|
+
}
|
|
747
|
+
else if (attempt === 0) {
|
|
748
|
+
presented = outcome.replacement;
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
else if (reportTransient) {
|
|
753
|
+
this.emit({ type: "error", error });
|
|
754
|
+
}
|
|
755
|
+
throw error;
|
|
727
756
|
}
|
|
728
|
-
throw error;
|
|
729
757
|
}
|
|
730
758
|
}
|
|
731
759
|
async #readRefreshToken(reportTransient) {
|
|
@@ -1010,6 +1038,9 @@ export class DirectClient extends OAuth2ClientBase {
|
|
|
1010
1038
|
* state, emits `logged_out`, and returns the OIDC end-session URL when the
|
|
1011
1039
|
* server advertises one.
|
|
1012
1040
|
*
|
|
1041
|
+
* The revocation is attempted even when clearing local storage fails, in
|
|
1042
|
+
* which case `logout` rejects with the storage's error and emits nothing.
|
|
1043
|
+
*
|
|
1013
1044
|
* Best effort covers the reads too: a refresh-token store that cannot be
|
|
1014
1045
|
* read skips the revocation, and a token store that cannot be read omits
|
|
1015
1046
|
* `id_token_hint`, rather than failing the sign-out, because a client that
|
|
@@ -1038,14 +1069,15 @@ export class DirectClient extends OAuth2ClientBase {
|
|
|
1038
1069
|
.then((tokens) => tokens?.idToken, () => undefined);
|
|
1039
1070
|
if (version !== this.#sessionVersion)
|
|
1040
1071
|
return {};
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1072
|
+
try {
|
|
1073
|
+
await this.#clearSession();
|
|
1074
|
+
this.emit({ type: "logged_out", reason: "user" });
|
|
1075
|
+
}
|
|
1076
|
+
finally {
|
|
1077
|
+
if (refreshToken) {
|
|
1078
|
+
await this.revoke(refreshToken, {
|
|
1079
|
+
tokenTypeHint: "refresh_token",
|
|
1080
|
+
}).catch(() => { });
|
|
1049
1081
|
}
|
|
1050
1082
|
}
|
|
1051
1083
|
let endSession;
|
|
@@ -1097,6 +1129,9 @@ export class DirectClient extends OAuth2ClientBase {
|
|
|
1097
1129
|
* out rather than leaving the UI authenticated over a dead token. An expired
|
|
1098
1130
|
* bundle that a stored refresh token could still revive also reads as signed
|
|
1099
1131
|
* in, with `sessionExpiresIn: 0` — call {@link renewSession} to revive it.
|
|
1132
|
+
* So does a stored refresh token with no bundle at all, as after a reload
|
|
1133
|
+
* with `IndexedDBRefreshTokenStorage` and an in-memory access token; `user`
|
|
1134
|
+
* is `null` until the renewal stores a bundle.
|
|
1100
1135
|
*
|
|
1101
1136
|
* `logoutUrl` is always `null`: sign-out runs through {@link logout}, which
|
|
1102
1137
|
* revokes and clears locally rather than sending the browser somewhere.
|
|
@@ -1112,8 +1147,16 @@ export class DirectClient extends OAuth2ClientBase {
|
|
|
1112
1147
|
async #session(quiet) {
|
|
1113
1148
|
try {
|
|
1114
1149
|
const tokens = await this.#tokenStorage.get();
|
|
1115
|
-
if (!tokens?.accessToken)
|
|
1116
|
-
|
|
1150
|
+
if (!tokens?.accessToken) {
|
|
1151
|
+
if (!(await this.#refreshTokenStorage?.get()))
|
|
1152
|
+
return SIGNED_OUT;
|
|
1153
|
+
return {
|
|
1154
|
+
isAuthenticated: true,
|
|
1155
|
+
user: null,
|
|
1156
|
+
sessionExpiresIn: 0,
|
|
1157
|
+
logoutUrl: null,
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1117
1160
|
const expiresIn = tokens.accessTokenExpiresAt
|
|
1118
1161
|
? Math.round((tokens.accessTokenExpiresAt - Date.now()) / 1000)
|
|
1119
1162
|
: null;
|
|
@@ -1267,12 +1310,27 @@ export class DirectClient extends OAuth2ClientBase {
|
|
|
1267
1310
|
}
|
|
1268
1311
|
#clearSession() {
|
|
1269
1312
|
this.#sessionVersion++;
|
|
1313
|
+
return this.#mutateSession(() => this.#clearStores());
|
|
1314
|
+
}
|
|
1315
|
+
#clearSessionUnlessReplaced(presented, version) {
|
|
1270
1316
|
return this.#mutateSession(async () => {
|
|
1271
|
-
await
|
|
1272
|
-
|
|
1273
|
-
|
|
1317
|
+
const stored = await Promise.resolve()
|
|
1318
|
+
.then(() => this.#refreshTokenStorage?.get())
|
|
1319
|
+
.catch(() => null);
|
|
1320
|
+
if (version !== this.#sessionVersion)
|
|
1321
|
+
return { superseded: true };
|
|
1322
|
+
if (stored && stored !== presented)
|
|
1323
|
+
return { replacement: stored };
|
|
1324
|
+
this.#sessionVersion++;
|
|
1325
|
+
await this.#clearStores();
|
|
1326
|
+
return {};
|
|
1274
1327
|
});
|
|
1275
1328
|
}
|
|
1329
|
+
async #clearStores() {
|
|
1330
|
+
await this.#tokenStorage.clear();
|
|
1331
|
+
await this.#refreshTokenStorage?.clear();
|
|
1332
|
+
await this.#authRequestStorage?.clear();
|
|
1333
|
+
}
|
|
1276
1334
|
}
|
|
1277
1335
|
function withOrigin(urlStr, origin) {
|
|
1278
1336
|
const url = new URL(urlStr);
|
|
@@ -19,7 +19,11 @@
|
|
|
19
19
|
*/
|
|
20
20
|
/** Per-account lockout state. */
|
|
21
21
|
export interface LockoutRecord {
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Consecutive sign-in attempts counted since the last success/unlock. An
|
|
24
|
+
* attempt is counted before its password is checked, so an attempt still in
|
|
25
|
+
* flight is included until a success clears the record.
|
|
26
|
+
*/
|
|
23
27
|
failures: number;
|
|
24
28
|
/** When the active lock expires (epoch ms); absent when not locked. */
|
|
25
29
|
lockedUntil?: number;
|
|
@@ -33,11 +37,13 @@ export interface LockoutStore {
|
|
|
33
37
|
*/
|
|
34
38
|
get(userId: string, now?: number): Promise<LockoutRecord | undefined>;
|
|
35
39
|
/**
|
|
36
|
-
* Add one
|
|
40
|
+
* Add one attempt and return the new record: an expired lock resets the
|
|
37
41
|
* count to 1 and drops the lock; otherwise `failures + 1` with any active
|
|
38
|
-
* lock kept.
|
|
39
|
-
*
|
|
40
|
-
*
|
|
42
|
+
* lock kept. `AccountLockout` calls it before the password is checked and
|
|
43
|
+
* admits the attempt only on the count it returns, so it must be atomic (a
|
|
44
|
+
* single statement / compare-and-set in shared stores) and return the
|
|
45
|
+
* post-increment count: a read-modify-write lets concurrent attempts share a
|
|
46
|
+
* count, and each one sharing it is another guess past `maxAttempts`.
|
|
41
47
|
*/
|
|
42
48
|
increment(userId: string, now: number): Promise<LockoutRecord>;
|
|
43
49
|
/**
|
|
@@ -130,9 +136,29 @@ export interface AccountLockoutLike {
|
|
|
130
136
|
/**
|
|
131
137
|
* Record one failed attempt and report the resulting state. `justLocked` must
|
|
132
138
|
* be true for exactly one attempt per lock — `IdentityService` fires the
|
|
133
|
-
* lockout event and any unlock email off it.
|
|
139
|
+
* lockout event and any unlock email off it. `IdentityService` calls it after
|
|
140
|
+
* a wrong password only when {@link AccountLockoutLike.reserveAttempt} is
|
|
141
|
+
* absent.
|
|
134
142
|
*/
|
|
135
143
|
recordFailure(userId: string, now?: number): Promise<LockoutFailureResult>;
|
|
144
|
+
/**
|
|
145
|
+
* Count one sign-in attempt atomically before its password is checked, and
|
|
146
|
+
* report the resulting state the way {@link AccountLockoutLike.recordFailure}
|
|
147
|
+
* does. `IdentityService` checks the password only when the result is
|
|
148
|
+
* unlocked or `justLocked` — the attempt that reaches the threshold is still
|
|
149
|
+
* checked — and refuses the rest under `"enforce"`. A wrong password then
|
|
150
|
+
* fires the lockout event off the reservation's `justLocked`; a success
|
|
151
|
+
* calls {@link AccountLockoutLike.reset}; an attempt that throws stays
|
|
152
|
+
* counted and, when its reservation was `justLocked`, still fires the
|
|
153
|
+
* lockout event.
|
|
154
|
+
*
|
|
155
|
+
* Optional. Without it `IdentityService` reads
|
|
156
|
+
* {@link AccountLockoutLike.status} and calls `recordFailure` only after a
|
|
157
|
+
* wrong password, so concurrent guesses that all read the account unlocked
|
|
158
|
+
* are each checked and can exceed the threshold. {@link AccountLockout}
|
|
159
|
+
* implements it.
|
|
160
|
+
*/
|
|
161
|
+
reserveAttempt?(userId: string, now?: number): Promise<LockoutFailureResult>;
|
|
136
162
|
/** Clear the account's failures and any lock (successful sign-in, unlock). */
|
|
137
163
|
reset(userId: string): Promise<void>;
|
|
138
164
|
}
|
|
@@ -159,6 +185,12 @@ export declare class AccountLockout implements AccountLockoutLike {
|
|
|
159
185
|
* threshold is crossed. An attempt after a lock expired starts a fresh count.
|
|
160
186
|
*/
|
|
161
187
|
recordFailure(userId: string, now?: number): Promise<LockoutFailureResult>;
|
|
188
|
+
/**
|
|
189
|
+
* Count one sign-in attempt before its password is checked, with the same
|
|
190
|
+
* accounting as {@link recordFailure}: of any number of concurrent attempts,
|
|
191
|
+
* only the first `maxAttempts` come back unlocked or `justLocked`.
|
|
192
|
+
*/
|
|
193
|
+
reserveAttempt(userId: string, now?: number): Promise<LockoutFailureResult>;
|
|
162
194
|
/** Clear the account's failures and any lock (successful sign-in, unlock). */
|
|
163
195
|
reset(userId: string): Promise<void>;
|
|
164
196
|
}
|
package/dist/identity/lockout.js
CHANGED
|
@@ -62,7 +62,18 @@ export class AccountLockout {
|
|
|
62
62
|
* Record one failed attempt, locking the account when the consecutive-failure
|
|
63
63
|
* threshold is crossed. An attempt after a lock expired starts a fresh count.
|
|
64
64
|
*/
|
|
65
|
-
|
|
65
|
+
recordFailure(userId, now = Date.now()) {
|
|
66
|
+
return this.#count(userId, now);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Count one sign-in attempt before its password is checked, with the same
|
|
70
|
+
* accounting as {@link recordFailure}: of any number of concurrent attempts,
|
|
71
|
+
* only the first `maxAttempts` come back unlocked or `justLocked`.
|
|
72
|
+
*/
|
|
73
|
+
reserveAttempt(userId, now = Date.now()) {
|
|
74
|
+
return this.#count(userId, now);
|
|
75
|
+
}
|
|
76
|
+
async #count(userId, now = Date.now()) {
|
|
66
77
|
const record = await this.#store.increment(userId, now);
|
|
67
78
|
const { failures } = record;
|
|
68
79
|
if (record.lockedUntil !== undefined && record.lockedUntil > now) {
|
|
@@ -334,7 +334,10 @@ export interface IdentityServiceOptions<User extends IdentityUser> {
|
|
|
334
334
|
* records consecutive wrong-password failures per account and — once the
|
|
335
335
|
* threshold locks the account — rejects further attempts with the same
|
|
336
336
|
* uniform, timing-equalized `null` an unknown identifier gets (no lockout
|
|
337
|
-
* oracle).
|
|
337
|
+
* oracle). With a lockout that implements
|
|
338
|
+
* {@link AccountLockoutLike.reserveAttempt}, as `AccountLockout` does,
|
|
339
|
+
* each attempt is counted before its password is checked, so concurrent
|
|
340
|
+
* guesses cannot exceed the threshold. A successful sign-in resets the count;
|
|
338
341
|
* {@link IdentityService.unlockAccount} clears a lock via an emailed
|
|
339
342
|
* single-use token.
|
|
340
343
|
*/
|
package/dist/identity/service.js
CHANGED
|
@@ -165,11 +165,22 @@ export class IdentityService {
|
|
|
165
165
|
});
|
|
166
166
|
return await this.#rejectSignIn(startedAt);
|
|
167
167
|
}
|
|
168
|
-
|
|
168
|
+
const lockReported = await this.#reportLock(user.id, identifier);
|
|
169
|
+
if (lockReported && this.#enforce) {
|
|
169
170
|
await this.#equalizeTiming(input.password);
|
|
170
171
|
return await this.#rejectSignIn(startedAt);
|
|
171
172
|
}
|
|
172
|
-
const
|
|
173
|
+
const attempt = this.#signInAttempt(user.id, identifier, lockReported);
|
|
174
|
+
let outcome;
|
|
175
|
+
try {
|
|
176
|
+
outcome = await this.#authenticate(user.id, input.password, attempt);
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
await attempt.abandon();
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
if (outcome === "refused")
|
|
183
|
+
return await this.#rejectSignIn(startedAt);
|
|
173
184
|
if (outcome !== "authenticated") {
|
|
174
185
|
await this.#emit({
|
|
175
186
|
type: "sign_in.failed",
|
|
@@ -177,9 +188,8 @@ export class IdentityService {
|
|
|
177
188
|
reason: outcome,
|
|
178
189
|
userId: user.id,
|
|
179
190
|
});
|
|
180
|
-
if (outcome === "wrong_password")
|
|
181
|
-
await
|
|
182
|
-
}
|
|
191
|
+
if (outcome === "wrong_password")
|
|
192
|
+
await attempt.fail();
|
|
183
193
|
return await this.#rejectSignIn(startedAt);
|
|
184
194
|
}
|
|
185
195
|
await this.#resetThrottle("signIn", identifier);
|
|
@@ -667,21 +677,51 @@ export class IdentityService {
|
|
|
667
677
|
await delay(remaining);
|
|
668
678
|
return null;
|
|
669
679
|
}
|
|
670
|
-
async #
|
|
680
|
+
async #reportLock(userId, identifier) {
|
|
671
681
|
if (!this.#lockout)
|
|
672
682
|
return false;
|
|
673
683
|
const status = await this.#lockout.status(userId);
|
|
674
684
|
if (!status.locked)
|
|
675
685
|
return false;
|
|
686
|
+
await this.#emitSignInLocked(userId, identifier);
|
|
687
|
+
return true;
|
|
688
|
+
}
|
|
689
|
+
async #emitSignInLocked(userId, identifier) {
|
|
676
690
|
await this.#emit({
|
|
677
691
|
type: "sign_in.locked",
|
|
678
692
|
userId,
|
|
679
693
|
identifier,
|
|
680
694
|
enforced: this.#enforce,
|
|
681
695
|
});
|
|
682
|
-
return this.#enforce;
|
|
683
696
|
}
|
|
684
|
-
|
|
697
|
+
#signInAttempt(userId, identifier, lockReported) {
|
|
698
|
+
const reserve = this.#lockout?.reserveAttempt?.bind(this.#lockout);
|
|
699
|
+
if (!reserve) {
|
|
700
|
+
return {
|
|
701
|
+
admit: () => Promise.resolve(true),
|
|
702
|
+
fail: () => this.#recordSignInFailure(userId, identifier),
|
|
703
|
+
abandon: () => Promise.resolve(),
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
let reservation;
|
|
707
|
+
const announceLock = async () => {
|
|
708
|
+
if (reservation)
|
|
709
|
+
await this.#emitLockout(userId, identifier, reservation);
|
|
710
|
+
};
|
|
711
|
+
return {
|
|
712
|
+
admit: async () => {
|
|
713
|
+
reservation = await reserve(userId);
|
|
714
|
+
if (!reservation.locked || reservation.justLocked)
|
|
715
|
+
return true;
|
|
716
|
+
if (!lockReported)
|
|
717
|
+
await this.#emitSignInLocked(userId, identifier);
|
|
718
|
+
return !this.#enforce;
|
|
719
|
+
},
|
|
720
|
+
fail: announceLock,
|
|
721
|
+
abandon: announceLock,
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
async #authenticate(userId, password, attempt) {
|
|
685
725
|
const credential = await this.#users.getCredential(userId);
|
|
686
726
|
// Native credential is authoritative: only try an imported hash when there
|
|
687
727
|
// is none, so a wrong password can't resurrect a stale one (no downgrade).
|
|
@@ -692,6 +732,10 @@ export class IdentityService {
|
|
|
692
732
|
await this.#equalizeTiming(password);
|
|
693
733
|
return "no_password";
|
|
694
734
|
}
|
|
735
|
+
if (!(await attempt.admit())) {
|
|
736
|
+
await this.#equalizeTiming(password);
|
|
737
|
+
return "refused";
|
|
738
|
+
}
|
|
695
739
|
if (credential && (await this.#passwords.verify(password, credential))) {
|
|
696
740
|
return (await this.#rehashCredential(userId, password, credential))
|
|
697
741
|
? "authenticated"
|
|
@@ -754,7 +798,9 @@ export class IdentityService {
|
|
|
754
798
|
async #recordSignInFailure(userId, identifier) {
|
|
755
799
|
if (!this.#lockout)
|
|
756
800
|
return;
|
|
757
|
-
|
|
801
|
+
await this.#emitLockout(userId, identifier, await this.#lockout.recordFailure(userId));
|
|
802
|
+
}
|
|
803
|
+
async #emitLockout(userId, identifier, result) {
|
|
758
804
|
if (!result.justLocked)
|
|
759
805
|
return;
|
|
760
806
|
await this.#emit({
|
package/dist/react/context.d.ts
CHANGED
|
@@ -22,7 +22,10 @@ export interface OAuth2State {
|
|
|
22
22
|
/**
|
|
23
23
|
* Current user claims, or `null` when unauthenticated. From
|
|
24
24
|
* `GET /auth/session` behind a `BffClient`; the decoded `id_token` claims
|
|
25
|
-
* (or the `userinfo_endpoint` body) behind a `DirectClient`.
|
|
25
|
+
* (or the `userinfo_endpoint` body) behind a `DirectClient`. Can also be
|
|
26
|
+
* `null` while `isAuthenticated` is `true`, until the claims load: a
|
|
27
|
+
* `DirectClient` reloaded with only a stored refresh token has none until
|
|
28
|
+
* its first refresh.
|
|
26
29
|
*/
|
|
27
30
|
user: UserInfoClaims | null;
|
|
28
31
|
/** Last error surfaced by the client, or `null`. */
|
package/dist/react/provider.js
CHANGED
|
@@ -75,12 +75,18 @@ export function OAuth2Provider(props) {
|
|
|
75
75
|
const [logoutsInFlight, setLogoutsInFlight] = useState(0);
|
|
76
76
|
useEffect(() => {
|
|
77
77
|
let cancelled = false;
|
|
78
|
+
let identityChanges = 0;
|
|
78
79
|
const handle = (event) => {
|
|
79
80
|
setState((prev) => reduce(prev, event));
|
|
81
|
+
if (event.type === "authenticated" || event.type === "logged_out") {
|
|
82
|
+
identityChanges++;
|
|
83
|
+
}
|
|
80
84
|
if (event.type === "authenticated") {
|
|
85
|
+
const lookup = identityChanges;
|
|
81
86
|
client.getUser().then((user) => {
|
|
82
|
-
if (
|
|
83
|
-
|
|
87
|
+
if (cancelled || lookup !== identityChanges)
|
|
88
|
+
return;
|
|
89
|
+
setState((prev) => ({ ...prev, user }));
|
|
84
90
|
}, () => { });
|
|
85
91
|
}
|
|
86
92
|
};
|
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
* Contract test suite for {@link LockoutStore} implementations — the
|
|
3
3
|
* per-account failure counter behind `AccountLockout`.
|
|
4
4
|
*
|
|
5
|
-
* `AccountLockout`
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* `AccountLockout` counts each sign-in attempt with `increment` before its
|
|
6
|
+
* password is checked, and admits the attempt only on the count `increment`
|
|
7
|
+
* returns. A store that lets concurrent attempts share a count admits one extra
|
|
8
|
+
* guess for every attempt sharing it: the brute-force floor the lockout is
|
|
9
|
+
* meant to be moves up by however many attempts an attacker can land at once.
|
|
9
10
|
*
|
|
10
11
|
* @example Verify a database-backed store
|
|
11
12
|
* ```ts
|
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
* Contract test suite for {@link LockoutStore} implementations — the
|
|
3
3
|
* per-account failure counter behind `AccountLockout`.
|
|
4
4
|
*
|
|
5
|
-
* `AccountLockout`
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* `AccountLockout` counts each sign-in attempt with `increment` before its
|
|
6
|
+
* password is checked, and admits the attempt only on the count `increment`
|
|
7
|
+
* returns. A store that lets concurrent attempts share a count admits one extra
|
|
8
|
+
* guess for every attempt sharing it: the brute-force floor the lockout is
|
|
9
|
+
* meant to be moves up by however many attempts an attacker can land at once.
|
|
9
10
|
*
|
|
10
11
|
* @example Verify a database-backed store
|
|
11
12
|
* ```ts
|
|
@@ -78,10 +79,18 @@ export function runLockoutStoreContractTests(options) {
|
|
|
78
79
|
});
|
|
79
80
|
it("gives every concurrent failure its own count", async () => {
|
|
80
81
|
const results = await Promise.all(Array.from({ length: 5 }, () => store.increment(USER, now)));
|
|
81
|
-
expect(results.map((result) => result.failures).sort((a, b) => a - b), "
|
|
82
|
-
"sharing a count
|
|
82
|
+
expect(results.map((result) => result.failures).sort((a, b) => a - b), "sign-in is admitted on the returned count — concurrent attempts " +
|
|
83
|
+
"sharing a count each get another guess past the threshold").toStrictEqual([1, 2, 3, 4, 5]);
|
|
83
84
|
expect((await store.get(USER))?.failures).toStrictEqual(5);
|
|
84
85
|
});
|
|
86
|
+
it("gives every concurrent attempt against an active lock its own count", async () => {
|
|
87
|
+
const lockedUntil = now + 60_000;
|
|
88
|
+
await store.set(USER, { failures: 3, lockedUntil });
|
|
89
|
+
const results = await Promise.all(Array.from({ length: 4 }, () => store.increment(USER, now)));
|
|
90
|
+
expect(results.map((result) => result.failures).sort((a, b) => a - b)).toStrictEqual([4, 5, 6, 7]);
|
|
91
|
+
expect(results.map((result) => result.lockedUntil), "every attempt counted during the lock must see it, or one is " +
|
|
92
|
+
"admitted to the password check").toStrictEqual([lockedUntil, lockedUntil, lockedUntil, lockedUntil]);
|
|
93
|
+
});
|
|
85
94
|
});
|
|
86
95
|
describe("set", () => {
|
|
87
96
|
it("persists the record as given", async () => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@udibo/oauth2",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.0",
|
|
4
4
|
"description": "A flexible OAuth2 toolkit: framework-agnostic authorization & resource servers, a typed client, Hono adapters (including a backend-for-frontend), Express adapters, and React bindings.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"authorization-server",
|