@basaltkit/auth 1.5.0 → 1.6.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 +6 -0
- package/dist/index.d.ts +23 -6
- package/dist/index.js +61 -16
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -242,6 +242,12 @@ const { userId } = await passkeys.finishAuthentication(sessionKey, browserRespon
|
|
|
242
242
|
// → mint your session/JWT for userId as usual
|
|
243
243
|
```
|
|
244
244
|
|
|
245
|
+
> **Security:** the registration challenge is bound to the `user.id` you pass to
|
|
246
|
+
> `startRegistration`; `finishRegistration` refuses (`WEBAUTHN_SUBJECT_MISMATCH`) if the
|
|
247
|
+
> `userId` doesn't match, so a passkey can never be bound to another account. Always
|
|
248
|
+
> derive `userId` from the authenticated session, never from request input. A duplicate
|
|
249
|
+
> credential id is rejected (`PASSKEY_EXISTS`) rather than overwriting an existing one.
|
|
250
|
+
|
|
245
251
|
`finishAuthentication` looks the credential up by id, verifies it, checks the
|
|
246
252
|
signature counter **increased** (a non-increasing counter throws `PasskeyClonedError`),
|
|
247
253
|
and persists the new counter. Use `passkeys.list(userId)` / `passkeys.remove(id)`
|
package/dist/index.d.ts
CHANGED
|
@@ -941,19 +941,27 @@ declare class MemoryPasskeyStore implements PasskeyStore {
|
|
|
941
941
|
updateCounter(credentialId: string, counter: number, lastUsedAt: number): Promise<void>;
|
|
942
942
|
remove(credentialId: string): Promise<void>;
|
|
943
943
|
}
|
|
944
|
+
/** A stored challenge plus the subject (user id) it was issued for, if any. */
|
|
945
|
+
interface StoredChallenge {
|
|
946
|
+
challenge: string;
|
|
947
|
+
/** The user the registration challenge is bound to — enforced at finish. */
|
|
948
|
+
userId?: string;
|
|
949
|
+
}
|
|
944
950
|
interface WebAuthnChallengeStore {
|
|
945
|
-
save(key: string,
|
|
951
|
+
save(key: string, value: StoredChallenge, expiresAt: number): Promise<void>;
|
|
946
952
|
/** Return AND consume the challenge (single-use), or null if missing/expired. */
|
|
947
|
-
take(key: string): Promise<
|
|
953
|
+
take(key: string): Promise<StoredChallenge | null>;
|
|
948
954
|
}
|
|
949
955
|
declare class MemoryWebAuthnChallengeStore implements WebAuthnChallengeStore {
|
|
950
956
|
private readonly entries;
|
|
951
957
|
private readonly now;
|
|
958
|
+
private readonly maxEntries;
|
|
952
959
|
constructor(options?: {
|
|
953
960
|
now?: () => number;
|
|
961
|
+
maxEntries?: number;
|
|
954
962
|
});
|
|
955
|
-
save(key: string,
|
|
956
|
-
take(key: string): Promise<
|
|
963
|
+
save(key: string, value: StoredChallenge, expiresAt: number): Promise<void>;
|
|
964
|
+
take(key: string): Promise<StoredChallenge | null>;
|
|
957
965
|
}
|
|
958
966
|
interface VerifyRegistrationInput {
|
|
959
967
|
/** The `RegistrationResponseJSON` from `@simplewebauthn/browser`. */
|
|
@@ -1046,6 +1054,14 @@ declare class PasskeyClonedError extends BasaltError {
|
|
|
1046
1054
|
readonly status = 401;
|
|
1047
1055
|
constructor();
|
|
1048
1056
|
}
|
|
1057
|
+
declare class PasskeyExistsError extends BasaltError {
|
|
1058
|
+
readonly status = 409;
|
|
1059
|
+
constructor();
|
|
1060
|
+
}
|
|
1061
|
+
declare class WebAuthnSubjectMismatchError extends BasaltError {
|
|
1062
|
+
readonly status = 403;
|
|
1063
|
+
constructor();
|
|
1064
|
+
}
|
|
1049
1065
|
interface WebAuthnConfig {
|
|
1050
1066
|
/** Relying Party ID — your registrable domain, e.g. 'example.com'. */
|
|
1051
1067
|
rpId: string;
|
|
@@ -1081,8 +1097,9 @@ declare class WebAuthnService {
|
|
|
1081
1097
|
constructor(options: WebAuthnServiceOptions);
|
|
1082
1098
|
private get uv();
|
|
1083
1099
|
private get timeout();
|
|
1100
|
+
private challengeKey;
|
|
1084
1101
|
private issueChallenge;
|
|
1085
|
-
/** Registration options for a known user; stores the challenge
|
|
1102
|
+
/** Registration options for a known user; stores the challenge bound to `user.id`. */
|
|
1086
1103
|
startRegistration(sessionKey: string, user: {
|
|
1087
1104
|
id: string;
|
|
1088
1105
|
name: string;
|
|
@@ -1120,4 +1137,4 @@ interface WebAuthnPluginOptions {
|
|
|
1120
1137
|
/** Registers a {@link WebAuthnService} under the {@link WEBAUTHN} token. */
|
|
1121
1138
|
declare function webauthnPlugin(options: WebAuthnPluginOptions): _basaltkit_core.BasaltPlugin<unknown>;
|
|
1122
1139
|
|
|
1123
|
-
export { API_KEYS, AUTH, AccountLockedError, type ApiKeyContext, type ApiKeyFilter, type ApiKeyInfo, type ApiKeyRecord, type ApiKeyStore, ApiKeys, type ApiKeysOptions, type ApiKeysPluginOptions, Auth, type AuthOptions, type AuthPluginOptions, AuthRequiredError, AuthTokenInvalidError, type AuthTokenPurpose, type AuthTokenRecord, type AuthTokenStore, type AuthUser, type AuthenticationOptions, EmailTakenError, InvalidCredentialsError, type IssueApiKeyInput, type JwtClaims, LoginThrottle, type LoginThrottleOptions, MemoryApiKeyStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryPasskeyStore, MemoryRefreshTokenStore, MemorySessionStore, MemoryTokenVersionStore, MemoryUserSource, MemoryWebAuthnChallengeStore, MfaInvalidCodeError, MfaNotEnrolledError, type MfaRecord, MfaRequiredError, type MfaStore, OAUTH, OAuth, OAuthExchangeError, type OAuthOptions, type OAuthPluginOptions, type OAuthProfile, type OAuthProvider, OAuthProviderUnknownError, type OAuthRoutesOptions, OAuthStateInvalidError, type OtpauthUriInput, PasskeyClonedError, type PasskeyCredential, PasskeyNotFoundError, type PasskeyStore, type PasswordHasher, type PublicUser, RefreshInvalidError, type RefreshRecord, RefreshReusedError, type RefreshTokenStore, type RegistrationOptions, ScopeRequiredError, ScryptPasswordHasher, type SessionRecord, type SessionStore, TokenExpiredError, TokenInvalidError, type TokenPair, type TokenVersionStore, type TotpOptions, type UserPatch, type UserSource, UserUpdateUnsupportedError, type VerifiedAuthentication, type VerifiedRegistration, type VerifyAuthenticationInput, type VerifyRegistrationInput, type VerifyTotpOptions, WEBAUTHN, WeakJwtSecretError, WebAuthnChallengeError, type WebAuthnChallengeStore, type WebAuthnConfig, type WebAuthnPluginOptions, WebAuthnService, type WebAuthnServiceOptions, WebAuthnVerificationError, type WebAuthnVerifier, apiKeyRoutes, apiKeysPlugin, authPlugin, authRoutes, base32Decode, base32Encode, discoverOidcProvider, generateTotpSecret, githubProvider, googleProvider, matchTotpStep, mfaRoutes, oauthPlugin, oauthRoutes, oidcProvider, otpauthUri, publicUser, scopesSatisfy, signJwt, totp, verifyJwt, verifyTotp, webauthnPlugin };
|
|
1140
|
+
export { API_KEYS, AUTH, AccountLockedError, type ApiKeyContext, type ApiKeyFilter, type ApiKeyInfo, type ApiKeyRecord, type ApiKeyStore, ApiKeys, type ApiKeysOptions, type ApiKeysPluginOptions, Auth, type AuthOptions, type AuthPluginOptions, AuthRequiredError, AuthTokenInvalidError, type AuthTokenPurpose, type AuthTokenRecord, type AuthTokenStore, type AuthUser, type AuthenticationOptions, EmailTakenError, InvalidCredentialsError, type IssueApiKeyInput, type JwtClaims, LoginThrottle, type LoginThrottleOptions, MemoryApiKeyStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryPasskeyStore, MemoryRefreshTokenStore, MemorySessionStore, MemoryTokenVersionStore, MemoryUserSource, MemoryWebAuthnChallengeStore, MfaInvalidCodeError, MfaNotEnrolledError, type MfaRecord, MfaRequiredError, type MfaStore, OAUTH, OAuth, OAuthExchangeError, type OAuthOptions, type OAuthPluginOptions, type OAuthProfile, type OAuthProvider, OAuthProviderUnknownError, type OAuthRoutesOptions, OAuthStateInvalidError, type OtpauthUriInput, PasskeyClonedError, type PasskeyCredential, PasskeyExistsError, PasskeyNotFoundError, type PasskeyStore, type PasswordHasher, type PublicUser, RefreshInvalidError, type RefreshRecord, RefreshReusedError, type RefreshTokenStore, type RegistrationOptions, ScopeRequiredError, ScryptPasswordHasher, type SessionRecord, type SessionStore, type StoredChallenge, TokenExpiredError, TokenInvalidError, type TokenPair, type TokenVersionStore, type TotpOptions, type UserPatch, type UserSource, UserUpdateUnsupportedError, type VerifiedAuthentication, type VerifiedRegistration, type VerifyAuthenticationInput, type VerifyRegistrationInput, type VerifyTotpOptions, WEBAUTHN, WeakJwtSecretError, WebAuthnChallengeError, type WebAuthnChallengeStore, type WebAuthnConfig, type WebAuthnPluginOptions, WebAuthnService, type WebAuthnServiceOptions, WebAuthnSubjectMismatchError, WebAuthnVerificationError, type WebAuthnVerifier, apiKeyRoutes, apiKeysPlugin, authPlugin, authRoutes, base32Decode, base32Encode, discoverOidcProvider, generateTotpSecret, githubProvider, googleProvider, matchTotpStep, mfaRoutes, oauthPlugin, oauthRoutes, oidcProvider, otpauthUri, publicUser, scopesSatisfy, signJwt, totp, verifyJwt, verifyTotp, webauthnPlugin };
|
package/dist/index.js
CHANGED
|
@@ -1503,17 +1503,28 @@ var MemoryPasskeyStore = class {
|
|
|
1503
1503
|
var MemoryWebAuthnChallengeStore = class {
|
|
1504
1504
|
entries = /* @__PURE__ */ new Map();
|
|
1505
1505
|
now;
|
|
1506
|
+
maxEntries;
|
|
1506
1507
|
constructor(options = {}) {
|
|
1507
1508
|
this.now = options.now ?? (() => Date.now());
|
|
1509
|
+
this.maxEntries = options.maxEntries ?? 1e4;
|
|
1508
1510
|
}
|
|
1509
|
-
async save(key,
|
|
1510
|
-
this.
|
|
1511
|
+
async save(key, value, expiresAt) {
|
|
1512
|
+
const now = this.now();
|
|
1513
|
+
for (const [k, entry] of this.entries) {
|
|
1514
|
+
if (entry.expiresAt <= now) this.entries.delete(k);
|
|
1515
|
+
}
|
|
1516
|
+
while (this.entries.size >= this.maxEntries) {
|
|
1517
|
+
const oldest = this.entries.keys().next().value;
|
|
1518
|
+
if (oldest === void 0) break;
|
|
1519
|
+
this.entries.delete(oldest);
|
|
1520
|
+
}
|
|
1521
|
+
this.entries.set(key, { value, expiresAt });
|
|
1511
1522
|
}
|
|
1512
1523
|
async take(key) {
|
|
1513
1524
|
const entry = this.entries.get(key);
|
|
1514
1525
|
if (!entry) return null;
|
|
1515
1526
|
this.entries.delete(key);
|
|
1516
|
-
return entry.expiresAt > this.now() ? entry.
|
|
1527
|
+
return entry.expiresAt > this.now() ? entry.value : null;
|
|
1517
1528
|
}
|
|
1518
1529
|
};
|
|
1519
1530
|
var DEFAULT_PUB_KEY_PARAMS = [
|
|
@@ -1544,6 +1555,21 @@ var PasskeyClonedError = class extends BasaltError7 {
|
|
|
1544
1555
|
super("PASSKEY_CLONED", "Signature counter did not increase \u2014 the authenticator may be cloned.");
|
|
1545
1556
|
}
|
|
1546
1557
|
};
|
|
1558
|
+
var PasskeyExistsError = class extends BasaltError7 {
|
|
1559
|
+
status = 409;
|
|
1560
|
+
constructor() {
|
|
1561
|
+
super("PASSKEY_EXISTS", "This credential is already registered.");
|
|
1562
|
+
}
|
|
1563
|
+
};
|
|
1564
|
+
var WebAuthnSubjectMismatchError = class extends BasaltError7 {
|
|
1565
|
+
status = 403;
|
|
1566
|
+
constructor() {
|
|
1567
|
+
super(
|
|
1568
|
+
"WEBAUTHN_SUBJECT_MISMATCH",
|
|
1569
|
+
"The challenge was issued for a different user \u2014 refusing to bind the passkey."
|
|
1570
|
+
);
|
|
1571
|
+
}
|
|
1572
|
+
};
|
|
1547
1573
|
var WebAuthnService = class {
|
|
1548
1574
|
config;
|
|
1549
1575
|
credentials;
|
|
@@ -1565,14 +1591,24 @@ var WebAuthnService = class {
|
|
|
1565
1591
|
get timeout() {
|
|
1566
1592
|
return this.config.timeoutMs ?? 6e4;
|
|
1567
1593
|
}
|
|
1568
|
-
|
|
1594
|
+
// Challenges are namespaced per ceremony so a registration and an
|
|
1595
|
+
// authentication on the same sessionKey never clobber or cross-consume.
|
|
1596
|
+
challengeKey(kind, sessionKey) {
|
|
1597
|
+
return `${kind}:${sessionKey}`;
|
|
1598
|
+
}
|
|
1599
|
+
async issueChallenge(kind, sessionKey, userId) {
|
|
1569
1600
|
const challenge = this.randomChallenge();
|
|
1570
|
-
|
|
1601
|
+
const value = userId === void 0 ? { challenge } : { challenge, userId };
|
|
1602
|
+
await this.challenges.save(
|
|
1603
|
+
this.challengeKey(kind, sessionKey),
|
|
1604
|
+
value,
|
|
1605
|
+
this.now() + (this.config.challengeTtlMs ?? 3e5)
|
|
1606
|
+
);
|
|
1571
1607
|
return challenge;
|
|
1572
1608
|
}
|
|
1573
|
-
/** Registration options for a known user; stores the challenge
|
|
1609
|
+
/** Registration options for a known user; stores the challenge bound to `user.id`. */
|
|
1574
1610
|
async startRegistration(sessionKey, user) {
|
|
1575
|
-
const challenge = await this.issueChallenge(sessionKey);
|
|
1611
|
+
const challenge = await this.issueChallenge("reg", sessionKey, user.id);
|
|
1576
1612
|
const existing = await this.credentials.forUser(user.id);
|
|
1577
1613
|
return {
|
|
1578
1614
|
challenge,
|
|
@@ -1591,16 +1627,20 @@ var WebAuthnService = class {
|
|
|
1591
1627
|
}
|
|
1592
1628
|
/** Verify a registration response and store the new passkey. Throws on failure. */
|
|
1593
1629
|
async finishRegistration(sessionKey, userId, response, deviceName) {
|
|
1594
|
-
const
|
|
1595
|
-
if (!
|
|
1630
|
+
const stored = await this.challenges.take(this.challengeKey("reg", sessionKey));
|
|
1631
|
+
if (!stored) throw new WebAuthnChallengeError();
|
|
1632
|
+
if (stored.userId !== void 0 && stored.userId !== userId) {
|
|
1633
|
+
throw new WebAuthnSubjectMismatchError();
|
|
1634
|
+
}
|
|
1596
1635
|
const result = await this.verifier.verifyRegistration({
|
|
1597
1636
|
response,
|
|
1598
|
-
expectedChallenge,
|
|
1637
|
+
expectedChallenge: stored.challenge,
|
|
1599
1638
|
expectedOrigin: this.config.origin,
|
|
1600
1639
|
expectedRpId: this.config.rpId,
|
|
1601
1640
|
requireUserVerification: this.uv === "required"
|
|
1602
1641
|
});
|
|
1603
1642
|
if (!result.verified || !result.credential) throw new WebAuthnVerificationError();
|
|
1643
|
+
if (await this.credentials.get(result.credential.id)) throw new PasskeyExistsError();
|
|
1604
1644
|
const credential = {
|
|
1605
1645
|
id: result.credential.id,
|
|
1606
1646
|
userId,
|
|
@@ -1615,7 +1655,7 @@ var WebAuthnService = class {
|
|
|
1615
1655
|
}
|
|
1616
1656
|
/** Authentication options; `userId` narrows allowCredentials, omit it for discoverable login. */
|
|
1617
1657
|
async startAuthentication(sessionKey, userId) {
|
|
1618
|
-
const challenge = await this.issueChallenge(sessionKey);
|
|
1658
|
+
const challenge = await this.issueChallenge("auth", sessionKey);
|
|
1619
1659
|
const creds = userId ? await this.credentials.forUser(userId) : [];
|
|
1620
1660
|
return {
|
|
1621
1661
|
challenge,
|
|
@@ -1635,15 +1675,18 @@ var WebAuthnService = class {
|
|
|
1635
1675
|
* and returns whose passkey authenticated. Throws on any failure.
|
|
1636
1676
|
*/
|
|
1637
1677
|
async finishAuthentication(sessionKey, response) {
|
|
1638
|
-
const
|
|
1639
|
-
if (
|
|
1678
|
+
const rawId = response?.id;
|
|
1679
|
+
if (typeof rawId !== "string" || rawId.length === 0 || rawId.length > 512) {
|
|
1680
|
+
throw new PasskeyNotFoundError();
|
|
1681
|
+
}
|
|
1682
|
+
const credentialId = rawId;
|
|
1683
|
+
const stored = await this.challenges.take(this.challengeKey("auth", sessionKey));
|
|
1684
|
+
if (!stored) throw new WebAuthnChallengeError();
|
|
1640
1685
|
const credential = await this.credentials.get(credentialId);
|
|
1641
1686
|
if (!credential) throw new PasskeyNotFoundError();
|
|
1642
|
-
const expectedChallenge = await this.challenges.take(sessionKey);
|
|
1643
|
-
if (!expectedChallenge) throw new WebAuthnChallengeError();
|
|
1644
1687
|
const result = await this.verifier.verifyAuthentication({
|
|
1645
1688
|
response,
|
|
1646
|
-
expectedChallenge,
|
|
1689
|
+
expectedChallenge: stored.challenge,
|
|
1647
1690
|
expectedOrigin: this.config.origin,
|
|
1648
1691
|
expectedRpId: this.config.rpId,
|
|
1649
1692
|
requireUserVerification: this.uv === "required",
|
|
@@ -1714,6 +1757,7 @@ export {
|
|
|
1714
1757
|
OAuthProviderUnknownError,
|
|
1715
1758
|
OAuthStateInvalidError,
|
|
1716
1759
|
PasskeyClonedError,
|
|
1760
|
+
PasskeyExistsError,
|
|
1717
1761
|
PasskeyNotFoundError,
|
|
1718
1762
|
RefreshInvalidError,
|
|
1719
1763
|
RefreshReusedError,
|
|
@@ -1726,6 +1770,7 @@ export {
|
|
|
1726
1770
|
WeakJwtSecretError,
|
|
1727
1771
|
WebAuthnChallengeError,
|
|
1728
1772
|
WebAuthnService,
|
|
1773
|
+
WebAuthnSubjectMismatchError,
|
|
1729
1774
|
WebAuthnVerificationError,
|
|
1730
1775
|
apiKeyRoutes,
|
|
1731
1776
|
apiKeysPlugin,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@basaltkit/auth",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "Authentication for Basalt: password hashing, JWT with refresh rotation and reuse detection, sessions, ready-made /auth routes and route guards.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"dist"
|
|
15
15
|
],
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@basaltkit/core": "^1.1.
|
|
17
|
+
"@basaltkit/core": "^1.1.1",
|
|
18
18
|
"@basaltkit/fastify": "^1.5.0"
|
|
19
19
|
},
|
|
20
20
|
"peerDependencies": {
|