@basaltkit/auth 3.1.0 → 4.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/README.md +159 -24
- package/dist/apikeys-plugin.d.ts +11 -1
- package/dist/apikeys-plugin.js +22 -2
- package/dist/auth.d.ts +108 -20
- package/dist/auth.js +170 -41
- package/dist/hashing.d.ts +3 -1
- package/dist/hashing.js +29 -7
- package/dist/index.d.ts +6 -5
- package/dist/index.js +6 -5
- package/dist/jwt.js +13 -1
- package/dist/oauth-plugin.d.ts +12 -1
- package/dist/oauth-plugin.js +6 -5
- package/dist/oauth.d.ts +81 -2
- package/dist/oauth.js +221 -40
- package/dist/plugin.d.ts +6 -1
- package/dist/secret-box.d.ts +80 -8
- package/dist/secret-box.js +178 -27
- package/dist/stores.d.ts +60 -0
- package/dist/stores.js +52 -0
- package/dist/throttle.d.ts +12 -4
- package/dist/throttle.js +16 -4
- package/dist/webauthn-plugin.js +1 -1
- package/dist/webauthn.d.ts +49 -8
- package/dist/webauthn.js +70 -11
- package/package.json +4 -4
package/dist/auth.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
2
|
-
import { BasaltError, parseDuration } from '@basaltkit/core';
|
|
2
|
+
import { BasaltError, isProductionEnvironment, parseDuration } from '@basaltkit/core';
|
|
3
3
|
import { ScryptPasswordHasher } from './hashing.js';
|
|
4
4
|
import { LoginThrottle } from './throttle.js';
|
|
5
5
|
import { signJwt, verifyJwt } from './jwt.js';
|
|
6
6
|
import { generateTotpSecret, matchTotpStep, otpauthUri } from './totp.js';
|
|
7
|
-
import {
|
|
8
|
-
import { MemoryAuthTokenStore, MemoryMfaStore, MemoryRefreshTokenStore, MemorySessionStore, } from './stores.js';
|
|
7
|
+
import { SecretBox, SecretBoxKeyError } from './secret-box.js';
|
|
8
|
+
import { MemoryAccountLinkStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryRefreshTokenStore, MemorySessionStore, } from './stores.js';
|
|
9
9
|
export class InvalidCredentialsError extends BasaltError {
|
|
10
10
|
status = 401;
|
|
11
11
|
constructor() {
|
|
@@ -116,6 +116,35 @@ export class SocialLinkRefusedError extends BasaltError {
|
|
|
116
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
117
|
}
|
|
118
118
|
}
|
|
119
|
+
/**
|
|
120
|
+
* A social / SSO login's provider account conflicts with an existing link: the
|
|
121
|
+
* local account is already linked to a different subject of the same provider
|
|
122
|
+
* (another IdP account asserting the same email), or the subject was bound to
|
|
123
|
+
* another account concurrently.
|
|
124
|
+
*/
|
|
125
|
+
export class AccountLinkConflictError extends BasaltError {
|
|
126
|
+
status = 409;
|
|
127
|
+
constructor() {
|
|
128
|
+
super('AUTH_ACCOUNT_LINK_CONFLICT', 'This account is linked to a different identity at this provider. Sign in with that identity or with your password.');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* A user store holds more than one account whose email differs only in letter
|
|
133
|
+
* case (rows written before emails were canonicalised), so an email lookup
|
|
134
|
+
* cannot tell which account is meant. Stores throw it instead of guessing:
|
|
135
|
+
* resolve the duplicates (e.g. `normalizeAuthUserEmails()` of
|
|
136
|
+
* `@basaltkit/auth-prisma` / `@basaltkit/auth-sqlite` reports them), then the
|
|
137
|
+
* lookup works again. Not exposed to the client.
|
|
138
|
+
*/
|
|
139
|
+
export class AccountEmailAmbiguousError extends BasaltError {
|
|
140
|
+
status = 500;
|
|
141
|
+
expose = false;
|
|
142
|
+
constructor(email) {
|
|
143
|
+
super('AUTH_EMAIL_AMBIGUOUS', `More than one account matches the email "${email}" in different letter cases; merge or rename the duplicates.`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** A provider name / subject usable as a link key part: non-empty, bounded, no NUL. */
|
|
147
|
+
const isLinkPart = (value) => typeof value === 'string' && value.length > 0 && value.length <= 1024 && !value.includes('\0');
|
|
119
148
|
/**
|
|
120
149
|
* Canonical form of an email identity: trimmed and lowercased. Every lookup,
|
|
121
150
|
* create and throttle key goes through it, so `Bob@acme.test` and
|
|
@@ -159,18 +188,20 @@ export class Auth {
|
|
|
159
188
|
verificationTtl;
|
|
160
189
|
resetTtl;
|
|
161
190
|
mfa;
|
|
191
|
+
accountLinks;
|
|
162
192
|
mfaIssuer;
|
|
163
|
-
|
|
193
|
+
mfaBox;
|
|
164
194
|
tokenVersions;
|
|
165
195
|
enumerationSafeRegister;
|
|
166
196
|
constructor(options) {
|
|
167
197
|
this.users = options.users;
|
|
168
198
|
this.secret = options.secret;
|
|
169
199
|
// Fail closed on a weak signing key. Always reject an empty secret; in
|
|
170
|
-
// production
|
|
200
|
+
// production (anything but an explicit NODE_ENV=development/test, unset
|
|
201
|
+
// included) require >= 32 chars (a short HS256 key is offline-forgeable).
|
|
171
202
|
if (!this.secret)
|
|
172
203
|
throw new WeakJwtSecretError('missing');
|
|
173
|
-
if (
|
|
204
|
+
if (isProductionEnvironment() && this.secret.length < 32) {
|
|
174
205
|
throw new WeakJwtSecretError('too short');
|
|
175
206
|
}
|
|
176
207
|
this.hasher = options.hasher ?? new ScryptPasswordHasher();
|
|
@@ -184,7 +215,7 @@ export class Auth {
|
|
|
184
215
|
path: options.sessionCookie?.path ?? '/',
|
|
185
216
|
httpOnly: options.sessionCookie?.httpOnly ?? true,
|
|
186
217
|
sameSite: options.sessionCookie?.sameSite ?? 'Lax',
|
|
187
|
-
secure: options.sessionCookie?.secure ??
|
|
218
|
+
secure: options.sessionCookie?.secure ?? isProductionEnvironment(),
|
|
188
219
|
};
|
|
189
220
|
this.hooks = options.hooks;
|
|
190
221
|
const shared = options.throttleStore ? { store: options.throttleStore } : {};
|
|
@@ -206,8 +237,16 @@ export class Auth {
|
|
|
206
237
|
this.verificationTtl = options.verificationTtl ?? '24h';
|
|
207
238
|
this.resetTtl = options.resetTtl ?? '1h';
|
|
208
239
|
this.mfa = options.mfa ?? new MemoryMfaStore();
|
|
240
|
+
this.accountLinks = options.accountLinks ?? new MemoryAccountLinkStore();
|
|
209
241
|
this.mfaIssuer = options.mfaIssuer ?? 'Basalt';
|
|
210
|
-
|
|
242
|
+
if (options.mfaEncryption && options.mfaEncryptionKey) {
|
|
243
|
+
throw new SecretBoxKeyError('set either mfaEncryption or mfaEncryptionKey, not both.');
|
|
244
|
+
}
|
|
245
|
+
this.mfaBox = options.mfaEncryption
|
|
246
|
+
? new SecretBox(options.mfaEncryption)
|
|
247
|
+
: options.mfaEncryptionKey
|
|
248
|
+
? new SecretBox({ keys: [{ id: 'default', key: options.mfaEncryptionKey }] })
|
|
249
|
+
: undefined;
|
|
211
250
|
this.tokenVersions = options.tokenVersions;
|
|
212
251
|
this.enumerationSafeRegister = options.enumerationSafeRegister ?? true;
|
|
213
252
|
}
|
|
@@ -223,26 +262,54 @@ export class Auth {
|
|
|
223
262
|
return publicUser(user);
|
|
224
263
|
}
|
|
225
264
|
/**
|
|
226
|
-
* Logs in an externally-authenticated user (e.g. from an OAuth provider)
|
|
227
|
-
*
|
|
228
|
-
*
|
|
229
|
-
*
|
|
230
|
-
*
|
|
265
|
+
* Logs in an externally-authenticated user (e.g. from an OAuth provider) —
|
|
266
|
+
* find-or-create. A new account is created **passwordless** (a random,
|
|
267
|
+
* unusable password hash), so password login won't work for it until a
|
|
268
|
+
* password is set. A provider-verified email flips `emailVerified`. Returns
|
|
269
|
+
* the tokens and whether the account was just created.
|
|
270
|
+
*
|
|
271
|
+
* With an `identity` (the provider name and its stable `subject`, which
|
|
272
|
+
* {@link OAuth} always passes) the account is matched by that link first
|
|
273
|
+
* (see {@link AccountLinkStore}): a linked provider account reaches its local
|
|
274
|
+
* account whatever email it asserts today. Without a link, the account is
|
|
275
|
+
* matched by email and the link is recorded — for an existing account only
|
|
276
|
+
* under the rules below. Once an account is linked to a provider, a
|
|
277
|
+
* **different** subject of that provider asserting the same email is refused
|
|
278
|
+
* ({@link AccountLinkConflictError}) unless `subjectConflict: 'link'`.
|
|
231
279
|
*
|
|
232
280
|
* Linking to an EXISTING account is refused ({@link SocialLinkRefusedError})
|
|
233
281
|
* unless `emailVerified` is `true` — an unverified provider email proves
|
|
234
282
|
* nothing about who owns the address. When the existing account had never
|
|
235
283
|
* verified its email, whoever registered it first is not trusted either: its
|
|
236
|
-
* password, sessions, refresh tokens and
|
|
237
|
-
* (`auth:social_account_adopted`). An account with MFA
|
|
238
|
-
* `mfaCode` ({@link MfaRequiredError}) unless `mfa: 'skip'`
|
|
239
|
-
* explicitly (only for an IdP that enforces its own second factor).
|
|
284
|
+
* password, sessions, refresh tokens, MFA and account links are revoked
|
|
285
|
+
* before it is adopted (`auth:social_account_adopted`). An account with MFA
|
|
286
|
+
* enabled requires `mfaCode` ({@link MfaRequiredError}) unless `mfa: 'skip'`
|
|
287
|
+
* is passed explicitly (only for an IdP that enforces its own second factor).
|
|
240
288
|
*/
|
|
241
289
|
async socialLogin(rawEmail, options = {}) {
|
|
242
290
|
const email = canonicalEmail(rawEmail);
|
|
291
|
+
const identity = options.identity;
|
|
292
|
+
if (identity !== undefined) {
|
|
293
|
+
if (!isLinkPart(identity.provider) || !isLinkPart(identity.subject))
|
|
294
|
+
throw new SocialLinkRefusedError();
|
|
295
|
+
}
|
|
296
|
+
const amr = ['fed'];
|
|
297
|
+
// 1. A known provider account: the link decides, not the email.
|
|
298
|
+
if (identity) {
|
|
299
|
+
const link = await this.accountLinks.find(identity.provider, identity.subject);
|
|
300
|
+
if (link) {
|
|
301
|
+
const linked = await this.users.findById(link.userId);
|
|
302
|
+
if (linked) {
|
|
303
|
+
await this.requireMfaForSocial(linked, options, amr);
|
|
304
|
+
return this.finishSocialLogin(linked, false, amr);
|
|
305
|
+
}
|
|
306
|
+
// The account is gone: the stale link must not block a fresh start.
|
|
307
|
+
await this.accountLinks.remove(identity.provider, identity.subject);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
// 2. First login of this provider account: match by email.
|
|
243
311
|
let user = await this.users.findByEmail(email);
|
|
244
312
|
let created = false;
|
|
245
|
-
const amr = ['fed'];
|
|
246
313
|
if (!user) {
|
|
247
314
|
user = await this.users.create({
|
|
248
315
|
email,
|
|
@@ -257,22 +324,49 @@ export class Auth {
|
|
|
257
324
|
else {
|
|
258
325
|
if (options.emailVerified !== true)
|
|
259
326
|
throw new SocialLinkRefusedError();
|
|
327
|
+
if (identity && options.subjectConflict !== 'link' && user.emailVerified) {
|
|
328
|
+
const others = (await this.accountLinks.forUser(user.id)).filter((l) => l.provider === identity.provider && l.subject !== identity.subject);
|
|
329
|
+
if (others.length > 0)
|
|
330
|
+
throw new AccountLinkConflictError();
|
|
331
|
+
}
|
|
260
332
|
if (!user.emailVerified) {
|
|
261
333
|
user = await this.adoptUnverifiedAccount(user);
|
|
262
334
|
}
|
|
263
|
-
else
|
|
264
|
-
|
|
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');
|
|
335
|
+
else {
|
|
336
|
+
await this.requireMfaForSocial(user, options, amr);
|
|
274
337
|
}
|
|
275
338
|
}
|
|
339
|
+
if (identity)
|
|
340
|
+
await this.linkIdentity(identity, user, email);
|
|
341
|
+
return this.finishSocialLogin(user, created, amr);
|
|
342
|
+
}
|
|
343
|
+
/** Records the link; a concurrent first login that bound the subject elsewhere wins. */
|
|
344
|
+
async linkIdentity(identity, user, email) {
|
|
345
|
+
const inserted = await this.accountLinks.create({ ...identity, userId: user.id, email, createdAt: Date.now() });
|
|
346
|
+
if (inserted) {
|
|
347
|
+
await this.hooks?.emit('auth:account_linked', { user: publicUser(user), provider: identity.provider });
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
const existing = await this.accountLinks.find(identity.provider, identity.subject);
|
|
351
|
+
if (existing?.userId !== user.id)
|
|
352
|
+
throw new AccountLinkConflictError();
|
|
353
|
+
}
|
|
354
|
+
/** MFA gate of a social login into an existing account (see {@link socialLogin}). */
|
|
355
|
+
async requireMfaForSocial(user, options, amr) {
|
|
356
|
+
if (options.mfa === 'skip' || !(await this.isMfaEnabled(user.id)))
|
|
357
|
+
return;
|
|
358
|
+
if (!options.mfaCode)
|
|
359
|
+
throw new MfaRequiredError();
|
|
360
|
+
const key = user.email;
|
|
361
|
+
await this.throttle?.reserve(key);
|
|
362
|
+
if (!(await this.verifyMfaCode(user.id, options.mfaCode))) {
|
|
363
|
+
await this.hooks?.emit('auth:mfa_failed', { userId: user.id });
|
|
364
|
+
throw new MfaInvalidCodeError();
|
|
365
|
+
}
|
|
366
|
+
await this.throttle?.reset(key);
|
|
367
|
+
amr.push('mfa');
|
|
368
|
+
}
|
|
369
|
+
async finishSocialLogin(user, created, amr) {
|
|
276
370
|
const tokens = await this.issueTokens(user.id, undefined, amr);
|
|
277
371
|
await this.hooks?.emit('auth:login', { user: publicUser(user) });
|
|
278
372
|
return { user: publicUser(user), tokens, created, amr };
|
|
@@ -293,6 +387,8 @@ export class Auth {
|
|
|
293
387
|
await this.sessions.deleteAllForUser?.(user.id);
|
|
294
388
|
await this.tokenVersions?.increment(user.id);
|
|
295
389
|
await this.mfa.delete(user.id);
|
|
390
|
+
// A provider account linked by whoever registered it is a login credential too.
|
|
391
|
+
await this.accountLinks.deleteAllForUser(user.id);
|
|
296
392
|
await this.hooks?.emit('auth:social_account_adopted', { user: publicUser(adopted) });
|
|
297
393
|
return adopted;
|
|
298
394
|
}
|
|
@@ -532,7 +628,16 @@ export class Auth {
|
|
|
532
628
|
for (const part of cookieHeader.split(';')) {
|
|
533
629
|
const [name, ...rest] = part.trim().split('=');
|
|
534
630
|
if (name === this.sessionCookie.name && rest.length > 0) {
|
|
535
|
-
|
|
631
|
+
// An unreadable cookie (malformed percent-encoding, e.g. tossed by a
|
|
632
|
+
// sibling subdomain) is no credential: the request is anonymous. It
|
|
633
|
+
// must never throw — the enricher runs on every route, public ones
|
|
634
|
+
// included, so a URIError here would 500 the whole site.
|
|
635
|
+
try {
|
|
636
|
+
return decodeURIComponent(rest.join('='));
|
|
637
|
+
}
|
|
638
|
+
catch {
|
|
639
|
+
return null;
|
|
640
|
+
}
|
|
536
641
|
}
|
|
537
642
|
}
|
|
538
643
|
return null;
|
|
@@ -642,19 +747,43 @@ export class Auth {
|
|
|
642
747
|
const record = await this.mfa.get(userId);
|
|
643
748
|
return { enabled: record?.enabled ?? false, pending: record !== null && !record.enabled };
|
|
644
749
|
}
|
|
750
|
+
/** Encrypt a TOTP secret for storage, bound to its user (no-op when no key is configured). */
|
|
751
|
+
encryptMfaSecret(userId, secret) {
|
|
752
|
+
return this.mfaBox ? this.mfaBox.seal(secret, { purpose: 'totp', subject: userId }) : secret;
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Decrypt a stored TOTP secret. With encryption configured, only an envelope
|
|
756
|
+
* sealed for this user opens; plaintext and `v1:` values need the explicit
|
|
757
|
+
* legacy opt-in (otherwise `AUTH_SECRET_UNREADABLE`, failing closed).
|
|
758
|
+
*/
|
|
759
|
+
decryptMfaSecret(userId, stored) {
|
|
760
|
+
return this.mfaBox ? this.mfaBox.open(stored, { purpose: 'totp', subject: userId }) : stored;
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Re-encrypts one user's stored TOTP secret under the active key of
|
|
764
|
+
* `mfaEncryption` — for key rotation, and to migrate `v1:` envelopes or
|
|
765
|
+
* plaintext secrets (reading those needs the matching `legacy` opt-in).
|
|
766
|
+
* Returns `'resealed'` when the row was rewritten, `'current'` when it was
|
|
767
|
+
* already sealed with the active key, `'none'` when the user has no MFA
|
|
768
|
+
* record. Run it over every user id with an MFA row, then drop `legacy`.
|
|
769
|
+
*/
|
|
770
|
+
async reencryptMfaSecret(userId) {
|
|
771
|
+
if (!this.mfaBox)
|
|
772
|
+
throw new SecretBoxKeyError('reencryptMfaSecret needs mfaEncryption (or mfaEncryptionKey).');
|
|
773
|
+
const record = await this.mfa.get(userId);
|
|
774
|
+
if (!record)
|
|
775
|
+
return 'none';
|
|
776
|
+
const resealed = this.mfaBox.reseal(record.secret, { purpose: 'totp', subject: userId });
|
|
777
|
+
if (resealed === null)
|
|
778
|
+
return 'current';
|
|
779
|
+
await this.mfa.set(userId, { ...record, secret: resealed });
|
|
780
|
+
return 'resealed';
|
|
781
|
+
}
|
|
645
782
|
/**
|
|
646
783
|
* Begins MFA enrollment: generates a fresh secret (not yet active) and
|
|
647
784
|
* returns it plus an `otpauth://` URI to render as a QR code. Call
|
|
648
785
|
* {@link activateMfa} with a code from the app to switch it on.
|
|
649
786
|
*/
|
|
650
|
-
/** Encrypt a TOTP secret for storage (no-op when no key is configured). */
|
|
651
|
-
encryptMfaSecret(secret) {
|
|
652
|
-
return this.mfaKey ? encryptSecret(secret, this.mfaKey) : secret;
|
|
653
|
-
}
|
|
654
|
-
/** Decrypt a stored TOTP secret (passes plaintext/legacy values through). */
|
|
655
|
-
decryptMfaSecret(stored) {
|
|
656
|
-
return this.mfaKey ? decryptSecret(stored, this.mfaKey) : stored;
|
|
657
|
-
}
|
|
658
787
|
async enrollMfa(userId) {
|
|
659
788
|
const user = await this.users.findById(userId);
|
|
660
789
|
if (!user)
|
|
@@ -664,7 +793,7 @@ export class Auth {
|
|
|
664
793
|
if ((await this.mfa.get(userId))?.enabled)
|
|
665
794
|
throw new MfaAlreadyEnabledError();
|
|
666
795
|
const secret = generateTotpSecret();
|
|
667
|
-
await this.mfa.set(userId, { secret: this.encryptMfaSecret(secret), enabled: false, recoveryCodes: [] });
|
|
796
|
+
await this.mfa.set(userId, { secret: this.encryptMfaSecret(userId, secret), enabled: false, recoveryCodes: [] });
|
|
668
797
|
return {
|
|
669
798
|
secret,
|
|
670
799
|
otpauthUri: otpauthUri({ secret, account: user.email, issuer: this.mfaIssuer }),
|
|
@@ -678,7 +807,7 @@ export class Auth {
|
|
|
678
807
|
const record = await this.mfa.get(userId);
|
|
679
808
|
if (!record || record.enabled)
|
|
680
809
|
throw new MfaNotEnrolledError();
|
|
681
|
-
const step = matchTotpStep(this.decryptMfaSecret(record.secret), code);
|
|
810
|
+
const step = matchTotpStep(this.decryptMfaSecret(userId, record.secret), code);
|
|
682
811
|
if (step === null)
|
|
683
812
|
throw new MfaInvalidCodeError();
|
|
684
813
|
const recoveryCodes = Array.from({ length: 10 }, () => this.generateRecoveryCode());
|
|
@@ -711,7 +840,7 @@ export class Auth {
|
|
|
711
840
|
const record = await this.mfa.get(userId);
|
|
712
841
|
if (!record || !record.enabled)
|
|
713
842
|
return false;
|
|
714
|
-
const step = matchTotpStep(this.decryptMfaSecret(record.secret), code);
|
|
843
|
+
const step = matchTotpStep(this.decryptMfaSecret(userId, record.secret), code);
|
|
715
844
|
if (step !== null) {
|
|
716
845
|
// Anti-replay: a code from a step already used cannot be reused within
|
|
717
846
|
// its ~90s window (an intercepted code is single-use).
|
package/dist/hashing.d.ts
CHANGED
|
@@ -9,7 +9,9 @@ export interface PasswordHasher {
|
|
|
9
9
|
*
|
|
10
10
|
* The default cost is N=2^16 (r=8, p=1) — ~64 MiB per hash. The parameters are
|
|
11
11
|
* embedded in every hash, so raising them here never breaks verification of
|
|
12
|
-
* older, cheaper hashes; those simply verify at their stored cost.
|
|
12
|
+
* older, cheaper hashes; those simply verify at their stored cost. A stored
|
|
13
|
+
* hash declaring more than N=2^20, r=32, p=16 (or more than 512 MiB) never
|
|
14
|
+
* verifies, so a tampered row cannot pin the CPU.
|
|
13
15
|
*/
|
|
14
16
|
export declare class ScryptPasswordHasher implements PasswordHasher {
|
|
15
17
|
private readonly params;
|
package/dist/hashing.js
CHANGED
|
@@ -5,6 +5,23 @@ const scryptAsync = promisify(scrypt);
|
|
|
5
5
|
// at N >= 2^16, which would throw. Raise the ceiling to ~512 MiB so both the
|
|
6
6
|
// default cost and any higher-N hash (up to 2^17) derive and verify cleanly.
|
|
7
7
|
const MAXMEM = 512 * 1024 * 1024;
|
|
8
|
+
/**
|
|
9
|
+
* Ceilings on the scrypt cost a hash may declare. The parameters are read from
|
|
10
|
+
* the STORED hash, so without a ceiling one planted or corrupted row (`N`, `r`
|
|
11
|
+
* or `p` in the millions) would turn every login attempt on that account into
|
|
12
|
+
* minutes of CPU on the libuv threadpool. Such a hash never verifies.
|
|
13
|
+
*/
|
|
14
|
+
const MAX_N = 2 ** 20;
|
|
15
|
+
const MAX_R = 32;
|
|
16
|
+
const MAX_P = 16;
|
|
17
|
+
/** `true` when `N`/`r`/`p` are sane scrypt parameters within the cost ceilings. */
|
|
18
|
+
function acceptableParams(N, r, p) {
|
|
19
|
+
return (Number.isSafeInteger(N) && N > 1 && N <= MAX_N && (N & (N - 1)) === 0 &&
|
|
20
|
+
Number.isSafeInteger(r) && r >= 1 && r <= MAX_R &&
|
|
21
|
+
Number.isSafeInteger(p) && p >= 1 && p <= MAX_P &&
|
|
22
|
+
128 * N * r <= MAXMEM);
|
|
23
|
+
}
|
|
24
|
+
const DECIMAL = /^[1-9][0-9]{0,9}$/;
|
|
8
25
|
/**
|
|
9
26
|
* Default hasher: scrypt from node:crypto — memory-hard, zero dependencies.
|
|
10
27
|
* An argon2id driver can be swapped in via the same contract (native module,
|
|
@@ -12,12 +29,17 @@ const MAXMEM = 512 * 1024 * 1024;
|
|
|
12
29
|
*
|
|
13
30
|
* The default cost is N=2^16 (r=8, p=1) — ~64 MiB per hash. The parameters are
|
|
14
31
|
* embedded in every hash, so raising them here never breaks verification of
|
|
15
|
-
* older, cheaper hashes; those simply verify at their stored cost.
|
|
32
|
+
* older, cheaper hashes; those simply verify at their stored cost. A stored
|
|
33
|
+
* hash declaring more than N=2^20, r=32, p=16 (or more than 512 MiB) never
|
|
34
|
+
* verifies, so a tampered row cannot pin the CPU.
|
|
16
35
|
*/
|
|
17
36
|
export class ScryptPasswordHasher {
|
|
18
37
|
params;
|
|
19
38
|
constructor(params = { N: 65536, r: 8, p: 1 }) {
|
|
20
39
|
this.params = params;
|
|
40
|
+
if (!acceptableParams(params.N, params.r, params.p)) {
|
|
41
|
+
throw new RangeError(`ScryptPasswordHasher: N must be a power of two <= 2^20, r <= ${MAX_R}, p <= ${MAX_P} and 128*N*r <= 512 MiB`);
|
|
42
|
+
}
|
|
21
43
|
}
|
|
22
44
|
async hash(plain) {
|
|
23
45
|
const salt = randomBytes(16);
|
|
@@ -30,12 +52,12 @@ export class ScryptPasswordHasher {
|
|
|
30
52
|
if (parts.length !== 6 || parts[0] !== 'scrypt')
|
|
31
53
|
return false;
|
|
32
54
|
const [, n, r, p, salt, expected] = parts;
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
});
|
|
55
|
+
if (!DECIMAL.test(n) || !DECIMAL.test(r) || !DECIMAL.test(p))
|
|
56
|
+
return false;
|
|
57
|
+
const params = { N: Number(n), r: Number(r), p: Number(p) };
|
|
58
|
+
if (!acceptableParams(params.N, params.r, params.p))
|
|
59
|
+
return false;
|
|
60
|
+
const derived = await scryptAsync(plain, Buffer.from(salt, 'base64url'), 32, { ...params, maxmem: MAXMEM });
|
|
39
61
|
const expectedBuffer = Buffer.from(expected, 'base64url');
|
|
40
62
|
return derived.length === expectedBuffer.length && timingSafeEqual(derived, expectedBuffer);
|
|
41
63
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { ScryptPasswordHasher, type PasswordHasher } from './hashing.js';
|
|
2
2
|
export { signJwt, verifyJwt, TokenInvalidError, TokenExpiredError, type JwtClaims, } from './jwt.js';
|
|
3
|
-
export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, type TokenVersionStore, type AuthUser, type PublicUser, type UserSource, type UserPatch, type SessionStore, type SessionRecord, type RefreshTokenStore, type RefreshRecord, type AuthTokenStore, type AuthTokenRecord, type AuthTokenPurpose, type ApiKeyStore, type ApiKeyRecord, type ApiKeyInfo, type ApiKeyFilter, type MfaStore, type MfaRecord, } from './stores.js';
|
|
3
|
+
export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, MemoryAccountLinkStore, type AccountLink, type AccountLinkStore, type TokenVersionStore, type AuthUser, type PublicUser, type UserSource, type UserPatch, type SessionStore, type SessionRecord, type RefreshTokenStore, type RefreshRecord, type AuthTokenStore, type AuthTokenRecord, type AuthTokenPurpose, type ApiKeyStore, type ApiKeyRecord, type ApiKeyInfo, type ApiKeyFilter, type MfaStore, type MfaRecord, } from './stores.js';
|
|
4
4
|
declare module '@basaltkit/http' {
|
|
5
5
|
interface RouteMeta {
|
|
6
6
|
/** `true` requires a session; `false` opts a route out. */
|
|
@@ -18,15 +18,16 @@ declare module '@basaltkit/http' {
|
|
|
18
18
|
account?: boolean;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
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';
|
|
21
|
+
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, AccountLinkConflictError, AccountEmailAmbiguousError, canonicalEmail, type AuthOptions, type SessionCookieOptions, type TokenPair, } from './auth.js';
|
|
22
22
|
export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, type TotpOptions, type VerifyTotpOptions, type OtpauthUriInput, } from './totp.js';
|
|
23
|
+
export { SecretBox, SecretBoxKeyError, SecretUnreadableError, type SecretBoxKey, type SecretBoxOptions, type SecretBoxLegacyOptions, type SecretContext, } from './secret-box.js';
|
|
23
24
|
export { authPlugin, AUTH, CsrfRejectedError, type AuthPluginOptions, type CsrfOptions } from './plugin.js';
|
|
24
25
|
export { ApiKeys, ApiKeyExpirationError, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
|
|
25
|
-
export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, type ApiKeysPluginOptions, } from './apikeys-plugin.js';
|
|
26
|
+
export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, type ApiKeysPluginOptions, } from './apikeys-plugin.js';
|
|
26
27
|
export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, type AuthRoutesOptions, type PasswordPolicy, } from './routes.js';
|
|
27
|
-
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, type OAuthProvider, type OAuthProfile, type OAuthOptions, } from './oauth.js';
|
|
28
|
+
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, OAuthProviderConfigError, type OAuthProvider, type OAuthProfile, type OAuthOptions, } from './oauth.js';
|
|
28
29
|
export { oauthPlugin, oauthRoutes, OAUTH, type OAuthPluginOptions, type OAuthRoutesOptions, } from './oauth-plugin.js';
|
|
29
30
|
export { LoginThrottle, MemoryThrottleStore, AccountLockedError, type LoginThrottleOptions, type MemoryThrottleStoreOptions, type ThrottleStore, type ThrottleWindow, } from './throttle.js';
|
|
30
31
|
export { RedisThrottleStore, type RedisThrottleClient, type RedisThrottleStoreOptions } from './redis-throttle.js';
|
|
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';
|
|
32
|
+
export { WebAuthnService, MemoryPasskeyStore, MemoryWebAuthnChallengeStore, WebAuthnChallengeError, WebAuthnVerificationError, PasskeyNotFoundError, PasskeyClonedError, PasskeyStoreOutdatedError, 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';
|
|
32
33
|
export { webauthnPlugin, WEBAUTHN, type WebAuthnPluginOptions } from './webauthn-plugin.js';
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
export { ScryptPasswordHasher } from './hashing.js';
|
|
2
2
|
export { signJwt, verifyJwt, TokenInvalidError, TokenExpiredError, } from './jwt.js';
|
|
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, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, canonicalEmail, } from './auth.js';
|
|
3
|
+
export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, MemoryAccountLinkStore, } from './stores.js';
|
|
4
|
+
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaStepUpRequiredError, MfaEnrollmentRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, MfaAlreadyEnabledError, SocialLinkRefusedError, AccountLinkConflictError, AccountEmailAmbiguousError, canonicalEmail, } from './auth.js';
|
|
5
5
|
export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, } from './totp.js';
|
|
6
|
+
export { SecretBox, SecretBoxKeyError, SecretUnreadableError, } from './secret-box.js';
|
|
6
7
|
export { authPlugin, AUTH, CsrfRejectedError } from './plugin.js';
|
|
7
8
|
export { ApiKeys, ApiKeyExpirationError, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
|
|
8
|
-
export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, } from './apikeys-plugin.js';
|
|
9
|
+
export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, } from './apikeys-plugin.js';
|
|
9
10
|
export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, } from './routes.js';
|
|
10
|
-
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, } from './oauth.js';
|
|
11
|
+
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, OAuthProviderConfigError, } from './oauth.js';
|
|
11
12
|
export { oauthPlugin, oauthRoutes, OAUTH, } from './oauth-plugin.js';
|
|
12
13
|
export { LoginThrottle, MemoryThrottleStore, AccountLockedError, } from './throttle.js';
|
|
13
14
|
export { RedisThrottleStore } from './redis-throttle.js';
|
|
14
|
-
export { WebAuthnService, MemoryPasskeyStore, MemoryWebAuthnChallengeStore, WebAuthnChallengeError, WebAuthnVerificationError, PasskeyNotFoundError, PasskeyClonedError, PasskeyExistsError, WebAuthnSubjectMismatchError, } from './webauthn.js';
|
|
15
|
+
export { WebAuthnService, MemoryPasskeyStore, MemoryWebAuthnChallengeStore, WebAuthnChallengeError, WebAuthnVerificationError, PasskeyNotFoundError, PasskeyClonedError, PasskeyStoreOutdatedError, PasskeyExistsError, WebAuthnSubjectMismatchError, } from './webauthn.js';
|
|
15
16
|
export { webauthnPlugin, WEBAUTHN } from './webauthn-plugin.js';
|
package/dist/jwt.js
CHANGED
|
@@ -12,6 +12,8 @@ export class TokenExpiredError extends BasaltError {
|
|
|
12
12
|
super('AUTH_TOKEN_EXPIRED', 'The token has expired.');
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
+
/** One unpadded base64url segment — nothing outside the alphabet, no `=`. */
|
|
16
|
+
const SEGMENT = /^[A-Za-z0-9_-]+$/;
|
|
15
17
|
const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
|
|
16
18
|
/** Signs a compact HS256 JWT — no dependencies, node:crypto only. */
|
|
17
19
|
export function signJwt(claims, options) {
|
|
@@ -36,9 +38,19 @@ export function verifyJwt(token, secret) {
|
|
|
36
38
|
if (parts.length !== 3)
|
|
37
39
|
throw new TokenInvalidError();
|
|
38
40
|
const [head, body, signature] = parts;
|
|
41
|
+
// Node's base64url decoder silently skips characters outside the alphabet
|
|
42
|
+
// and ignores the unused low bits of the last character, so without these
|
|
43
|
+
// checks `token + '!!!'` (or a tweaked final char) would still verify —
|
|
44
|
+
// token strings would be malleable, defeating denylists or idempotency keyed
|
|
45
|
+
// on the exact token. Only the canonical encoding is accepted.
|
|
46
|
+
if (!SEGMENT.test(head) || !SEGMENT.test(body) || !SEGMENT.test(signature)) {
|
|
47
|
+
throw new TokenInvalidError();
|
|
48
|
+
}
|
|
39
49
|
const expected = createHmac('sha256', secret).update(`${head}.${body}`).digest();
|
|
40
50
|
const received = Buffer.from(signature, 'base64url');
|
|
41
|
-
if (
|
|
51
|
+
if (received.toString('base64url') !== signature ||
|
|
52
|
+
expected.length !== received.length ||
|
|
53
|
+
!timingSafeEqual(expected, received)) {
|
|
42
54
|
throw new TokenInvalidError();
|
|
43
55
|
}
|
|
44
56
|
let claims;
|
package/dist/oauth-plugin.d.ts
CHANGED
|
@@ -25,13 +25,24 @@ export interface OAuthRoutesOptions {
|
|
|
25
25
|
successRedirect?: string;
|
|
26
26
|
/**
|
|
27
27
|
* The HttpOnly cookie that binds a login to the browser that started it.
|
|
28
|
-
* `secure` defaults to
|
|
28
|
+
* `secure` defaults to true unless `NODE_ENV` is explicitly `development`
|
|
29
|
+
* or `test` (an unset NODE_ENV counts as production); when secure, the cookie is named
|
|
29
30
|
* `__Host-basalt_oauth` (host-only, so a sibling subdomain cannot plant it).
|
|
30
31
|
*/
|
|
31
32
|
bindingCookie?: {
|
|
32
33
|
secure?: boolean;
|
|
33
34
|
maxAgeSeconds?: number;
|
|
34
35
|
};
|
|
36
|
+
/**
|
|
37
|
+
* `meta.rateLimit` on both routes (enforced by the http `securityPlugin`'s
|
|
38
|
+
* rate limiter). Default 10 requests per minute per ip and route — each
|
|
39
|
+
* callback costs a token-endpoint and a profile round-trip to the provider.
|
|
40
|
+
* `false` removes it.
|
|
41
|
+
*/
|
|
42
|
+
rateLimit?: {
|
|
43
|
+
limit: number;
|
|
44
|
+
windowMs: number;
|
|
45
|
+
} | false;
|
|
35
46
|
}
|
|
36
47
|
/**
|
|
37
48
|
* Ready-made OAuth routes:
|
package/dist/oauth-plugin.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { createToken, ctx, definePlugin } from '@basaltkit/core';
|
|
1
|
+
import { createToken, ctx, definePlugin, isProductionEnvironment } from '@basaltkit/core';
|
|
2
2
|
import { route } from '@basaltkit/http';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { AUTH } from './plugin.js';
|
|
5
|
-
import { ACCOUNT_META } from './routes.js';
|
|
5
|
+
import { ACCOUNT_META, DEFAULT_AUTH_RATE_LIMIT } from './routes.js';
|
|
6
6
|
import { OAuth, stripTrailingSlashes } from './oauth.js';
|
|
7
7
|
export const OAUTH = createToken('auth.oauth');
|
|
8
8
|
/**
|
|
@@ -44,16 +44,17 @@ export function oauthRoutes(options) {
|
|
|
44
44
|
const oauth = () => ctx().container.get(OAUTH);
|
|
45
45
|
const base = stripTrailingSlashes(options.callbackBaseUrl);
|
|
46
46
|
const redirectUri = (provider) => `${base}/auth/oauth/${provider}/callback`;
|
|
47
|
-
const secure = options.bindingCookie?.secure ??
|
|
47
|
+
const secure = options.bindingCookie?.secure ?? isProductionEnvironment();
|
|
48
48
|
const cookieName = secure ? '__Host-basalt_oauth' : 'basalt_oauth';
|
|
49
49
|
const maxAge = options.bindingCookie?.maxAgeSeconds ?? 15 * 60;
|
|
50
50
|
// SameSite=Lax: the provider redirects back with a top-level GET, which Lax allows.
|
|
51
|
+
const limit = options.rateLimit === false ? {} : { rateLimit: options.rateLimit ?? { ...DEFAULT_AUTH_RATE_LIMIT } };
|
|
51
52
|
const cookie = (value, age) => `${cookieName}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${age}${secure ? '; Secure' : ''}`;
|
|
52
53
|
return [
|
|
53
54
|
route({
|
|
54
55
|
method: 'GET',
|
|
55
56
|
url: '/auth/oauth/:provider',
|
|
56
|
-
meta: { ...ACCOUNT_META },
|
|
57
|
+
meta: { ...ACCOUNT_META, ...limit },
|
|
57
58
|
params: z.object({ provider: z.string() }),
|
|
58
59
|
async handler({ params, reply }) {
|
|
59
60
|
const { url, binding } = oauth().authorize(params.provider, redirectUri(params.provider));
|
|
@@ -63,7 +64,7 @@ export function oauthRoutes(options) {
|
|
|
63
64
|
route({
|
|
64
65
|
method: 'GET',
|
|
65
66
|
url: '/auth/oauth/:provider/callback',
|
|
66
|
-
meta: { ...ACCOUNT_META },
|
|
67
|
+
meta: { ...ACCOUNT_META, ...limit },
|
|
67
68
|
params: z.object({ provider: z.string() }),
|
|
68
69
|
query: z.object({ code: z.string().max(4096), state: z.string().max(4096) }),
|
|
69
70
|
async handler({ params, query, request, reply }) {
|