@udibo/oauth2 0.53.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 +2 -2
- package/dist/identity/events.d.ts +1 -1
- package/dist/identity/lockout.d.ts +52 -2
- package/dist/identity/lockout.js +36 -0
- package/dist/identity/migration.d.ts +62 -5
- package/dist/identity/migration.js +62 -4
- package/dist/identity/service.d.ts +7 -1
- package/dist/identity/service.js +52 -10
- package/dist/testing/contract/lockout-store.d.ts +9 -2
- package/dist/testing/contract/lockout-store.js +97 -2
- package/package.json +1 -1
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 **
|
|
31
|
-
assessment within **
|
|
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"
|
|
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
|
}
|
package/dist/identity/lockout.js
CHANGED
|
@@ -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
|
-
*
|
|
66
|
-
*
|
|
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
|
|
80
|
-
*
|
|
81
|
-
*
|
|
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
|
|
48
|
-
*
|
|
49
|
-
*
|
|
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
|
package/dist/identity/service.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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;
|
|
@@ -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
|
|
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
|
|
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.
|
|
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",
|