@basaltkit/auth 1.4.1 → 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 +91 -0
- package/dist/index.d.ts +233 -1
- package/dist/index.js +267 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -162,6 +162,97 @@ Flow (all routes require login):
|
|
|
162
162
|
3. From then on, `POST /auth/login` requires the extra `mfaCode` field (TOTP code or a recovery code). Correct password without a code → `AUTH_MFA_REQUIRED` error.
|
|
163
163
|
4. `GET /auth/mfa/status` and `POST /auth/mfa/disable` (with `{ code }`) complete the cycle.
|
|
164
164
|
|
|
165
|
+
### Passkeys — WebAuthn (`webauthnPlugin`)
|
|
166
|
+
|
|
167
|
+
Passkeys let users sign in with Face ID / Touch ID / a security key — no password.
|
|
168
|
+
The framework drives the whole **ceremony** (challenges, browser options, credential
|
|
169
|
+
storage, single-use challenges, the clone-detection counter check) and delegates
|
|
170
|
+
only the **cryptographic verification** to a small `WebAuthnVerifier` you implement
|
|
171
|
+
over [`@simplewebauthn/server`](https://simplewebauthn.dev) — so `@basaltkit/auth`
|
|
172
|
+
never depends on a WebAuthn crypto library.
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
import { webauthnPlugin, type WebAuthnVerifier } from '@basaltkit/auth'
|
|
176
|
+
import {
|
|
177
|
+
verifyRegistrationResponse,
|
|
178
|
+
verifyAuthenticationResponse,
|
|
179
|
+
} from '@simplewebauthn/server'
|
|
180
|
+
|
|
181
|
+
const verifier: WebAuthnVerifier = {
|
|
182
|
+
async verifyRegistration(input) {
|
|
183
|
+
const v = await verifyRegistrationResponse({
|
|
184
|
+
response: input.response as never,
|
|
185
|
+
expectedChallenge: input.expectedChallenge,
|
|
186
|
+
expectedOrigin: input.expectedOrigin,
|
|
187
|
+
expectedRPID: input.expectedRpId,
|
|
188
|
+
requireUserVerification: input.requireUserVerification,
|
|
189
|
+
})
|
|
190
|
+
if (!v.verified || !v.registrationInfo) return { verified: false }
|
|
191
|
+
const { credential } = v.registrationInfo
|
|
192
|
+
return {
|
|
193
|
+
verified: true,
|
|
194
|
+
credential: {
|
|
195
|
+
id: credential.id,
|
|
196
|
+
publicKey: Buffer.from(credential.publicKey).toString('base64url'),
|
|
197
|
+
counter: credential.counter,
|
|
198
|
+
transports: input.response && (input.response as any).response?.transports,
|
|
199
|
+
},
|
|
200
|
+
}
|
|
201
|
+
},
|
|
202
|
+
async verifyAuthentication(input) {
|
|
203
|
+
const v = await verifyAuthenticationResponse({
|
|
204
|
+
response: input.response as never,
|
|
205
|
+
expectedChallenge: input.expectedChallenge,
|
|
206
|
+
expectedOrigin: input.expectedOrigin,
|
|
207
|
+
expectedRPID: input.expectedRpId,
|
|
208
|
+
requireUserVerification: input.requireUserVerification,
|
|
209
|
+
credential: {
|
|
210
|
+
id: input.credential.id,
|
|
211
|
+
publicKey: Buffer.from(input.credential.publicKey, 'base64url'),
|
|
212
|
+
counter: input.credential.counter,
|
|
213
|
+
},
|
|
214
|
+
})
|
|
215
|
+
return { verified: v.verified, newCounter: v.authenticationInfo?.newCounter ?? input.credential.counter }
|
|
216
|
+
},
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
app.use(webauthnPlugin({
|
|
220
|
+
config: { rpId: 'example.com', rpName: 'Example', origin: 'https://example.com' },
|
|
221
|
+
verifier,
|
|
222
|
+
// credentials / challenges default to in-memory — pass durable stores in prod
|
|
223
|
+
}))
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Then drive the four steps from your routes, resolving the service from the `WEBAUTHN`
|
|
227
|
+
token. The **sessionKey** ties a challenge to the current session (use the user id,
|
|
228
|
+
or a session id for logged-out login):
|
|
229
|
+
|
|
230
|
+
```ts
|
|
231
|
+
import { WEBAUTHN } from '@basaltkit/auth'
|
|
232
|
+
const passkeys = container.get(WEBAUTHN)
|
|
233
|
+
|
|
234
|
+
// Register a passkey for a signed-in user
|
|
235
|
+
const options = await passkeys.startRegistration(sessionKey, { id: user.id, name: user.email })
|
|
236
|
+
// → send options to @simplewebauthn/browser's startRegistration(), post the result back:
|
|
237
|
+
await passkeys.finishRegistration(sessionKey, user.id, browserResponse, 'MacBook')
|
|
238
|
+
|
|
239
|
+
// Sign in with a passkey (usernameless: omit the userId)
|
|
240
|
+
const authOptions = await passkeys.startAuthentication(sessionKey)
|
|
241
|
+
const { userId } = await passkeys.finishAuthentication(sessionKey, browserResponse)
|
|
242
|
+
// → mint your session/JWT for userId as usual
|
|
243
|
+
```
|
|
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
|
+
|
|
251
|
+
`finishAuthentication` looks the credential up by id, verifies it, checks the
|
|
252
|
+
signature counter **increased** (a non-increasing counter throws `PasskeyClonedError`),
|
|
253
|
+
and persists the new counter. Use `passkeys.list(userId)` / `passkeys.remove(id)`
|
|
254
|
+
for a "manage devices" screen.
|
|
255
|
+
|
|
165
256
|
### Social login (OAuth)
|
|
166
257
|
|
|
167
258
|
Sign in with Google, GitHub, or any OpenID Connect provider via the OAuth 2.0
|
package/dist/index.d.ts
CHANGED
|
@@ -905,4 +905,236 @@ interface OAuthRoutesOptions {
|
|
|
905
905
|
*/
|
|
906
906
|
declare function oauthRoutes(options: OAuthRoutesOptions): BasaltRoute[];
|
|
907
907
|
|
|
908
|
-
|
|
908
|
+
/**
|
|
909
|
+
* WebAuthn / passkeys ceremony orchestration. The framework owns everything that
|
|
910
|
+
* is NOT cryptography — issuing challenges, assembling the browser options,
|
|
911
|
+
* storing credentials, and the counter/clone check — and delegates the actual
|
|
912
|
+
* attestation/assertion verification to a pluggable {@link WebAuthnVerifier}
|
|
913
|
+
* (implement it over `@simplewebauthn/server` or similar). This keeps the
|
|
914
|
+
* framework free of a crypto dependency while still driving the full flow.
|
|
915
|
+
*/
|
|
916
|
+
interface PasskeyCredential {
|
|
917
|
+
/** base64url credential id. */
|
|
918
|
+
id: string;
|
|
919
|
+
userId: string;
|
|
920
|
+
/** base64url COSE public key (opaque to the framework; the verifier reads it). */
|
|
921
|
+
publicKey: string;
|
|
922
|
+
/** Signature counter for clone detection. */
|
|
923
|
+
counter: number;
|
|
924
|
+
transports?: string[];
|
|
925
|
+
deviceName?: string;
|
|
926
|
+
createdAt: number;
|
|
927
|
+
lastUsedAt?: number;
|
|
928
|
+
}
|
|
929
|
+
interface PasskeyStore {
|
|
930
|
+
add(credential: PasskeyCredential): Promise<void>;
|
|
931
|
+
get(credentialId: string): Promise<PasskeyCredential | null>;
|
|
932
|
+
forUser(userId: string): Promise<PasskeyCredential[]>;
|
|
933
|
+
updateCounter(credentialId: string, counter: number, lastUsedAt: number): Promise<void>;
|
|
934
|
+
remove(credentialId: string): Promise<void>;
|
|
935
|
+
}
|
|
936
|
+
declare class MemoryPasskeyStore implements PasskeyStore {
|
|
937
|
+
private readonly byId;
|
|
938
|
+
add(credential: PasskeyCredential): Promise<void>;
|
|
939
|
+
get(credentialId: string): Promise<PasskeyCredential | null>;
|
|
940
|
+
forUser(userId: string): Promise<PasskeyCredential[]>;
|
|
941
|
+
updateCounter(credentialId: string, counter: number, lastUsedAt: number): Promise<void>;
|
|
942
|
+
remove(credentialId: string): Promise<void>;
|
|
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
|
+
}
|
|
950
|
+
interface WebAuthnChallengeStore {
|
|
951
|
+
save(key: string, value: StoredChallenge, expiresAt: number): Promise<void>;
|
|
952
|
+
/** Return AND consume the challenge (single-use), or null if missing/expired. */
|
|
953
|
+
take(key: string): Promise<StoredChallenge | null>;
|
|
954
|
+
}
|
|
955
|
+
declare class MemoryWebAuthnChallengeStore implements WebAuthnChallengeStore {
|
|
956
|
+
private readonly entries;
|
|
957
|
+
private readonly now;
|
|
958
|
+
private readonly maxEntries;
|
|
959
|
+
constructor(options?: {
|
|
960
|
+
now?: () => number;
|
|
961
|
+
maxEntries?: number;
|
|
962
|
+
});
|
|
963
|
+
save(key: string, value: StoredChallenge, expiresAt: number): Promise<void>;
|
|
964
|
+
take(key: string): Promise<StoredChallenge | null>;
|
|
965
|
+
}
|
|
966
|
+
interface VerifyRegistrationInput {
|
|
967
|
+
/** The `RegistrationResponseJSON` from `@simplewebauthn/browser`. */
|
|
968
|
+
response: unknown;
|
|
969
|
+
expectedChallenge: string;
|
|
970
|
+
expectedOrigin: string | string[];
|
|
971
|
+
expectedRpId: string;
|
|
972
|
+
requireUserVerification: boolean;
|
|
973
|
+
}
|
|
974
|
+
interface VerifiedRegistration {
|
|
975
|
+
verified: boolean;
|
|
976
|
+
credential?: {
|
|
977
|
+
id: string;
|
|
978
|
+
publicKey: string;
|
|
979
|
+
counter: number;
|
|
980
|
+
transports?: string[];
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
interface VerifyAuthenticationInput {
|
|
984
|
+
/** The `AuthenticationResponseJSON` from `@simplewebauthn/browser`. */
|
|
985
|
+
response: unknown;
|
|
986
|
+
expectedChallenge: string;
|
|
987
|
+
expectedOrigin: string | string[];
|
|
988
|
+
expectedRpId: string;
|
|
989
|
+
requireUserVerification: boolean;
|
|
990
|
+
credential: {
|
|
991
|
+
id: string;
|
|
992
|
+
publicKey: string;
|
|
993
|
+
counter: number;
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
interface VerifiedAuthentication {
|
|
997
|
+
verified: boolean;
|
|
998
|
+
newCounter: number;
|
|
999
|
+
}
|
|
1000
|
+
/** The cryptographic boundary — implement over a WebAuthn library. */
|
|
1001
|
+
interface WebAuthnVerifier {
|
|
1002
|
+
verifyRegistration(input: VerifyRegistrationInput): Promise<VerifiedRegistration>;
|
|
1003
|
+
verifyAuthentication(input: VerifyAuthenticationInput): Promise<VerifiedAuthentication>;
|
|
1004
|
+
}
|
|
1005
|
+
interface PublicKeyParam {
|
|
1006
|
+
type: 'public-key';
|
|
1007
|
+
alg: number;
|
|
1008
|
+
}
|
|
1009
|
+
interface CredentialDescriptor {
|
|
1010
|
+
type: 'public-key';
|
|
1011
|
+
id: string;
|
|
1012
|
+
transports?: string[];
|
|
1013
|
+
}
|
|
1014
|
+
interface RegistrationOptions {
|
|
1015
|
+
challenge: string;
|
|
1016
|
+
rp: {
|
|
1017
|
+
id: string;
|
|
1018
|
+
name: string;
|
|
1019
|
+
};
|
|
1020
|
+
user: {
|
|
1021
|
+
id: string;
|
|
1022
|
+
name: string;
|
|
1023
|
+
displayName: string;
|
|
1024
|
+
};
|
|
1025
|
+
pubKeyCredParams: PublicKeyParam[];
|
|
1026
|
+
timeout: number;
|
|
1027
|
+
attestation: 'none';
|
|
1028
|
+
excludeCredentials: CredentialDescriptor[];
|
|
1029
|
+
authenticatorSelection: {
|
|
1030
|
+
userVerification: string;
|
|
1031
|
+
residentKey: 'preferred';
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
interface AuthenticationOptions {
|
|
1035
|
+
challenge: string;
|
|
1036
|
+
timeout: number;
|
|
1037
|
+
rpId: string;
|
|
1038
|
+
userVerification: string;
|
|
1039
|
+
allowCredentials: CredentialDescriptor[];
|
|
1040
|
+
}
|
|
1041
|
+
declare class WebAuthnChallengeError extends BasaltError {
|
|
1042
|
+
readonly status = 400;
|
|
1043
|
+
constructor();
|
|
1044
|
+
}
|
|
1045
|
+
declare class WebAuthnVerificationError extends BasaltError {
|
|
1046
|
+
readonly status = 400;
|
|
1047
|
+
constructor();
|
|
1048
|
+
}
|
|
1049
|
+
declare class PasskeyNotFoundError extends BasaltError {
|
|
1050
|
+
readonly status = 404;
|
|
1051
|
+
constructor();
|
|
1052
|
+
}
|
|
1053
|
+
declare class PasskeyClonedError extends BasaltError {
|
|
1054
|
+
readonly status = 401;
|
|
1055
|
+
constructor();
|
|
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
|
+
}
|
|
1065
|
+
interface WebAuthnConfig {
|
|
1066
|
+
/** Relying Party ID — your registrable domain, e.g. 'example.com'. */
|
|
1067
|
+
rpId: string;
|
|
1068
|
+
/** Human-readable RP name shown in the OS prompt. */
|
|
1069
|
+
rpName: string;
|
|
1070
|
+
/** Expected origin(s), e.g. 'https://example.com'. */
|
|
1071
|
+
origin: string | string[];
|
|
1072
|
+
/** Challenge TTL in ms. Default 5 minutes. */
|
|
1073
|
+
challengeTtlMs?: number;
|
|
1074
|
+
/** User-verification requirement. Default 'preferred'. */
|
|
1075
|
+
userVerification?: 'required' | 'preferred' | 'discouraged';
|
|
1076
|
+
/** Ceremony timeout advertised to the browser, ms. Default 60s. */
|
|
1077
|
+
timeoutMs?: number;
|
|
1078
|
+
/** Override the accepted algorithms. Default ES256 + RS256. */
|
|
1079
|
+
pubKeyCredParams?: PublicKeyParam[];
|
|
1080
|
+
}
|
|
1081
|
+
interface WebAuthnServiceOptions {
|
|
1082
|
+
config: WebAuthnConfig;
|
|
1083
|
+
credentials: PasskeyStore;
|
|
1084
|
+
challenges: WebAuthnChallengeStore;
|
|
1085
|
+
verifier: WebAuthnVerifier;
|
|
1086
|
+
now?: () => number;
|
|
1087
|
+
/** Challenge generator (tests). Default: 32 random bytes, base64url. */
|
|
1088
|
+
randomChallenge?: () => string;
|
|
1089
|
+
}
|
|
1090
|
+
declare class WebAuthnService {
|
|
1091
|
+
private readonly config;
|
|
1092
|
+
private readonly credentials;
|
|
1093
|
+
private readonly challenges;
|
|
1094
|
+
private readonly verifier;
|
|
1095
|
+
private readonly now;
|
|
1096
|
+
private readonly randomChallenge;
|
|
1097
|
+
constructor(options: WebAuthnServiceOptions);
|
|
1098
|
+
private get uv();
|
|
1099
|
+
private get timeout();
|
|
1100
|
+
private challengeKey;
|
|
1101
|
+
private issueChallenge;
|
|
1102
|
+
/** Registration options for a known user; stores the challenge bound to `user.id`. */
|
|
1103
|
+
startRegistration(sessionKey: string, user: {
|
|
1104
|
+
id: string;
|
|
1105
|
+
name: string;
|
|
1106
|
+
displayName?: string;
|
|
1107
|
+
}): Promise<RegistrationOptions>;
|
|
1108
|
+
/** Verify a registration response and store the new passkey. Throws on failure. */
|
|
1109
|
+
finishRegistration(sessionKey: string, userId: string, response: unknown, deviceName?: string): Promise<PasskeyCredential>;
|
|
1110
|
+
/** Authentication options; `userId` narrows allowCredentials, omit it for discoverable login. */
|
|
1111
|
+
startAuthentication(sessionKey: string, userId?: string): Promise<AuthenticationOptions>;
|
|
1112
|
+
/**
|
|
1113
|
+
* Verify an authentication response. Looks the credential up by its id, checks
|
|
1114
|
+
* the signature counter increased (clone detection), persists the new counter,
|
|
1115
|
+
* and returns whose passkey authenticated. Throws on any failure.
|
|
1116
|
+
*/
|
|
1117
|
+
finishAuthentication(sessionKey: string, response: unknown): Promise<{
|
|
1118
|
+
userId: string;
|
|
1119
|
+
credentialId: string;
|
|
1120
|
+
}>;
|
|
1121
|
+
/** A user's registered passkeys (for a "manage devices" screen). */
|
|
1122
|
+
list(userId: string): Promise<PasskeyCredential[]>;
|
|
1123
|
+
/** Remove a passkey (revoke a device). */
|
|
1124
|
+
remove(credentialId: string): Promise<void>;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
declare const WEBAUTHN: _basaltkit_core.Token<WebAuthnService>;
|
|
1128
|
+
interface WebAuthnPluginOptions {
|
|
1129
|
+
config: WebAuthnConfig;
|
|
1130
|
+
/** The crypto boundary — implement over `@simplewebauthn/server`. Required. */
|
|
1131
|
+
verifier: WebAuthnVerifier;
|
|
1132
|
+
/** Passkey storage. Default: in-memory (swap for a durable store). */
|
|
1133
|
+
credentials?: PasskeyStore;
|
|
1134
|
+
/** Challenge storage. Default: in-memory. */
|
|
1135
|
+
challenges?: WebAuthnChallengeStore;
|
|
1136
|
+
}
|
|
1137
|
+
/** Registers a {@link WebAuthnService} under the {@link WEBAUTHN} token. */
|
|
1138
|
+
declare function webauthnPlugin(options: WebAuthnPluginOptions): _basaltkit_core.BasaltPlugin<unknown>;
|
|
1139
|
+
|
|
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
|
@@ -1473,6 +1473,261 @@ function oauthRoutes(options) {
|
|
|
1473
1473
|
})
|
|
1474
1474
|
];
|
|
1475
1475
|
}
|
|
1476
|
+
|
|
1477
|
+
// src/webauthn.ts
|
|
1478
|
+
import { randomBytes as randomBytes8 } from "crypto";
|
|
1479
|
+
import { BasaltError as BasaltError7 } from "@basaltkit/core";
|
|
1480
|
+
var MemoryPasskeyStore = class {
|
|
1481
|
+
byId = /* @__PURE__ */ new Map();
|
|
1482
|
+
async add(credential) {
|
|
1483
|
+
this.byId.set(credential.id, { ...credential });
|
|
1484
|
+
}
|
|
1485
|
+
async get(credentialId) {
|
|
1486
|
+
const found = this.byId.get(credentialId);
|
|
1487
|
+
return found ? { ...found } : null;
|
|
1488
|
+
}
|
|
1489
|
+
async forUser(userId) {
|
|
1490
|
+
return [...this.byId.values()].filter((c) => c.userId === userId).map((c) => ({ ...c }));
|
|
1491
|
+
}
|
|
1492
|
+
async updateCounter(credentialId, counter, lastUsedAt) {
|
|
1493
|
+
const found = this.byId.get(credentialId);
|
|
1494
|
+
if (found) {
|
|
1495
|
+
found.counter = counter;
|
|
1496
|
+
found.lastUsedAt = lastUsedAt;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
async remove(credentialId) {
|
|
1500
|
+
this.byId.delete(credentialId);
|
|
1501
|
+
}
|
|
1502
|
+
};
|
|
1503
|
+
var MemoryWebAuthnChallengeStore = class {
|
|
1504
|
+
entries = /* @__PURE__ */ new Map();
|
|
1505
|
+
now;
|
|
1506
|
+
maxEntries;
|
|
1507
|
+
constructor(options = {}) {
|
|
1508
|
+
this.now = options.now ?? (() => Date.now());
|
|
1509
|
+
this.maxEntries = options.maxEntries ?? 1e4;
|
|
1510
|
+
}
|
|
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 });
|
|
1522
|
+
}
|
|
1523
|
+
async take(key) {
|
|
1524
|
+
const entry = this.entries.get(key);
|
|
1525
|
+
if (!entry) return null;
|
|
1526
|
+
this.entries.delete(key);
|
|
1527
|
+
return entry.expiresAt > this.now() ? entry.value : null;
|
|
1528
|
+
}
|
|
1529
|
+
};
|
|
1530
|
+
var DEFAULT_PUB_KEY_PARAMS = [
|
|
1531
|
+
{ type: "public-key", alg: -7 },
|
|
1532
|
+
{ type: "public-key", alg: -257 }
|
|
1533
|
+
];
|
|
1534
|
+
var WebAuthnChallengeError = class extends BasaltError7 {
|
|
1535
|
+
status = 400;
|
|
1536
|
+
constructor() {
|
|
1537
|
+
super("WEBAUTHN_CHALLENGE_INVALID", "No matching WebAuthn challenge \u2014 it expired or was already used.");
|
|
1538
|
+
}
|
|
1539
|
+
};
|
|
1540
|
+
var WebAuthnVerificationError = class extends BasaltError7 {
|
|
1541
|
+
status = 400;
|
|
1542
|
+
constructor() {
|
|
1543
|
+
super("WEBAUTHN_VERIFICATION_FAILED", "The WebAuthn response could not be verified.");
|
|
1544
|
+
}
|
|
1545
|
+
};
|
|
1546
|
+
var PasskeyNotFoundError = class extends BasaltError7 {
|
|
1547
|
+
status = 404;
|
|
1548
|
+
constructor() {
|
|
1549
|
+
super("PASSKEY_NOT_FOUND", "No passkey matches the presented credential.");
|
|
1550
|
+
}
|
|
1551
|
+
};
|
|
1552
|
+
var PasskeyClonedError = class extends BasaltError7 {
|
|
1553
|
+
status = 401;
|
|
1554
|
+
constructor() {
|
|
1555
|
+
super("PASSKEY_CLONED", "Signature counter did not increase \u2014 the authenticator may be cloned.");
|
|
1556
|
+
}
|
|
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
|
+
};
|
|
1573
|
+
var WebAuthnService = class {
|
|
1574
|
+
config;
|
|
1575
|
+
credentials;
|
|
1576
|
+
challenges;
|
|
1577
|
+
verifier;
|
|
1578
|
+
now;
|
|
1579
|
+
randomChallenge;
|
|
1580
|
+
constructor(options) {
|
|
1581
|
+
this.config = options.config;
|
|
1582
|
+
this.credentials = options.credentials;
|
|
1583
|
+
this.challenges = options.challenges;
|
|
1584
|
+
this.verifier = options.verifier;
|
|
1585
|
+
this.now = options.now ?? (() => Date.now());
|
|
1586
|
+
this.randomChallenge = options.randomChallenge ?? (() => randomBytes8(32).toString("base64url"));
|
|
1587
|
+
}
|
|
1588
|
+
get uv() {
|
|
1589
|
+
return this.config.userVerification ?? "preferred";
|
|
1590
|
+
}
|
|
1591
|
+
get timeout() {
|
|
1592
|
+
return this.config.timeoutMs ?? 6e4;
|
|
1593
|
+
}
|
|
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) {
|
|
1600
|
+
const challenge = this.randomChallenge();
|
|
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
|
+
);
|
|
1607
|
+
return challenge;
|
|
1608
|
+
}
|
|
1609
|
+
/** Registration options for a known user; stores the challenge bound to `user.id`. */
|
|
1610
|
+
async startRegistration(sessionKey, user) {
|
|
1611
|
+
const challenge = await this.issueChallenge("reg", sessionKey, user.id);
|
|
1612
|
+
const existing = await this.credentials.forUser(user.id);
|
|
1613
|
+
return {
|
|
1614
|
+
challenge,
|
|
1615
|
+
rp: { id: this.config.rpId, name: this.config.rpName },
|
|
1616
|
+
user: { id: user.id, name: user.name, displayName: user.displayName ?? user.name },
|
|
1617
|
+
pubKeyCredParams: this.config.pubKeyCredParams ?? DEFAULT_PUB_KEY_PARAMS,
|
|
1618
|
+
timeout: this.timeout,
|
|
1619
|
+
attestation: "none",
|
|
1620
|
+
excludeCredentials: existing.map((c) => ({
|
|
1621
|
+
type: "public-key",
|
|
1622
|
+
id: c.id,
|
|
1623
|
+
...c.transports ? { transports: c.transports } : {}
|
|
1624
|
+
})),
|
|
1625
|
+
authenticatorSelection: { userVerification: this.uv, residentKey: "preferred" }
|
|
1626
|
+
};
|
|
1627
|
+
}
|
|
1628
|
+
/** Verify a registration response and store the new passkey. Throws on failure. */
|
|
1629
|
+
async finishRegistration(sessionKey, userId, response, deviceName) {
|
|
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
|
+
}
|
|
1635
|
+
const result = await this.verifier.verifyRegistration({
|
|
1636
|
+
response,
|
|
1637
|
+
expectedChallenge: stored.challenge,
|
|
1638
|
+
expectedOrigin: this.config.origin,
|
|
1639
|
+
expectedRpId: this.config.rpId,
|
|
1640
|
+
requireUserVerification: this.uv === "required"
|
|
1641
|
+
});
|
|
1642
|
+
if (!result.verified || !result.credential) throw new WebAuthnVerificationError();
|
|
1643
|
+
if (await this.credentials.get(result.credential.id)) throw new PasskeyExistsError();
|
|
1644
|
+
const credential = {
|
|
1645
|
+
id: result.credential.id,
|
|
1646
|
+
userId,
|
|
1647
|
+
publicKey: result.credential.publicKey,
|
|
1648
|
+
counter: result.credential.counter,
|
|
1649
|
+
...result.credential.transports ? { transports: result.credential.transports } : {},
|
|
1650
|
+
...deviceName ? { deviceName } : {},
|
|
1651
|
+
createdAt: this.now()
|
|
1652
|
+
};
|
|
1653
|
+
await this.credentials.add(credential);
|
|
1654
|
+
return credential;
|
|
1655
|
+
}
|
|
1656
|
+
/** Authentication options; `userId` narrows allowCredentials, omit it for discoverable login. */
|
|
1657
|
+
async startAuthentication(sessionKey, userId) {
|
|
1658
|
+
const challenge = await this.issueChallenge("auth", sessionKey);
|
|
1659
|
+
const creds = userId ? await this.credentials.forUser(userId) : [];
|
|
1660
|
+
return {
|
|
1661
|
+
challenge,
|
|
1662
|
+
timeout: this.timeout,
|
|
1663
|
+
rpId: this.config.rpId,
|
|
1664
|
+
userVerification: this.uv,
|
|
1665
|
+
allowCredentials: creds.map((c) => ({
|
|
1666
|
+
type: "public-key",
|
|
1667
|
+
id: c.id,
|
|
1668
|
+
...c.transports ? { transports: c.transports } : {}
|
|
1669
|
+
}))
|
|
1670
|
+
};
|
|
1671
|
+
}
|
|
1672
|
+
/**
|
|
1673
|
+
* Verify an authentication response. Looks the credential up by its id, checks
|
|
1674
|
+
* the signature counter increased (clone detection), persists the new counter,
|
|
1675
|
+
* and returns whose passkey authenticated. Throws on any failure.
|
|
1676
|
+
*/
|
|
1677
|
+
async finishAuthentication(sessionKey, response) {
|
|
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();
|
|
1685
|
+
const credential = await this.credentials.get(credentialId);
|
|
1686
|
+
if (!credential) throw new PasskeyNotFoundError();
|
|
1687
|
+
const result = await this.verifier.verifyAuthentication({
|
|
1688
|
+
response,
|
|
1689
|
+
expectedChallenge: stored.challenge,
|
|
1690
|
+
expectedOrigin: this.config.origin,
|
|
1691
|
+
expectedRpId: this.config.rpId,
|
|
1692
|
+
requireUserVerification: this.uv === "required",
|
|
1693
|
+
credential: { id: credential.id, publicKey: credential.publicKey, counter: credential.counter }
|
|
1694
|
+
});
|
|
1695
|
+
if (!result.verified) throw new WebAuthnVerificationError();
|
|
1696
|
+
if (credential.counter > 0 && result.newCounter <= credential.counter) {
|
|
1697
|
+
throw new PasskeyClonedError();
|
|
1698
|
+
}
|
|
1699
|
+
await this.credentials.updateCounter(credential.id, result.newCounter, this.now());
|
|
1700
|
+
return { userId: credential.userId, credentialId: credential.id };
|
|
1701
|
+
}
|
|
1702
|
+
/** A user's registered passkeys (for a "manage devices" screen). */
|
|
1703
|
+
async list(userId) {
|
|
1704
|
+
return this.credentials.forUser(userId);
|
|
1705
|
+
}
|
|
1706
|
+
/** Remove a passkey (revoke a device). */
|
|
1707
|
+
async remove(credentialId) {
|
|
1708
|
+
await this.credentials.remove(credentialId);
|
|
1709
|
+
}
|
|
1710
|
+
};
|
|
1711
|
+
|
|
1712
|
+
// src/webauthn-plugin.ts
|
|
1713
|
+
import { createToken as createToken4, definePlugin as definePlugin4 } from "@basaltkit/core";
|
|
1714
|
+
var WEBAUTHN = createToken4("auth:webauthn");
|
|
1715
|
+
function webauthnPlugin(options) {
|
|
1716
|
+
return definePlugin4({
|
|
1717
|
+
name: "basalt:auth-webauthn",
|
|
1718
|
+
register({ container }) {
|
|
1719
|
+
container.singleton(
|
|
1720
|
+
WEBAUTHN,
|
|
1721
|
+
() => new WebAuthnService({
|
|
1722
|
+
config: options.config,
|
|
1723
|
+
verifier: options.verifier,
|
|
1724
|
+
credentials: options.credentials ?? new MemoryPasskeyStore(),
|
|
1725
|
+
challenges: options.challenges ?? new MemoryWebAuthnChallengeStore()
|
|
1726
|
+
})
|
|
1727
|
+
);
|
|
1728
|
+
}
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
1476
1731
|
export {
|
|
1477
1732
|
API_KEYS,
|
|
1478
1733
|
AUTH,
|
|
@@ -1487,10 +1742,12 @@ export {
|
|
|
1487
1742
|
MemoryApiKeyStore,
|
|
1488
1743
|
MemoryAuthTokenStore,
|
|
1489
1744
|
MemoryMfaStore,
|
|
1745
|
+
MemoryPasskeyStore,
|
|
1490
1746
|
MemoryRefreshTokenStore,
|
|
1491
1747
|
MemorySessionStore,
|
|
1492
1748
|
MemoryTokenVersionStore,
|
|
1493
1749
|
MemoryUserSource,
|
|
1750
|
+
MemoryWebAuthnChallengeStore,
|
|
1494
1751
|
MfaInvalidCodeError,
|
|
1495
1752
|
MfaNotEnrolledError,
|
|
1496
1753
|
MfaRequiredError,
|
|
@@ -1499,6 +1756,9 @@ export {
|
|
|
1499
1756
|
OAuthExchangeError,
|
|
1500
1757
|
OAuthProviderUnknownError,
|
|
1501
1758
|
OAuthStateInvalidError,
|
|
1759
|
+
PasskeyClonedError,
|
|
1760
|
+
PasskeyExistsError,
|
|
1761
|
+
PasskeyNotFoundError,
|
|
1502
1762
|
RefreshInvalidError,
|
|
1503
1763
|
RefreshReusedError,
|
|
1504
1764
|
ScopeRequiredError,
|
|
@@ -1506,7 +1766,12 @@ export {
|
|
|
1506
1766
|
TokenExpiredError,
|
|
1507
1767
|
TokenInvalidError,
|
|
1508
1768
|
UserUpdateUnsupportedError,
|
|
1769
|
+
WEBAUTHN,
|
|
1509
1770
|
WeakJwtSecretError,
|
|
1771
|
+
WebAuthnChallengeError,
|
|
1772
|
+
WebAuthnService,
|
|
1773
|
+
WebAuthnSubjectMismatchError,
|
|
1774
|
+
WebAuthnVerificationError,
|
|
1510
1775
|
apiKeyRoutes,
|
|
1511
1776
|
apiKeysPlugin,
|
|
1512
1777
|
authPlugin,
|
|
@@ -1528,5 +1793,6 @@ export {
|
|
|
1528
1793
|
signJwt,
|
|
1529
1794
|
totp,
|
|
1530
1795
|
verifyJwt,
|
|
1531
|
-
verifyTotp
|
|
1796
|
+
verifyTotp,
|
|
1797
|
+
webauthnPlugin
|
|
1532
1798
|
};
|
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,8 +14,8 @@
|
|
|
14
14
|
"dist"
|
|
15
15
|
],
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@basaltkit/core": "^1.
|
|
18
|
-
"@basaltkit/fastify": "^1.
|
|
17
|
+
"@basaltkit/core": "^1.1.1",
|
|
18
|
+
"@basaltkit/fastify": "^1.5.0"
|
|
19
19
|
},
|
|
20
20
|
"peerDependencies": {
|
|
21
21
|
"zod": "^3.24.0 || ^4.0.0"
|