@udibo/oauth2 0.46.0 → 0.48.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.
@@ -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: await this.#readRefreshToken(reportTransient),
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
- try {
709
- const response = await this.#postToken(new URLSearchParams({
710
- grant_type: "refresh_token",
711
- refresh_token: refreshToken,
712
- }));
713
- const tokens = await this.#saveTokens(response, version, true);
714
- this.emit({ type: "token_refreshed", tokens });
715
- return tokens.accessToken;
716
- }
717
- catch (error) {
718
- if (version !== this.#sessionVersion) {
719
- throw new InvalidGrantError("session changed during refresh");
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
- else if (reportTransient) {
726
- this.emit({ type: "error", error });
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
- await this.#clearSession();
1042
- this.emit({ type: "logged_out", reason: "user" });
1043
- if (refreshToken) {
1044
- try {
1045
- await this.revoke(refreshToken, { tokenTypeHint: "refresh_token" });
1046
- }
1047
- catch {
1048
- // Non-fatal; the local session clears regardless.
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
- return SIGNED_OUT;
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 this.#tokenStorage.clear();
1272
- await this.#refreshTokenStorage?.clear();
1273
- await this.#authRequestStorage?.clear();
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
- /** Consecutive failed sign-in attempts since the last success/unlock. */
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 failure and return the new record: an expired lock resets the
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. Must be atomic (a single statement / compare-and-set in shared
39
- * stores) — a read-modify-write here lets concurrent failed attempts lose
40
- * counts and undershoot the lockout threshold.
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
  /**
@@ -45,6 +51,23 @@ export interface LockoutStore {
45
51
  * merging: a record with no `lockedUntil` leaves the account unlocked.
46
52
  */
47
53
  set(userId: string, record: LockoutRecord): Promise<void>;
54
+ /**
55
+ * Optional: lock the account until `record.lockedUntil` only while its stored
56
+ * count is still at least `record.failures`, keeping the stored count, and
57
+ * resolve whether the lock was written. It must be one conditional write
58
+ * (`UPDATE … SET locked_until = $until WHERE failures >= $failures`, checking
59
+ * the row count), never a read then a write. `now` is the clock `increment`
60
+ * was given, for a store that expires records.
61
+ *
62
+ * `AccountLockout` calls it instead of {@link LockoutStore.set} when an
63
+ * attempt's count reaches `maxAttempts`. Without it, the lock is an
64
+ * unconditional `set` after `increment`, so an over-budget attempt whose
65
+ * lock lands after a concurrent {@link LockoutStore.clear} re-locks an
66
+ * account that just signed in, and no lockout event reports it.
67
+ */
68
+ lock?(userId: string, record: LockoutRecord & {
69
+ lockedUntil: number;
70
+ }, now: number): Promise<boolean>;
48
71
  /** Clear the account's record (successful sign-in or unlock). */
49
72
  clear(userId: string): Promise<void>;
50
73
  }
@@ -130,9 +153,29 @@ export interface AccountLockoutLike {
130
153
  /**
131
154
  * Record one failed attempt and report the resulting state. `justLocked` must
132
155
  * be true for exactly one attempt per lock — `IdentityService` fires the
133
- * lockout event and any unlock email off it.
156
+ * lockout event and any unlock email off it. `IdentityService` calls it after
157
+ * a wrong password only when {@link AccountLockoutLike.reserveAttempt} is
158
+ * absent.
134
159
  */
135
160
  recordFailure(userId: string, now?: number): Promise<LockoutFailureResult>;
161
+ /**
162
+ * Count one sign-in attempt atomically before its password is checked, and
163
+ * report the resulting state the way {@link AccountLockoutLike.recordFailure}
164
+ * does. `IdentityService` checks the password only when the result is
165
+ * unlocked or `justLocked` — the attempt that reaches the threshold is still
166
+ * checked — and refuses the rest under `"enforce"`. A wrong password then
167
+ * fires the lockout event off the reservation's `justLocked`; a success
168
+ * calls {@link AccountLockoutLike.reset}; an attempt that throws stays
169
+ * counted and, when its reservation was `justLocked`, still fires the
170
+ * lockout event.
171
+ *
172
+ * Optional. Without it `IdentityService` reads
173
+ * {@link AccountLockoutLike.status} and calls `recordFailure` only after a
174
+ * wrong password, so concurrent guesses that all read the account unlocked
175
+ * are each checked and can exceed the threshold. {@link AccountLockout}
176
+ * implements it.
177
+ */
178
+ reserveAttempt?(userId: string, now?: number): Promise<LockoutFailureResult>;
136
179
  /** Clear the account's failures and any lock (successful sign-in, unlock). */
137
180
  reset(userId: string): Promise<void>;
138
181
  }
@@ -159,6 +202,12 @@ export declare class AccountLockout implements AccountLockoutLike {
159
202
  * threshold is crossed. An attempt after a lock expired starts a fresh count.
160
203
  */
161
204
  recordFailure(userId: string, now?: number): Promise<LockoutFailureResult>;
205
+ /**
206
+ * Count one sign-in attempt before its password is checked, with the same
207
+ * accounting as {@link recordFailure}: of any number of concurrent attempts,
208
+ * only the first `maxAttempts` come back unlocked or `justLocked`.
209
+ */
210
+ reserveAttempt(userId: string, now?: number): Promise<LockoutFailureResult>;
162
211
  /** Clear the account's failures and any lock (successful sign-in, unlock). */
163
212
  reset(userId: string): Promise<void>;
164
213
  }
@@ -221,6 +270,13 @@ export declare class MemoryLockoutStore implements LockoutStore {
221
270
  * record for an account with none is timed from now.
222
271
  */
223
272
  set(userId: string, record: LockoutRecord): Promise<void>;
273
+ /**
274
+ * Lock `userId` until `record.lockedUntil` when its live record still
275
+ * counts at least `record.failures`; resolves whether it did.
276
+ */
277
+ lock(userId: string, record: LockoutRecord & {
278
+ lockedUntil: number;
279
+ }, now: number): Promise<boolean>;
224
280
  /** Drop `userId`'s record. */
225
281
  clear(userId: string): Promise<void>;
226
282
  }
@@ -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
- async recordFailure(userId, now = Date.now()) {
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(), recounted = false) {
66
77
  const record = await this.#store.increment(userId, now);
67
78
  const { failures } = record;
68
79
  if (record.lockedUntil !== undefined && record.lockedUntil > now) {
@@ -75,7 +86,11 @@ export class AccountLockout {
75
86
  }
76
87
  if (failures >= this.#maxAttempts) {
77
88
  const lockedUntil = now + this.#lockDurationMs;
78
- await this.#store.set(userId, { failures, lockedUntil });
89
+ if (!(await this.#lock(userId, { failures, lockedUntil }, now))) {
90
+ if (!recounted)
91
+ return this.#count(userId, now, true);
92
+ return { failures, locked: false, justLocked: false };
93
+ }
79
94
  // Concurrent attempts can overshoot the threshold before the lock lands;
80
95
  // only the attempt that hits it exactly reports justLocked, so the
81
96
  // lockout event (and any unlock email) fires once.
@@ -88,6 +103,12 @@ export class AccountLockout {
88
103
  }
89
104
  return { failures, locked: false, justLocked: false };
90
105
  }
106
+ async #lock(userId, record, now) {
107
+ if (this.#store.lock)
108
+ return this.#store.lock(userId, record, now);
109
+ await this.#store.set(userId, record);
110
+ return true;
111
+ }
91
112
  /** Clear the account's failures and any lock (successful sign-in, unlock). */
92
113
  reset(userId) {
93
114
  return this.#store.clear(userId);
@@ -184,6 +205,20 @@ export class MemoryLockoutStore {
184
205
  this.#collect(userId, touchedAt);
185
206
  return Promise.resolve();
186
207
  }
208
+ /**
209
+ * Lock `userId` until `record.lockedUntil` when its live record still
210
+ * counts at least `record.failures`; resolves whether it did.
211
+ */
212
+ lock(userId, record, now) {
213
+ const entry = this.#entries.get(userId);
214
+ if (!entry ||
215
+ this.#expired(entry, now) ||
216
+ entry.record.failures < record.failures) {
217
+ return Promise.resolve(false);
218
+ }
219
+ entry.record = { ...entry.record, lockedUntil: record.lockedUntil };
220
+ return Promise.resolve(true);
221
+ }
187
222
  /** Drop `userId`'s record. */
188
223
  clear(userId) {
189
224
  this.#entries.delete(userId);
@@ -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). A successful sign-in resets the count;
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
  */
@@ -165,11 +165,22 @@ export class IdentityService {
165
165
  });
166
166
  return await this.#rejectSignIn(startedAt);
167
167
  }
168
- if (await this.#isLockedOut(user.id, identifier)) {
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 outcome = await this.#authenticate(user.id, input.password);
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 this.#recordSignInFailure(user.id, identifier);
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 #isLockedOut(userId, identifier) {
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
- async #authenticate(userId, password) {
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
- const result = await this.#lockout.recordFailure(userId);
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({
@@ -78,6 +78,20 @@ export interface TokenFlowStore {
78
78
  * really was used, instead of the generic `invalid`.
79
79
  */
80
80
  deleteBySubject?(purpose: string, subject: string): Promise<void>;
81
+ /**
82
+ * Optional: delete every still-pending record for `(record.purpose,
83
+ * record.subject)` and save `record`, as one atomic step. Concurrent calls
84
+ * for one pair must leave exactly one of their records pending, so serialize
85
+ * them on the pair (a row lock or advisory lock taken before the delete, or
86
+ * a unique index on pending rows): two transactions that each delete and
87
+ * then insert under read committed both leave their row behind. Keep
88
+ * consumed records, as {@link TokenFlowStore.deleteBySubject} does.
89
+ *
90
+ * {@link TokenFlowService.create} calls it for `invalidateExisting` when
91
+ * present. Without it, the service deletes and then saves in two calls, so
92
+ * concurrent requests for one pair each leave a live link.
93
+ */
94
+ replacePending?(record: TokenFlowRecord): Promise<void>;
81
95
  }
82
96
  /** Options for {@link TokenFlowService.create}. */
83
97
  export interface CreateTokenOptions {
@@ -90,9 +104,11 @@ export interface CreateTokenOptions {
90
104
  /** Lifetime in milliseconds. */
91
105
  ttlMs: number;
92
106
  /**
93
- * Invalidate any existing pending tokens for this `(purpose, subject)` first.
94
- * Silently skipped when the store lacks
95
- * {@link TokenFlowStore.deleteBySubject}. Defaults to `false`.
107
+ * Invalidate any existing pending tokens for this `(purpose, subject)`,
108
+ * atomically with saving the new one when the store implements
109
+ * {@link TokenFlowStore.replacePending}. Silently skipped when the store
110
+ * implements neither it nor {@link TokenFlowStore.deleteBySubject}. Defaults
111
+ * to `false`.
96
112
  */
97
113
  invalidateExisting?: boolean;
98
114
  }
@@ -211,4 +227,9 @@ export declare class MemoryTokenFlowStore implements TokenFlowStore {
211
227
  * still report `consumed` rather than the generic `invalid`.
212
228
  */
213
229
  deleteBySubject(purpose: string, subject: string): Promise<void>;
230
+ /**
231
+ * Drop the pending records for the record's `(purpose, subject)` and save
232
+ * it, in one synchronous step.
233
+ */
234
+ replacePending(record: TokenFlowRecord): Promise<void>;
214
235
  }
@@ -59,20 +59,26 @@ export class TokenFlowService {
59
59
  }
60
60
  /** Mint a token; stores its hash and returns the raw token (once). */
61
61
  async create(opts) {
62
- if (opts.invalidateExisting) {
63
- await this.invalidate(opts.purpose, opts.subject);
64
- }
65
62
  const token = randomToken();
66
63
  const now = Date.now();
67
64
  const expiresAt = now + opts.ttlMs;
68
- await this.#store.save({
65
+ const record = {
69
66
  tokenHash: await sha256Hash(token),
70
67
  purpose: opts.purpose,
71
68
  subject: opts.subject,
72
69
  data: opts.data,
73
70
  expiresAt,
74
71
  createdAt: now,
75
- });
72
+ };
73
+ if (opts.invalidateExisting && this.#store.replacePending) {
74
+ await this.#store.replacePending(record);
75
+ }
76
+ else {
77
+ if (opts.invalidateExisting) {
78
+ await this.invalidate(opts.purpose, opts.subject);
79
+ }
80
+ await this.#store.save(record);
81
+ }
76
82
  return { token, expiresAt };
77
83
  }
78
84
  /**
@@ -161,6 +167,19 @@ export class MemoryTokenFlowStore {
161
167
  * still report `consumed` rather than the generic `invalid`.
162
168
  */
163
169
  deleteBySubject(purpose, subject) {
170
+ this.#deletePending(purpose, subject);
171
+ return Promise.resolve();
172
+ }
173
+ /**
174
+ * Drop the pending records for the record's `(purpose, subject)` and save
175
+ * it, in one synchronous step.
176
+ */
177
+ replacePending(record) {
178
+ this.#deletePending(record.purpose, record.subject);
179
+ this.#byHash.set(record.tokenHash, record);
180
+ return Promise.resolve();
181
+ }
182
+ #deletePending(purpose, subject) {
164
183
  for (const [hash, record] of this.#byHash) {
165
184
  if (record.purpose === purpose &&
166
185
  record.subject === subject &&
@@ -168,6 +187,5 @@ export class MemoryTokenFlowStore {
168
187
  this.#byHash.delete(hash);
169
188
  }
170
189
  }
171
- return Promise.resolve();
172
190
  }
173
191
  }
@@ -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`. */
@@ -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 (!cancelled)
83
- setState((prev) => ({ ...prev, user }));
87
+ if (cancelled || lookup !== identityChanges)
88
+ return;
89
+ setState((prev) => ({ ...prev, user }));
84
90
  }, () => { });
85
91
  }
86
92
  };