@udibo/oauth2 0.53.0 → 0.55.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/SECURITY.md CHANGED
@@ -13,7 +13,7 @@ reports seriously and value the time of security researchers.
13
13
 
14
14
  Pre-1.0, security fixes land on the latest release only. From 1.0 on, the latest
15
15
  minor of the current major receives fixes, and the final minor of the previous
16
- major receives critical fixes for 6 months after a new major ships.
16
+ major receives critical fixes for 6 months after a new major ships. Security fixes are announced through a GitHub security advisory or by deprecating affected versions on npm, so a pinned release that a fix affects can be found.
17
17
 
18
18
  ## Reporting a vulnerability
19
19
 
@@ -27,8 +27,8 @@ Email **security@udibo.com** with:
27
27
  - The impact you believe it has (what an attacker gains).
28
28
  - Any suggested remediation, if you have one.
29
29
 
30
- You will receive an acknowledgment within **72 hours** and a substantive
31
- assessment within **7 days**. We ask that you give us **90 days** to remediate
30
+ You will receive an acknowledgment within **5 business days** and a substantive
31
+ assessment within **14 days**. We ask that you give us **90 days** to remediate
32
32
  before public disclosure; we will credit you in the release notes unless you
33
33
  prefer otherwise. We do not operate a paid bounty program.
34
34
 
@@ -27,7 +27,7 @@
27
27
  */
28
28
  import type { DeliveryHooks } from "./delivery.ts";
29
29
  /** Why a sign-in attempt failed. Internal detail — never shown to the user. */
30
- export type SignInFailureReason = "unknown_identifier" | "no_password" | "wrong_password";
30
+ export type SignInFailureReason = "unknown_identifier" | "no_password" | "wrong_password" | "not_checked";
31
31
  /**
32
32
  * Why a sign-in code verification failed. Internal detail — never shown to the
33
33
  * user: `IdentityService.verifySignInCode` reports every one of these as
@@ -22,7 +22,9 @@ export interface LockoutRecord {
22
22
  /**
23
23
  * Consecutive sign-in attempts counted since the last success/unlock. An
24
24
  * attempt is counted before its password is checked, so an attempt still in
25
- * flight is included until a success clears the record.
25
+ * flight is included until a success clears the record or, for an attempt
26
+ * whose password is never checked, {@link LockoutStore.release} takes it
27
+ * back.
26
28
  */
27
29
  failures: number;
28
30
  /** When the active lock expires (epoch ms); absent when not locked. */
@@ -68,6 +70,23 @@ export interface LockoutStore {
68
70
  lock?(userId: string, record: LockoutRecord & {
69
71
  lockedUntil: number;
70
72
  }, now: number): Promise<boolean>;
73
+ /**
74
+ * Optional: take back one attempt `increment` counted, as one atomic write:
75
+ * `failures - 1` (never below zero), dropping `lockedUntil` when the new
76
+ * count is below `maxAttempts`
77
+ * (`UPDATE … SET failures = failures - 1, locked_until = CASE WHEN
78
+ * failures - 1 < $max THEN NULL ELSE locked_until END WHERE failures > 0
79
+ * AND (locked_until IS NULL OR locked_until > $now)`). An account with no
80
+ * live record, or whose lock has expired, is left as it is, so the next
81
+ * attempt still starts a fresh count; a record left at zero may be kept or
82
+ * dropped. `now` is the clock `increment` was given, for a
83
+ * store that expires records.
84
+ *
85
+ * `AccountLockout.releaseAttempt` calls it for an attempt whose password was
86
+ * never checked, including an attempt refused because the account was
87
+ * locked. Without it the attempt stays counted.
88
+ */
89
+ release?(userId: string, maxAttempts: number, now: number): Promise<void>;
71
90
  /** Clear the account's record (successful sign-in or unlock). */
72
91
  clear(userId: string): Promise<void>;
73
92
  }
