@basaltkit/auth 2.2.0 → 3.1.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/README.md +52 -15
- package/dist/apikeys-plugin.d.ts +46 -0
- package/dist/apikeys-plugin.js +72 -7
- package/dist/apikeys.d.ts +5 -0
- package/dist/apikeys.js +10 -0
- package/dist/auth.d.ts +117 -9
- package/dist/auth.js +288 -48
- package/dist/index.d.ts +17 -5
- package/dist/index.js +6 -5
- package/dist/jwt.d.ts +5 -0
- package/dist/oauth-plugin.d.ts +9 -0
- package/dist/oauth-plugin.js +31 -4
- package/dist/oauth.d.ts +41 -4
- package/dist/oauth.js +99 -11
- package/dist/plugin.d.ts +76 -2
- package/dist/plugin.js +107 -16
- package/dist/redis-throttle.d.ts +34 -0
- package/dist/redis-throttle.js +69 -0
- package/dist/routes.d.ts +35 -1
- package/dist/routes.js +77 -29
- package/dist/stores.d.ts +14 -0
- package/dist/stores.js +24 -1
- package/dist/throttle.d.ts +107 -10
- package/dist/throttle.js +127 -17
- package/dist/webauthn-plugin.js +9 -1
- package/package.json +7 -7
package/dist/auth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
1
|
+
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { BasaltError, parseDuration } from '@basaltkit/core';
|
|
3
3
|
import { ScryptPasswordHasher } from './hashing.js';
|
|
4
4
|
import { LoginThrottle } from './throttle.js';
|
|
@@ -69,6 +69,28 @@ export class MfaRequiredError extends BasaltError {
|
|
|
69
69
|
super('AUTH_MFA_REQUIRED', 'A multi-factor authentication code is required.');
|
|
70
70
|
}
|
|
71
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* The route needs a credential obtained with a second factor (MFA policy or
|
|
74
|
+
* `meta.mfa: true`), and the account has MFA enabled: sign in again with a
|
|
75
|
+
* code. Distinct from the 401 {@link MfaRequiredError} of the login itself.
|
|
76
|
+
*/
|
|
77
|
+
export class MfaStepUpRequiredError extends BasaltError {
|
|
78
|
+
status = 403;
|
|
79
|
+
constructor() {
|
|
80
|
+
super('AUTH_MFA_REQUIRED', 'This action requires a sign-in with multi-factor authentication. Sign in again with your code.');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The route needs a credential obtained with a second factor, and the account
|
|
85
|
+
* has not enabled MFA yet: enrol (`/auth/mfa/enroll` + `/activate`), then sign
|
|
86
|
+
* in again with a code.
|
|
87
|
+
*/
|
|
88
|
+
export class MfaEnrollmentRequiredError extends BasaltError {
|
|
89
|
+
status = 403;
|
|
90
|
+
constructor() {
|
|
91
|
+
super('AUTH_MFA_ENROLLMENT_REQUIRED', 'Multi-factor authentication is required for this account. Enable it, then sign in again.');
|
|
92
|
+
}
|
|
93
|
+
}
|
|
72
94
|
/** The supplied MFA (or recovery) code was wrong. */
|
|
73
95
|
export class MfaInvalidCodeError extends BasaltError {
|
|
74
96
|
status = 401;
|
|
@@ -76,6 +98,30 @@ export class MfaInvalidCodeError extends BasaltError {
|
|
|
76
98
|
super('AUTH_MFA_INVALID', 'The authentication code is incorrect.');
|
|
77
99
|
}
|
|
78
100
|
}
|
|
101
|
+
/** MFA is already active: re-enrolling would silently switch it off. Disable it (with a code) first. */
|
|
102
|
+
export class MfaAlreadyEnabledError extends BasaltError {
|
|
103
|
+
status = 409;
|
|
104
|
+
constructor() {
|
|
105
|
+
super('AUTH_MFA_ALREADY_ENABLED', 'MFA is already enabled. Disable it with a valid code before enrolling again.');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* A social / SSO login matched an existing account by email, but the provider
|
|
110
|
+
* did not vouch for that email (unverified), so linking would let anyone who
|
|
111
|
+
* can create an IdP account with the address take the account over.
|
|
112
|
+
*/
|
|
113
|
+
export class SocialLinkRefusedError extends BasaltError {
|
|
114
|
+
status = 403;
|
|
115
|
+
constructor() {
|
|
116
|
+
super('AUTH_SOCIAL_LINK_REFUSED', 'An account with this email already exists and the identity provider did not verify the email. Sign in with your password instead.');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Canonical form of an email identity: trimmed and lowercased. Every lookup,
|
|
121
|
+
* create and throttle key goes through it, so `Bob@acme.test` and
|
|
122
|
+
* `bob@acme.test` are one account.
|
|
123
|
+
*/
|
|
124
|
+
export const canonicalEmail = (email) => email.trim().toLowerCase();
|
|
79
125
|
/** An MFA action needed an enrollment that doesn't exist. */
|
|
80
126
|
export class MfaNotEnrolledError extends BasaltError {
|
|
81
127
|
status = 400;
|
|
@@ -83,6 +129,13 @@ export class MfaNotEnrolledError extends BasaltError {
|
|
|
83
129
|
super('AUTH_MFA_NOT_ENROLLED', 'No MFA enrollment is in progress for this account.');
|
|
84
130
|
}
|
|
85
131
|
}
|
|
132
|
+
/** Authentication methods (`amr`) values Basalt issues. */
|
|
133
|
+
const AMR_VALUE = /^[a-z]{1,16}$/;
|
|
134
|
+
/** Whether a value is a well-formed `amr` list (non-empty, short lowercase words). */
|
|
135
|
+
export const isAmr = (value) => Array.isArray(value) &&
|
|
136
|
+
value.length > 0 &&
|
|
137
|
+
value.length <= 8 &&
|
|
138
|
+
value.every((v) => typeof v === 'string' && AMR_VALUE.test(v));
|
|
86
139
|
export const publicUser = (user) => ({
|
|
87
140
|
id: user.id,
|
|
88
141
|
email: user.email,
|
|
@@ -101,6 +154,7 @@ export class Auth {
|
|
|
101
154
|
hooks;
|
|
102
155
|
throttle;
|
|
103
156
|
ipThrottle;
|
|
157
|
+
requestThrottle;
|
|
104
158
|
tokens;
|
|
105
159
|
verificationTtl;
|
|
106
160
|
resetTtl;
|
|
@@ -133,11 +187,21 @@ export class Auth {
|
|
|
133
187
|
secure: options.sessionCookie?.secure ?? process.env['NODE_ENV'] === 'production',
|
|
134
188
|
};
|
|
135
189
|
this.hooks = options.hooks;
|
|
136
|
-
|
|
190
|
+
const shared = options.throttleStore ? { store: options.throttleStore } : {};
|
|
191
|
+
this.throttle =
|
|
192
|
+
options.loginThrottle === false
|
|
193
|
+
? undefined
|
|
194
|
+
: options.loginThrottle ?? new LoginThrottle({ ...shared, namespace: 'login' });
|
|
137
195
|
this.ipThrottle =
|
|
138
196
|
options.ipLoginThrottle === false
|
|
139
197
|
? undefined
|
|
140
|
-
: options.ipLoginThrottle ??
|
|
198
|
+
: options.ipLoginThrottle ??
|
|
199
|
+
new LoginThrottle({ ...shared, namespace: 'login-ip', maxAttempts: 50, windowMs: 15 * 60_000 });
|
|
200
|
+
this.requestThrottle =
|
|
201
|
+
options.emailRequestThrottle === false
|
|
202
|
+
? undefined
|
|
203
|
+
: options.emailRequestThrottle ??
|
|
204
|
+
new LoginThrottle({ ...shared, namespace: 'email-request', maxAttempts: 3, windowMs: 15 * 60_000 });
|
|
141
205
|
this.tokens = options.tokens ?? new MemoryAuthTokenStore();
|
|
142
206
|
this.verificationTtl = options.verificationTtl ?? '24h';
|
|
143
207
|
this.resetTtl = options.resetTtl ?? '1h';
|
|
@@ -147,7 +211,8 @@ export class Auth {
|
|
|
147
211
|
this.tokenVersions = options.tokenVersions;
|
|
148
212
|
this.enumerationSafeRegister = options.enumerationSafeRegister ?? true;
|
|
149
213
|
}
|
|
150
|
-
async register(
|
|
214
|
+
async register(rawEmail, password) {
|
|
215
|
+
const email = canonicalEmail(rawEmail);
|
|
151
216
|
if (await this.users.findByEmail(email))
|
|
152
217
|
throw new EmailTakenError();
|
|
153
218
|
const user = await this.users.create({
|
|
@@ -163,10 +228,21 @@ export class Auth {
|
|
|
163
228
|
* (a random, unusable password hash), so password login won't work for it
|
|
164
229
|
* until a password is set. A provider-verified email flips `emailVerified`.
|
|
165
230
|
* Returns the tokens and whether the account was just created.
|
|
231
|
+
*
|
|
232
|
+
* Linking to an EXISTING account is refused ({@link SocialLinkRefusedError})
|
|
233
|
+
* unless `emailVerified` is `true` — an unverified provider email proves
|
|
234
|
+
* nothing about who owns the address. When the existing account had never
|
|
235
|
+
* verified its email, whoever registered it first is not trusted either: its
|
|
236
|
+
* password, sessions, refresh tokens and MFA are revoked before it is adopted
|
|
237
|
+
* (`auth:social_account_adopted`). An account with MFA enabled requires
|
|
238
|
+
* `mfaCode` ({@link MfaRequiredError}) unless `mfa: 'skip'` is passed
|
|
239
|
+
* explicitly (only for an IdP that enforces its own second factor).
|
|
166
240
|
*/
|
|
167
|
-
async socialLogin(
|
|
241
|
+
async socialLogin(rawEmail, options = {}) {
|
|
242
|
+
const email = canonicalEmail(rawEmail);
|
|
168
243
|
let user = await this.users.findByEmail(email);
|
|
169
244
|
let created = false;
|
|
245
|
+
const amr = ['fed'];
|
|
170
246
|
if (!user) {
|
|
171
247
|
user = await this.users.create({
|
|
172
248
|
email,
|
|
@@ -174,13 +250,51 @@ export class Auth {
|
|
|
174
250
|
});
|
|
175
251
|
created = true;
|
|
176
252
|
await this.hooks?.emit('auth:registered', { user: publicUser(user) });
|
|
253
|
+
if (options.emailVerified === true && this.users.update) {
|
|
254
|
+
user = (await this.users.update(user.id, { emailVerified: true })) ?? user;
|
|
255
|
+
}
|
|
177
256
|
}
|
|
178
|
-
|
|
179
|
-
|
|
257
|
+
else {
|
|
258
|
+
if (options.emailVerified !== true)
|
|
259
|
+
throw new SocialLinkRefusedError();
|
|
260
|
+
if (!user.emailVerified) {
|
|
261
|
+
user = await this.adoptUnverifiedAccount(user);
|
|
262
|
+
}
|
|
263
|
+
else if (options.mfa !== 'skip' && (await this.isMfaEnabled(user.id))) {
|
|
264
|
+
if (!options.mfaCode)
|
|
265
|
+
throw new MfaRequiredError();
|
|
266
|
+
const key = user.email;
|
|
267
|
+
await this.throttle?.reserve(key);
|
|
268
|
+
if (!(await this.verifyMfaCode(user.id, options.mfaCode))) {
|
|
269
|
+
await this.hooks?.emit('auth:mfa_failed', { userId: user.id });
|
|
270
|
+
throw new MfaInvalidCodeError();
|
|
271
|
+
}
|
|
272
|
+
await this.throttle?.reset(key);
|
|
273
|
+
amr.push('mfa');
|
|
274
|
+
}
|
|
180
275
|
}
|
|
181
|
-
const tokens = await this.issueTokens(user.id);
|
|
276
|
+
const tokens = await this.issueTokens(user.id, undefined, amr);
|
|
182
277
|
await this.hooks?.emit('auth:login', { user: publicUser(user) });
|
|
183
|
-
return { user: publicUser(user), tokens, created };
|
|
278
|
+
return { user: publicUser(user), tokens, created, amr };
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* A provider-verified login is taking over an account whose email was never
|
|
282
|
+
* verified: whoever registered it could be anyone (pre-account hijacking), so
|
|
283
|
+
* every credential they may hold is revoked before the verified owner gets in.
|
|
284
|
+
*/
|
|
285
|
+
async adoptUnverifiedAccount(user) {
|
|
286
|
+
if (!this.users.update)
|
|
287
|
+
throw new SocialLinkRefusedError();
|
|
288
|
+
const adopted = (await this.users.update(user.id, {
|
|
289
|
+
passwordHash: await this.hasher.hash(randomBytes(32).toString('hex')),
|
|
290
|
+
emailVerified: true,
|
|
291
|
+
})) ?? user;
|
|
292
|
+
await this.refreshTokens.revokeAllForUser?.(user.id);
|
|
293
|
+
await this.sessions.deleteAllForUser?.(user.id);
|
|
294
|
+
await this.tokenVersions?.increment(user.id);
|
|
295
|
+
await this.mfa.delete(user.id);
|
|
296
|
+
await this.hooks?.emit('auth:social_account_adopted', { user: publicUser(adopted) });
|
|
297
|
+
return adopted;
|
|
184
298
|
}
|
|
185
299
|
/**
|
|
186
300
|
* Enumeration-safe registration for the public endpoint: creates the account
|
|
@@ -192,7 +306,8 @@ export class Auth {
|
|
|
192
306
|
* With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
|
|
193
307
|
* duplicate instead (the classic, enumerable behavior).
|
|
194
308
|
*/
|
|
195
|
-
async registerSafely(
|
|
309
|
+
async registerSafely(rawEmail, password) {
|
|
310
|
+
const email = canonicalEmail(rawEmail);
|
|
196
311
|
const existing = await this.users.findByEmail(email);
|
|
197
312
|
if (existing) {
|
|
198
313
|
if (!this.enumerationSafeRegister)
|
|
@@ -211,7 +326,7 @@ export class Auth {
|
|
|
211
326
|
}
|
|
212
327
|
/** Verifies credentials without side effects. Null on failure. */
|
|
213
328
|
async attempt(email, password) {
|
|
214
|
-
const user = await this.users.findByEmail(email);
|
|
329
|
+
const user = await this.users.findByEmail(canonicalEmail(email));
|
|
215
330
|
if (!user) {
|
|
216
331
|
// Equalize timing: a missing account must cost the same as a wrong
|
|
217
332
|
// password, or the response time reveals which emails are registered
|
|
@@ -235,36 +350,63 @@ export class Auth {
|
|
|
235
350
|
* required: a correct password with a missing code throws
|
|
236
351
|
* {@link MfaRequiredError} (without counting as a failed attempt), and a
|
|
237
352
|
* wrong code throws {@link MfaInvalidCodeError}.
|
|
353
|
+
*
|
|
354
|
+
* `amr` lists the authentication methods used — `['pwd']`, or
|
|
355
|
+
* `['pwd', 'mfa']` when a second factor was verified. It is also embedded in
|
|
356
|
+
* the access token (`amr` claim) and carried by every refresh of this login;
|
|
357
|
+
* pass it to {@link createSession} so a cookie session carries it too.
|
|
238
358
|
*/
|
|
239
359
|
async login(email, password, mfaCode, context = {}) {
|
|
240
|
-
const key = email
|
|
360
|
+
const key = canonicalEmail(email);
|
|
241
361
|
const ipKey = context.ip ? `ip:${context.ip}` : undefined;
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
this.throttle?.
|
|
362
|
+
// Reserve the attempt BEFORE the (async) verification: the counter moves
|
|
363
|
+
// synchronously, so a parallel burst cannot run more password or MFA
|
|
364
|
+
// guesses than the budget allows. Success gives the reservation back.
|
|
365
|
+
try {
|
|
366
|
+
await this.throttle?.reserve(key);
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
await this.hooks?.emit('auth:locked_out', { email: key });
|
|
370
|
+
throw error;
|
|
371
|
+
}
|
|
372
|
+
if (ipKey && this.ipThrottle) {
|
|
373
|
+
try {
|
|
374
|
+
await this.ipThrottle.reserve(ipKey);
|
|
375
|
+
}
|
|
376
|
+
catch (error) {
|
|
377
|
+
await this.throttle?.release(key);
|
|
378
|
+
await this.hooks?.emit('auth:locked_out', { email: key, ip: context.ip });
|
|
379
|
+
throw error;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
const release = async () => {
|
|
383
|
+
await this.throttle?.release(key);
|
|
247
384
|
if (ipKey)
|
|
248
|
-
this.ipThrottle?.
|
|
385
|
+
await this.ipThrottle?.release(ipKey);
|
|
249
386
|
};
|
|
250
|
-
const user = await this.attempt(
|
|
387
|
+
const user = await this.attempt(key, password);
|
|
251
388
|
if (!user) {
|
|
252
|
-
|
|
253
|
-
await this.hooks?.emit('auth:login_failed', { email });
|
|
389
|
+
await this.hooks?.emit('auth:login_failed', { email: key });
|
|
254
390
|
throw new InvalidCredentialsError();
|
|
255
391
|
}
|
|
392
|
+
const amr = ['pwd'];
|
|
256
393
|
if (await this.isMfaEnabled(user.id)) {
|
|
257
|
-
if (!mfaCode)
|
|
258
|
-
|
|
394
|
+
if (!mfaCode) {
|
|
395
|
+
await release(); // password was correct — not a failure
|
|
396
|
+
throw new MfaRequiredError();
|
|
397
|
+
}
|
|
259
398
|
if (!(await this.verifyMfaCode(user.id, mfaCode))) {
|
|
260
|
-
|
|
399
|
+
await this.hooks?.emit('auth:mfa_failed', { userId: user.id });
|
|
261
400
|
throw new MfaInvalidCodeError();
|
|
262
401
|
}
|
|
402
|
+
amr.push('mfa');
|
|
263
403
|
}
|
|
264
|
-
this.throttle?.reset(key);
|
|
265
|
-
|
|
404
|
+
await this.throttle?.reset(key);
|
|
405
|
+
if (ipKey)
|
|
406
|
+
await this.ipThrottle?.release(ipKey);
|
|
407
|
+
const tokens = await this.issueTokens(user.id, undefined, amr);
|
|
266
408
|
await this.hooks?.emit('auth:login', { user: publicUser(user) });
|
|
267
|
-
return { user: publicUser(user), tokens };
|
|
409
|
+
return { user: publicUser(user), tokens, amr };
|
|
268
410
|
}
|
|
269
411
|
/**
|
|
270
412
|
* Refresh rotation with reuse detection: every refresh consumes the token
|
|
@@ -276,19 +418,36 @@ export class Auth {
|
|
|
276
418
|
const record = await this.refreshTokens.find(hashed);
|
|
277
419
|
if (!record)
|
|
278
420
|
throw new RefreshInvalidError();
|
|
279
|
-
if (record.usedAt !== undefined)
|
|
280
|
-
|
|
281
|
-
throw new RefreshReusedError();
|
|
282
|
-
}
|
|
421
|
+
if (record.usedAt !== undefined)
|
|
422
|
+
return this.reuseDetected(record.userId, record.familyId);
|
|
283
423
|
if (Date.now() >= record.expiresAt)
|
|
284
424
|
throw new RefreshInvalidError();
|
|
425
|
+
// A deleted account must not keep minting tokens from a leftover refresh token.
|
|
426
|
+
if (!(await this.users.findById(record.userId))) {
|
|
427
|
+
await this.refreshTokens.revokeFamily(record.familyId);
|
|
428
|
+
throw new RefreshInvalidError();
|
|
429
|
+
}
|
|
285
430
|
// Compare-and-swap: `false` means another caller consumed this exact token
|
|
286
431
|
// between our read and this write — the very race reuse detection exists for.
|
|
287
432
|
if ((await this.refreshTokens.markUsed(hashed)) === false) {
|
|
433
|
+
return this.reuseDetected(record.userId, record.familyId);
|
|
434
|
+
}
|
|
435
|
+
const pair = await this.issueTokens(record.userId, record.familyId, amrOfFamily(record.familyId));
|
|
436
|
+
// The consumed token is the witness that the family is still alive:
|
|
437
|
+
// revokeFamily/revokeAllForUser delete every row of it. If a concurrent
|
|
438
|
+
// revocation (a reuse loser, a logout, a logout-everywhere) ran between our
|
|
439
|
+
// CAS and the insert above, the row is gone — revoke again so the token we
|
|
440
|
+
// just stored does not outlive its family, and refuse.
|
|
441
|
+
if (!(await this.refreshTokens.find(hashed))) {
|
|
288
442
|
await this.refreshTokens.revokeFamily(record.familyId);
|
|
289
443
|
throw new RefreshReusedError();
|
|
290
444
|
}
|
|
291
|
-
return
|
|
445
|
+
return pair;
|
|
446
|
+
}
|
|
447
|
+
async reuseDetected(userId, familyId) {
|
|
448
|
+
await this.refreshTokens.revokeFamily(familyId);
|
|
449
|
+
await this.hooks?.emit('auth:refresh_reused', { userId, familyId });
|
|
450
|
+
throw new RefreshReusedError();
|
|
292
451
|
}
|
|
293
452
|
/** Revokes a refresh family — logout for token-based clients. */
|
|
294
453
|
async revoke(refreshToken) {
|
|
@@ -317,14 +476,49 @@ export class Auth {
|
|
|
317
476
|
}
|
|
318
477
|
/**
|
|
319
478
|
* Revokes every access token issued so far for the user (logout-everywhere),
|
|
320
|
-
*
|
|
321
|
-
*
|
|
479
|
+
* revoking every refresh token and server-side session (when the stores
|
|
480
|
+
* implement `revokeAllForUser` / `deleteAllForUser`, as the bundled ones do)
|
|
481
|
+
* and bumping the token version so outstanding access tokens die too (needs a
|
|
482
|
+
* {@link TokenVersionStore}; without one, access tokens live until their TTL).
|
|
322
483
|
*/
|
|
323
484
|
async revokeAllTokens(userId) {
|
|
485
|
+
await this.refreshTokens.revokeAllForUser?.(userId);
|
|
486
|
+
await this.sessions.deleteAllForUser?.(userId);
|
|
324
487
|
await this.tokenVersions?.increment(userId);
|
|
325
488
|
}
|
|
326
|
-
|
|
327
|
-
|
|
489
|
+
/**
|
|
490
|
+
* Creates a server-side session. With `amr` (from {@link login}), the
|
|
491
|
+
* returned id — the value to put in the cookie — also carries those
|
|
492
|
+
* authentication methods, HMAC-signed with the auth secret so a client cannot
|
|
493
|
+
* add `mfa` to a password-only session. Stores are unaffected: they only
|
|
494
|
+
* ever see the random part.
|
|
495
|
+
*/
|
|
496
|
+
async createSession(userId, options = {}) {
|
|
497
|
+
const record = await this.sessions.create(userId, parseDuration(this.sessionTtl));
|
|
498
|
+
const amr = options.amr ? [...options.amr] : undefined;
|
|
499
|
+
if (!amr || !isAmr(amr))
|
|
500
|
+
return record;
|
|
501
|
+
const tag = amr.join('+');
|
|
502
|
+
return { ...record, id: `${record.id}.${tag}.${this.sessionTagSignature(record.id, tag)}` };
|
|
503
|
+
}
|
|
504
|
+
sessionTagSignature(rawId, tag) {
|
|
505
|
+
return createHmac('sha256', this.secret).update(`basalt-session-amr\u0000${rawId}.${tag}`).digest('base64url');
|
|
506
|
+
}
|
|
507
|
+
/** Splits a session id minted by {@link createSession} into the store id and its signed `amr`. */
|
|
508
|
+
parseSessionId(sessionId) {
|
|
509
|
+
const parts = sessionId.split('.');
|
|
510
|
+
if (parts.length !== 3)
|
|
511
|
+
return { rawId: sessionId };
|
|
512
|
+
const [rawId, tag, signature] = parts;
|
|
513
|
+
const expected = Buffer.from(this.sessionTagSignature(rawId, tag));
|
|
514
|
+
const received = Buffer.from(signature);
|
|
515
|
+
const amr = tag.split('+');
|
|
516
|
+
if (expected.length !== received.length || !timingSafeEqual(expected, received) || !isAmr(amr)) {
|
|
517
|
+
// Not a signed composite: treat the whole value as an opaque store id
|
|
518
|
+
// (a tampered composite then simply matches no session).
|
|
519
|
+
return { rawId: sessionId };
|
|
520
|
+
}
|
|
521
|
+
return { rawId, amr };
|
|
328
522
|
}
|
|
329
523
|
sessionCookieHeader(sessionId) {
|
|
330
524
|
const ttlMs = parseDuration(this.sessionTtl);
|
|
@@ -348,12 +542,24 @@ export class Auth {
|
|
|
348
542
|
return `${cookie.name}=; Path=${cookie.path};${cookie.httpOnly ? ' HttpOnly;' : ''} SameSite=${cookie.sameSite}; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT${cookie.secure ? '; Secure' : ''}`;
|
|
349
543
|
}
|
|
350
544
|
async sessionUser(sessionId) {
|
|
351
|
-
|
|
352
|
-
|
|
545
|
+
return (await this.sessionAuth(sessionId))?.user ?? null;
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* The user of a session plus the authentication methods it was created with
|
|
549
|
+
* (`amr` is absent for sessions created without them, e.g. before this option).
|
|
550
|
+
*/
|
|
551
|
+
async sessionAuth(sessionId) {
|
|
552
|
+
const { rawId, amr } = this.parseSessionId(sessionId);
|
|
553
|
+
const session = await this.sessions.find(rawId);
|
|
554
|
+
const user = session ? await this.users.findById(session.userId) : null;
|
|
555
|
+
if (!user)
|
|
556
|
+
return null;
|
|
557
|
+
return amr ? { user, amr } : { user };
|
|
353
558
|
}
|
|
354
559
|
async logout(sessionId) {
|
|
355
|
-
const
|
|
356
|
-
await this.sessions.
|
|
560
|
+
const { rawId } = this.parseSessionId(sessionId);
|
|
561
|
+
const session = await this.sessions.find(rawId);
|
|
562
|
+
await this.sessions.delete(rawId);
|
|
357
563
|
if (session) {
|
|
358
564
|
const user = await this.users.findById(session.userId);
|
|
359
565
|
if (user)
|
|
@@ -368,8 +574,8 @@ export class Auth {
|
|
|
368
574
|
* whether the email exists.
|
|
369
575
|
*/
|
|
370
576
|
async requestEmailVerification(email) {
|
|
371
|
-
const user = await this.users.findByEmail(email);
|
|
372
|
-
if (!user)
|
|
577
|
+
const user = await this.users.findByEmail(canonicalEmail(email));
|
|
578
|
+
if (!user || !(await this.allowEmailRequest('verify_email', user.id)))
|
|
373
579
|
return null;
|
|
374
580
|
const token = await this.issueOneTimeToken(user.id, 'verify_email', this.verificationTtl);
|
|
375
581
|
await this.hooks?.emit('auth:verify_requested', { user: publicUser(user), token });
|
|
@@ -382,15 +588,28 @@ export class Auth {
|
|
|
382
588
|
await this.hooks?.emit('auth:email_verified', { user: publicUser(user) });
|
|
383
589
|
return publicUser(user);
|
|
384
590
|
}
|
|
591
|
+
/** Per-account budget for reset/verification mails; false = drop silently. */
|
|
592
|
+
async allowEmailRequest(purpose, userId) {
|
|
593
|
+
if (!this.requestThrottle)
|
|
594
|
+
return true;
|
|
595
|
+
try {
|
|
596
|
+
await this.requestThrottle.reserve(`${purpose}:${userId}`);
|
|
597
|
+
return true;
|
|
598
|
+
}
|
|
599
|
+
catch {
|
|
600
|
+
return false;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
385
603
|
// --- password reset ------------------------------------------------------
|
|
386
604
|
/**
|
|
387
605
|
* Starts a password reset: mints a single-use token and emits
|
|
388
|
-
* `auth:password_reset_requested`. Returns null when no account matches
|
|
389
|
-
* the
|
|
606
|
+
* `auth:password_reset_requested`. Returns null when no account matches (or
|
|
607
|
+
* the per-account request budget is spent — the live link then stays valid),
|
|
608
|
+
* so the caller always responds 200 (no account enumeration).
|
|
390
609
|
*/
|
|
391
610
|
async requestPasswordReset(email) {
|
|
392
|
-
const user = await this.users.findByEmail(email);
|
|
393
|
-
if (!user)
|
|
611
|
+
const user = await this.users.findByEmail(canonicalEmail(email));
|
|
612
|
+
if (!user || !(await this.allowEmailRequest('reset_password', user.id)))
|
|
394
613
|
return null;
|
|
395
614
|
const token = await this.issueOneTimeToken(user.id, 'reset_password', this.resetTtl);
|
|
396
615
|
await this.hooks?.emit('auth:password_reset_requested', { user: publicUser(user), token });
|
|
@@ -440,6 +659,10 @@ export class Auth {
|
|
|
440
659
|
const user = await this.users.findById(userId);
|
|
441
660
|
if (!user)
|
|
442
661
|
throw new AuthRequiredError();
|
|
662
|
+
// Overwriting an active record would switch MFA off without a code —
|
|
663
|
+
// exactly what disableMfa() refuses to do.
|
|
664
|
+
if ((await this.mfa.get(userId))?.enabled)
|
|
665
|
+
throw new MfaAlreadyEnabledError();
|
|
443
666
|
const secret = generateTotpSecret();
|
|
444
667
|
await this.mfa.set(userId, { secret: this.encryptMfaSecret(secret), enabled: false, recoveryCodes: [] });
|
|
445
668
|
return {
|
|
@@ -494,6 +717,10 @@ export class Auth {
|
|
|
494
717
|
// its ~90s window (an intercepted code is single-use).
|
|
495
718
|
if (record.lastUsedStep !== undefined && step <= record.lastUsedStep)
|
|
496
719
|
return false;
|
|
720
|
+
// Atomic consume when the store supports it: two parallel requests with
|
|
721
|
+
// the same code must not both pass the read-then-write above.
|
|
722
|
+
if (this.mfa.consumeTotpStep)
|
|
723
|
+
return this.mfa.consumeTotpStep(userId, step);
|
|
497
724
|
record.lastUsedStep = step;
|
|
498
725
|
await this.mfa.set(userId, record);
|
|
499
726
|
return true;
|
|
@@ -502,6 +729,8 @@ export class Auth {
|
|
|
502
729
|
const index = record.recoveryCodes.indexOf(hash);
|
|
503
730
|
if (index === -1)
|
|
504
731
|
return false;
|
|
732
|
+
if (this.mfa.consumeRecoveryCode)
|
|
733
|
+
return this.mfa.consumeRecoveryCode(userId, hash);
|
|
505
734
|
record.recoveryCodes.splice(index, 1); // consume it
|
|
506
735
|
await this.mfa.set(userId, record);
|
|
507
736
|
return true;
|
|
@@ -554,7 +783,10 @@ export class Auth {
|
|
|
554
783
|
throw new AuthTokenInvalidError(); // user vanished between issue and consume
|
|
555
784
|
return user;
|
|
556
785
|
}
|
|
557
|
-
async issueTokens(userId,
|
|
786
|
+
async issueTokens(userId, family, amr) {
|
|
787
|
+
// A new family records the login's authentication methods in its id, so
|
|
788
|
+
// every rotation carries them forward without a store schema change.
|
|
789
|
+
const familyId = family ?? (amr && isAmr(amr) ? `${randomUUID()}.${amr.join('+')}` : randomUUID());
|
|
558
790
|
const refreshToken = randomBytes(32).toString('base64url');
|
|
559
791
|
await this.refreshTokens.create({
|
|
560
792
|
// Persist only the hash; the raw token is returned to the client below.
|
|
@@ -565,8 +797,16 @@ export class Auth {
|
|
|
565
797
|
});
|
|
566
798
|
const tv = this.tokenVersions ? await this.tokenVersions.get(userId) : undefined;
|
|
567
799
|
return {
|
|
568
|
-
accessToken: signJwt({ sub: userId, ...(tv !== undefined ? { tv } : {}) }, { secret: this.secret, expiresIn: this.accessTtl }),
|
|
800
|
+
accessToken: signJwt({ sub: userId, ...(tv !== undefined ? { tv } : {}), ...(amr && isAmr(amr) ? { amr } : {}) }, { secret: this.secret, expiresIn: this.accessTtl }),
|
|
569
801
|
refreshToken,
|
|
570
802
|
};
|
|
571
803
|
}
|
|
572
804
|
}
|
|
805
|
+
/** The `amr` recorded in a refresh family id by {@link Auth} (undefined for older families). */
|
|
806
|
+
function amrOfFamily(familyId) {
|
|
807
|
+
const dot = familyId.lastIndexOf('.');
|
|
808
|
+
if (dot === -1)
|
|
809
|
+
return undefined;
|
|
810
|
+
const amr = familyId.slice(dot + 1).split('+');
|
|
811
|
+
return isAmr(amr) ? amr : undefined;
|
|
812
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,16 +5,28 @@ declare module '@basaltkit/http' {
|
|
|
5
5
|
interface RouteMeta {
|
|
6
6
|
/** `true` requires a session; `false` opts a route out. */
|
|
7
7
|
auth?: boolean;
|
|
8
|
+
/**
|
|
9
|
+
* `true`: the route requires a credential obtained with a second factor
|
|
10
|
+
* (step-up). `false`: exempt from `authPlugin({ requireMfa })`.
|
|
11
|
+
*/
|
|
12
|
+
mfa?: boolean;
|
|
13
|
+
/**
|
|
14
|
+
* The route is about the caller's own account (sign-in, profile, MFA,
|
|
15
|
+
* accepting an invitation), not a tenant's data: tenant-membership guards
|
|
16
|
+
* (`@basaltkit/teams`' `tenantMembershipPlugin`) let non-members through.
|
|
17
|
+
*/
|
|
18
|
+
account?: boolean;
|
|
8
19
|
}
|
|
9
20
|
}
|
|
10
|
-
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, type AuthOptions, type SessionCookieOptions, type TokenPair, } from './auth.js';
|
|
21
|
+
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, canonicalEmail, type AuthOptions, type SessionCookieOptions, type TokenPair, } from './auth.js';
|
|
11
22
|
export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, type TotpOptions, type VerifyTotpOptions, type OtpauthUriInput, } from './totp.js';
|
|
12
|
-
export { authPlugin, AUTH, type AuthPluginOptions } from './plugin.js';
|
|
23
|
+
export { authPlugin, AUTH, CsrfRejectedError, type AuthPluginOptions, type CsrfOptions } from './plugin.js';
|
|
13
24
|
export { ApiKeys, ApiKeyExpirationError, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
|
|
14
|
-
export { apiKeysPlugin, API_KEYS, type ApiKeysPluginOptions } from './apikeys-plugin.js';
|
|
15
|
-
export { authRoutes, apiKeyRoutes, mfaRoutes, type AuthRoutesOptions, type PasswordPolicy, } from './routes.js';
|
|
25
|
+
export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, type ApiKeysPluginOptions, } from './apikeys-plugin.js';
|
|
26
|
+
export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, type AuthRoutesOptions, type PasswordPolicy, } from './routes.js';
|
|
16
27
|
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, type OAuthProvider, type OAuthProfile, type OAuthOptions, } from './oauth.js';
|
|
17
28
|
export { oauthPlugin, oauthRoutes, OAUTH, type OAuthPluginOptions, type OAuthRoutesOptions, } from './oauth-plugin.js';
|
|
18
|
-
export { LoginThrottle, AccountLockedError, type LoginThrottleOptions } from './throttle.js';
|
|
29
|
+
export { LoginThrottle, MemoryThrottleStore, AccountLockedError, type LoginThrottleOptions, type MemoryThrottleStoreOptions, type ThrottleStore, type ThrottleWindow, } from './throttle.js';
|
|
30
|
+
export { RedisThrottleStore, type RedisThrottleClient, type RedisThrottleStoreOptions } from './redis-throttle.js';
|
|
19
31
|
export { WebAuthnService, MemoryPasskeyStore, MemoryWebAuthnChallengeStore, WebAuthnChallengeError, WebAuthnVerificationError, PasskeyNotFoundError, PasskeyClonedError, PasskeyExistsError, WebAuthnSubjectMismatchError, type PasskeyCredential, type StoredChallenge, type PasskeyStore, type WebAuthnChallengeStore, type WebAuthnVerifier, type VerifyRegistrationInput, type VerifiedRegistration, type VerifyAuthenticationInput, type VerifiedAuthentication, type WebAuthnConfig, type WebAuthnServiceOptions, type RegistrationOptions, type AuthenticationOptions, } from './webauthn.js';
|
|
20
32
|
export { webauthnPlugin, WEBAUTHN, type WebAuthnPluginOptions } from './webauthn-plugin.js';
|
package/dist/index.js
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
export { ScryptPasswordHasher } from './hashing.js';
|
|
2
2
|
export { signJwt, verifyJwt, TokenInvalidError, TokenExpiredError, } from './jwt.js';
|
|
3
3
|
export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, } from './stores.js';
|
|
4
|
-
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, } from './auth.js';
|
|
4
|
+
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, canonicalEmail, } from './auth.js';
|
|
5
5
|
export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, } from './totp.js';
|
|
6
|
-
export { authPlugin, AUTH } from './plugin.js';
|
|
6
|
+
export { authPlugin, AUTH, CsrfRejectedError } from './plugin.js';
|
|
7
7
|
export { ApiKeys, ApiKeyExpirationError, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
|
|
8
|
-
export { apiKeysPlugin, API_KEYS } from './apikeys-plugin.js';
|
|
9
|
-
export { authRoutes, apiKeyRoutes, mfaRoutes, } from './routes.js';
|
|
8
|
+
export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, } from './apikeys-plugin.js';
|
|
9
|
+
export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, } from './routes.js';
|
|
10
10
|
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, } from './oauth.js';
|
|
11
11
|
export { oauthPlugin, oauthRoutes, OAUTH, } from './oauth-plugin.js';
|
|
12
|
-
export { LoginThrottle, AccountLockedError } from './throttle.js';
|
|
12
|
+
export { LoginThrottle, MemoryThrottleStore, AccountLockedError, } from './throttle.js';
|
|
13
|
+
export { RedisThrottleStore } from './redis-throttle.js';
|
|
13
14
|
export { WebAuthnService, MemoryPasskeyStore, MemoryWebAuthnChallengeStore, WebAuthnChallengeError, WebAuthnVerificationError, PasskeyNotFoundError, PasskeyClonedError, PasskeyExistsError, WebAuthnSubjectMismatchError, } from './webauthn.js';
|
|
14
15
|
export { webauthnPlugin, WEBAUTHN } from './webauthn-plugin.js';
|
package/dist/jwt.d.ts
CHANGED
|
@@ -13,6 +13,11 @@ export interface JwtClaims {
|
|
|
13
13
|
exp?: number;
|
|
14
14
|
/** Access-token version — checked against TokenVersionStore for revocation. */
|
|
15
15
|
tv?: number;
|
|
16
|
+
/**
|
|
17
|
+
* Authentication methods used at sign-in (RFC 8176 style): `pwd` (password),
|
|
18
|
+
* `fed` (social / SSO provider), `mfa` (a second factor was verified).
|
|
19
|
+
*/
|
|
20
|
+
amr?: string[];
|
|
16
21
|
[claim: string]: unknown;
|
|
17
22
|
}
|
|
18
23
|
/** Signs a compact HS256 JWT — no dependencies, node:crypto only. */
|
package/dist/oauth-plugin.d.ts
CHANGED
|
@@ -23,6 +23,15 @@ export interface OAuthRoutesOptions {
|
|
|
23
23
|
* When omitted, the callback responds with JSON `{ user, accessToken, refreshToken }`.
|
|
24
24
|
*/
|
|
25
25
|
successRedirect?: string;
|
|
26
|
+
/**
|
|
27
|
+
* The HttpOnly cookie that binds a login to the browser that started it.
|
|
28
|
+
* `secure` defaults to production-only; when secure, the cookie is named
|
|
29
|
+
* `__Host-basalt_oauth` (host-only, so a sibling subdomain cannot plant it).
|
|
30
|
+
*/
|
|
31
|
+
bindingCookie?: {
|
|
32
|
+
secure?: boolean;
|
|
33
|
+
maxAgeSeconds?: number;
|
|
34
|
+
};
|
|
26
35
|
}
|
|
27
36
|
/**
|
|
28
37
|
* Ready-made OAuth routes:
|