@udibo/oauth2 0.52.0 → 0.54.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
@@ -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
  /**
@@ -211,6 +214,90 @@ export interface IdentityServiceOptions<User extends IdentityUser> {
211
214
  * Successful sign-ins are never delayed.
212
215
  */
213
216
  failedSignInFloorMs?: number;
217
+ /**
218
+ * Resolve a sign-in whose identifier matches no account, typically by
219
+ * checking the password against the system your users are moving from and
220
+ * creating the account on a match. {@link IdentityService.signIn} calls it
221
+ * only after the sign-in throttle admits the attempt and
222
+ * {@link IdentityUserStore.findByIdentifier} finds no account. It receives
223
+ * the trimmed identifier and the password exactly as submitted.
224
+ *
225
+ * Return the user to sign them in: typically the account you just created
226
+ * for this identifier with this password. The service signs it in only when
227
+ * {@link IdentityUserStore.findByIdentifier} now finds that same account for
228
+ * the identifier and its stored credential accepts the submitted password, so
229
+ * a resolver can never sign in an account the identifier does not reach (a
230
+ * casing variant, an account your store hides from sign-in) or one whose own
231
+ * password differs. On a uniqueness conflict, return `null` or throw rather
232
+ * than the existing row. The service then refuses a locked account under
233
+ * `"enforce"`, as for any other sign-in, and otherwise resets the throttle
234
+ * and the lockout count and emits `sign_in.succeeded`. Return `null` to
235
+ * refuse; an account that fails the check above is refused the same way.
236
+ * A throw
237
+ * also refuses: the service logs that the resolver threw, never the error
238
+ * itself, which may carry the password. A refusal returns the same `null`,
239
+ * runs the same equalizing password hash, emits the same `sign_in.failed`
240
+ * event with reason `unknown_identifier`, and is held to the same
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`.
245
+ *
246
+ * The resolver's own running time adds to the refusal's work, so set
247
+ * {@link failedSignInFloorMs} above its slowest refusal plus one password
248
+ * hash. A refusal after the other system accepted the password (the create
249
+ * failed) is usually the slowest: your request timeout, the hash and write
250
+ * of the create, then the service's hash. Below that, response time tells an
251
+ * unauthenticated caller which identifiers had no local account, or that a
252
+ * guessed password works on the other system. Only the
253
+ * per-identifier throttle bounds how often it runs, and only when a
254
+ * sign-in rate limiter (`rateLimiter` or `rateLimiters.signIn`) is
255
+ * configured: there is no account to lock, the throttle
256
+ * never stops one password tried across many identifiers, and under
257
+ * `protectionMode: "log-only"` it reports without stopping anything. Limit
258
+ * calls inside the resolver when it reaches another system. Compare the
259
+ * other system's answer against the identifier in the same normalized form
260
+ * your store resolves accounts by.
261
+ *
262
+ * @example Create an account from a password check against another system
263
+ * ```ts
264
+ * import {
265
+ * IdentityService,
266
+ * type IdentityUser,
267
+ * type IdentityUserStore,
268
+ * PasswordIdentityService,
269
+ * } from "@udibo/oauth2/identity";
270
+ *
271
+ * interface AppUser extends IdentityUser {
272
+ * email: string;
273
+ * }
274
+ *
275
+ * declare const users: IdentityUserStore<AppUser>;
276
+ * declare function checkPreviousSystem(
277
+ * email: string,
278
+ * password: string,
279
+ * ): Promise<{ email: string } | null>;
280
+ *
281
+ * const passwords = new PasswordIdentityService();
282
+ * const identity = new IdentityService<AppUser>({
283
+ * users,
284
+ * passwords,
285
+ * failedSignInFloorMs: 3_000,
286
+ * resolveUnknownIdentifier: async ({ identifier, password }) => {
287
+ * const profile = await checkPreviousSystem(identifier, password);
288
+ * if (profile?.email !== identifier) return null;
289
+ * return await users.create(
290
+ * { email: profile.email },
291
+ * await passwords.hash(password),
292
+ * );
293
+ * },
294
+ * });
295
+ * ```
296
+ */
297
+ resolveUnknownIdentifier?: (input: {
298
+ identifier: string;
299
+ password: string;
300
+ }) => Promise<User | null>;
214
301
  /**
215
302
  * Session revocation, called on a successful password reset. Optional. When
216
303
  * the user store implements {@link IdentityUserStore.resetCredential}, the
@@ -493,6 +580,10 @@ export declare class IdentityService<User extends IdentityUser> {
493
580
  * longer (typically a foreign KDF) stays visible by its excess. A success
494
581
  * returns as soon as it is done.
495
582
  *
583
+ * With {@link IdentityServiceOptions.resolveUnknownIdentifier} set, an
584
+ * identifier that finds no account is offered to it first; a user it returns
585
+ * signs in, and a refusal is the same `null` an unknown identifier gets.
586
+ *
496
587
  * @throws {IdentityError} `rate_limited` (with `retryAfterMs`) when a
497
588
  * `rateLimiter` is configured, the identifier's limit is hit, and
498
589
  * `protectionMode` is `"enforce"`. Rate-limit rejections throw before the
@@ -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
@@ -70,6 +71,7 @@ export class IdentityService {
70
71
  #onEvent;
71
72
  #legacyVerifiers;
72
73
  #failedSignInFloorMs;
74
+ #resolveUnknownIdentifier;
73
75
  /** Wires the user store and optional collaborators; applies the TTL and hasher defaults. */