@@ -163,7 +182,9 @@ export interface AccountLockoutLike {
163
182
  * report the resulting state the way {@link AccountLockoutLike.recordFailure}
164
183
  * does. `IdentityService` checks the password only when the result is
165
184
  * unlocked or `justLocked` — the attempt that reaches the threshold is still
166
- * checked — and refuses the rest under `"enforce"`. A wrong password then
185
+ * checked — and refuses the rest under `"enforce"`, taking a refused
186
+ * attempt back through {@link AccountLockoutLike.releaseAttempt} when it is
187
+ * implemented. A wrong password then
167
188
  * fires the lockout event off the reservation's `justLocked`; a success
168
189
  * calls {@link AccountLockoutLike.reset}; an attempt that throws stays
169
190
  * counted and, when its reservation was `justLocked`, still fires the
@@ -176,6 +197,23 @@ export interface AccountLockoutLike {
176
197
  * implements it.
177
198
  */
178
199
  reserveAttempt?(userId: string, now?: number): Promise<LockoutFailureResult>;
200
+ /**
201
+ * Take back one attempt {@link AccountLockoutLike.reserveAttempt} counted,
202
+ * because its password was never checked, and resolve whether it is no
203
+ * longer counted. Undo any lock that attempt's count created, unless the
204
+ * attempts still counted reach the threshold on their own.
205
+ *
206
+ * Optional, and used only alongside `reserveAttempt`. `IdentityService`
207
+ * calls it when a legacy verifier throws `PasswordNotCheckedError` and, under
208
+ * `"enforce"`, for an attempt it refuses because the account is locked. When
209
+ * the released reservation was `justLocked` and the account is still locked
210
+ * afterwards, the service fires the lockout event. When it is absent,
211
+ * resolves `false` or throws, the attempt stays counted and, when its
212
+ * reservation was `justLocked`, the lockout event still fires.
213
+ * {@link AccountLockout} implements it when its store implements
214
+ * {@link LockoutStore.release}.
215
+ */
216
+ releaseAttempt?(userId: string, now?: number): Promise<boolean>;
179
217
  /** Clear the account's failures and any lock (successful sign-in, unlock). */
180
218
  reset(userId: string): Promise<void>;
181
219
  }
@@ -208,6 +246,13 @@ export declare class AccountLockout implements AccountLockoutLike {
208
246
  * only the first `maxAttempts` come back unlocked or `justLocked`.
209
247
  */
210
248
  reserveAttempt(userId: string, now?: number): Promise<LockoutFailureResult>;
249
+ /**
250
+ * Take back one attempt {@link reserveAttempt} counted whose password was
251
+ * never checked, dropping the lock when the remaining count is below
252
+ * `maxAttempts`. Resolves `false`, leaving the attempt counted, when the
253
+ * store does not implement {@link LockoutStore.release}.
254
+ */
255
+ releaseAttempt(userId: string, now?: number): Promise<boolean>;
211
256
  /** Clear the account's failures and any lock (successful sign-in, unlock). */
212
257
  reset(userId: string): Promise<void>;
213
258
  }
@@ -277,6 +322,11 @@ export declare class MemoryLockoutStore implements LockoutStore {
277
322
  lock(userId: string, record: LockoutRecord & {
278
323
  lockedUntil: number;
279
324
  }, now: number): Promise<boolean>;
325
+ /**
326
+ * Take back one counted attempt for `userId`, dropping its lock once the
327
+ * count falls below `maxAttempts`. A record that reaches zero is dropped.
328
+ */
329
+ release(userId: string, maxAttempts: number, now: number): Promise<void>;
280
330
  /** Drop `userId`'s record. */
281
331
  clear(userId: string): Promise<void>;
282
332
  }
@@ -73,6 +73,18 @@ export class AccountLockout {
73
73
  reserveAttempt(userId, now = Date.now()) {
74
74
  return this.#count(userId, now);
75
75
  }
76
+ /**
77
+ * Take back one attempt {@link reserveAttempt} counted whose password was
78
+ * never checked, dropping the lock when the remaining count is below
79
+ * `maxAttempts`. Resolves `false`, leaving the attempt counted, when the
80
+ * store does not implement {@link LockoutStore.release}.
81
+ */
82
+ async releaseAttempt(userId, now = Date.now()) {
83
+ if (!this.#store.release)
84
+ return false;
85
+ await this.#store.release(userId, this.#maxAttempts, now);
86
+ return true;
87
+ }
76
88
  async #count(userId, now = Date.now(), recounted = false) {
77
89
  const record = await this.#store.increment(userId, now);
78
90
  const { failures } = record;
@@ -219,6 +231,30 @@ export class MemoryLockoutStore {
219
231
  entry.record = { ...entry.record, lockedUntil: record.lockedUntil };
220
232
  return Promise.resolve(true);
221
233
  }
234
+ /**
235
+ * Take back one counted attempt for `userId`, dropping its lock once the
236
+ * count falls below `maxAttempts`. A record that reaches zero is dropped.
237
+ */
238
+ release(userId, maxAttempts, now) {
239
+ const entry = this.#entries.get(userId);
240
+ if (!entry || this.#expired(entry, now))
241
+ return Promise.resolve();
242
+ const { lockedUntil } = entry.record;
243
+ if (lockedUntil !== undefined && lockedUntil <= now) {
244
+ return Promise.resolve();
245
+ }
246
+ const failures = entry.record.failures - 1;
247
+ if (failures <= 0) {
248
+ this.#entries.delete(userId);
249
+ }
250
+ else {
251
+ entry.record =
252
+ lockedUntil !== undefined && failures >= maxAttempts
253
+ ? { failures, lockedUntil }
254
+ : { failures };
255
+ }
256
+ return Promise.resolve();
257
+ }
222
258
  /** Drop `userId`'s record. */
223
259
  clear(userId) {
224
260
  this.#entries.delete(userId);
@@ -62,11 +62,63 @@ export interface LegacyPasswordVerifier {
62
62
  /**
63
63
  * Verify `password` against the stored foreign hash `phc`. Called only when
64
64
  * {@link LegacyPasswordVerifier.canVerify} returned `true`. Resolve `false`
65
- * (never throw) on a mismatch or a malformed hash. Use a constant-time
66
- * comparison.
65
+ * on a mismatch or a malformed hash. Use a constant-time comparison.
66
+ *
67
+ * Throw {@link PasswordNotCheckedError} only when the password was never
68
+ * checked and never left your process, such as a spent call budget or an
69
+ * open circuit breaker: the sign-in is refused without counting toward the
70
+ * account lockout. Any other throw is treated as a wrong password.
67
71
  */
68
72
  verify(password: string, phc: string): Promise<boolean>;
69
73
  }
74
+ /**
75
+ * Thrown by a {@link LegacyPasswordVerifier.verify} or an
76
+ * `IdentityServiceOptions.resolveUnknownIdentifier` that did not check the
77
+ * password at all, as distinct from finding it wrong.
78
+ *
79
+ * Throw it only when the password never left your process: a call budget is
80
+ * spent, a circuit breaker is open, or remote checking is switched off
81
+ * (monitor-only) so no request is made. Never send the password and then
82
+ * throw it.
83
+ * Once the password has been sent to another system, report that system's
84
+ * answer, and treat a timeout or a non-answer as a wrong password, because the
85
+ * other system may already have counted the attempt.
86
+ *
87
+ * `IdentityService.signIn` refuses the attempt exactly as it refuses a wrong
88
+ * password (the same `null`, equalizing hash and `failedSignInFloorMs`), does
89
+ * not count it toward the account lockout, and emits `sign_in.failed` with
90
+ * reason `not_checked`. The service never logs or returns the error, but keep
91
+ * the password out of its message anyway. The service recognizes it with
92
+ * `instanceof`, so import it from the same copy of the package the service
93
+ * runs from; an error from another copy is treated as a wrong password.
94
+ *
95
+ * @example A verifier that declines once its call budget is spent
96
+ * ```ts
97
+ * import {
98
+ * type LegacyPasswordVerifier,
99
+ * PasswordNotCheckedError,
100
+ * } from "@udibo/oauth2/identity/migration";
101
+ *
102
+ * declare const budget: { take(): boolean };
103
+ * declare function checkRemotely(
104
+ * password: string,
105
+ * phc: string,
106
+ * ): Promise<boolean>;
107
+ *
108
+ * const remoteVerifier: LegacyPasswordVerifier = {
109
+ * id: "remote",
110
+ * canVerify: (phc) => phc.startsWith("remote$"),
111
+ * async verify(password, phc) {
112
+ * if (!budget.take()) throw new PasswordNotCheckedError("budget spent");
113
+ * return await checkRemotely(password, phc);
114
+ * },
115
+ * };
116
+ * ```
117
+ */
118
+ export declare class PasswordNotCheckedError extends Error {
119
+ /** Creates the error. Keep the password out of `message`. */
120
+ constructor(message?: string);
121
+ }
70
122
  /**
71
123
  * The first verifier in `verifiers` (in order) whose `canVerify` accepts `phc`,
72
124
  * or `undefined` if none do. A verifier that throws from `canVerify` is skipped
@@ -76,9 +128,14 @@ export declare function findLegacyVerifier(verifiers: readonly LegacyPasswordVer
76
128
  /**
77
129
  * Verify `password` against a stored foreign hash `phc` using the first matching
78
130
  * verifier in `verifiers`. Resolves `false` when no verifier recognizes `phc` or
79
- * the matched verifier rejects the password or throws. Useful for a
80
- * bulk-import dry-run/validation pass; {@link IdentityService.signIn} uses the
81
- * same selection for upgrade-on-login.
131
+ * the matched verifier rejects the password or throws, except that a
132
+ * {@link PasswordNotCheckedError} is rethrown so a password that was never
133
+ * checked is not reported as wrong. Useful for a bulk-import
134
+ * dry-run/validation pass; {@link IdentityService.signIn} uses the same
135
+ * selection for upgrade-on-login.
136
+ *
137
+ * @throws {PasswordNotCheckedError} When the matched verifier did not check
138
+ * the password.
82
139
  */
83
140
  export declare function verifyLegacyPassword(verifiers: readonly LegacyPasswordVerifier[], password: string, phc: string): Promise<boolean>;
84
141
  /**
@@ -26,6 +26,57 @@
26
26
  */
27
27
  import { timingSafeEqual } from "node:crypto";
28
28
  import { decodeBase64 } from "../utils/_encoding.js";
29
+ /**
30
+ * Thrown by a {@link LegacyPasswordVerifier.verify} or an
31
+ * `IdentityServiceOptions.resolveUnknownIdentifier` that did not check the
32
+ * password at all, as distinct from finding it wrong.
33
+ *
34
+ * Throw it only when the password never left your process: a call budget is
35
+ * spent, a circuit breaker is open, or remote checking is switched off
36
+ * (monitor-only) so no request is made. Never send the password and then
37
+ * throw it.
38
+ * Once the password has been sent to another system, report that system's
39
+ * answer, and treat a timeout or a non-answer as a wrong password, because the
40
+ * other system may already have counted the attempt.
41
+ *
42
+ * `IdentityService.signIn` refuses the attempt exactly as it refuses a wrong
43
+ * password (the same `null`, equalizing hash and `failedSignInFloorMs`), does
44
+ * not count it toward the account lockout, and emits `sign_in.failed` with
45
+ * reason `not_checked`. The service never logs or returns the error, but keep
46
+ * the password out of its message anyway. The service recognizes it with
47
+ * `instanceof`, so import it from the same copy of the package the service
48
+ * runs from; an error from another copy is treated as a wrong password.
49
+ *
50
+ * @example A verifier that declines once its call budget is spent
51
+ * ```ts
52
+ * import {
53
+ * type LegacyPasswordVerifier,
54
+ * PasswordNotCheckedError,
55
+ * } from "@udibo/oauth2/identity/migration";
56
+ *
57
+ * declare const budget: { take(): boolean };
58
+ * declare function checkRemotely(
59
+ * password: string,
60
+ * phc: string,
61
+ * ): Promise<boolean>;
62
+ *
63
+ * const remoteVerifier: LegacyPasswordVerifier = {
64
+ * id: "remote",
65
+ * canVerify: (phc) => phc.startsWith("remote$"),
66
+ * async verify(password, phc) {
67
+ * if (!budget.take()) throw new PasswordNotCheckedError("budget spent");
68
+ * return await checkRemotely(password, phc);
69
+ * },
70
+ * };
71
+ * ```
72
+ */
73
+ export class PasswordNotCheckedError extends Error {
74
+ /** Creates the error. Keep the password out of `message`. */
75
+ constructor(message = "password not checked") {
76
+ super(message);
77
+ this.name = "PasswordNotCheckedError";
78
+ }
79
+ }
29
80
  /**
30
81
  * The first verifier in `verifiers` (in order) whose `canVerify` accepts `phc`,
31
82
  * or `undefined` if none do. A verifier that throws from `canVerify` is skipped
@@ -44,9 +95,14 @@ export function findLegacyVerifier(verifiers, phc) {
44
95
  /**
45
96
  * Verify `password` against a stored foreign hash `phc` using the first matching
46
97
  * verifier in `verifiers`. Resolves `false` when no verifier recognizes `phc` or
47
- * the matched verifier rejects the password or throws. Useful for a
48
- * bulk-import dry-run/validation pass; {@link IdentityService.signIn} uses the
49
- * same selection for upgrade-on-login.
98
+ * the matched verifier rejects the password or throws, except that a
99
+ * {@link PasswordNotCheckedError} is rethrown so a password that was never
100
+ * checked is not reported as wrong. Useful for a bulk-import
101
+ * dry-run/validation pass; {@link IdentityService.signIn} uses the same
102
+ * selection for upgrade-on-login.
103
+ *
104
+ * @throws {PasswordNotCheckedError} When the matched verifier did not check
105
+ * the password.
50
106
  */
51
107
  export async function verifyLegacyPassword(verifiers, password, phc) {
52
108
  const verifier = findLegacyVerifier(verifiers, phc);
@@ -55,7 +111,9 @@ export async function verifyLegacyPassword(verifiers, password, phc) {
55
111
  try {
56
112
  return await verifier.verify(password, phc);
57
113
  }
58
- catch {
114
+ catch (error) {
115
+ if (error instanceof PasswordNotCheckedError)
116
+ throw error;
59
117
  return false;
60
118
  }
61
119
  }
@@ -186,6 +186,9 @@ export interface IdentityServiceOptions<User extends IdentityUser> {
186
186
  * upgrade. The package ships
187
187
  * {@link pbkdf2Verifier} built-in; bcrypt/argon2/scrypt are bring-your-own via
188
188
  * the {@link LegacyPasswordVerifier} seam (no dep-free implementation exists).
189
+ * A verifier that throws {@link PasswordNotCheckedError} is refused like a
190
+ * wrong password but not counted toward the `lockout`, and `sign_in.failed`
191
+ * reports reason `not_checked`.
189
192
  */
190
193
  legacyVerifiers?: LegacyPasswordVerifier[];
191
194
  /**
@@ -235,7 +238,10 @@ export interface IdentityServiceOptions<User extends IdentityUser> {
235
238
  * itself, which may carry the password. A refusal returns the same `null`,
236
239
  * runs the same equalizing password hash, emits the same `sign_in.failed`
237
240
  * event with reason `unknown_identifier`, and is held to the same
238
- * {@link failedSignInFloorMs} as an unknown identifier with no resolver.
241
+ * {@link failedSignInFloorMs} as an unknown identifier with no resolver. A
242
+ * resolver that did not check the password at all throws
243
+ * {@link PasswordNotCheckedError} instead: it is refused the same way, not
244
+ * logged, and the event reports reason `not_checked`.
239
245
  *
240
246
  * The resolver's own running time adds to the refusal's work, so set
241
247
  * {@link failedSignInFloorMs} above its slowest refusal plus one password
@@ -27,7 +27,7 @@ import { IdentityError } from "./errors.js";
27
27
  import { enforceRateLimit } from "./rate-limit.js";
28
28
  import { EmailOtpService, otpRateKey } from "./otp.js";
29
29
  import { dispatchIdentityEvent, } from "./events.js";
30
- import { findLegacyVerifier, } from "./migration.js";
30
+ import { findLegacyVerifier, PasswordNotCheckedError, } from "./migration.js";
31
31
  const DEFAULT_RESET_TTL = 60 * 60 * 1000;
32
32
  const DEFAULT_VERIFY_TTL = 24 * 60 * 60 * 1000;
33
33
  const DEFAULT_UNLOCK_TTL = 60 * 60 * 1000;
@@ -49,6 +49,7 @@ const RATE_KEYS = {
49
49
  signInLink: (email) => `pwless:${foldEmail(email)}`,
50
50
  signInCode: (email) => otpRateKey(TokenPurpose.SignIn, email),
51
51
  };
52
+ const NOT_CHECKED = Symbol("not checked");
52
53
  /**
53
54
  * Composable own-auth flows. Construct once with your dependencies and call the
54
55
  * methods from your routes; the credential form, copy, and session creation stay
@@ -196,13 +197,16 @@ export class IdentityService {
196
197
  });
197
198
  if (outcome === "wrong_password")
198
199
  await attempt.fail();
200
+ if (outcome === "not_checked")
201
+ await attempt.release();
199
202
  return await this.#rejectSignIn(startedAt);
200
203
  }
201
204
  return await this.#completeSignIn(user, identifier);
202
205
  }
203
206
  async #signInUnknownIdentifier(identifier, password, startedAt) {
204
207
  const resolved = await this.#tryResolveUnknownIdentifier(identifier, password);
205
- const user = resolved &&
208
+ const user = resolved !== null &&
209
+ resolved !== NOT_CHECKED &&
206
210
  (await this.#bindResolvedUser(resolved, identifier, password));
207
211
  if (user) {
208
212
  if ((await this.#reportLock(user.id, identifier)) && this.#enforce) {
@@ -215,7 +219,7 @@ export class IdentityService {
215
219
  await this.#emit({
216
220
  type: "sign_in.failed",
217
221
  identifier,
218
- reason: "unknown_identifier",
222
+ reason: resolved === NOT_CHECKED ? "not_checked" : "unknown_identifier",
219
223
  });
220
224
  return await this.#rejectSignIn(startedAt);
221
225
  }
@@ -225,7 +229,9 @@ export class IdentityService {
225
229
  try {
226
230
  return ((await this.#resolveUnknownIdentifier({ identifier, password })) ?? null);
227
231
  }
228
- catch {
232
+ catch (error) {
233
+ if (error instanceof PasswordNotCheckedError)
234
+ return NOT_CHECKED;
229
235
  // Never log the error object: it may echo the submitted password.
230
236
  console.error("[@udibo/oauth2] resolveUnknownIdentifier threw");
231
237
  return null;
@@ -550,13 +556,15 @@ export class IdentityService {
550
556
  }
551
557
  async #tryLegacy(verifier, password, phc) {
552
558
  try {
553
- return await verifier.verify(password, phc);
559
+ return (await verifier.verify(password, phc)) ? "verified" : "rejected";
554
560
  }
555
- catch {
561
+ catch (error) {
562
+ if (error instanceof PasswordNotCheckedError)
563
+ return "not_checked";
556
564
  // Never log the error object: a BYO verifier may echo the hash or the
557
565
  // submitted password in its message. Fail closed.
558
566
  console.error(`[@udibo/oauth2] legacy password verifier ${verifier.id} threw`);
559
- return false;
567
+ return "rejected";
560
568
  }
561
569
  }
562
570
  /**
@@ -781,9 +789,11 @@ export class IdentityService {
781
789
  return {
782
790
  admit: () => Promise.resolve(true),
783
791
  fail: () => this.#recordSignInFailure(userId, identifier),
792
+ release: () => Promise.resolve(),
784
793
  abandon: () => Promise.resolve(),
785
794
  };
786
795
  }
796
+ const unreserve = this.#lockout?.releaseAttempt?.bind(this.#lockout);
787
797
  let reservation;
788
798
  const announceLock = async () => {
789
799
  if (reservation)
@@ -796,9 +806,27 @@ export class IdentityService {
796
806
  return true;
797
807
  if (!lockReported)
798
808
  await this.#emitSignInLocked(userId, identifier);
799
- return !this.#enforce;
809
+ if (!this.#enforce)
810
+ return true;
811
+ await unreserve?.(userId);
812
+ return false;
800
813
  },
801
814
  fail: announceLock,
815
+ release: async () => {
816
+ let released;
817
+ try {
818
+ released = (await unreserve?.(userId)) ?? false;
819
+ }
820
+ catch (error) {
821
+ await announceLock();
822
+ throw error;
823
+ }
824
+ if (!released)
825
+ return await announceLock();
826
+ if (reservation?.justLocked) {
827
+ await this.#announceSurvivingLock(userId, identifier);
828
+ }
829
+ },
802
830
  abandon: announceLock,
803
831
  };
804
832
  }
@@ -825,9 +853,12 @@ export class IdentityService {
825
853
  if (!legacyHash)
826
854
  return "wrong_password";
827
855
  const verifier = findLegacyVerifier(this.#legacyVerifiers, legacyHash);
828
- if (!verifier || !(await this.#tryLegacy(verifier, password, legacyHash))) {
856
+ const check = verifier
857
+ ? await this.#tryLegacy(verifier, password, legacyHash)
858
+ : "rejected";
859
+ if (!verifier || check !== "verified") {
829
860
  await this.#equalizeTiming(password);
830
- return "wrong_password";
861
+ return check === "not_checked" ? "not_checked" : "wrong_password";
831
862
  }
832
863
  return (await this.#upgradeCredential(userId, password, verifier.id))
833
864
  ? "authenticated"
@@ -876,6 +907,17 @@ export class IdentityService {
876
907
  #logPersistFailure(operation, error) {
877
908
  console.error(`[@udibo/oauth2] ${operation} persist failed:`, error instanceof Error ? error.message : error);
878
909
  }
910
+ async #announceSurvivingLock(userId, identifier) {
911
+ const status = await this.#lockout.status(userId);
912
+ if (!status.locked)
913
+ return;
914
+ await this.#emitLockout(userId, identifier, {
915
+ failures: status.failures,
916
+ locked: true,
917
+ justLocked: true,
918
+ lockedUntil: status.lockedUntil,
919
+ });
920
+ }
879
921
  async #recordSignInFailure(userId, identifier) {
880
922
  if (!this.#lockout)
881
923
  return;
@@ -0,0 +1,45 @@
1
+ import { type ReactNode, type RefObject } from "react";
2
+ import type { AccountActionResult } from "./types.ts";
3
+ export interface AccountActionRunner {
4
+ pendingKey: string | null;
5
+ error: string | null;
6
+ successCount: number;
7
+ /** The element that had focus when the last action started. */
8
+ focusedAtStart: RefObject<Element | null>;
9
+ run(key: string, action: () => Promise<AccountActionResult | void> | AccountActionResult | void): Promise<void>;
10
+ }
11
+ /**
12
+ * One in-flight action at a time across a list's buttons: a second activation
13
+ * while one is pending is ignored, and a returned `error` or a throw becomes
14
+ * the list's error message.
15
+ */
16
+ export declare function useAccountAction(): AccountActionRunner;
17
+ /**
18
+ * Moves focus to the list root when the control that had focus as a
19
+ * successful action started leaves the page (a removed row's button drops
20
+ * focus to `<body>`). It stops watching once focus moves away from that
21
+ * control, and never moves focus that is somewhere else on the page.
22
+ */
23
+ export declare function useFocusAfterRemoval(runner: AccountActionRunner, items: unknown): RefObject<HTMLDivElement | null>;
24
+ export declare function AccountActionError(props: {
25
+ error: string | null;
26
+ className: string | undefined;
27
+ }): ReactNode;
28
+ /**
29
+ * A one-button `<form>`: its hidden `fields` post natively to `action` before
30
+ * JavaScript runs, and `onActivate` handles the submit once it does. Always
31
+ * `post`, so a pre-hydration submit never puts the fields in a URL.
32
+ */
33
+ export declare function ActionForm(props: {
34
+ fields: Record<string, string>;
35
+ action: string | undefined;
36
+ onActivate: () => void;
37
+ pending: boolean;
38
+ label: string;
39
+ pendingLabel: string;
40
+ accessibleName?: string;
41
+ dataAttribute: `data-oauth2-${string}`;
42
+ dataValue?: string;
43
+ className: string | undefined;
44
+ }): ReactNode;
45
+ export declare function formatAccountDate(date: Date): string;
@@ -0,0 +1,111 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useCallback, useEffect, useRef, useState, } from "react";
3
+ /**
4
+ * One in-flight action at a time across a list's buttons: a second activation
5
+ * while one is pending is ignored, and a returned `error` or a throw becomes
6
+ * the list's error message.
7
+ */
8
+ export function useAccountAction() {
9
+ const [pendingKey, setPendingKey] = useState(null);
10
+ const [error, setError] = useState(null);
11
+ const [successCount, setSuccessCount] = useState(0);
12
+ const runningRef = useRef(false);
13
+ const focusedAtStart = useRef(null);
14
+ const run = useCallback(async (key, action) => {
15
+ if (runningRef.current)
16
+ return;
17
+ runningRef.current = true;
18
+ focusedAtStart.current =
19
+ typeof document === "undefined" ? null : document.activeElement;
20
+ setPendingKey(key);
21
+ setError(null);
22
+ let message = null;
23
+ try {
24
+ const result = await action();
25
+ if (result?.error)
26
+ message = result.error;
27
+ }
28
+ catch (thrown) {
29
+ message =
30
+ thrown instanceof Error ? thrown.message : "Something went wrong.";
31
+ }
32
+ finally {
33
+ runningRef.current = false;
34
+ setPendingKey(null);
35
+ }
36
+ if (message)
37
+ setError(message);
38
+ else
39
+ setSuccessCount((count) => count + 1);
40
+ }, []);
41
+ return { pendingKey, error, successCount, focusedAtStart, run };
42
+ }
43
+ /**
44
+ * Moves focus to the list root when the control that had focus as a
45
+ * successful action started leaves the page (a removed row's button drops
46
+ * focus to `<body>`). It stops watching once focus moves away from that
47
+ * control, and never moves focus that is somewhere else on the page.
48
+ */
49
+ export function useFocusAfterRemoval(runner, items) {
50
+ const rootRef = useRef(null);
51
+ const handled = useRef(0);
52
+ const watched = useRef(null);
53
+ useEffect(() => {
54
+ if (typeof document === "undefined")
55
+ return;
56
+ if (runner.successCount !== handled.current) {
57
+ handled.current = runner.successCount;
58
+ const control = runner.focusedAtStart.current;
59
+ watched.current =
60
+ control === null || control === document.body ? null : control;
61
+ }
62
+ const control = watched.current;
63
+ if (!control)
64
+ return;
65
+ const active = document.activeElement;
66
+ if (!control.isConnected) {
67
+ watched.current = null;
68
+ if (active === null || active === document.body) {
69
+ rootRef.current?.focus({ preventScroll: true });
70
+ }
71
+ }
72
+ else if (active !== control) {
73
+ watched.current = null;
74
+ }
75
+ }, [runner.successCount, items, runner.focusedAtStart]);
76
+ return rootRef;
77
+ }
78
+ export function AccountActionError(props) {
79
+ const { error, className } = props;
80
+ const ref = useRef(null);
81
+ useEffect(() => {
82
+ if (error)
83
+ ref.current?.focus();
84
+ }, [error]);
85
+ if (!error)
86
+ return null;
87
+ return (_jsx("div", { ref: ref, tabIndex: -1, "data-oauth2-error-summary": "", className: className, children: _jsx("span", { role: "alert", "data-oauth2-error-summary-message": "", children: error }) }));
88
+ }
89
+ function ignoreActivation(event) {
90
+ event.preventDefault();
91
+ }
92
+ /**
93
+ * A one-button `<form>`: its hidden `fields` post natively to `action` before
94
+ * JavaScript runs, and `onActivate` handles the submit once it does. Always
95
+ * `post`, so a pre-hydration submit never puts the fields in a URL.
96
+ */
97
+ export function ActionForm(props) {
98
+ const { fields, action, onActivate, pending, label, pendingLabel, accessibleName, dataAttribute, dataValue = "", className, } = props;
99
+ const onSubmit = (event) => {
100
+ event.preventDefault();
101
+ onActivate();
102
+ };
103
+ const text = pending ? pendingLabel : label;
104
+ return (_jsxs("form", { onSubmit: onSubmit, action: action, method: "post", "data-oauth2-action-form": "", children: [Object.entries(fields).map(([name, value]) => (_jsx("input", { type: "hidden", name: name, value: value }, name))), _jsx("button", { type: "submit", "aria-disabled": pending ? true : undefined, "aria-label": accessibleName ? `${text} ${accessibleName}` : undefined, onClick: pending ? ignoreActivation : undefined, [dataAttribute]: dataValue, className: className, children: text })] }));
105
+ }
106
+ export function formatAccountDate(date) {
107
+ return date.toLocaleString(undefined, {
108
+ dateStyle: "medium",
109
+ timeStyle: "short",
110
+ });
111
+ }