@c9up/warden 0.2.6 → 0.2.7
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/README.md +4 -2
- package/dist/AttemptStore.d.ts.map +1 -1
- package/dist/AttemptStore.js +12 -0
- package/dist/AttemptStore.js.map +1 -1
- package/dist/AuthManager.d.ts +11 -6
- package/dist/AuthManager.d.ts.map +1 -1
- package/dist/AuthManager.js +19 -9
- package/dist/AuthManager.js.map +1 -1
- package/dist/AuthRateLimiter.d.ts +16 -3
- package/dist/AuthRateLimiter.d.ts.map +1 -1
- package/dist/AuthRateLimiter.js +25 -6
- package/dist/AuthRateLimiter.js.map +1 -1
- package/dist/Authenticator.d.ts +79 -9
- package/dist/Authenticator.d.ts.map +1 -1
- package/dist/Authenticator.js +186 -16
- package/dist/Authenticator.js.map +1 -1
- package/dist/RedisBlacklistDriver.d.ts.map +1 -1
- package/dist/RedisBlacklistDriver.js +11 -0
- package/dist/RedisBlacklistDriver.js.map +1 -1
- package/dist/RefreshTokenStore.d.ts +37 -6
- package/dist/RefreshTokenStore.d.ts.map +1 -1
- package/dist/RefreshTokenStore.js +51 -10
- package/dist/RefreshTokenStore.js.map +1 -1
- package/dist/ResilientBlacklistDriver.d.ts.map +1 -1
- package/dist/ResilientBlacklistDriver.js +2 -1
- package/dist/ResilientBlacklistDriver.js.map +1 -1
- package/dist/TokenBlacklist.d.ts +3 -1
- package/dist/TokenBlacklist.d.ts.map +1 -1
- package/dist/TokenBlacklist.js +27 -1
- package/dist/TokenBlacklist.js.map +1 -1
- package/dist/authFinder.d.ts +58 -0
- package/dist/authFinder.d.ts.map +1 -0
- package/dist/authFinder.js +77 -0
- package/dist/authFinder.js.map +1 -0
- package/dist/bearer.d.ts +12 -0
- package/dist/bearer.d.ts.map +1 -0
- package/dist/bearer.js +19 -0
- package/dist/bearer.js.map +1 -0
- package/dist/bouncer/Bouncer.d.ts +2 -2
- package/dist/bouncer/Bouncer.d.ts.map +1 -1
- package/dist/bouncer/Bouncer.js +17 -4
- package/dist/bouncer/Bouncer.js.map +1 -1
- package/dist/bouncer/PolicyAuthorizer.d.ts +1 -1
- package/dist/bouncer/PolicyAuthorizer.d.ts.map +1 -1
- package/dist/bouncer/PolicyAuthorizer.js +1 -1
- package/dist/bouncer/PolicyAuthorizer.js.map +1 -1
- package/dist/bouncer/evaluate.d.ts +5 -1
- package/dist/bouncer/evaluate.d.ts.map +1 -1
- package/dist/bouncer/evaluate.js +7 -6
- package/dist/bouncer/evaluate.js.map +1 -1
- package/dist/errors.d.ts +28 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +63 -2
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/mfa/MfaManager.d.ts +17 -4
- package/dist/mfa/MfaManager.d.ts.map +1 -1
- package/dist/mfa/MfaManager.js +37 -14
- package/dist/mfa/MfaManager.js.map +1 -1
- package/dist/mfa/TotpProvider.d.ts.map +1 -1
- package/dist/mfa/TotpProvider.js +8 -0
- package/dist/mfa/TotpProvider.js.map +1 -1
- package/dist/mfa/WebauthnProvider.d.ts +22 -0
- package/dist/mfa/WebauthnProvider.d.ts.map +1 -1
- package/dist/mfa/WebauthnProvider.js +57 -12
- package/dist/mfa/WebauthnProvider.js.map +1 -1
- package/dist/middleware.d.ts +13 -3
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +1 -1
- package/dist/middleware.js.map +1 -1
- package/dist/rights/RightsResolver.d.ts +10 -0
- package/dist/rights/RightsResolver.d.ts.map +1 -1
- package/dist/rights/RightsResolver.js +23 -0
- package/dist/rights/RightsResolver.js.map +1 -1
- package/dist/sanitize.d.ts.map +1 -1
- package/dist/sanitize.js +3 -1
- package/dist/sanitize.js.map +1 -1
- package/dist/services/main.d.ts.map +1 -1
- package/dist/services/main.js +12 -2
- package/dist/services/main.js.map +1 -1
- package/dist/standalone.d.ts.map +1 -1
- package/dist/standalone.js +2 -4
- package/dist/standalone.js.map +1 -1
- package/dist/strategies/ApiKeyStrategy.d.ts +5 -4
- package/dist/strategies/ApiKeyStrategy.d.ts.map +1 -1
- package/dist/strategies/ApiKeyStrategy.js +10 -5
- package/dist/strategies/ApiKeyStrategy.js.map +1 -1
- package/dist/strategies/BasicAuthStrategy.d.ts.map +1 -1
- package/dist/strategies/BasicAuthStrategy.js +5 -2
- package/dist/strategies/BasicAuthStrategy.js.map +1 -1
- package/dist/strategies/JwtStrategy.d.ts +6 -2
- package/dist/strategies/JwtStrategy.d.ts.map +1 -1
- package/dist/strategies/JwtStrategy.js +55 -8
- package/dist/strategies/JwtStrategy.js.map +1 -1
- package/dist/strategies/SessionStrategy.d.ts.map +1 -1
- package/dist/strategies/SessionStrategy.js +4 -1
- package/dist/strategies/SessionStrategy.js.map +1 -1
- package/dist/vendor/quasarConnection.d.ts +18 -0
- package/dist/vendor/quasarConnection.d.ts.map +1 -1
- package/dist/vendor/quasarConnection.js +20 -0
- package/dist/vendor/quasarConnection.js.map +1 -1
- package/index.darwin-arm64.node +0 -0
- package/index.darwin-x64.node +0 -0
- package/index.linux-arm64-gnu.node +0 -0
- package/index.linux-x64-gnu.node +0 -0
- package/index.win32-x64-msvc.node +0 -0
- package/package.json +3 -4
- package/src/AttemptStore.ts +13 -0
- package/src/AuthManager.ts +35 -16
- package/src/AuthRateLimiter.ts +24 -8
- package/src/Authenticator.ts +243 -19
- package/src/RedisBlacklistDriver.ts +11 -0
- package/src/RefreshTokenStore.ts +79 -13
- package/src/ResilientBlacklistDriver.ts +2 -1
- package/src/TokenBlacklist.ts +28 -1
- package/src/authFinder.ts +118 -0
- package/src/bearer.ts +16 -0
- package/src/bouncer/Bouncer.ts +21 -6
- package/src/bouncer/PolicyAuthorizer.ts +1 -1
- package/src/bouncer/evaluate.ts +7 -10
- package/src/errors.ts +80 -2
- package/src/index.ts +11 -0
- package/src/mfa/MfaManager.ts +59 -16
- package/src/mfa/TotpProvider.ts +15 -2
- package/src/mfa/WebauthnProvider.ts +77 -13
- package/src/middleware.ts +16 -3
- package/src/rights/RightsResolver.ts +27 -0
- package/src/sanitize.ts +4 -2
- package/src/services/main.ts +14 -2
- package/src/standalone.ts +2 -5
- package/src/strategies/ApiKeyStrategy.ts +10 -5
- package/src/strategies/BasicAuthStrategy.ts +7 -2
- package/src/strategies/JwtStrategy.ts +58 -9
- package/src/strategies/SessionStrategy.ts +4 -1
- package/src/vendor/quasarConnection.ts +21 -0
- package/stubs/config/auth.stub +3 -0
- package/scripts/build-napi-types.mjs +0 -69
- package/scripts/copy-napi.mjs +0 -75
- package/scripts/generate-napi-types.mjs +0 -156
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Timing-safe credential lookup — the counterpart of the upstream
|
|
3
|
+
* `withAuthFinder` mixin's `verifyCredentials`, without the ORM.
|
|
4
|
+
*
|
|
5
|
+
* Why it exists: a login that returns early for an unknown account answers in
|
|
6
|
+
* microseconds, and one that verifies a password hash for a known account
|
|
7
|
+
* answers in ~100 ms. That difference alone lets an anonymous caller list the
|
|
8
|
+
* registered emails, with no rate limit to bypass. The counter-measure is to pay
|
|
9
|
+
* one hash for an unknown uid too, and to fail every case with the same error.
|
|
10
|
+
*
|
|
11
|
+
* Upstream mixes the methods into a Lucid model; warden knows no ORM, so the
|
|
12
|
+
* lookup is passed in (`findForAuth`) and the methods come back as plain
|
|
13
|
+
* functions, bound, ready to hand to a guard:
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* const users = authFinder({ hash, findForAuth: (email) => User.findBy('email', email) })
|
|
17
|
+
* jwtGuard({ secret, findUser, verifyCredentials: users.verifyCredentials })
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { E_INVALID_CREDENTIALS } from "./errors.js";
|
|
22
|
+
|
|
23
|
+
/** What `authFinder` hashes with — `make` and `verify`, AdonisJS argument order. */
|
|
24
|
+
export interface AuthFinderHasher {
|
|
25
|
+
make(value: string): Promise<string>;
|
|
26
|
+
verify(hashedValue: string, plainValue: string): Promise<boolean>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface AuthFinderOptions<User extends object> {
|
|
30
|
+
/** The hasher the passwords were made with (a sigil `Hash`, for one). */
|
|
31
|
+
hash: AuthFinderHasher;
|
|
32
|
+
/**
|
|
33
|
+
* Find the user a sign-in names — by email, username, whatever the uid is.
|
|
34
|
+
* `null` or `undefined` for none.
|
|
35
|
+
*/
|
|
36
|
+
findForAuth: (uid: string) => Promise<User | null | undefined>;
|
|
37
|
+
/** The property the password hash lives under. Default `password`. */
|
|
38
|
+
passwordColumnName?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface AuthFinder<User extends object> {
|
|
42
|
+
/**
|
|
43
|
+
* Find the user by `uid` and verify `password`. Safe from timing attacks:
|
|
44
|
+
* an unknown uid pays the same one hash a known one does. Every failure
|
|
45
|
+
* throws {@link E_INVALID_CREDENTIALS}.
|
|
46
|
+
*/
|
|
47
|
+
verifyCredentials(uid: string, password: string): Promise<User>;
|
|
48
|
+
/** Whether `password` matches `user`'s stored hash. */
|
|
49
|
+
verifyPassword(user: User, password: string): Promise<boolean>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function authFinder<User extends object>(
|
|
53
|
+
options: AuthFinderOptions<User>,
|
|
54
|
+
): AuthFinder<User> {
|
|
55
|
+
const { hash, findForAuth } = options;
|
|
56
|
+
const column = options.passwordColumnName ?? "password";
|
|
57
|
+
|
|
58
|
+
const storedHash = (user: User): string | undefined => {
|
|
59
|
+
const value: unknown = Reflect.get(user, column);
|
|
60
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const verifyPassword = async (
|
|
64
|
+
user: User,
|
|
65
|
+
password: string,
|
|
66
|
+
): Promise<boolean> => {
|
|
67
|
+
const hashed = storedHash(user);
|
|
68
|
+
if (hashed === undefined) {
|
|
69
|
+
// NAMED DEVIATION — upstream throws a RuntimeException (a 500) for
|
|
70
|
+
// a row without a hash. An account that signs in elsewhere (SSO)
|
|
71
|
+
// has none, and a distinct 500 for it would tell a caller the
|
|
72
|
+
// account exists. It is a password that does not match, and it
|
|
73
|
+
// pays the hash a match would have cost.
|
|
74
|
+
await hash.make(password);
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
return hash.verify(hashed, password);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const verifyCredentials = async (
|
|
81
|
+
uid: string,
|
|
82
|
+
password: string,
|
|
83
|
+
): Promise<User> => {
|
|
84
|
+
if (!uid || !password) throw new E_INVALID_CREDENTIALS();
|
|
85
|
+
const user = await findForAuth(uid);
|
|
86
|
+
if (user === null || user === undefined) {
|
|
87
|
+
// The hash a known uid would cost, paid for nothing: without it the
|
|
88
|
+
// response time says whether the account exists.
|
|
89
|
+
await hash.make(password);
|
|
90
|
+
throw new E_INVALID_CREDENTIALS();
|
|
91
|
+
}
|
|
92
|
+
if (await verifyPassword(user, password)) return user;
|
|
93
|
+
throw new E_INVALID_CREDENTIALS();
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
return { verifyCredentials, verifyPassword };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* A guard's `verifyCredentials` answers a wrong credential with `null`; one
|
|
101
|
+
* built on {@link authFinder} throws {@link E_INVALID_CREDENTIALS} instead, as
|
|
102
|
+
* upstream's does. Both mean the same rejection, so a guard reads them alike.
|
|
103
|
+
*
|
|
104
|
+
* NAMED DEVIATION — upstream's user provider swallows EVERY error into `null`,
|
|
105
|
+
* so a database outage reads as a wrong password. Only E_INVALID_CREDENTIALS
|
|
106
|
+
* is a rejection here; anything else propagates and the auth manager reports it
|
|
107
|
+
* as the strategy crash it is.
|
|
108
|
+
*/
|
|
109
|
+
export async function rejectedAsNull<User>(
|
|
110
|
+
verification: Promise<User | null>,
|
|
111
|
+
): Promise<User | null> {
|
|
112
|
+
try {
|
|
113
|
+
return await verification;
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (error instanceof E_INVALID_CREDENTIALS) return null;
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
package/src/bearer.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read the token out of an `Authorization: Bearer <token>` header.
|
|
3
|
+
*
|
|
4
|
+
* The scheme is matched case-insensitively (RFC 7235: auth-schemes are
|
|
5
|
+
* case-insensitive), so `bearer` and `BEARER` are the same credential, as
|
|
6
|
+
* `Basic` already was. Split on the first spaces like the reference guard:
|
|
7
|
+
* the scheme, then the token; a header with no token is no credential.
|
|
8
|
+
*
|
|
9
|
+
* @returns The token, or `""` when the header carries no bearer credential.
|
|
10
|
+
*/
|
|
11
|
+
export function readBearerToken(header: unknown): string {
|
|
12
|
+
if (typeof header !== "string") return "";
|
|
13
|
+
const [type, token] = header.split(" ");
|
|
14
|
+
if (type?.toLowerCase() !== "bearer" || !token) return "";
|
|
15
|
+
return token;
|
|
16
|
+
}
|
package/src/bouncer/Bouncer.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* 2026-06-01): standalone abilities via `Bouncer.ability`, class-based policies
|
|
6
6
|
* via `with(Policy)`, the four verbs `allows`/`denies`/`authorize`/`execute`,
|
|
7
7
|
* and guest-denied-by-default. The user is `UserPayload | null` (guest = null,
|
|
8
|
-
* D3); `authorize` throws `
|
|
8
|
+
* D3); `authorize` throws `E_AUTHORIZATION_FAILURE` carrying `status: 403`
|
|
9
9
|
* (D2). 56.2 ships PURE mechanics — it does NOT consult the Layer-1
|
|
10
10
|
* `RightsResolver` (D4); abilities/policy methods receive `(user, ...args)` and
|
|
11
11
|
* the developer writes the predicate, exactly as Adonis does.
|
|
@@ -13,7 +13,10 @@
|
|
|
13
13
|
|
|
14
14
|
import type { UserPayload } from "../AuthManager.js";
|
|
15
15
|
import { WardenError } from "../errors.js";
|
|
16
|
-
import
|
|
16
|
+
import {
|
|
17
|
+
narrowToAccessToken,
|
|
18
|
+
type RightsResolver,
|
|
19
|
+
} from "../rights/RightsResolver.js";
|
|
17
20
|
import type { EffectivePermissions, Scope } from "../rights/types.js";
|
|
18
21
|
import { AbilitiesBuilder } from "./AbilitiesBuilder.js";
|
|
19
22
|
import { AuthorizationResponse } from "./AuthorizationResponse.js";
|
|
@@ -133,9 +136,14 @@ export class Bouncer {
|
|
|
133
136
|
#resolvePermissions(): Promise<EffectivePermissions> {
|
|
134
137
|
if (this.#resolved === undefined) {
|
|
135
138
|
const user = this.#getUser();
|
|
139
|
+
// Narrowed by the request's access token, exactly as the coarse
|
|
140
|
+
// `hasPermission` is: a token minted for `orders:read` must not pass
|
|
141
|
+
// a policy that asks `this.permissions.has('orders:delete')`.
|
|
136
142
|
this.#resolved =
|
|
137
143
|
this.#resolver !== undefined && user !== null
|
|
138
|
-
? this.#resolver
|
|
144
|
+
? this.#resolver
|
|
145
|
+
.resolve(user, this.#scope)
|
|
146
|
+
.then((effective) => narrowToAccessToken(effective, user))
|
|
139
147
|
: Promise.resolve(emptyPermissions(this.#scope));
|
|
140
148
|
}
|
|
141
149
|
return this.#resolved;
|
|
@@ -321,7 +329,7 @@ export class Bouncer {
|
|
|
321
329
|
return !(await this.#evaluateAbility(ability, args)).authorized;
|
|
322
330
|
}
|
|
323
331
|
|
|
324
|
-
/** Resolves on allow; throws `
|
|
332
|
+
/** Resolves on allow; throws `E_AUTHORIZATION_FAILURE` on deny (D2). */
|
|
325
333
|
authorize<Args extends unknown[]>(
|
|
326
334
|
ability: Ability<Args>,
|
|
327
335
|
...args: Args
|
|
@@ -357,7 +365,12 @@ export class Bouncer {
|
|
|
357
365
|
}
|
|
358
366
|
|
|
359
367
|
#resolveAbility(name: string): Ability<never[]> {
|
|
360
|
-
|
|
368
|
+
// Own keys only: the registry is a plain object, and a name never
|
|
369
|
+
// registered ("constructor", "toString") must not resolve to an
|
|
370
|
+
// Object.prototype member and fail as a TypeError.
|
|
371
|
+
const found = Object.hasOwn(this.#abilities, name)
|
|
372
|
+
? this.#abilities[name]
|
|
373
|
+
: undefined;
|
|
361
374
|
if (found === undefined) {
|
|
362
375
|
throw new WardenError(
|
|
363
376
|
"UNKNOWN_ABILITY",
|
|
@@ -373,7 +386,9 @@ export class Bouncer {
|
|
|
373
386
|
// name surfaces as a promise rejection (like every other verb error),
|
|
374
387
|
// not a synchronous throw at `with()` time.
|
|
375
388
|
return () => {
|
|
376
|
-
const ctor = this.#policies
|
|
389
|
+
const ctor = Object.hasOwn(this.#policies, name)
|
|
390
|
+
? this.#policies[name]
|
|
391
|
+
: undefined;
|
|
377
392
|
if (ctor === undefined) {
|
|
378
393
|
throw new WardenError(
|
|
379
394
|
"UNKNOWN_POLICY",
|
|
@@ -145,7 +145,7 @@ export class PolicyAuthorizer {
|
|
|
145
145
|
return !(await this.execute(action, ...args)).authorized;
|
|
146
146
|
}
|
|
147
147
|
|
|
148
|
-
/** Resolves on allow; throws `
|
|
148
|
+
/** Resolves on allow; throws `E_AUTHORIZATION_FAILURE` on deny (D2). */
|
|
149
149
|
async authorize(action: string, ...args: unknown[]): Promise<void> {
|
|
150
150
|
const response = await this.execute(action, ...args);
|
|
151
151
|
if (!response.authorized) {
|
package/src/bouncer/evaluate.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import type { UserPayload } from "../AuthManager.js";
|
|
12
|
-
import {
|
|
12
|
+
import { E_AUTHORIZATION_FAILURE } from "../errors.js";
|
|
13
13
|
import { AuthorizationResponse } from "./AuthorizationResponse.js";
|
|
14
14
|
import type { AuthorizerResponse, HookResponse } from "./types.js";
|
|
15
15
|
|
|
@@ -56,18 +56,15 @@ export function isAction(value: unknown): value is Action {
|
|
|
56
56
|
return typeof value === "function";
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* Throw the canonical authorization failure for a denied response (D2) —
|
|
61
|
+
* `E_AUTHORIZATION_FAILURE`, carrying the response so its status, message and
|
|
62
|
+
* translation reach whoever handles the error.
|
|
63
|
+
*/
|
|
60
64
|
export function throwAuthorizationFailure(
|
|
61
65
|
response: AuthorizationResponse,
|
|
62
66
|
): never {
|
|
63
|
-
throw new
|
|
64
|
-
"AUTHORIZATION_FAILURE",
|
|
65
|
-
response.message ?? "Authorization failed",
|
|
66
|
-
{
|
|
67
|
-
hint: "The current user is not authorized for this action.",
|
|
68
|
-
status: response.status ?? 403,
|
|
69
|
-
},
|
|
70
|
-
);
|
|
67
|
+
throw new E_AUTHORIZATION_FAILURE(response);
|
|
71
68
|
}
|
|
72
69
|
|
|
73
70
|
/** Run the D5 evaluation pipeline and resolve to the final response. */
|
package/src/errors.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { AuthorizationResponse } from "./bouncer/AuthorizationResponse.js";
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* WardenError — structured error for Warden auth.
|
|
3
5
|
*/
|
|
@@ -23,8 +25,9 @@ export class WardenError extends Error {
|
|
|
23
25
|
// alone would mean three different things across the ecosystem and an
|
|
24
26
|
// application could not tell them apart.
|
|
25
27
|
//
|
|
26
|
-
// The AdonisJS
|
|
27
|
-
// `E_INVALID_CREDENTIALS`) are
|
|
28
|
+
// The AdonisJS identifiers (`E_UNAUTHORIZED_ACCESS`,
|
|
29
|
+
// `E_INVALID_CREDENTIALS`, bouncer's `E_AUTHORIZATION_FAILURE`) are
|
|
30
|
+
// PRESERVED verbatim — they already start
|
|
28
31
|
// with `E_` and fall through untouched — so a consumer branching on
|
|
29
32
|
// `error.code === 'E_UNAUTHORIZED_ACCESS'` sees the same string it
|
|
30
33
|
// would under `@adonisjs/auth`.
|
|
@@ -79,3 +82,78 @@ export class E_INVALID_CREDENTIALS extends WardenError {
|
|
|
79
82
|
super("E_INVALID_CREDENTIALS", message, { status: 400 });
|
|
80
83
|
}
|
|
81
84
|
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The slice of an i18n service {@link E_AUTHORIZATION_FAILURE} translates
|
|
88
|
+
* through: `ctx.i18n.t(identifier, data, { defaultValue })`, the shape of the
|
|
89
|
+
* ecosystem's i18n package. Structural, so warden imports none.
|
|
90
|
+
*/
|
|
91
|
+
interface Translator {
|
|
92
|
+
t(
|
|
93
|
+
identifier: string,
|
|
94
|
+
data?: Record<string, unknown>,
|
|
95
|
+
options?: { defaultValue?: string },
|
|
96
|
+
): string;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function translatorOf(ctx: unknown): Translator | undefined {
|
|
100
|
+
const i18n: unknown =
|
|
101
|
+
typeof ctx === "object" && ctx !== null
|
|
102
|
+
? Reflect.get(ctx, "i18n")
|
|
103
|
+
: undefined;
|
|
104
|
+
if (typeof i18n !== "object" || i18n === null) return undefined;
|
|
105
|
+
const t: unknown = Reflect.get(i18n, "t");
|
|
106
|
+
if (typeof t !== "function") return undefined;
|
|
107
|
+
return {
|
|
108
|
+
t: (identifier, data, options) => {
|
|
109
|
+
const translated: unknown = t.call(i18n, identifier, data, options);
|
|
110
|
+
return typeof translated === "string"
|
|
111
|
+
? translated
|
|
112
|
+
: (options?.defaultValue ?? identifier);
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* `E_AUTHORIZATION_FAILURE` — thrown by a denied `authorize()` (AdonisJS
|
|
119
|
+
* `@adonisjs/bouncer` parity: same class name, same `code`, same
|
|
120
|
+
* `identifier`). Carries the {@link AuthorizationResponse} it was thrown for,
|
|
121
|
+
* so a handler reads the denial's `status`, `message` and `translation`.
|
|
122
|
+
*
|
|
123
|
+
* NAMED DEVIATION — upstream's class fields override what the constructor
|
|
124
|
+
* passed, so its `error.message` is always "Access denied" and `error.status`
|
|
125
|
+
* always 403; only its own `handle()` reads the response. Here `message` and
|
|
126
|
+
* `status` ARE the response's (falling back to "Access denied" / 403), because
|
|
127
|
+
* warden ships no renderer: the host's exception handler renders the error from
|
|
128
|
+
* those two fields, and a `deny('Not found', 404)` must reach it as a 404.
|
|
129
|
+
*/
|
|
130
|
+
export class E_AUTHORIZATION_FAILURE extends WardenError {
|
|
131
|
+
/** The i18n key looked up when the response sets no translation. */
|
|
132
|
+
readonly identifier = "errors.E_AUTHORIZATION_FAILURE";
|
|
133
|
+
/** The denial this error was thrown for. */
|
|
134
|
+
readonly response: AuthorizationResponse;
|
|
135
|
+
|
|
136
|
+
constructor(response: AuthorizationResponse) {
|
|
137
|
+
super("E_AUTHORIZATION_FAILURE", response.message || "Access denied", {
|
|
138
|
+
hint: "The current user is not authorized for this action.",
|
|
139
|
+
status: response.status || 403,
|
|
140
|
+
});
|
|
141
|
+
this.name = "E_AUTHORIZATION_FAILURE";
|
|
142
|
+
this.response = response;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The message to send for this denial (AdonisJS `getResponseMessage`): the
|
|
147
|
+
* response's translation when the context carries an i18n service, its
|
|
148
|
+
* message otherwise. The translation falls back to the static identifier,
|
|
149
|
+
* then to the message when the catalog has neither.
|
|
150
|
+
*/
|
|
151
|
+
getResponseMessage(ctx: unknown): string {
|
|
152
|
+
const message = this.response.message || this.message;
|
|
153
|
+
const translator = translatorOf(ctx);
|
|
154
|
+
if (translator === undefined) return message;
|
|
155
|
+
const identifier = this.response.translation?.identifier || this.identifier;
|
|
156
|
+
const data = this.response.translation?.data || {};
|
|
157
|
+
return translator.t(identifier, data, { defaultValue: message });
|
|
158
|
+
}
|
|
159
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -54,6 +54,12 @@ export type {
|
|
|
54
54
|
AuthRateLimiterConfig,
|
|
55
55
|
} from "./AuthRateLimiter.js";
|
|
56
56
|
export { AuthRateLimiter } from "./AuthRateLimiter.js";
|
|
57
|
+
export type {
|
|
58
|
+
AuthFinder,
|
|
59
|
+
AuthFinderHasher,
|
|
60
|
+
AuthFinderOptions,
|
|
61
|
+
} from "./authFinder.js";
|
|
62
|
+
export { authFinder } from "./authFinder.js";
|
|
57
63
|
export { AbilitiesBuilder } from "./bouncer/AbilitiesBuilder.js";
|
|
58
64
|
export { AuthorizationResponse } from "./bouncer/AuthorizationResponse.js";
|
|
59
65
|
export { BasePolicy } from "./bouncer/BasePolicy.js";
|
|
@@ -87,6 +93,7 @@ export { configure } from "./configure.js";
|
|
|
87
93
|
export type { TokenDuration } from "./duration.js";
|
|
88
94
|
export { parseDurationSeconds } from "./duration.js";
|
|
89
95
|
export {
|
|
96
|
+
E_AUTHORIZATION_FAILURE,
|
|
90
97
|
E_INVALID_CREDENTIALS,
|
|
91
98
|
E_UNAUTHORIZED_ACCESS,
|
|
92
99
|
WardenError,
|
|
@@ -152,6 +159,7 @@ export type {
|
|
|
152
159
|
export {
|
|
153
160
|
MemoryWebauthnChallengeStore,
|
|
154
161
|
MemoryWebauthnCredentialStore,
|
|
162
|
+
WebauthnCredentialExistsError,
|
|
155
163
|
WebauthnProvider,
|
|
156
164
|
} from "./mfa/WebauthnProvider.js";
|
|
157
165
|
export { quasarConnection } from "./quasar.js";
|
|
@@ -161,12 +169,15 @@ export type {
|
|
|
161
169
|
} from "./RedisBlacklistDriver.js";
|
|
162
170
|
export { RedisBlacklistDriver } from "./RedisBlacklistDriver.js";
|
|
163
171
|
export type {
|
|
172
|
+
MintedRefreshToken,
|
|
164
173
|
RefreshTokenDriver,
|
|
165
174
|
StoredRefreshToken,
|
|
166
175
|
} from "./RefreshTokenStore.js";
|
|
167
176
|
export {
|
|
168
177
|
generateRefreshToken,
|
|
178
|
+
hashRefreshToken,
|
|
169
179
|
MemoryRefreshTokenDriver,
|
|
180
|
+
mintRefreshToken,
|
|
170
181
|
} from "./RefreshTokenStore.js";
|
|
171
182
|
export {
|
|
172
183
|
DEFAULT_SECRET_LENGTH,
|
package/src/mfa/MfaManager.ts
CHANGED
|
@@ -106,7 +106,11 @@ export interface MfaManagerConfig {
|
|
|
106
106
|
totp?: TotpProvider;
|
|
107
107
|
backupCodes?: BackupCodesProvider;
|
|
108
108
|
store?: MfaFactorStore;
|
|
109
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* Per-user brute-force protection on `verify()`, `verifyTotp()`,
|
|
111
|
+
* `verifyBackupCode()` and `confirmTotp()`, one shared count. Defaults to
|
|
112
|
+
* 5 / 15 min.
|
|
113
|
+
*/
|
|
110
114
|
rateLimit?: MfaRateLimitConfig;
|
|
111
115
|
}
|
|
112
116
|
|
|
@@ -188,9 +192,23 @@ export class MfaManager {
|
|
|
188
192
|
return true;
|
|
189
193
|
}
|
|
190
194
|
|
|
191
|
-
/**
|
|
195
|
+
/**
|
|
196
|
+
* Verify a TOTP code against the user's confirmed authenticator factors.
|
|
197
|
+
*
|
|
198
|
+
* Counts against the same per-user lockout as {@link verify}: an app
|
|
199
|
+
* calling this directly (to tell the factors apart in its UI) must not get
|
|
200
|
+
* unlimited guesses at a six-digit code.
|
|
201
|
+
*/
|
|
192
202
|
async verifyTotp(userId: string, code: string): Promise<boolean> {
|
|
193
203
|
const totp = this.#requireTotp();
|
|
204
|
+
return this.#limited(userId, () => this.#checkTotp(totp, userId, code));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async #checkTotp(
|
|
208
|
+
totp: TotpProvider,
|
|
209
|
+
userId: string,
|
|
210
|
+
code: string,
|
|
211
|
+
): Promise<boolean> {
|
|
194
212
|
const factors = await this.#store.findByUser(userId);
|
|
195
213
|
// Sequential, not Promise.all: the replay guard must see one accepted
|
|
196
214
|
// code at a time, and stopping at the first match avoids burning the
|
|
@@ -237,9 +255,22 @@ export class MfaManager {
|
|
|
237
255
|
return codes;
|
|
238
256
|
}
|
|
239
257
|
|
|
240
|
-
/**
|
|
258
|
+
/**
|
|
259
|
+
* Verify and consume one backup code for the user. Counts against the same
|
|
260
|
+
* per-user lockout as {@link verify}.
|
|
261
|
+
*/
|
|
241
262
|
async verifyBackupCode(userId: string, code: string): Promise<boolean> {
|
|
242
263
|
const provider = this.#requireBackupCodes();
|
|
264
|
+
return this.#limited(userId, () =>
|
|
265
|
+
this.#checkBackupCode(provider, userId, code),
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async #checkBackupCode(
|
|
270
|
+
provider: BackupCodesProvider,
|
|
271
|
+
userId: string,
|
|
272
|
+
code: string,
|
|
273
|
+
): Promise<boolean> {
|
|
243
274
|
const factors = await this.#store.findByUser(userId);
|
|
244
275
|
for (const factor of factors) {
|
|
245
276
|
if (factor.kind !== "backup_codes" || !factor.backupHashes) {
|
|
@@ -265,28 +296,40 @@ export class MfaManager {
|
|
|
265
296
|
* factors first, then falls back to consuming a backup code.
|
|
266
297
|
*/
|
|
267
298
|
async verify(userId: string, code: string): Promise<boolean> {
|
|
268
|
-
//
|
|
269
|
-
|
|
270
|
-
|
|
299
|
+
// One attempt for the code, whichever factor ends up answering it.
|
|
300
|
+
return this.#limited(userId, async () => {
|
|
301
|
+
const totp = this.#totp;
|
|
302
|
+
if (totp && (await this.#checkTotp(totp, userId, code))) return true;
|
|
303
|
+
const backupCodes = this.#backupCodes;
|
|
304
|
+
return (
|
|
305
|
+
backupCodes !== undefined &&
|
|
306
|
+
(await this.#checkBackupCode(backupCodes, userId, code))
|
|
307
|
+
);
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Run one code check under the per-user lockout.
|
|
313
|
+
*
|
|
314
|
+
* Counted BEFORE the code is checked, by one atomic increment: reading
|
|
315
|
+
* "not locked" first and counting the failure after let a burst of
|
|
316
|
+
* concurrent attempts all reach the providers. A success clears the count.
|
|
317
|
+
*/
|
|
318
|
+
async #limited(
|
|
319
|
+
userId: string,
|
|
320
|
+
check: () => Promise<boolean>,
|
|
321
|
+
): Promise<boolean> {
|
|
271
322
|
const key = lockoutKey(userId);
|
|
272
323
|
if (!(await this.#limiter.attempt(key)).allowed) {
|
|
273
324
|
return false;
|
|
274
325
|
}
|
|
275
|
-
|
|
276
|
-
if (this.#totp && (await this.verifyTotp(userId, code))) {
|
|
277
|
-
ok = true;
|
|
278
|
-
} else if (
|
|
279
|
-
this.#backupCodes &&
|
|
280
|
-
(await this.verifyBackupCode(userId, code))
|
|
281
|
-
) {
|
|
282
|
-
ok = true;
|
|
283
|
-
}
|
|
326
|
+
const ok = await check();
|
|
284
327
|
if (ok) await this.#limiter.clear(key);
|
|
285
328
|
return ok;
|
|
286
329
|
}
|
|
287
330
|
|
|
288
331
|
/**
|
|
289
|
-
* Whether the user is currently locked out of
|
|
332
|
+
* Whether the user is currently locked out of the code checks after too many
|
|
290
333
|
* failed attempts. Use it to surface a "try again later" message.
|
|
291
334
|
*/
|
|
292
335
|
isLocked(userId: string): Promise<boolean> {
|
package/src/mfa/TotpProvider.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
11
11
|
import { WardenError } from "../errors.js";
|
|
12
|
+
import { hasEnded } from "../vendor/quasarConnection.js";
|
|
12
13
|
import { base32Decode, base32Encode } from "./base32.js";
|
|
13
14
|
|
|
14
15
|
export type TotpAlgorithm = "SHA1" | "SHA256" | "SHA512";
|
|
@@ -124,6 +125,13 @@ export class RedisTotpReplayGuard implements TotpReplayGuard {
|
|
|
124
125
|
}
|
|
125
126
|
|
|
126
127
|
async claim(key: string, ttlMs: number): Promise<boolean> {
|
|
128
|
+
// Resolved again once the client has ended for good: quasar retires
|
|
129
|
+
// a connection whose retry strategy gave up and hands out a fresh one,
|
|
130
|
+
// and keeping the dead client refused every code until restart. A
|
|
131
|
+
// client handed in directly is kept whatever its state.
|
|
132
|
+
if (typeof this.#source === "function" && hasEnded(this.#resolved)) {
|
|
133
|
+
this.#resolved = undefined;
|
|
134
|
+
}
|
|
127
135
|
if (this.#resolved === undefined) {
|
|
128
136
|
this.#resolved =
|
|
129
137
|
typeof this.#source === "function"
|
|
@@ -149,8 +157,13 @@ export interface TotpEnrollment {
|
|
|
149
157
|
uri: string;
|
|
150
158
|
}
|
|
151
159
|
|
|
152
|
-
const DEFAULTS
|
|
153
|
-
algorithm:
|
|
160
|
+
const DEFAULTS: {
|
|
161
|
+
algorithm: TotpAlgorithm;
|
|
162
|
+
digits: number;
|
|
163
|
+
period: number;
|
|
164
|
+
window: number;
|
|
165
|
+
} = {
|
|
166
|
+
algorithm: "SHA1",
|
|
154
167
|
digits: 6,
|
|
155
168
|
period: 30,
|
|
156
169
|
window: 1,
|
|
@@ -117,6 +117,24 @@ export interface WebauthnChallengeStore {
|
|
|
117
117
|
take(state: string): Promise<WebauthnCeremony | null>;
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
+
/**
|
|
121
|
+
* Thrown by `WebauthnCredentialStore.save` when the credential id is already
|
|
122
|
+
* registered. `finishRegistration` turns it into `{ verified: false }`; any
|
|
123
|
+
* other error from the store is an outage and propagates.
|
|
124
|
+
*/
|
|
125
|
+
export class WebauthnCredentialExistsError extends WardenError {
|
|
126
|
+
constructor(credentialId: string) {
|
|
127
|
+
super(
|
|
128
|
+
"E_WARDEN_WEBAUTHN_CREDENTIAL_EXISTS",
|
|
129
|
+
`The WebAuthn credential "${credentialId}" is already registered.`,
|
|
130
|
+
{
|
|
131
|
+
hint: "A credential id belongs to the account that registered it first. Keep it unique in the store (INSERT, never upsert).",
|
|
132
|
+
},
|
|
133
|
+
);
|
|
134
|
+
this.name = "WebauthnCredentialExistsError";
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
120
138
|
/** A registered passkey, persisted between ceremonies. */
|
|
121
139
|
export interface StoredPasskey {
|
|
122
140
|
/** Base64URL credential id. */
|
|
@@ -131,6 +149,19 @@ export interface StoredPasskey {
|
|
|
131
149
|
}
|
|
132
150
|
|
|
133
151
|
export interface WebauthnCredentialStore {
|
|
152
|
+
/**
|
|
153
|
+
* Persist a NEW passkey. This is an INSERT, never an upsert.
|
|
154
|
+
*
|
|
155
|
+
* The credential id comes from authenticator data the client chose
|
|
156
|
+
* (attestation is `none`), and a victim's ids are listed to anyone who
|
|
157
|
+
* starts an authentication ceremony for them. A store that replaced an
|
|
158
|
+
* existing row let an attacker register their own key under the victim's
|
|
159
|
+
* id and take the passkey over. `finishRegistration` checks `findById`
|
|
160
|
+
* first; the store closes the race between that check and this write: a
|
|
161
|
+
* persistent store keeps `id` unique (primary key / unique index, Redis
|
|
162
|
+
* `SET … NX`) and throws `WebauthnCredentialExistsError` when the id is
|
|
163
|
+
* already taken, so a concurrent registration of the same id fails.
|
|
164
|
+
*/
|
|
134
165
|
save(passkey: StoredPasskey): Promise<void>;
|
|
135
166
|
findById(id: string): Promise<StoredPasskey | null>;
|
|
136
167
|
findByUser(userId: string): Promise<StoredPasskey[]>;
|
|
@@ -277,6 +308,11 @@ export class MemoryWebauthnChallengeStore implements WebauthnChallengeStore {
|
|
|
277
308
|
export class MemoryWebauthnCredentialStore implements WebauthnCredentialStore {
|
|
278
309
|
#store = new Map<string, StoredPasskey>();
|
|
279
310
|
async save(passkey: StoredPasskey): Promise<void> {
|
|
311
|
+
// Check and write with no `await` between them: atomic on a
|
|
312
|
+
// single-threaded runtime, so two registrations of one id cannot both land.
|
|
313
|
+
if (this.#store.has(passkey.id)) {
|
|
314
|
+
throw new WebauthnCredentialExistsError(passkey.id);
|
|
315
|
+
}
|
|
280
316
|
this.#store.set(passkey.id, passkey);
|
|
281
317
|
}
|
|
282
318
|
async findById(id: string): Promise<StoredPasskey | null> {
|
|
@@ -494,14 +530,31 @@ export class WebauthnProvider {
|
|
|
494
530
|
if (parsed === null || !this.#algorithms.includes(parsed.alg)) {
|
|
495
531
|
return { verified: false };
|
|
496
532
|
}
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
}
|
|
533
|
+
// WebAuthn L2 7.1 step 22: a credential id already registered, for ANY
|
|
534
|
+
// user, fails the ceremony. The id is client-chosen; replacing the row
|
|
535
|
+
// handed the victim's passkey to whoever sent it, and re-registering
|
|
536
|
+
// one's own id reset the counter that betrays a cloned authenticator.
|
|
537
|
+
const id = bufferToBase64url(parsed.credentialId);
|
|
538
|
+
if ((await this.#credentials.findById(id)) !== null) {
|
|
539
|
+
return { verified: false };
|
|
540
|
+
}
|
|
541
|
+
try {
|
|
542
|
+
await this.#credentials.save({
|
|
543
|
+
id,
|
|
544
|
+
userId,
|
|
545
|
+
publicKey: bufferToBase64url(parsed.publicKeyBytes),
|
|
546
|
+
alg: parsed.alg,
|
|
547
|
+
counter: parsed.signCount,
|
|
548
|
+
transports: response.response.transports,
|
|
549
|
+
});
|
|
550
|
+
} catch (error) {
|
|
551
|
+
// A concurrent registration took the id between the check and the
|
|
552
|
+
// insert. Any other store failure is infrastructure and propagates.
|
|
553
|
+
if (error instanceof WebauthnCredentialExistsError) {
|
|
554
|
+
return { verified: false };
|
|
555
|
+
}
|
|
556
|
+
throw error;
|
|
557
|
+
}
|
|
505
558
|
return { verified: true };
|
|
506
559
|
}
|
|
507
560
|
|
|
@@ -640,17 +693,28 @@ export class WebauthnProvider {
|
|
|
640
693
|
expectedType: "webauthn.create" | "webauthn.get",
|
|
641
694
|
expectedChallenge: string,
|
|
642
695
|
): boolean {
|
|
643
|
-
let parsed:
|
|
696
|
+
let parsed: unknown;
|
|
644
697
|
try {
|
|
645
698
|
parsed = JSON.parse(base64urlToBuffer(clientDataB64).toString("utf8"));
|
|
646
699
|
} catch {
|
|
647
700
|
return false;
|
|
648
701
|
}
|
|
702
|
+
// Attacker-supplied: `null`, an array or a scalar parse fine and are not
|
|
703
|
+
// client data. Reading a field off `null` threw a TypeError that escaped
|
|
704
|
+
// the ceremony as a 500 instead of a plain refusal.
|
|
705
|
+
if (
|
|
706
|
+
typeof parsed !== "object" ||
|
|
707
|
+
parsed === null ||
|
|
708
|
+
Array.isArray(parsed)
|
|
709
|
+
) {
|
|
710
|
+
return false;
|
|
711
|
+
}
|
|
712
|
+
const origin: unknown = Reflect.get(parsed, "origin");
|
|
649
713
|
return (
|
|
650
|
-
parsed
|
|
651
|
-
parsed
|
|
652
|
-
typeof
|
|
653
|
-
this.#origins.includes(
|
|
714
|
+
Reflect.get(parsed, "type") === expectedType &&
|
|
715
|
+
Reflect.get(parsed, "challenge") === expectedChallenge &&
|
|
716
|
+
typeof origin === "string" &&
|
|
717
|
+
this.#origins.includes(origin)
|
|
654
718
|
);
|
|
655
719
|
}
|
|
656
720
|
|