74
76
  constructor(options) {
75
77
  this.#users = options.users;
@@ -112,6 +114,7 @@ export class IdentityService {
112
114
  Number.isFinite(floor) && floor >= 0
113
115
  ? floor
114
116
  : DEFAULT_FAILED_SIGN_IN_FLOOR_MS;
117
+ this.#resolveUnknownIdentifier = options.resolveUnknownIdentifier;
115
118
  }
116
119
  /**
117
120
  * Create a user with a hashed password. `profile` is your app's own fields.
@@ -148,6 +151,10 @@ export class IdentityService {
148
151
  * longer (typically a foreign KDF) stays visible by its excess. A success
149
152
  * returns as soon as it is done.
150
153
  *
154
+ * With {@link IdentityServiceOptions.resolveUnknownIdentifier} set, an
155
+ * identifier that finds no account is offered to it first; a user it returns
156
+ * signs in, and a refusal is the same `null` an unknown identifier gets.
157
+ *
151
158
  * @throws {IdentityError} `rate_limited` (with `retryAfterMs`) when a
152
159
  * `rateLimiter` is configured, the identifier's limit is hit, and
153
160
  * `protectionMode` is `"enforce"`. Rate-limit rejections throw before the
@@ -163,13 +170,7 @@ export class IdentityService {
163
170
  });
164
171
  const user = await this.#users.findByIdentifier(identifier);
165
172
  if (!user) {
166
- await this.#equalizeTiming(input.password);
167
- await this.#emit({
168
- type: "sign_in.failed",
169
- identifier,
170
- reason: "unknown_identifier",
171
- });
172
- return await this.#rejectSignIn(startedAt);
173
+ return await this.#signInUnknownIdentifier(identifier, input.password, startedAt);
173
174
  }
174
175
  const lockReported = await this.#reportLock(user.id, identifier);
175
176
  if (lockReported && this.#enforce) {
@@ -196,8 +197,60 @@ 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
  }
204
+ return await this.#completeSignIn(user, identifier);
205
+ }
206
+ async #signInUnknownIdentifier(identifier, password, startedAt) {
207
+ const resolved = await this.#tryResolveUnknownIdentifier(identifier, password);
208
+ const user = resolved !== null &&
209
+ resolved !== NOT_CHECKED &&
210
+ (await this.#bindResolvedUser(resolved, identifier, password));
211
+ if (user) {
212
+ if ((await this.#reportLock(user.id, identifier)) && this.#enforce) {
213
+ await this.#equalizeTiming(password);
214
+ return await this.#rejectSignIn(startedAt);
215
+ }
216
+ return await this.#completeSignIn(user, identifier);
217
+ }
218
+ await this.#equalizeTiming(password);
219
+ await this.#emit({
220
+ type: "sign_in.failed",
221
+ identifier,
222
+ reason: resolved === NOT_CHECKED ? "not_checked" : "unknown_identifier",
223
+ });
224
+ return await this.#rejectSignIn(startedAt);
225
+ }
226
+ async #tryResolveUnknownIdentifier(identifier, password) {
227
+ if (!this.#resolveUnknownIdentifier)
228
+ return null;
229
+ try {
230
+ return ((await this.#resolveUnknownIdentifier({ identifier, password })) ?? null);
231
+ }
232
+ catch (error) {
233
+ if (error instanceof PasswordNotCheckedError)
234
+ return NOT_CHECKED;
235
+ // Never log the error object: it may echo the submitted password.
236
+ console.error("[@udibo/oauth2] resolveUnknownIdentifier threw");
237
+ return null;
238
+ }
239
+ }
240
+ async #bindResolvedUser(resolved, identifier, password) {
241
+ const found = await this.#users.findByIdentifier(identifier);
242
+ const credential = found?.id === resolved.id
243
+ ? await this.#users.getCredential(found.id)
244
+ : undefined;
245
+ if (found &&
246
+ credential &&
247
+ (await this.#passwords.verify(password, credential))) {
248
+ return found;
249
+ }
250
+ console.error("[@udibo/oauth2] resolveUnknownIdentifier returned an account the identifier and password do not sign in to; refused");
251
+ return null;
252
+ }
253
+ async #completeSignIn(user, identifier) {
201
254
  await this.#resetThrottle("signIn", identifier);
202
255
  if (this.#lockout)
203
256
  await this.#lockout.reset(user.id);
@@ -503,13 +556,15 @@ export class IdentityService {
503
556
  }
504
557
  async #tryLegacy(verifier, password, phc) {
505
558
  try {
506
- return await verifier.verify(password, phc);
559
+ return (await verifier.verify(password, phc)) ? "verified" : "rejected";
507
560
  }
508
- catch {
561
+ catch (error) {
562
+ if (error instanceof PasswordNotCheckedError)
563
+ return "not_checked";
509
564
  // Never log the error object: a BYO verifier may echo the hash or the
510
565
  // submitted password in its message. Fail closed.
511
566
  console.error(`[@udibo/oauth2] legacy password verifier ${verifier.id} threw`);
512
- return false;
567
+ return "rejected";
513
568
  }
514
569
  }
515
570
  /**
@@ -734,9 +789,11 @@ export class IdentityService {
734
789
  return {
735
790
  admit: () => Promise.resolve(true),
736
791
  fail: () => this.#recordSignInFailure(userId, identifier),
792
+ release: () => Promise.resolve(),
737
793
  abandon: () => Promise.resolve(),
738
794
  };
739
795
  }
796
+ const unreserve = this.#lockout?.releaseAttempt?.bind(this.#lockout);
740
797
  let reservation;
741
798
  const announceLock = async () => {
742
799
  if (reservation)
@@ -749,9 +806,27 @@ export class IdentityService {
749
806
  return true;
750
807
  if (!lockReported)
751
808
  await this.#emitSignInLocked(userId, identifier);
752
- return !this.#enforce;
809
+ if (!this.#enforce)
810
+ return true;
811
+ await unreserve?.(userId);
812
+ return false;
753
813
  },
754
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
+ },
755
830
  abandon: announceLock,
756
831
  };
757
832
  }
@@ -778,9 +853,12 @@ export class IdentityService {
778
853
  if (!legacyHash)
779
854
  return "wrong_password";
780
855
  const verifier = findLegacyVerifier(this.#legacyVerifiers, legacyHash);
781
- 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") {
782
860
  await this.#equalizeTiming(password);
783
- return "wrong_password";
861
+ return check === "not_checked" ? "not_checked" : "wrong_password";
784
862
  }
785
863
  return (await this.#upgradeCredential(userId, password, verifier.id))
786
864
  ? "authenticated"
@@ -829,6 +907,17 @@ export class IdentityService {
829
907
  #logPersistFailure(operation, error) {
830
908
  console.error(`[@udibo/oauth2] ${operation} persist failed:`, error instanceof Error ? error.message : error);
831
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
+ }
832
921
  async #recordSignInFailure(userId, identifier) {
833
922
  if (!this.#lockout)
834
923
  return;
@@ -8,8 +8,8 @@
8
8
  * guess for every attempt sharing it: the brute-force floor the lockout is
9
9
  * meant to be moves up by however many attempts an attacker can land at once.
10
10
  *
11
- * The optional `lock` cases run when the store implements it and are skipped,
12
- * with a note naming the gap, when it does not.
11
+ * The optional `lock` and `release` cases run when the store implements the
12
+ * method and are skipped, with a note naming the gap, when it does not.
13
13
  *
14
14
  * @example Verify a database-backed store
15
15
  * ```ts
@@ -53,6 +53,13 @@ export interface LockoutStoreContractOptions {
53
53
  * it does not.
54
54
  */
55
55
  lock?: boolean;
56
+ /**
57
+ * Set to `true` to require the optional {@link LockoutStore.release}: the
58
+ * suite then fails a store that does not implement it. Left unset, the
59
+ * `release` cases run when the store implements it and are skipped with a
60
+ * note when it does not.
61
+ */
62
+ release?: boolean;
56
63
  /**
57
64
  * Overrides the name passed to the outer `describe` block. Defaults to
58
65
  * `"LockoutStore contract"`.
@@ -8,8 +8,8 @@
8
8
  * guess for every attempt sharing it: the brute-force floor the lockout is
9
9
  * meant to be moves up by however many attempts an attacker can land at once.
10
10
  *
11
- * The optional `lock` cases run when the store implements it and are skipped,
12
- * with a note naming the gap, when it does not.
11
+ * The optional `lock` and `release` cases run when the store implements the
12
+ * method and are skipped, with a note naming the gap, when it does not.
13
13
  *
14
14
  * @example Verify a database-backed store
15
15
  * ```ts
@@ -169,6 +169,101 @@ export function runLockoutStoreContractTests(options) {
169
169
  expect((await store.get(OTHER_USER))?.lockedUntil).toBe(undefined);
170
170
  });
171
171
  });
172
+ describe("release (optional)", () => {
173
+ const NOT_IMPLEMENTED = "release is not implemented — an attempt whose password was never " +
174
+ "checked stays counted toward the lockout";
175
+ const MAX_ATTEMPTS = 3;
176
+ if (options.release) {
177
+ it("is implemented", () => {
178
+ assert(typeof store.release === "function", `${NOT_IMPLEMENTED}. Implement it, or drop \`release: true\`.`);
179
+ });
180
+ }
181
+ it("takes back one counted attempt", async ({ skip }) => {
182
+ if (!store.release)
183
+ return skip(NOT_IMPLEMENTED);
184
+ await store.increment(USER, now);
185
+ await store.increment(USER, now);
186
+ await store.release(USER, MAX_ATTEMPTS, now);
187
+ expect((await store.get(USER, now))?.failures).toStrictEqual(1);
188
+ expect((await store.increment(USER, now)).failures).toStrictEqual(2);
189
+ });
190
+ it("leaves no count behind for the last attempt", async ({ skip }) => {
191
+ if (!store.release)
192
+ return skip(NOT_IMPLEMENTED);
193
+ await store.increment(USER, now);
194
+ await store.release(USER, MAX_ATTEMPTS, now);
195
+ expect((await store.get(USER, now))?.failures ?? 0).toStrictEqual(0);
196
+ expect((await store.increment(USER, now)).failures).toStrictEqual(1);
197
+ });
198
+ it("never takes the count below zero", async ({ skip }) => {
199
+ if (!store.release)
200
+ return skip(NOT_IMPLEMENTED);
201
+ await store.release(USER, MAX_ATTEMPTS, now);
202
+ await store.release(USER, MAX_ATTEMPTS, now);
203
+ expect((await store.get(USER, now))?.failures ?? 0).toStrictEqual(0);
204
+ expect((await store.increment(USER, now)).failures).toStrictEqual(1);
205
+ });
206
+ it("drops the lock once the count falls below maxAttempts", async ({ skip, }) => {
207
+ if (!store.release)
208
+ return skip(NOT_IMPLEMENTED);
209
+ await store.set(USER, {
210
+ failures: MAX_ATTEMPTS,
211
+ lockedUntil: now + 60_000,
212
+ });
213
+ await store.release(USER, MAX_ATTEMPTS, now);
214
+ const record = await store.get(USER, now);
215
+ expect(record?.failures).toStrictEqual(MAX_ATTEMPTS - 1);
216
+ expect(record?.lockedUntil, "a lock the counted attempts no longer reach must not stand").toBe(undefined);
217
+ });
218
+ it("keeps the lock while the count still reaches maxAttempts", async ({ skip, }) => {
219
+ if (!store.release)
220
+ return skip(NOT_IMPLEMENTED);
221
+ const lockedUntil = now + 60_000;
222
+ await store.set(USER, { failures: MAX_ATTEMPTS + 1, lockedUntil });
223
+ await store.release(USER, MAX_ATTEMPTS, now);
224
+ const record = await store.get(USER, now);
225
+ expect(record?.failures).toStrictEqual(MAX_ATTEMPTS);
226
+ expect(record?.lockedUntil).toBe(lockedUntil);
227
+ });
228
+ it("takes back exactly one attempt per release among concurrent attempts", async ({ skip, }) => {
229
+ if (!store.release)
230
+ return skip(NOT_IMPLEMENTED);
231
+ for (let i = 0; i < 5; i++)
232
+ await store.increment(USER, now);
233
+ const release = store.release.bind(store);
234
+ await Promise.all([
235
+ ...Array.from({ length: 3 }, () => release(USER, 100, now)),
236
+ ...Array.from({ length: 3 }, () => store.increment(USER, now)),
237
+ ]);
238
+ expect((await store.get(USER, now))?.failures, "a read-modify-write lets a release overwrite a concurrent " +
239
+ "attempt's count").toStrictEqual(5);
240
+ });
241
+ it("takes back one attempt per concurrent release", async ({ skip }) => {
242
+ if (!store.release)
243
+ return skip(NOT_IMPLEMENTED);
244
+ for (let i = 0; i < 5; i++)
245
+ await store.increment(USER, now);
246
+ const release = store.release.bind(store);
247
+ await Promise.all(Array.from({ length: 3 }, () => release(USER, 100, now)));
248
+ expect((await store.get(USER, now))?.failures, "a read-modify-write lets concurrent releases share one decrement").toStrictEqual(2);
249
+ });
250
+ it("leaves a record whose lock has expired as it is", async ({ skip, }) => {
251
+ if (!store.release)
252
+ return skip(NOT_IMPLEMENTED);
253
+ await store.set(USER, { failures: MAX_ATTEMPTS, lockedUntil: now - 1 });
254
+ await store.release(USER, MAX_ATTEMPTS, now);
255
+ expect((await store.increment(USER, now)).failures, "the expired lock's window is over, so the next attempt starts a " +
256
+ "fresh count").toStrictEqual(1);
257
+ });
258
+ it("releases only the account it is given", async ({ skip }) => {
259
+ if (!store.release)
260
+ return skip(NOT_IMPLEMENTED);
261
+ await store.increment(USER, now);
262
+ await store.increment(OTHER_USER, now);
263
+ await store.release(USER, MAX_ATTEMPTS, now);
264
+ expect((await store.get(OTHER_USER, now))?.failures).toStrictEqual(1);
265
+ });
266
+ });
172
267
  describe("clear", () => {
173
268
  it("drops the account's failures and lock", async () => {
174
269
  await store.set(USER, { failures: 10, lockedUntil: now + 60_000 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@udibo/oauth2",
3
- "version": "0.52.0",
3
+ "version": "0.54.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",