@zudojs/auth 0.1.1 → 1.0.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/LICENSE +21 -0
- package/README.md +216 -19
- package/dist/authErrors/authError.base.d.ts +50 -16
- package/dist/authErrors/authError.base.js +94 -18
- package/dist/authErrors/index.d.ts +1 -1
- package/dist/authErrors/index.js +1 -1
- package/dist/authPassword/authPassword.core.d.ts +25 -2
- package/dist/authPassword/authPassword.core.js +50 -2
- package/dist/authPassword/index.d.ts +1 -1
- package/dist/authPassword/index.js +1 -1
- package/dist/authProvider/authAttempt.memory.d.ts +21 -0
- package/dist/authProvider/authAttempt.memory.js +91 -0
- package/dist/authProvider/authProvider.core.d.ts +52 -9
- package/dist/authProvider/authProvider.core.js +197 -37
- package/dist/authProvider/index.d.ts +2 -1
- package/dist/authProvider/index.js +1 -0
- package/dist/authSession/authSession.core.d.ts +13 -3
- package/dist/authSession/authSession.core.js +51 -21
- package/dist/authToken/authToken.core.d.ts +27 -1
- package/dist/authToken/authToken.core.js +31 -1
- package/dist/authToken/authToken.encoding.d.ts +43 -0
- package/dist/authToken/authToken.encoding.js +74 -0
- package/dist/authToken/authToken.revocation.d.ts +10 -2
- package/dist/authToken/authToken.revocation.js +42 -7
- package/dist/authToken/authToken.signing.d.ts +24 -1
- package/dist/authToken/authToken.signing.js +102 -28
- package/dist/authToken/jwt.namespace.d.ts +18 -8
- package/dist/authToken/jwt.namespace.js +11 -1
- package/dist/authTypes/authAttempt.type.d.ts +63 -0
- package/dist/authTypes/authAttempt.type.js +7 -0
- package/dist/authTypes/authCredentials.type.d.ts +26 -0
- package/dist/authTypes/authCredentials.type.js +11 -0
- package/dist/authTypes/authSession.type.d.ts +31 -3
- package/dist/authTypes/authSession.type.js +17 -1
- package/dist/authTypes/authToken.type.d.ts +29 -1
- package/dist/authTypes/authUser.type.d.ts +12 -0
- package/dist/authTypes/authUser.type.js +17 -1
- package/dist/authTypes/index.d.ts +5 -4
- package/dist/authTypes/index.js +5 -4
- package/dist/authUtils/authUtils.helper.d.ts +31 -10
- package/dist/authUtils/authUtils.helper.js +70 -31
- package/package.json +23 -16
- package/dist/.tsbuildinfo +0 -1
- package/dist/authErrors/authError.base.d.ts.map +0 -1
- package/dist/authErrors/authError.base.js.map +0 -1
- package/dist/authErrors/index.d.ts.map +0 -1
- package/dist/authErrors/index.js.map +0 -1
- package/dist/authPassword/authPassword.core.d.ts.map +0 -1
- package/dist/authPassword/authPassword.core.js.map +0 -1
- package/dist/authPassword/index.d.ts.map +0 -1
- package/dist/authPassword/index.js.map +0 -1
- package/dist/authProvider/authProvider.core.d.ts.map +0 -1
- package/dist/authProvider/authProvider.core.js.map +0 -1
- package/dist/authProvider/index.d.ts.map +0 -1
- package/dist/authProvider/index.js.map +0 -1
- package/dist/authSession/authSession.core.d.ts.map +0 -1
- package/dist/authSession/authSession.core.js.map +0 -1
- package/dist/authSession/index.d.ts.map +0 -1
- package/dist/authSession/index.js.map +0 -1
- package/dist/authToken/authToken.core.d.ts.map +0 -1
- package/dist/authToken/authToken.core.js.map +0 -1
- package/dist/authToken/authToken.revocation.d.ts.map +0 -1
- package/dist/authToken/authToken.revocation.js.map +0 -1
- package/dist/authToken/authToken.signing.d.ts.map +0 -1
- package/dist/authToken/authToken.signing.js.map +0 -1
- package/dist/authToken/index.d.ts.map +0 -1
- package/dist/authToken/index.js.map +0 -1
- package/dist/authToken/jwt.namespace.d.ts.map +0 -1
- package/dist/authToken/jwt.namespace.js.map +0 -1
- package/dist/authTypes/authRbac.type.d.ts.map +0 -1
- package/dist/authTypes/authRbac.type.js.map +0 -1
- package/dist/authTypes/authSession.type.d.ts.map +0 -1
- package/dist/authTypes/authSession.type.js.map +0 -1
- package/dist/authTypes/authStrategy.type.d.ts +0 -83
- package/dist/authTypes/authStrategy.type.d.ts.map +0 -1
- package/dist/authTypes/authStrategy.type.js +0 -7
- package/dist/authTypes/authStrategy.type.js.map +0 -1
- package/dist/authTypes/authToken.type.d.ts.map +0 -1
- package/dist/authTypes/authToken.type.js.map +0 -1
- package/dist/authTypes/authUser.type.d.ts.map +0 -1
- package/dist/authTypes/authUser.type.js.map +0 -1
- package/dist/authTypes/index.d.ts.map +0 -1
- package/dist/authTypes/index.js.map +0 -1
- package/dist/authUtils/authUtils.helper.d.ts.map +0 -1
- package/dist/authUtils/authUtils.helper.js.map +0 -1
- package/dist/authUtils/index.d.ts.map +0 -1
- package/dist/authUtils/index.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
|
@@ -7,8 +7,22 @@
|
|
|
7
7
|
* Compatible with Node.js ≥ 24 (no external dependencies).
|
|
8
8
|
*/
|
|
9
9
|
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
|
10
|
+
import { ErrorCode } from "@zudojs/errors";
|
|
11
|
+
import { AuthError } from "../authErrors/authError.base.js";
|
|
10
12
|
/** Default salt length in bytes. */
|
|
11
13
|
const SALT_LENGTH = 32;
|
|
14
|
+
/** Accepted range for a caller-supplied salt length, in bytes. */
|
|
15
|
+
export const MIN_SALT_LENGTH = 16;
|
|
16
|
+
export const MAX_SALT_LENGTH = 64;
|
|
17
|
+
/**
|
|
18
|
+
* Maximum accepted password length in bytes.
|
|
19
|
+
*
|
|
20
|
+
* scrypt's cost is set by N/r, not by the input length, so a long password
|
|
21
|
+
* is not a work-factor amplifier — but it is still an unbounded allocation
|
|
22
|
+
* driven by an unauthenticated request body. 1024 bytes is far past any
|
|
23
|
+
* real passphrase.
|
|
24
|
+
*/
|
|
25
|
+
export const MAX_PASSWORD_BYTES = 1024;
|
|
12
26
|
/** Default key length for scrypt. */
|
|
13
27
|
const KEY_LENGTH = 64;
|
|
14
28
|
/** Scrypt parameters (N, r, p). */
|
|
@@ -18,11 +32,30 @@ const SCRYPT_P = 1;
|
|
|
18
32
|
/**
|
|
19
33
|
* Hash a plain-text password.
|
|
20
34
|
*
|
|
21
|
-
* @param password - Plain-text password
|
|
22
|
-
*
|
|
35
|
+
* @param password - Plain-text password. Must be at most
|
|
36
|
+
* {@link MAX_PASSWORD_BYTES} bytes of UTF-8.
|
|
37
|
+
* @param saltLength - Salt length in bytes (default: 32). Must be an integer
|
|
38
|
+
* between {@link MIN_SALT_LENGTH} and {@link MAX_SALT_LENGTH}; `0` would
|
|
39
|
+
* otherwise silently produce unsalted, rainbow-table-able hashes.
|
|
23
40
|
* @returns Hashed password string in format "scrypt$N$r$p$salt$hash"
|
|
41
|
+
* @throws {AuthError} with `ErrorCode.INVALID_INPUT` when the password is
|
|
42
|
+
* not a string, is too long, or the salt length is out of range.
|
|
24
43
|
*/
|
|
25
44
|
export async function hashPassword(password, saltLength = SALT_LENGTH) {
|
|
45
|
+
if (typeof password !== "string") {
|
|
46
|
+
throw new AuthError("Password must be a string.", {
|
|
47
|
+
code: ErrorCode.INVALID_INPUT,
|
|
48
|
+
statusCode: 400,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
if (Buffer.byteLength(password, "utf-8") > MAX_PASSWORD_BYTES) {
|
|
52
|
+
throw new AuthError(`Password exceeds the maximum of ${MAX_PASSWORD_BYTES} bytes.`, { code: ErrorCode.INVALID_INPUT, statusCode: 400 });
|
|
53
|
+
}
|
|
54
|
+
if (!Number.isInteger(saltLength) ||
|
|
55
|
+
saltLength < MIN_SALT_LENGTH ||
|
|
56
|
+
saltLength > MAX_SALT_LENGTH) {
|
|
57
|
+
throw new AuthError(`saltLength must be an integer between ${MIN_SALT_LENGTH} and ${MAX_SALT_LENGTH} bytes.`, { code: ErrorCode.INVALID_INPUT, statusCode: 400 });
|
|
58
|
+
}
|
|
26
59
|
const salt = randomBytes(saltLength).toString("hex");
|
|
27
60
|
const derivedKey = await deriveKey(password, salt, {
|
|
28
61
|
N: SCRYPT_N,
|
|
@@ -37,11 +70,23 @@ export async function hashPassword(password, saltLength = SALT_LENGTH) {
|
|
|
37
70
|
* Accepts the current "scrypt$N$r$p$salt$hash" format as well as the
|
|
38
71
|
* legacy "scrypt<salt>$<hash>" format produced by versions ≤ 0.1.1.
|
|
39
72
|
*
|
|
73
|
+
* Never throws: any input this function cannot make sense of — a
|
|
74
|
+
* non-string, an over-length password (see {@link MAX_PASSWORD_BYTES}), an
|
|
75
|
+
* unparseable hash — is a non-match. Callers are on the request path and
|
|
76
|
+
* treat a `false` as "wrong password", which is the correct outcome for all
|
|
77
|
+
* of those.
|
|
78
|
+
*
|
|
40
79
|
* @param password - Plain-text password to verify
|
|
41
80
|
* @param hashedPassword - Previously hashed password
|
|
42
81
|
* @returns Whether the password matches
|
|
43
82
|
*/
|
|
44
83
|
export async function verifyPassword(password, hashedPassword) {
|
|
84
|
+
if (typeof password !== "string" || typeof hashedPassword !== "string") {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
if (Buffer.byteLength(password, "utf-8") > MAX_PASSWORD_BYTES) {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
45
90
|
const parsed = parseHash(hashedPassword);
|
|
46
91
|
if (!parsed)
|
|
47
92
|
return false;
|
|
@@ -84,6 +129,9 @@ export function needsRehash(hashedPassword) {
|
|
|
84
129
|
* @returns Hex-encoded random string
|
|
85
130
|
*/
|
|
86
131
|
export function generateRandomToken(length = 32) {
|
|
132
|
+
if (!Number.isInteger(length) || length < 16 || length > 1024) {
|
|
133
|
+
throw new AuthError("generateRandomToken length must be an integer between 16 and 1024 bytes.", { code: ErrorCode.INVALID_INPUT, statusCode: 400 });
|
|
134
|
+
}
|
|
87
135
|
return randomBytes(length).toString("hex");
|
|
88
136
|
}
|
|
89
137
|
function parseHash(hashedPassword) {
|
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @module authPassword
|
|
5
5
|
*/
|
|
6
|
-
export { hashPassword, verifyPassword, needsRehash, generateRandomToken, } from "./authPassword.core.js";
|
|
6
|
+
export { hashPassword, verifyPassword, needsRehash, generateRandomToken, MIN_SALT_LENGTH, MAX_SALT_LENGTH, MAX_PASSWORD_BYTES, } from "./authPassword.core.js";
|
|
7
7
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @module authPassword
|
|
5
5
|
*/
|
|
6
|
-
export { hashPassword, verifyPassword, needsRehash, generateRandomToken, } from "./authPassword.core.js";
|
|
6
|
+
export { hashPassword, verifyPassword, needsRehash, generateRandomToken, MIN_SALT_LENGTH, MAX_SALT_LENGTH, MAX_PASSWORD_BYTES, } from "./authPassword.core.js";
|
|
7
7
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory login attempt store.
|
|
3
|
+
*
|
|
4
|
+
* @module authProvider/authAttempt.memory
|
|
5
|
+
*
|
|
6
|
+
* Single-process only: counters are not shared between instances. Back
|
|
7
|
+
* `LoginAttemptStore` with Redis for a real deployment.
|
|
8
|
+
*/
|
|
9
|
+
import type { LoginAttemptStore } from "../authTypes/authAttempt.type.js";
|
|
10
|
+
/**
|
|
11
|
+
* Create an in-memory {@link LoginAttemptStore}.
|
|
12
|
+
*
|
|
13
|
+
* @param options.windowSeconds - Rate-limit window length (default: 60).
|
|
14
|
+
* @param options.purgeIntervalMs - Minimum gap between sweeps of stale
|
|
15
|
+
* entries (default: 60000).
|
|
16
|
+
*/
|
|
17
|
+
export declare function createMemoryLoginAttemptStore(options?: {
|
|
18
|
+
readonly windowSeconds?: number;
|
|
19
|
+
readonly purgeIntervalMs?: number;
|
|
20
|
+
}): LoginAttemptStore;
|
|
21
|
+
//# sourceMappingURL=authAttempt.memory.d.ts.map
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory login attempt store.
|
|
3
|
+
*
|
|
4
|
+
* @module authProvider/authAttempt.memory
|
|
5
|
+
*
|
|
6
|
+
* Single-process only: counters are not shared between instances. Back
|
|
7
|
+
* `LoginAttemptStore` with Redis for a real deployment.
|
|
8
|
+
*/
|
|
9
|
+
const DEFAULT_WINDOW_SECONDS = 60;
|
|
10
|
+
const DEFAULT_PURGE_INTERVAL_MS = 60_000;
|
|
11
|
+
const EMPTY = { failures: 0, attempts: 0 };
|
|
12
|
+
/**
|
|
13
|
+
* Create an in-memory {@link LoginAttemptStore}.
|
|
14
|
+
*
|
|
15
|
+
* @param options.windowSeconds - Rate-limit window length (default: 60).
|
|
16
|
+
* @param options.purgeIntervalMs - Minimum gap between sweeps of stale
|
|
17
|
+
* entries (default: 60000).
|
|
18
|
+
*/
|
|
19
|
+
export function createMemoryLoginAttemptStore(options) {
|
|
20
|
+
const windowMs = (options?.windowSeconds ?? DEFAULT_WINDOW_SECONDS) * 1000;
|
|
21
|
+
const purgeIntervalMs = options?.purgeIntervalMs ?? DEFAULT_PURGE_INTERVAL_MS;
|
|
22
|
+
const entries = new Map();
|
|
23
|
+
let lastPurge = 0;
|
|
24
|
+
function maybePurge(now) {
|
|
25
|
+
if (now - lastPurge < purgeIntervalMs)
|
|
26
|
+
return;
|
|
27
|
+
lastPurge = now;
|
|
28
|
+
for (const [key, entry] of entries) {
|
|
29
|
+
const locked = entry.lockedUntil !== undefined && entry.lockedUntil > now;
|
|
30
|
+
const fresh = now - entry.windowStart < windowMs;
|
|
31
|
+
if (!locked && !fresh && entry.failures === 0) {
|
|
32
|
+
entries.delete(key);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function load(identifier, now) {
|
|
37
|
+
maybePurge(now);
|
|
38
|
+
let entry = entries.get(identifier);
|
|
39
|
+
if (!entry) {
|
|
40
|
+
entry = { failures: 0, attempts: 0, windowStart: now };
|
|
41
|
+
entries.set(identifier, entry);
|
|
42
|
+
}
|
|
43
|
+
if (now - entry.windowStart >= windowMs) {
|
|
44
|
+
entry.windowStart = now;
|
|
45
|
+
entry.attempts = 0;
|
|
46
|
+
}
|
|
47
|
+
if (entry.lockedUntil !== undefined && entry.lockedUntil <= now) {
|
|
48
|
+
// Lockout lapsed: clear it and the failure streak that caused it.
|
|
49
|
+
delete entry.lockedUntil;
|
|
50
|
+
entry.failures = 0;
|
|
51
|
+
}
|
|
52
|
+
return entry;
|
|
53
|
+
}
|
|
54
|
+
function snapshot(entry) {
|
|
55
|
+
return entry.lockedUntil !== undefined
|
|
56
|
+
? {
|
|
57
|
+
failures: entry.failures,
|
|
58
|
+
attempts: entry.attempts,
|
|
59
|
+
lockedUntil: entry.lockedUntil,
|
|
60
|
+
}
|
|
61
|
+
: { failures: entry.failures, attempts: entry.attempts };
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
async get(identifier) {
|
|
65
|
+
const now = Date.now();
|
|
66
|
+
if (!entries.has(identifier)) {
|
|
67
|
+
maybePurge(now);
|
|
68
|
+
return EMPTY;
|
|
69
|
+
}
|
|
70
|
+
return snapshot(load(identifier, now));
|
|
71
|
+
},
|
|
72
|
+
async recordAttempt(identifier) {
|
|
73
|
+
const entry = load(identifier, Date.now());
|
|
74
|
+
entry.attempts++;
|
|
75
|
+
return snapshot(entry);
|
|
76
|
+
},
|
|
77
|
+
async recordFailure(identifier) {
|
|
78
|
+
const entry = load(identifier, Date.now());
|
|
79
|
+
entry.failures++;
|
|
80
|
+
return snapshot(entry);
|
|
81
|
+
},
|
|
82
|
+
async lock(identifier, until) {
|
|
83
|
+
const entry = load(identifier, Date.now());
|
|
84
|
+
entry.lockedUntil = until;
|
|
85
|
+
},
|
|
86
|
+
async reset(identifier) {
|
|
87
|
+
entries.delete(identifier);
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
//# sourceMappingURL=authAttempt.memory.js.map
|
|
@@ -4,12 +4,15 @@
|
|
|
4
4
|
* @module authProvider/authProvider
|
|
5
5
|
*/
|
|
6
6
|
import type { AuthUser, UserCredentials, UserId } from "../authTypes/authUser.type.js";
|
|
7
|
-
import type { TokenPair, TokenConfig, TokenRevocationStore } from "../authTypes/authToken.type.js";
|
|
7
|
+
import type { TokenPair, TokenPayload, TokenConfig, TokenRevocationStore } from "../authTypes/authToken.type.js";
|
|
8
8
|
import type { SessionStore, SessionId } from "../authTypes/authSession.type.js";
|
|
9
|
-
import type {
|
|
9
|
+
import type { LoginThrottleConfig } from "../authTypes/authAttempt.type.js";
|
|
10
|
+
import type { GuardContext, GuardResult } from "../authTypes/authRbac.type.js";
|
|
10
11
|
import type { PermissionEngine } from "@zudojs/permissions";
|
|
11
|
-
/** User lookup function provided by the consumer. */
|
|
12
|
+
/** User lookup function provided by the consumer, keyed by login identifier. */
|
|
12
13
|
export type UserLookup = (identifier: string) => Promise<AuthUser | null>;
|
|
14
|
+
/** User lookup function provided by the consumer, keyed by user id. */
|
|
15
|
+
export type UserByIdLookup = (userId: UserId) => Promise<AuthUser | null>;
|
|
13
16
|
/** Password verifier function provided by the consumer. */
|
|
14
17
|
export type PasswordVerifier = (userId: UserId, password: string) => Promise<boolean>;
|
|
15
18
|
/**
|
|
@@ -20,19 +23,52 @@ export interface AuthServiceConfig {
|
|
|
20
23
|
readonly token: TokenConfig;
|
|
21
24
|
/** Session store */
|
|
22
25
|
readonly sessionStore: SessionStore;
|
|
23
|
-
/** User lookup function */
|
|
26
|
+
/** User lookup function, keyed by the identifier submitted at login */
|
|
24
27
|
readonly findUser: UserLookup;
|
|
28
|
+
/**
|
|
29
|
+
* User lookup keyed by user id (the `sub` claim).
|
|
30
|
+
*
|
|
31
|
+
* Used by `refresh()` to re-load the user on every rotation so that
|
|
32
|
+
* deactivation and role changes take effect instead of being frozen into
|
|
33
|
+
* the refresh token for its whole lifetime.
|
|
34
|
+
*
|
|
35
|
+
* Required. `findUser` is keyed by the login identifier, which for most
|
|
36
|
+
* deployments is an email or username rather than an id — silently reusing
|
|
37
|
+
* it here would make every refresh fail closed at runtime. Requiring this
|
|
38
|
+
* surfaces the mismatch at compile time instead. If your `findUser` really
|
|
39
|
+
* is id-keyed, pass it for both.
|
|
40
|
+
*/
|
|
41
|
+
readonly findUserById: UserByIdLookup;
|
|
25
42
|
/** Password verifier function */
|
|
26
43
|
readonly verifyPassword: PasswordVerifier;
|
|
27
|
-
/** Session TTL in seconds */
|
|
44
|
+
/** Session idle TTL in seconds */
|
|
28
45
|
readonly sessionTtlSeconds: number;
|
|
46
|
+
/**
|
|
47
|
+
* Absolute maximum session lifetime in seconds. Without it, a session that
|
|
48
|
+
* is used at least once per idle window never expires.
|
|
49
|
+
*/
|
|
50
|
+
readonly absoluteSessionTtlSeconds?: number;
|
|
29
51
|
/** Optional permission engine */
|
|
30
52
|
readonly permissions?: PermissionEngine;
|
|
31
53
|
/**
|
|
32
54
|
* Optional revocation store. When provided, `refresh()` rotates refresh
|
|
33
|
-
* tokens: the used token's `jti` is revoked so it cannot be
|
|
55
|
+
* tokens atomically: the used token's `jti` is revoked so it cannot be
|
|
56
|
+
* replayed, and a replay attempt destroys the user's sessions.
|
|
34
57
|
*/
|
|
35
58
|
readonly revocationStore?: TokenRevocationStore;
|
|
59
|
+
/** Optional brute-force lockout and login rate limiting. */
|
|
60
|
+
readonly loginThrottle?: LoginThrottleConfig;
|
|
61
|
+
/**
|
|
62
|
+
* Allow `checkAccess()` to fall back to the built-in `simpleGuard` when no
|
|
63
|
+
* `permissions` engine is configured.
|
|
64
|
+
*
|
|
65
|
+
* The fallback grants a resource owner *every* permission and grants the
|
|
66
|
+
* `admin` role everything, so it is opt-in: without this flag,
|
|
67
|
+
* `checkAccess()` throws instead of silently returning `allowed: true`.
|
|
68
|
+
*/
|
|
69
|
+
readonly allowInsecureFallbackGuard?: boolean;
|
|
70
|
+
/** Role name the fallback guard treats as superuser (default: "admin"). */
|
|
71
|
+
readonly fallbackAdminRole?: string;
|
|
36
72
|
}
|
|
37
73
|
/**
|
|
38
74
|
* Auth service interface.
|
|
@@ -42,10 +78,17 @@ export interface AuthService {
|
|
|
42
78
|
readonly userAgent?: string;
|
|
43
79
|
readonly ip?: string;
|
|
44
80
|
}): Promise<LoginResult>;
|
|
45
|
-
|
|
81
|
+
/**
|
|
82
|
+
* Verify an access token and return its payload.
|
|
83
|
+
*
|
|
84
|
+
* Async because a token carrying a `sid` claim is only accepted while its
|
|
85
|
+
* session is still alive.
|
|
86
|
+
*/
|
|
87
|
+
verifyToken(token: string): Promise<TokenPayload>;
|
|
46
88
|
refresh(refreshToken: string): Promise<TokenPair>;
|
|
47
|
-
logout(sessionId: SessionId): Promise<void>;
|
|
48
|
-
|
|
89
|
+
logout(sessionId: SessionId, refreshToken?: string): Promise<void>;
|
|
90
|
+
logoutAll(userId: UserId): Promise<void>;
|
|
91
|
+
checkAccess(context: GuardContext): Promise<GuardResult>;
|
|
49
92
|
hashPassword(password: string): Promise<string>;
|
|
50
93
|
verifyPasswordHash(password: string, hash: string): Promise<boolean>;
|
|
51
94
|
}
|
|
@@ -5,57 +5,165 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { hashPassword, verifyPassword, } from "../authPassword/authPassword.core.js";
|
|
7
7
|
import { createTokenPair, verifyAccessToken, verifyRefreshToken, } from "../authToken/authToken.core.js";
|
|
8
|
-
import { InvalidCredentialsError, TokenExpiredError, TokenInvalidError, TokenRevokedError,
|
|
8
|
+
import { AccountDeactivatedError, AccountLockedError, AuthConfigurationError, AuthRateLimitError, InvalidCredentialsError, SessionExpiredError, TokenExpiredError, TokenInvalidError, TokenRevokedError, } from "../authErrors/authError.base.js";
|
|
9
|
+
/**
|
|
10
|
+
* A syntactically valid hash that no password matches.
|
|
11
|
+
*
|
|
12
|
+
* Verifying against it costs the same scrypt work as a real verification, so
|
|
13
|
+
* the unknown-user path takes comparable time to the wrong-password path and
|
|
14
|
+
* the response time does not disclose whether an account exists.
|
|
15
|
+
*/
|
|
16
|
+
const DUMMY_PASSWORD_HASH = `scrypt$16384$8$1$${"0".repeat(64)}$${"0".repeat(128)}`;
|
|
17
|
+
const DEFAULT_MAX_FAILED_ATTEMPTS = 5;
|
|
18
|
+
const DEFAULT_LOCKOUT_SECONDS = 900;
|
|
19
|
+
const DEFAULT_MAX_ATTEMPTS_PER_WINDOW = 20;
|
|
20
|
+
const DEFAULT_WINDOW_SECONDS = 60;
|
|
9
21
|
/**
|
|
10
22
|
* Create an auth service.
|
|
11
23
|
*/
|
|
12
24
|
export function createAuthService(config) {
|
|
13
|
-
const { token: tokenConfig, sessionStore, findUser, verifyPassword: verifyPwd, sessionTtlSeconds, permissions, revocationStore, } = config;
|
|
25
|
+
const { token: tokenConfig, sessionStore, findUser, findUserById, verifyPassword: verifyPwd, sessionTtlSeconds, absoluteSessionTtlSeconds, permissions, revocationStore, loginThrottle, allowInsecureFallbackGuard, fallbackAdminRole, } = config;
|
|
26
|
+
const maxFailedAttempts = loginThrottle?.maxFailedAttempts ?? DEFAULT_MAX_FAILED_ATTEMPTS;
|
|
27
|
+
const lockoutSeconds = loginThrottle?.lockoutSeconds ?? DEFAULT_LOCKOUT_SECONDS;
|
|
28
|
+
const maxAttemptsPerWindow = loginThrottle?.maxAttemptsPerWindow ?? DEFAULT_MAX_ATTEMPTS_PER_WINDOW;
|
|
29
|
+
const windowSeconds = loginThrottle?.windowSeconds ?? DEFAULT_WINDOW_SECONDS;
|
|
30
|
+
/** Throw if the identifier is locked out or over its attempt budget. */
|
|
31
|
+
async function enforceThrottle(identifier) {
|
|
32
|
+
if (!loginThrottle)
|
|
33
|
+
return;
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const current = await loginThrottle.store.get(identifier);
|
|
36
|
+
if (current.lockedUntil !== undefined && current.lockedUntil > now) {
|
|
37
|
+
throw new AccountLockedError(undefined, {
|
|
38
|
+
retryAfterSeconds: Math.ceil((current.lockedUntil - now) / 1000),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const updated = await loginThrottle.store.recordAttempt(identifier);
|
|
42
|
+
if (updated.attempts > maxAttemptsPerWindow) {
|
|
43
|
+
throw new AuthRateLimitError(undefined, {
|
|
44
|
+
retryAfterSeconds: windowSeconds,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Record a failed authentication and lock the identifier if warranted. */
|
|
49
|
+
async function recordFailure(identifier) {
|
|
50
|
+
if (!loginThrottle)
|
|
51
|
+
return;
|
|
52
|
+
const updated = await loginThrottle.store.recordFailure(identifier);
|
|
53
|
+
if (updated.failures >= maxFailedAttempts) {
|
|
54
|
+
await loginThrottle.store.lock(identifier, Date.now() + lockoutSeconds * 1000);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Reject the token unless the session it was issued against is still
|
|
59
|
+
* alive; refresh the session's idle timer when it is.
|
|
60
|
+
*/
|
|
61
|
+
async function requireLiveSession(payload) {
|
|
62
|
+
const sid = payload.sid;
|
|
63
|
+
// Tokens minted by `createTokenPair` directly carry no `sid`; they cannot
|
|
64
|
+
// be forged, and there is no session to check for them.
|
|
65
|
+
if (!sid)
|
|
66
|
+
return undefined;
|
|
67
|
+
const session = await sessionStore.get(sid);
|
|
68
|
+
if (!session) {
|
|
69
|
+
throw new SessionExpiredError("Session is no longer active");
|
|
70
|
+
}
|
|
71
|
+
await sessionStore.touch(sid);
|
|
72
|
+
return sid;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Atomically claim the used refresh token id.
|
|
76
|
+
*
|
|
77
|
+
* @returns true when this call was the one that revoked it.
|
|
78
|
+
*/
|
|
79
|
+
async function claimRefreshToken(store, jti, exp) {
|
|
80
|
+
if (store.revokeIfNotRevoked) {
|
|
81
|
+
return store.revokeIfNotRevoked(jti, exp);
|
|
82
|
+
}
|
|
83
|
+
// Racy fallback for stores predating `revokeIfNotRevoked`.
|
|
84
|
+
if (await store.isRevoked(jti))
|
|
85
|
+
return false;
|
|
86
|
+
await store.revoke(jti, exp);
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
14
89
|
return {
|
|
15
90
|
/**
|
|
16
91
|
* Authenticate a user with credentials and return tokens + session.
|
|
92
|
+
*
|
|
93
|
+
* Unknown user, wrong password and (before the password is proven)
|
|
94
|
+
* deactivated account are indistinguishable to the caller: the same
|
|
95
|
+
* `InvalidCredentialsError` is thrown, and the unknown-user path performs
|
|
96
|
+
* the same scrypt work as the known-user path.
|
|
17
97
|
*/
|
|
18
98
|
async login(credentials, context) {
|
|
19
|
-
const
|
|
20
|
-
|
|
99
|
+
const identifier = credentials.identifier;
|
|
100
|
+
await enforceThrottle(identifier);
|
|
101
|
+
const user = await findUser(identifier);
|
|
102
|
+
let authenticated = false;
|
|
103
|
+
if (user) {
|
|
104
|
+
authenticated = await verifyPwd(user.id, credentials.password);
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
// Burn comparable work so response time does not reveal that the
|
|
108
|
+
// account does not exist.
|
|
109
|
+
await verifyPassword(credentials.password, DUMMY_PASSWORD_HASH);
|
|
110
|
+
}
|
|
111
|
+
if (!user || !authenticated) {
|
|
112
|
+
await recordFailure(identifier);
|
|
21
113
|
throw new InvalidCredentialsError();
|
|
22
114
|
}
|
|
115
|
+
// The credentials were correct, so the attempt counter is cleared even
|
|
116
|
+
// if the account turns out to be unusable.
|
|
117
|
+
await loginThrottle?.store.reset(identifier);
|
|
118
|
+
// Account state is only disclosed once the password has been proven,
|
|
119
|
+
// so it cannot be probed without a valid credential.
|
|
23
120
|
if (!user.active) {
|
|
24
121
|
throw new AccountDeactivatedError();
|
|
25
122
|
}
|
|
26
|
-
const valid = await verifyPwd(user.id, credentials.password);
|
|
27
|
-
if (!valid) {
|
|
28
|
-
throw new InvalidCredentialsError();
|
|
29
|
-
}
|
|
30
|
-
const tokens = createTokenPair(user.id, tokenConfig, {
|
|
31
|
-
roles: user.roles,
|
|
32
|
-
});
|
|
33
123
|
const session = await sessionStore.create({
|
|
34
124
|
userId: user.id,
|
|
35
125
|
userAgent: context?.userAgent,
|
|
36
126
|
ip: context?.ip,
|
|
37
127
|
ttlSeconds: sessionTtlSeconds,
|
|
128
|
+
absoluteTtlSeconds: absoluteSessionTtlSeconds,
|
|
129
|
+
});
|
|
130
|
+
const tokens = createTokenPair(user.id, tokenConfig, {
|
|
131
|
+
roles: user.roles,
|
|
132
|
+
sessionId: session.id,
|
|
38
133
|
});
|
|
39
134
|
return { user, tokens, sessionId: session.id };
|
|
40
135
|
},
|
|
41
136
|
/**
|
|
42
137
|
* Verify an access token and return the payload.
|
|
138
|
+
*
|
|
139
|
+
* @throws {TokenExpiredError} expired token
|
|
140
|
+
* @throws {TokenInvalidError} malformed, mis-signed or wrong-type token
|
|
141
|
+
* @throws {SessionExpiredError} the session the token was issued against
|
|
142
|
+
* has been destroyed (logout) or expired
|
|
43
143
|
*/
|
|
44
|
-
verifyToken(token) {
|
|
144
|
+
async verifyToken(token) {
|
|
45
145
|
const result = verifyAccessToken(token, tokenConfig);
|
|
46
|
-
if (!result.valid) {
|
|
146
|
+
if (!result.valid || !result.payload) {
|
|
47
147
|
if (result.error === "Token expired") {
|
|
48
148
|
throw new TokenExpiredError(result.error);
|
|
49
149
|
}
|
|
50
150
|
throw new TokenInvalidError(result.error ?? "Token verification failed");
|
|
51
151
|
}
|
|
52
|
-
|
|
152
|
+
const payload = result.payload;
|
|
153
|
+
await requireLiveSession(payload);
|
|
154
|
+
return payload;
|
|
53
155
|
},
|
|
54
156
|
/**
|
|
55
157
|
* Refresh an access token using a refresh token.
|
|
56
158
|
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
159
|
+
* Rotation is atomic when the revocation store implements
|
|
160
|
+
* `revokeIfNotRevoked`: exactly one of two concurrent refreshes of the
|
|
161
|
+
* same token wins, and the loser is treated as a replay — the user's
|
|
162
|
+
* sessions are destroyed and `TokenRevokedError` is thrown.
|
|
163
|
+
*
|
|
164
|
+
* The user is re-loaded on every refresh, so deactivation and role
|
|
165
|
+
* changes take effect immediately rather than at the end of the refresh
|
|
166
|
+
* token's 7-day life.
|
|
59
167
|
*/
|
|
60
168
|
async refresh(refreshToken) {
|
|
61
169
|
const result = verifyRefreshToken(refreshToken, tokenConfig);
|
|
@@ -65,27 +173,61 @@ export function createAuthService(config) {
|
|
|
65
173
|
}
|
|
66
174
|
throw new TokenInvalidError("Refresh token is invalid");
|
|
67
175
|
}
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
}
|
|
72
|
-
const tokens = createTokenPair(sub, tokenConfig, { roles });
|
|
176
|
+
const payload = result.payload;
|
|
177
|
+
const { sub, jti, exp } = payload;
|
|
178
|
+
const sid = await requireLiveSession(payload);
|
|
73
179
|
if (revocationStore) {
|
|
74
|
-
await revocationStore
|
|
180
|
+
const claimed = await claimRefreshToken(revocationStore, jti, exp);
|
|
181
|
+
if (!claimed) {
|
|
182
|
+
// Reuse of an already-rotated refresh token: assume the chain is
|
|
183
|
+
// compromised and terminate every session for the user
|
|
184
|
+
// (RFC 6819 §5.2.2.3).
|
|
185
|
+
await sessionStore.destroyAllForUser(sub);
|
|
186
|
+
throw new TokenRevokedError("Refresh token has already been used");
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const user = await findUserById(sub);
|
|
190
|
+
if (!user || !user.active) {
|
|
191
|
+
throw new AccountDeactivatedError("User account is no longer active");
|
|
75
192
|
}
|
|
76
|
-
return
|
|
193
|
+
return createTokenPair(user.id, tokenConfig, {
|
|
194
|
+
roles: user.roles,
|
|
195
|
+
...(sid ? { sessionId: sid } : {}),
|
|
196
|
+
});
|
|
77
197
|
},
|
|
78
198
|
/**
|
|
79
|
-
* Logout — destroy the session
|
|
199
|
+
* Logout — destroy the session, which invalidates every access and
|
|
200
|
+
* refresh token carrying that `sid`.
|
|
201
|
+
*
|
|
202
|
+
* @param refreshToken - The refresh token being surrendered. When given
|
|
203
|
+
* alongside a revocation store, its `jti` is revoked too, so the token
|
|
204
|
+
* stays dead even if it is later presented against a new session.
|
|
80
205
|
*/
|
|
81
|
-
async logout(sessionId) {
|
|
206
|
+
async logout(sessionId, refreshToken) {
|
|
82
207
|
await sessionStore.destroy(sessionId);
|
|
208
|
+
if (refreshToken && revocationStore) {
|
|
209
|
+
const result = verifyRefreshToken(refreshToken, tokenConfig);
|
|
210
|
+
if (result.valid && result.payload) {
|
|
211
|
+
await revocationStore.revoke(result.payload.jti, result.payload.exp);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
/**
|
|
216
|
+
* Sign out everywhere — destroy every session for a user. Tokens bound
|
|
217
|
+
* to those sessions stop verifying immediately.
|
|
218
|
+
*/
|
|
219
|
+
async logoutAll(userId) {
|
|
220
|
+
await sessionStore.destroyAllForUser(userId);
|
|
83
221
|
},
|
|
84
222
|
/**
|
|
85
223
|
* Check if a user has a specific permission.
|
|
86
|
-
* Delegates to @zudojs/permissions engine when configured.
|
|
224
|
+
* Delegates to the @zudojs/permissions engine when configured.
|
|
225
|
+
*
|
|
226
|
+
* @throws {AuthConfigurationError} when no engine is configured and
|
|
227
|
+
* `allowInsecureFallbackGuard` was not set.
|
|
87
228
|
*/
|
|
88
|
-
async checkAccess(
|
|
229
|
+
async checkAccess(context) {
|
|
230
|
+
const { userId, roles: userRoles, permission, resourceOwnerId } = context;
|
|
89
231
|
if (permissions) {
|
|
90
232
|
const actor = { id: userId, roles: [...userRoles] };
|
|
91
233
|
const resource = resourceOwnerId
|
|
@@ -99,8 +241,12 @@ export function createAuthService(config) {
|
|
|
99
241
|
userRoles: [...userRoles],
|
|
100
242
|
};
|
|
101
243
|
}
|
|
102
|
-
|
|
103
|
-
|
|
244
|
+
if (!allowInsecureFallbackGuard) {
|
|
245
|
+
throw new AuthConfigurationError("checkAccess() requires a `permissions` engine. Set " +
|
|
246
|
+
"`allowInsecureFallbackGuard: true` to opt into the built-in " +
|
|
247
|
+
"fallback, which grants resource owners every permission.");
|
|
248
|
+
}
|
|
249
|
+
return simpleGuard(userRoles, permission, userId, resourceOwnerId, fallbackAdminRole ?? "admin");
|
|
104
250
|
},
|
|
105
251
|
/**
|
|
106
252
|
* Hash a password (for user registration).
|
|
@@ -117,17 +263,31 @@ export function createAuthService(config) {
|
|
|
117
263
|
};
|
|
118
264
|
}
|
|
119
265
|
/**
|
|
120
|
-
* Simple fallback guard when no permissions engine is configured
|
|
121
|
-
*
|
|
122
|
-
*
|
|
266
|
+
* Simple fallback guard used only when no permissions engine is configured
|
|
267
|
+
* *and* the consumer opted in with `allowInsecureFallbackGuard`.
|
|
268
|
+
*
|
|
269
|
+
* It grants a resource owner every permission and grants the configured
|
|
270
|
+
* admin role everything — it does no permission matching at all. Every
|
|
271
|
+
* allowed result carries a `reason` naming the fallback so the decision is
|
|
272
|
+
* distinguishable from an engine-backed one in an audit log.
|
|
123
273
|
*/
|
|
124
|
-
function simpleGuard(userRoles, permission, userId, resourceOwnerId) {
|
|
125
|
-
// Ownership check
|
|
274
|
+
function simpleGuard(userRoles, permission, userId, resourceOwnerId, adminRole) {
|
|
275
|
+
// Ownership check — note this ignores `permission` entirely.
|
|
126
276
|
if (resourceOwnerId && resourceOwnerId === userId) {
|
|
127
|
-
return {
|
|
277
|
+
return {
|
|
278
|
+
allowed: true,
|
|
279
|
+
reason: "granted by fallback guard: resource ownership",
|
|
280
|
+
requiredPermission: permission,
|
|
281
|
+
userRoles: [...userRoles],
|
|
282
|
+
};
|
|
128
283
|
}
|
|
129
|
-
if (userRoles.includes(
|
|
130
|
-
return {
|
|
284
|
+
if (userRoles.includes(adminRole)) {
|
|
285
|
+
return {
|
|
286
|
+
allowed: true,
|
|
287
|
+
reason: `granted by fallback guard: "${adminRole}" role`,
|
|
288
|
+
requiredPermission: permission,
|
|
289
|
+
userRoles: [...userRoles],
|
|
290
|
+
};
|
|
131
291
|
}
|
|
132
292
|
return {
|
|
133
293
|
allowed: false,
|
|
@@ -3,5 +3,6 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @module authProvider
|
|
5
5
|
*/
|
|
6
|
-
export { createAuthService, type AuthServiceConfig, type LoginResult, type UserLookup, type PasswordVerifier, } from "./authProvider.core.js";
|
|
6
|
+
export { createAuthService, type AuthService, type AuthServiceConfig, type LoginResult, type UserLookup, type UserByIdLookup, type PasswordVerifier, } from "./authProvider.core.js";
|
|
7
|
+
export { createMemoryLoginAttemptStore } from "./authAttempt.memory.js";
|
|
7
8
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -9,8 +9,18 @@ import type { SessionStore } from "../authTypes/authSession.type.js";
|
|
|
9
9
|
/**
|
|
10
10
|
* Create an in-memory session store.
|
|
11
11
|
*
|
|
12
|
-
* Good for development and testing. For production,
|
|
13
|
-
*
|
|
12
|
+
* Good for development and testing. For production, implement SessionStore
|
|
13
|
+
* with Redis or a database.
|
|
14
|
+
*
|
|
15
|
+
* Expired sessions are reclaimed on any access — `create`, `get` and `touch`
|
|
16
|
+
* all run a rate-limited sweep — so a store that stops receiving logins
|
|
17
|
+
* still releases its memory. The sweep is rate-limited rather than run per
|
|
18
|
+
* call so that a large store does not turn an O(1) lookup into an O(n) walk.
|
|
19
|
+
*
|
|
20
|
+
* @param options.purgeIntervalMs - Minimum gap between full sweeps
|
|
21
|
+
* (default: 60000). Set to 0 to sweep on every access.
|
|
14
22
|
*/
|
|
15
|
-
export declare function createMemorySessionStore(
|
|
23
|
+
export declare function createMemorySessionStore(storeOptions?: {
|
|
24
|
+
readonly purgeIntervalMs?: number;
|
|
25
|
+
}): SessionStore;
|
|
16
26
|
//# sourceMappingURL=authSession.core.d.ts.map
|