@basaltkit/auth 1.6.0 → 1.6.2
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 +6 -0
- package/dist/apikeys-plugin.d.ts +37 -0
- package/dist/apikeys-plugin.js +56 -0
- package/dist/apikeys.d.ts +54 -0
- package/dist/apikeys.js +86 -0
- package/dist/auth.d.ts +279 -0
- package/dist/auth.js +535 -0
- package/dist/hashing.d.ts +23 -0
- package/dist/hashing.js +42 -0
- package/dist/index.d.ts +14 -1140
- package/dist/index.js +14 -1798
- package/dist/jwt.d.ts +26 -0
- package/dist/jwt.js +57 -0
- package/dist/oauth-plugin.d.ts +32 -0
- package/dist/oauth-plugin.js +63 -0
- package/dist/oauth.d.ts +115 -0
- package/dist/oauth.js +242 -0
- package/dist/plugin.d.ts +56 -0
- package/dist/plugin.js +44 -0
- package/dist/routes.d.ts +23 -0
- package/dist/routes.js +223 -0
- package/dist/secret-box.d.ts +10 -0
- package/dist/secret-box.js +38 -0
- package/dist/stores.d.ts +196 -0
- package/dist/stores.js +169 -0
- package/dist/throttle.d.ts +32 -0
- package/dist/throttle.js +45 -0
- package/dist/totp.d.ts +40 -0
- package/dist/totp.js +108 -0
- package/dist/webauthn-plugin.d.ts +13 -0
- package/dist/webauthn-plugin.js +17 -0
- package/dist/webauthn.d.ts +219 -0
- package/dist/webauthn.js +248 -0
- package/package.json +11 -12
package/dist/auth.js
ADDED
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { BasaltError, parseDuration } from '@basaltkit/core';
|
|
3
|
+
import { ScryptPasswordHasher } from './hashing.js';
|
|
4
|
+
import { LoginThrottle } from './throttle.js';
|
|
5
|
+
import { signJwt, verifyJwt } from './jwt.js';
|
|
6
|
+
import { generateTotpSecret, matchTotpStep, otpauthUri } from './totp.js';
|
|
7
|
+
import { decryptSecret, deriveKey, encryptSecret } from './secret-box.js';
|
|
8
|
+
import { MemoryAuthTokenStore, MemoryMfaStore, MemoryRefreshTokenStore, MemorySessionStore, } from './stores.js';
|
|
9
|
+
export class InvalidCredentialsError extends BasaltError {
|
|
10
|
+
status = 401;
|
|
11
|
+
constructor() {
|
|
12
|
+
super('AUTH_INVALID_CREDENTIALS', 'Invalid email or password.');
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export class EmailTakenError extends BasaltError {
|
|
16
|
+
status = 409;
|
|
17
|
+
constructor() {
|
|
18
|
+
super('AUTH_EMAIL_TAKEN', 'An account with this email already exists.');
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Thrown at construction when the JWT signing secret is missing or too weak. A
|
|
23
|
+
* short/low-entropy HS256 key can be brute-forced offline, letting an attacker
|
|
24
|
+
* forge access tokens for any account — so this fails closed rather than boot
|
|
25
|
+
* with a guessable key. Use `@basaltkit/env`'s `secret({ minLength: 32 })`.
|
|
26
|
+
*/
|
|
27
|
+
export class WeakJwtSecretError extends BasaltError {
|
|
28
|
+
constructor(reason) {
|
|
29
|
+
super('AUTH_WEAK_SECRET', `The auth signing secret is ${reason}. Set a strong APP_SECRET (>= 32 chars).`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export class RefreshInvalidError extends BasaltError {
|
|
33
|
+
status = 401;
|
|
34
|
+
constructor() {
|
|
35
|
+
super('AUTH_REFRESH_INVALID', 'The refresh token is invalid or expired.');
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** A used refresh token came back — the whole family is revoked. */
|
|
39
|
+
export class RefreshReusedError extends BasaltError {
|
|
40
|
+
status = 401;
|
|
41
|
+
constructor() {
|
|
42
|
+
super('AUTH_REFRESH_REUSED', 'Refresh token reuse detected. All sessions of this family were revoked.');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export class AuthRequiredError extends BasaltError {
|
|
46
|
+
status = 401;
|
|
47
|
+
constructor() {
|
|
48
|
+
super('AUTH_REQUIRED', 'Authentication required.');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** A verification / reset token was unknown, already used, or expired. */
|
|
52
|
+
export class AuthTokenInvalidError extends BasaltError {
|
|
53
|
+
status = 400;
|
|
54
|
+
constructor() {
|
|
55
|
+
super('AUTH_TOKEN_INVALID', 'The link is invalid or has expired. Request a new one.');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** The configured UserSource can't be updated (needed for verification/reset). */
|
|
59
|
+
export class UserUpdateUnsupportedError extends BasaltError {
|
|
60
|
+
status = 500;
|
|
61
|
+
constructor() {
|
|
62
|
+
super('AUTH_UPDATE_UNSUPPORTED', 'The UserSource does not implement update() — required for this flow.');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Credentials were correct but the account has MFA — a code is required. */
|
|
66
|
+
export class MfaRequiredError extends BasaltError {
|
|
67
|
+
status = 401;
|
|
68
|
+
constructor() {
|
|
69
|
+
super('AUTH_MFA_REQUIRED', 'A multi-factor authentication code is required.');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** The supplied MFA (or recovery) code was wrong. */
|
|
73
|
+
export class MfaInvalidCodeError extends BasaltError {
|
|
74
|
+
status = 401;
|
|
75
|
+
constructor() {
|
|
76
|
+
super('AUTH_MFA_INVALID', 'The authentication code is incorrect.');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** An MFA action needed an enrollment that doesn't exist. */
|
|
80
|
+
export class MfaNotEnrolledError extends BasaltError {
|
|
81
|
+
status = 400;
|
|
82
|
+
constructor() {
|
|
83
|
+
super('AUTH_MFA_NOT_ENROLLED', 'No MFA enrollment is in progress for this account.');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export const publicUser = (user) => ({
|
|
87
|
+
id: user.id,
|
|
88
|
+
email: user.email,
|
|
89
|
+
emailVerified: user.emailVerified ?? false,
|
|
90
|
+
});
|
|
91
|
+
export class Auth {
|
|
92
|
+
users;
|
|
93
|
+
hasher;
|
|
94
|
+
sessions;
|
|
95
|
+
refreshTokens;
|
|
96
|
+
secret;
|
|
97
|
+
accessTtl;
|
|
98
|
+
refreshTtl;
|
|
99
|
+
sessionTtl;
|
|
100
|
+
hooks;
|
|
101
|
+
throttle;
|
|
102
|
+
ipThrottle;
|
|
103
|
+
tokens;
|
|
104
|
+
verificationTtl;
|
|
105
|
+
resetTtl;
|
|
106
|
+
mfa;
|
|
107
|
+
mfaIssuer;
|
|
108
|
+
mfaKey;
|
|
109
|
+
tokenVersions;
|
|
110
|
+
enumerationSafeRegister;
|
|
111
|
+
constructor(options) {
|
|
112
|
+
this.users = options.users;
|
|
113
|
+
this.secret = options.secret;
|
|
114
|
+
// Fail closed on a weak signing key. Always reject an empty secret; in
|
|
115
|
+
// production require >= 32 chars (a short HS256 key is offline-forgeable).
|
|
116
|
+
if (!this.secret)
|
|
117
|
+
throw new WeakJwtSecretError('missing');
|
|
118
|
+
if (process.env['NODE_ENV'] === 'production' && this.secret.length < 32) {
|
|
119
|
+
throw new WeakJwtSecretError('too short');
|
|
120
|
+
}
|
|
121
|
+
this.hasher = options.hasher ?? new ScryptPasswordHasher();
|
|
122
|
+
this.sessions = options.sessions ?? new MemorySessionStore();
|
|
123
|
+
this.refreshTokens = options.refreshTokens ?? new MemoryRefreshTokenStore();
|
|
124
|
+
this.accessTtl = options.accessTtl ?? '15m';
|
|
125
|
+
this.refreshTtl = options.refreshTtl ?? '30d';
|
|
126
|
+
this.sessionTtl = options.sessionTtl ?? '30d';
|
|
127
|
+
this.hooks = options.hooks;
|
|
128
|
+
this.throttle = options.loginThrottle === false ? undefined : options.loginThrottle ?? new LoginThrottle();
|
|
129
|
+
this.ipThrottle =
|
|
130
|
+
options.ipLoginThrottle === false
|
|
131
|
+
? undefined
|
|
132
|
+
: options.ipLoginThrottle ?? new LoginThrottle({ maxAttempts: 50, windowMs: 15 * 60_000 });
|
|
133
|
+
this.tokens = options.tokens ?? new MemoryAuthTokenStore();
|
|
134
|
+
this.verificationTtl = options.verificationTtl ?? '24h';
|
|
135
|
+
this.resetTtl = options.resetTtl ?? '1h';
|
|
136
|
+
this.mfa = options.mfa ?? new MemoryMfaStore();
|
|
137
|
+
this.mfaIssuer = options.mfaIssuer ?? 'Basalt';
|
|
138
|
+
this.mfaKey = options.mfaEncryptionKey ? deriveKey(options.mfaEncryptionKey) : undefined;
|
|
139
|
+
this.tokenVersions = options.tokenVersions;
|
|
140
|
+
this.enumerationSafeRegister = options.enumerationSafeRegister ?? true;
|
|
141
|
+
}
|
|
142
|
+
async register(email, password) {
|
|
143
|
+
if (await this.users.findByEmail(email))
|
|
144
|
+
throw new EmailTakenError();
|
|
145
|
+
const user = await this.users.create({
|
|
146
|
+
email,
|
|
147
|
+
passwordHash: await this.hasher.hash(password),
|
|
148
|
+
});
|
|
149
|
+
await this.hooks?.emit('auth:registered', { user: publicUser(user) });
|
|
150
|
+
return publicUser(user);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Logs in an externally-authenticated user (e.g. from an OAuth provider),
|
|
154
|
+
* matched by email — find-or-create. A new account is created **passwordless**
|
|
155
|
+
* (a random, unusable password hash), so password login won't work for it
|
|
156
|
+
* until a password is set. A provider-verified email flips `emailVerified`.
|
|
157
|
+
* Returns the tokens and whether the account was just created.
|
|
158
|
+
*/
|
|
159
|
+
async socialLogin(email, options = {}) {
|
|
160
|
+
let user = await this.users.findByEmail(email);
|
|
161
|
+
let created = false;
|
|
162
|
+
if (!user) {
|
|
163
|
+
user = await this.users.create({
|
|
164
|
+
email,
|
|
165
|
+
passwordHash: await this.hasher.hash(randomBytes(32).toString('hex')),
|
|
166
|
+
});
|
|
167
|
+
created = true;
|
|
168
|
+
await this.hooks?.emit('auth:registered', { user: publicUser(user) });
|
|
169
|
+
}
|
|
170
|
+
if (options.emailVerified && !user.emailVerified && this.users.update) {
|
|
171
|
+
user = (await this.users.update(user.id, { emailVerified: true })) ?? user;
|
|
172
|
+
}
|
|
173
|
+
const tokens = await this.issueTokens(user.id);
|
|
174
|
+
await this.hooks?.emit('auth:login', { user: publicUser(user) });
|
|
175
|
+
return { user: publicUser(user), tokens, created };
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Enumeration-safe registration for the public endpoint: creates the account
|
|
179
|
+
* for a new email, or — when the email is already taken — does equivalent work
|
|
180
|
+
* (so timing doesn't leak) and emits `auth:register_existing_email` so the app
|
|
181
|
+
* can send an out-of-band "you already have an account" email. Returns nothing
|
|
182
|
+
* either way, so the response can't reveal whether the account existed.
|
|
183
|
+
*
|
|
184
|
+
* With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
|
|
185
|
+
* duplicate instead (the classic, enumerable behavior).
|
|
186
|
+
*/
|
|
187
|
+
async registerSafely(email, password) {
|
|
188
|
+
const existing = await this.users.findByEmail(email);
|
|
189
|
+
if (existing) {
|
|
190
|
+
if (!this.enumerationSafeRegister)
|
|
191
|
+
throw new EmailTakenError();
|
|
192
|
+
// Equalize timing with the create path (which hashes), then signal the
|
|
193
|
+
// collision out-of-band — never in the HTTP response.
|
|
194
|
+
await this.hasher.hash(password);
|
|
195
|
+
await this.hooks?.emit('auth:register_existing_email', { email });
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const user = await this.users.create({
|
|
199
|
+
email,
|
|
200
|
+
passwordHash: await this.hasher.hash(password),
|
|
201
|
+
});
|
|
202
|
+
await this.hooks?.emit('auth:registered', { user: publicUser(user) });
|
|
203
|
+
}
|
|
204
|
+
/** Verifies credentials without side effects. Null on failure. */
|
|
205
|
+
async attempt(email, password) {
|
|
206
|
+
const user = await this.users.findByEmail(email);
|
|
207
|
+
if (!user) {
|
|
208
|
+
// Equalize timing: a missing account must cost the same as a wrong
|
|
209
|
+
// password, or the response time reveals which emails are registered
|
|
210
|
+
// (account enumeration). Verify against a throwaway hash and discard.
|
|
211
|
+
await this.hasher.verify(password, await this.dummyHash());
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
return (await this.hasher.verify(password, user.passwordHash)) ? user : null;
|
|
215
|
+
}
|
|
216
|
+
dummyHashPromise;
|
|
217
|
+
/** A valid hash of a throwaway secret, produced once by the configured hasher. */
|
|
218
|
+
dummyHash() {
|
|
219
|
+
return (this.dummyHashPromise ??= this.hasher.hash('basalt-timing-equalizer'));
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Credentials → token pair. Emits auth:login / auth:login_failed. Locks the
|
|
223
|
+
* account after too many failures (see {@link LoginThrottle}); a success
|
|
224
|
+
* clears the counter.
|
|
225
|
+
*
|
|
226
|
+
* When the account has MFA enabled, `mfaCode` (a TOTP or recovery code) is
|
|
227
|
+
* required: a correct password with a missing code throws
|
|
228
|
+
* {@link MfaRequiredError} (without counting as a failed attempt), and a
|
|
229
|
+
* wrong code throws {@link MfaInvalidCodeError}.
|
|
230
|
+
*/
|
|
231
|
+
async login(email, password, mfaCode, context = {}) {
|
|
232
|
+
const key = email.toLowerCase();
|
|
233
|
+
const ipKey = context.ip ? `ip:${context.ip}` : undefined;
|
|
234
|
+
this.throttle?.assertAllowed(key);
|
|
235
|
+
if (ipKey)
|
|
236
|
+
this.ipThrottle?.assertAllowed(ipKey);
|
|
237
|
+
const recordFailure = () => {
|
|
238
|
+
this.throttle?.recordFailure(key);
|
|
239
|
+
if (ipKey)
|
|
240
|
+
this.ipThrottle?.recordFailure(ipKey);
|
|
241
|
+
};
|
|
242
|
+
const user = await this.attempt(email, password);
|
|
243
|
+
if (!user) {
|
|
244
|
+
recordFailure();
|
|
245
|
+
await this.hooks?.emit('auth:login_failed', { email });
|
|
246
|
+
throw new InvalidCredentialsError();
|
|
247
|
+
}
|
|
248
|
+
if (await this.isMfaEnabled(user.id)) {
|
|
249
|
+
if (!mfaCode)
|
|
250
|
+
throw new MfaRequiredError(); // password was correct — not a failure
|
|
251
|
+
if (!(await this.verifyMfaCode(user.id, mfaCode))) {
|
|
252
|
+
recordFailure();
|
|
253
|
+
throw new MfaInvalidCodeError();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
this.throttle?.reset(key);
|
|
257
|
+
const tokens = await this.issueTokens(user.id);
|
|
258
|
+
await this.hooks?.emit('auth:login', { user: publicUser(user) });
|
|
259
|
+
return { user: publicUser(user), tokens };
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Refresh rotation with reuse detection: every refresh consumes the token
|
|
263
|
+
* and issues a new one in the same family. If a consumed token comes back
|
|
264
|
+
* (theft indicator), the whole family is revoked.
|
|
265
|
+
*/
|
|
266
|
+
async refresh(refreshToken) {
|
|
267
|
+
const hashed = this.hashToken(refreshToken);
|
|
268
|
+
const record = await this.refreshTokens.find(hashed);
|
|
269
|
+
if (!record)
|
|
270
|
+
throw new RefreshInvalidError();
|
|
271
|
+
if (record.usedAt !== undefined) {
|
|
272
|
+
await this.refreshTokens.revokeFamily(record.familyId);
|
|
273
|
+
throw new RefreshReusedError();
|
|
274
|
+
}
|
|
275
|
+
if (Date.now() >= record.expiresAt)
|
|
276
|
+
throw new RefreshInvalidError();
|
|
277
|
+
await this.refreshTokens.markUsed(hashed);
|
|
278
|
+
return this.issueTokens(record.userId, record.familyId);
|
|
279
|
+
}
|
|
280
|
+
/** Revokes a refresh family — logout for token-based clients. */
|
|
281
|
+
async revoke(refreshToken) {
|
|
282
|
+
const record = await this.refreshTokens.find(this.hashToken(refreshToken));
|
|
283
|
+
if (record)
|
|
284
|
+
await this.refreshTokens.revokeFamily(record.familyId);
|
|
285
|
+
}
|
|
286
|
+
/** Structural JWT verification only (signature + expiry). */
|
|
287
|
+
verifyAccess(accessToken) {
|
|
288
|
+
return verifyJwt(accessToken, this.secret);
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Verifies the access token AND, when token-version revocation is enabled,
|
|
292
|
+
* rejects a token minted before the user's version was last bumped (i.e.
|
|
293
|
+
* revoked by a password reset / `revokeAllTokens`). Prefer this over
|
|
294
|
+
* {@link verifyAccess} on the request path.
|
|
295
|
+
*/
|
|
296
|
+
async verifyAccessToken(accessToken) {
|
|
297
|
+
const claims = this.verifyAccess(accessToken);
|
|
298
|
+
if (this.tokenVersions) {
|
|
299
|
+
const current = await this.tokenVersions.get(claims.sub);
|
|
300
|
+
if ((claims.tv ?? 0) < current)
|
|
301
|
+
throw new AuthTokenInvalidError();
|
|
302
|
+
}
|
|
303
|
+
return claims;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Revokes every access token issued so far for the user (logout-everywhere),
|
|
307
|
+
* by bumping the token version. No-op unless a {@link TokenVersionStore} is
|
|
308
|
+
* configured. Pair with refresh/session revocation for a full logout.
|
|
309
|
+
*/
|
|
310
|
+
async revokeAllTokens(userId) {
|
|
311
|
+
await this.tokenVersions?.increment(userId);
|
|
312
|
+
}
|
|
313
|
+
async createSession(userId) {
|
|
314
|
+
return this.sessions.create(userId, parseDuration(this.sessionTtl));
|
|
315
|
+
}
|
|
316
|
+
async sessionUser(sessionId) {
|
|
317
|
+
const session = await this.sessions.find(sessionId);
|
|
318
|
+
return session ? this.users.findById(session.userId) : null;
|
|
319
|
+
}
|
|
320
|
+
async logout(sessionId) {
|
|
321
|
+
const session = await this.sessions.find(sessionId);
|
|
322
|
+
await this.sessions.delete(sessionId);
|
|
323
|
+
if (session) {
|
|
324
|
+
const user = await this.users.findById(session.userId);
|
|
325
|
+
if (user)
|
|
326
|
+
await this.hooks?.emit('auth:logout', { user: publicUser(user) });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
// --- email verification --------------------------------------------------
|
|
330
|
+
/**
|
|
331
|
+
* Starts email verification: mints a single-use token and emits
|
|
332
|
+
* `auth:verify_requested` for the app to email. Returns the token (so a
|
|
333
|
+
* caller can build the link) or null if no account matches — never reveals
|
|
334
|
+
* whether the email exists.
|
|
335
|
+
*/
|
|
336
|
+
async requestEmailVerification(email) {
|
|
337
|
+
const user = await this.users.findByEmail(email);
|
|
338
|
+
if (!user)
|
|
339
|
+
return null;
|
|
340
|
+
const token = await this.issueOneTimeToken(user.id, 'verify_email', this.verificationTtl);
|
|
341
|
+
await this.hooks?.emit('auth:verify_requested', { user: publicUser(user), token });
|
|
342
|
+
return { user: publicUser(user), token };
|
|
343
|
+
}
|
|
344
|
+
/** Consumes a verification token and marks the user's email verified. */
|
|
345
|
+
async verifyEmail(token) {
|
|
346
|
+
const record = await this.consumeToken(token, 'verify_email');
|
|
347
|
+
const user = await this.updateUser(record.userId, { emailVerified: true });
|
|
348
|
+
await this.hooks?.emit('auth:email_verified', { user: publicUser(user) });
|
|
349
|
+
return publicUser(user);
|
|
350
|
+
}
|
|
351
|
+
// --- password reset ------------------------------------------------------
|
|
352
|
+
/**
|
|
353
|
+
* Starts a password reset: mints a single-use token and emits
|
|
354
|
+
* `auth:password_reset_requested`. Returns null when no account matches, so
|
|
355
|
+
* the caller always responds 200 (no account enumeration).
|
|
356
|
+
*/
|
|
357
|
+
async requestPasswordReset(email) {
|
|
358
|
+
const user = await this.users.findByEmail(email);
|
|
359
|
+
if (!user)
|
|
360
|
+
return null;
|
|
361
|
+
const token = await this.issueOneTimeToken(user.id, 'reset_password', this.resetTtl);
|
|
362
|
+
await this.hooks?.emit('auth:password_reset_requested', { user: publicUser(user), token });
|
|
363
|
+
return { user: publicUser(user), token };
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Consumes a reset token, sets the new password, and revokes every existing
|
|
367
|
+
* session/refresh token for the user (a reset logs everyone else out).
|
|
368
|
+
*/
|
|
369
|
+
async resetPassword(token, newPassword) {
|
|
370
|
+
const record = await this.consumeToken(token, 'reset_password');
|
|
371
|
+
const user = await this.updateUser(record.userId, {
|
|
372
|
+
passwordHash: await this.hasher.hash(newPassword),
|
|
373
|
+
});
|
|
374
|
+
// A reset must lock out anyone already in — both token-based clients and
|
|
375
|
+
// active server-side sessions (cookie logins survived this before).
|
|
376
|
+
await this.refreshTokens.revokeAllForUser?.(user.id);
|
|
377
|
+
await this.sessions.deleteAllForUser?.(user.id);
|
|
378
|
+
// Bump the token version so outstanding access tokens are rejected before
|
|
379
|
+
// their TTL expires (no-op unless a TokenVersionStore is configured).
|
|
380
|
+
await this.tokenVersions?.increment(user.id);
|
|
381
|
+
await this.hooks?.emit('auth:password_reset', { user: publicUser(user) });
|
|
382
|
+
return publicUser(user);
|
|
383
|
+
}
|
|
384
|
+
// --- MFA (TOTP) ----------------------------------------------------------
|
|
385
|
+
async isMfaEnabled(userId) {
|
|
386
|
+
return (await this.mfa.get(userId))?.enabled ?? false;
|
|
387
|
+
}
|
|
388
|
+
async mfaStatus(userId) {
|
|
389
|
+
const record = await this.mfa.get(userId);
|
|
390
|
+
return { enabled: record?.enabled ?? false, pending: record !== null && !record.enabled };
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Begins MFA enrollment: generates a fresh secret (not yet active) and
|
|
394
|
+
* returns it plus an `otpauth://` URI to render as a QR code. Call
|
|
395
|
+
* {@link activateMfa} with a code from the app to switch it on.
|
|
396
|
+
*/
|
|
397
|
+
/** Encrypt a TOTP secret for storage (no-op when no key is configured). */
|
|
398
|
+
encryptMfaSecret(secret) {
|
|
399
|
+
return this.mfaKey ? encryptSecret(secret, this.mfaKey) : secret;
|
|
400
|
+
}
|
|
401
|
+
/** Decrypt a stored TOTP secret (passes plaintext/legacy values through). */
|
|
402
|
+
decryptMfaSecret(stored) {
|
|
403
|
+
return this.mfaKey ? decryptSecret(stored, this.mfaKey) : stored;
|
|
404
|
+
}
|
|
405
|
+
async enrollMfa(userId) {
|
|
406
|
+
const user = await this.users.findById(userId);
|
|
407
|
+
if (!user)
|
|
408
|
+
throw new AuthRequiredError();
|
|
409
|
+
const secret = generateTotpSecret();
|
|
410
|
+
await this.mfa.set(userId, { secret: this.encryptMfaSecret(secret), enabled: false, recoveryCodes: [] });
|
|
411
|
+
return {
|
|
412
|
+
secret,
|
|
413
|
+
otpauthUri: otpauthUri({ secret, account: user.email, issuer: this.mfaIssuer }),
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Confirms enrollment by checking a code against the pending secret, enables
|
|
418
|
+
* MFA, and returns freshly generated single-use recovery codes (shown once).
|
|
419
|
+
*/
|
|
420
|
+
async activateMfa(userId, code) {
|
|
421
|
+
const record = await this.mfa.get(userId);
|
|
422
|
+
if (!record || record.enabled)
|
|
423
|
+
throw new MfaNotEnrolledError();
|
|
424
|
+
const step = matchTotpStep(this.decryptMfaSecret(record.secret), code);
|
|
425
|
+
if (step === null)
|
|
426
|
+
throw new MfaInvalidCodeError();
|
|
427
|
+
const recoveryCodes = Array.from({ length: 10 }, () => this.generateRecoveryCode());
|
|
428
|
+
await this.mfa.set(userId, {
|
|
429
|
+
secret: record.secret,
|
|
430
|
+
enabled: true,
|
|
431
|
+
recoveryCodes: recoveryCodes.map((c) => this.hashRecoveryCode(c)),
|
|
432
|
+
});
|
|
433
|
+
const user = await this.users.findById(userId);
|
|
434
|
+
if (user)
|
|
435
|
+
await this.hooks?.emit('auth:mfa_enabled', { user: publicUser(user) });
|
|
436
|
+
return { recoveryCodes };
|
|
437
|
+
}
|
|
438
|
+
/** Turns MFA off. Requires a valid current code (or recovery code). */
|
|
439
|
+
async disableMfa(userId, code) {
|
|
440
|
+
if (!(await this.isMfaEnabled(userId)))
|
|
441
|
+
throw new MfaNotEnrolledError();
|
|
442
|
+
if (!(await this.verifyMfaCode(userId, code)))
|
|
443
|
+
throw new MfaInvalidCodeError();
|
|
444
|
+
await this.mfa.delete(userId);
|
|
445
|
+
const user = await this.users.findById(userId);
|
|
446
|
+
if (user)
|
|
447
|
+
await this.hooks?.emit('auth:mfa_disabled', { user: publicUser(user) });
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Verifies a TOTP code or, failing that, a single-use recovery code (which
|
|
451
|
+
* is consumed on success). Returns false unless MFA is enabled.
|
|
452
|
+
*/
|
|
453
|
+
async verifyMfaCode(userId, code) {
|
|
454
|
+
const record = await this.mfa.get(userId);
|
|
455
|
+
if (!record || !record.enabled)
|
|
456
|
+
return false;
|
|
457
|
+
const step = matchTotpStep(this.decryptMfaSecret(record.secret), code);
|
|
458
|
+
if (step !== null) {
|
|
459
|
+
// Anti-replay: a code from a step already used cannot be reused within
|
|
460
|
+
// its ~90s window (an intercepted code is single-use).
|
|
461
|
+
if (record.lastUsedStep !== undefined && step <= record.lastUsedStep)
|
|
462
|
+
return false;
|
|
463
|
+
record.lastUsedStep = step;
|
|
464
|
+
await this.mfa.set(userId, record);
|
|
465
|
+
return true;
|
|
466
|
+
}
|
|
467
|
+
const hash = this.hashRecoveryCode(code);
|
|
468
|
+
const index = record.recoveryCodes.indexOf(hash);
|
|
469
|
+
if (index === -1)
|
|
470
|
+
return false;
|
|
471
|
+
record.recoveryCodes.splice(index, 1); // consume it
|
|
472
|
+
await this.mfa.set(userId, record);
|
|
473
|
+
return true;
|
|
474
|
+
}
|
|
475
|
+
generateRecoveryCode() {
|
|
476
|
+
// 80 bits of entropy (was 40): a leaked recovery-code hash can't be brute
|
|
477
|
+
// forced offline even with a fast/unsalted digest. 20 hex chars, grouped.
|
|
478
|
+
const raw = randomBytes(10).toString('hex');
|
|
479
|
+
return `${raw.slice(0, 5)}-${raw.slice(5, 10)}-${raw.slice(10, 15)}-${raw.slice(15)}`;
|
|
480
|
+
}
|
|
481
|
+
hashRecoveryCode(code) {
|
|
482
|
+
return createHash('sha256').update(code.replace(/-/g, '').toLowerCase()).digest('hex');
|
|
483
|
+
}
|
|
484
|
+
// --- token helpers -------------------------------------------------------
|
|
485
|
+
/** SHA-256 of a bearer secret (one-time token, refresh token) — only this is
|
|
486
|
+
* persisted, so a leak of the token/session table can't be replayed. */
|
|
487
|
+
hashToken(token) {
|
|
488
|
+
return createHash('sha256').update(token).digest('hex');
|
|
489
|
+
}
|
|
490
|
+
async issueOneTimeToken(userId, purpose, ttl) {
|
|
491
|
+
await this.tokens.deleteForUser(userId, purpose); // one live token per purpose
|
|
492
|
+
const token = randomBytes(32).toString('base64url');
|
|
493
|
+
// Store only the hash: a leak of the token table can't be replayed to reset
|
|
494
|
+
// or verify accounts (the raw token lives only in the user's inbox/link).
|
|
495
|
+
await this.tokens.create({
|
|
496
|
+
token: this.hashToken(token),
|
|
497
|
+
userId,
|
|
498
|
+
purpose,
|
|
499
|
+
expiresAt: Date.now() + parseDuration(ttl),
|
|
500
|
+
});
|
|
501
|
+
return token;
|
|
502
|
+
}
|
|
503
|
+
async consumeToken(token, purpose) {
|
|
504
|
+
const hashed = this.hashToken(token);
|
|
505
|
+
const record = await this.tokens.find(hashed);
|
|
506
|
+
if (!record || record.purpose !== purpose || record.usedAt !== undefined || Date.now() >= record.expiresAt) {
|
|
507
|
+
throw new AuthTokenInvalidError();
|
|
508
|
+
}
|
|
509
|
+
await this.tokens.markUsed(hashed);
|
|
510
|
+
return record;
|
|
511
|
+
}
|
|
512
|
+
async updateUser(id, patch) {
|
|
513
|
+
if (!this.users.update)
|
|
514
|
+
throw new UserUpdateUnsupportedError();
|
|
515
|
+
const user = await this.users.update(id, patch);
|
|
516
|
+
if (!user)
|
|
517
|
+
throw new AuthTokenInvalidError(); // user vanished between issue and consume
|
|
518
|
+
return user;
|
|
519
|
+
}
|
|
520
|
+
async issueTokens(userId, familyId = randomUUID()) {
|
|
521
|
+
const refreshToken = randomBytes(32).toString('base64url');
|
|
522
|
+
await this.refreshTokens.create({
|
|
523
|
+
// Persist only the hash; the raw token is returned to the client below.
|
|
524
|
+
token: this.hashToken(refreshToken),
|
|
525
|
+
familyId,
|
|
526
|
+
userId,
|
|
527
|
+
expiresAt: Date.now() + parseDuration(this.refreshTtl),
|
|
528
|
+
});
|
|
529
|
+
const tv = this.tokenVersions ? await this.tokenVersions.get(userId) : undefined;
|
|
530
|
+
return {
|
|
531
|
+
accessToken: signJwt({ sub: userId, ...(tv !== undefined ? { tv } : {}) }, { secret: this.secret, expiresIn: this.accessTtl }),
|
|
532
|
+
refreshToken,
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export interface PasswordHasher {
|
|
2
|
+
hash(plain: string): Promise<string>;
|
|
3
|
+
verify(plain: string, hashed: string): Promise<boolean>;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Default hasher: scrypt from node:crypto — memory-hard, zero dependencies.
|
|
7
|
+
* An argon2id driver can be swapped in via the same contract (native module,
|
|
8
|
+
* left out of the core install).
|
|
9
|
+
*
|
|
10
|
+
* The default cost is N=2^16 (r=8, p=1) — ~64 MiB per hash. The parameters are
|
|
11
|
+
* embedded in every hash, so raising them here never breaks verification of
|
|
12
|
+
* older, cheaper hashes; those simply verify at their stored cost.
|
|
13
|
+
*/
|
|
14
|
+
export declare class ScryptPasswordHasher implements PasswordHasher {
|
|
15
|
+
private readonly params;
|
|
16
|
+
constructor(params?: {
|
|
17
|
+
N: number;
|
|
18
|
+
r: number;
|
|
19
|
+
p: number;
|
|
20
|
+
});
|
|
21
|
+
hash(plain: string): Promise<string>;
|
|
22
|
+
verify(plain: string, hashed: string): Promise<boolean>;
|
|
23
|
+
}
|
package/dist/hashing.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
const scryptAsync = promisify(scrypt);
|
|
4
|
+
// scrypt needs ~128 * N * r bytes; Node's default maxmem (32 MiB) is exceeded
|
|
5
|
+
// at N >= 2^16, which would throw. Raise the ceiling to ~512 MiB so both the
|
|
6
|
+
// default cost and any higher-N hash (up to 2^17) derive and verify cleanly.
|
|
7
|
+
const MAXMEM = 512 * 1024 * 1024;
|
|
8
|
+
/**
|
|
9
|
+
* Default hasher: scrypt from node:crypto — memory-hard, zero dependencies.
|
|
10
|
+
* An argon2id driver can be swapped in via the same contract (native module,
|
|
11
|
+
* left out of the core install).
|
|
12
|
+
*
|
|
13
|
+
* The default cost is N=2^16 (r=8, p=1) — ~64 MiB per hash. The parameters are
|
|
14
|
+
* embedded in every hash, so raising them here never breaks verification of
|
|
15
|
+
* older, cheaper hashes; those simply verify at their stored cost.
|
|
16
|
+
*/
|
|
17
|
+
export class ScryptPasswordHasher {
|
|
18
|
+
params;
|
|
19
|
+
constructor(params = { N: 65536, r: 8, p: 1 }) {
|
|
20
|
+
this.params = params;
|
|
21
|
+
}
|
|
22
|
+
async hash(plain) {
|
|
23
|
+
const salt = randomBytes(16);
|
|
24
|
+
const derived = await scryptAsync(plain, salt, 32, { ...this.params, maxmem: MAXMEM });
|
|
25
|
+
const { N, r, p } = this.params;
|
|
26
|
+
return `scrypt$${N}$${r}$${p}$${salt.toString('base64url')}$${derived.toString('base64url')}`;
|
|
27
|
+
}
|
|
28
|
+
async verify(plain, hashed) {
|
|
29
|
+
const parts = hashed.split('$');
|
|
30
|
+
if (parts.length !== 6 || parts[0] !== 'scrypt')
|
|
31
|
+
return false;
|
|
32
|
+
const [, n, r, p, salt, expected] = parts;
|
|
33
|
+
const derived = await scryptAsync(plain, Buffer.from(salt, 'base64url'), 32, {
|
|
34
|
+
N: Number(n),
|
|
35
|
+
r: Number(r),
|
|
36
|
+
p: Number(p),
|
|
37
|
+
maxmem: MAXMEM,
|
|
38
|
+
});
|
|
39
|
+
const expectedBuffer = Buffer.from(expected, 'base64url');
|
|
40
|
+
return derived.length === expectedBuffer.length && timingSafeEqual(derived, expectedBuffer);
|
|
41
|
+
}
|
|
42
|
+
}
|