@basaltkit/auth 1.4.0 → 1.5.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 +156 -3
- package/dist/index.d.ts +216 -1
- package/dist/index.js +222 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @basaltkit/auth
|
|
2
2
|
|
|
3
|
-
Complete authentication for Basalt applications: user registration and login, JWT tokens with secure renewal, sessions, email verification, password recovery, two-factor authentication (MFA/TOTP), and API keys — all with ready-to-use HTTP routes.
|
|
3
|
+
Complete authentication for Basalt applications: user registration and login, JWT tokens with secure renewal, sessions, email verification, password recovery, two-factor authentication (MFA/TOTP), social login (Google, GitHub, or any OpenID Connect provider), and API keys — all with ready-to-use HTTP routes.
|
|
4
4
|
|
|
5
5
|
You need this module whenever your application has users who log in.
|
|
6
6
|
|
|
@@ -10,7 +10,7 @@ When an application has user accounts, it needs to answer two questions on every
|
|
|
10
10
|
|
|
11
11
|
`@basaltkit/auth` handles all of this for you. Passwords are never stored in plain text — only an irreversibly scrambled version (**hash**, using the scrypt algorithm). Login returns a pair of tokens: an **access token** (short-lived JWT, 15 minutes by default, sent with every request) and a **refresh token** (long-lived, 30 days, used only to obtain a new access token). If a refresh token is used twice — a typical sign of theft — the entire token "family" is automatically revoked.
|
|
12
12
|
|
|
13
|
-
It also includes, with nothing extra to install: account lockout after too many failed attempts, email verification and password recovery via single-use links, MFA via authenticator app (Google Authenticator, etc.) with recovery codes, and API keys for programmatic access (scripts, integrations).
|
|
13
|
+
It also includes, with nothing extra to install: account lockout after too many failed attempts, email verification and password recovery via single-use links, MFA via authenticator app (Google Authenticator, etc.) with recovery codes, social login (OAuth 2.0 / OpenID Connect), and API keys for programmatic access (scripts, integrations).
|
|
14
14
|
|
|
15
15
|
## Installation
|
|
16
16
|
|
|
@@ -162,6 +162,150 @@ 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
|
+
`finishAuthentication` looks the credential up by id, verifies it, checks the
|
|
246
|
+
signature counter **increased** (a non-increasing counter throws `PasskeyClonedError`),
|
|
247
|
+
and persists the new counter. Use `passkeys.list(userId)` / `passkeys.remove(id)`
|
|
248
|
+
for a "manage devices" screen.
|
|
249
|
+
|
|
250
|
+
### Social login (OAuth)
|
|
251
|
+
|
|
252
|
+
Sign in with Google, GitHub, or any OpenID Connect provider via the OAuth 2.0
|
|
253
|
+
authorization-code flow — no SDK, and cookieless (the CSRF `state` is HMAC-signed
|
|
254
|
+
and stateless). Register `oauthPlugin` with your providers and `oauthRoutes` with
|
|
255
|
+
your app's **base URL**:
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
import {
|
|
259
|
+
authPlugin, authRoutes, oauthPlugin, oauthRoutes, googleProvider, githubProvider,
|
|
260
|
+
} from '@basaltkit/auth'
|
|
261
|
+
import { fastifyPlugin } from '@basaltkit/fastify'
|
|
262
|
+
|
|
263
|
+
createApp({
|
|
264
|
+
plugins: [
|
|
265
|
+
authPlugin({ users, secret: process.env.AUTH_SECRET! }),
|
|
266
|
+
oauthPlugin({
|
|
267
|
+
secret: process.env.AUTH_SECRET!, // signs the stateless `state`
|
|
268
|
+
providers: [
|
|
269
|
+
googleProvider({ clientId: env.GOOGLE_ID, clientSecret: env.GOOGLE_SECRET }),
|
|
270
|
+
githubProvider({ clientId: env.GITHUB_ID, clientSecret: env.GITHUB_SECRET }),
|
|
271
|
+
],
|
|
272
|
+
}),
|
|
273
|
+
fastifyPlugin({
|
|
274
|
+
routes: [
|
|
275
|
+
...authRoutes(),
|
|
276
|
+
// callbackBaseUrl is your app's BASE url — the module appends
|
|
277
|
+
// /auth/oauth/:provider/callback itself.
|
|
278
|
+
...oauthRoutes({ callbackBaseUrl: 'https://app.example.com' }),
|
|
279
|
+
],
|
|
280
|
+
}),
|
|
281
|
+
],
|
|
282
|
+
})
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
Two routes are added per provider:
|
|
286
|
+
|
|
287
|
+
- `GET /auth/oauth/:provider` → 302 to the provider's consent screen.
|
|
288
|
+
- `GET /auth/oauth/:provider/callback` → verifies the `state`, exchanges the code,
|
|
289
|
+
and logs the user in. Returns JSON `{ user, accessToken, refreshToken }`; pass
|
|
290
|
+
`successRedirect` to `oauthRoutes` to bounce the browser back to your SPA with
|
|
291
|
+
the tokens in the URL fragment instead.
|
|
292
|
+
|
|
293
|
+
**Register the redirect URI with each provider exactly** as
|
|
294
|
+
`${callbackBaseUrl}/auth/oauth/:provider/callback` — e.g.
|
|
295
|
+
`https://app.example.com/auth/oauth/github/callback`. It must match
|
|
296
|
+
character-for-character, or the provider rejects it with *"redirect_uri is not
|
|
297
|
+
associated with this application"*.
|
|
298
|
+
|
|
299
|
+
New accounts are created **passwordless** and a provider-verified email flips
|
|
300
|
+
`emailVerified`. Accounts are matched by email, so only trust providers that
|
|
301
|
+
return a **verified** address (Google and the built-in GitHub driver both do).
|
|
302
|
+
`Auth.socialLogin(email)` is the underlying primitive for custom providers.
|
|
303
|
+
|
|
304
|
+
**Enterprise SSO (OIDC):** any OpenID Connect IdP (Okta, Entra ID, Auth0,
|
|
305
|
+
Keycloak…) plugs in via `oidcProvider({ clientId, clientSecret, authorizationUrl,
|
|
306
|
+
tokenUrl, userinfoUrl })`, or let `discoverOidcProvider(issuerUrl, keys)` read the
|
|
307
|
+
endpoints from the IdP's `.well-known/openid-configuration`.
|
|
308
|
+
|
|
165
309
|
### API keys
|
|
166
310
|
|
|
167
311
|
For programmatic access (scripts, CI, integrations) without interactive login. A key has the format `mk_live_...`, is shown **only once** when created, and only its SHA-256 hash is stored.
|
|
@@ -254,12 +398,14 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
254
398
|
| `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
|
|
255
399
|
| `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
|
|
256
400
|
| `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
|
|
401
|
+
| `socialLogin(email, { emailVerified? })` | Find-or-create a passwordless account for an OAuth/OIDC identity; returns `{ user, tokens }`. |
|
|
257
402
|
|
|
258
403
|
### Ready-made routes
|
|
259
404
|
|
|
260
405
|
- `authRoutes()`: `POST /auth/register`, `POST /auth/login`, `POST /auth/refresh`, `POST /auth/logout`, `GET /auth/me`, `POST /auth/verify/request`, `POST /auth/verify`, `POST /auth/password/forgot`, `POST /auth/password/reset`. These are regular routes — you can omit or replace any of them.
|
|
261
406
|
- `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys`, `DELETE /apikeys/:id` (all require login; scoped to the current tenant/user).
|
|
262
407
|
- `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
|
|
408
|
+
- `oauthRoutes({ callbackBaseUrl, successRedirect? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider.
|
|
263
409
|
|
|
264
410
|
### `apiKeysPlugin(options)` and the `ApiKeys` class
|
|
265
411
|
|
|
@@ -283,7 +429,9 @@ Options (`ApiKeysPluginOptions`):
|
|
|
283
429
|
| `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `clock`) | Anti brute-force. |
|
|
284
430
|
| `generateTotpSecret`, `totp`, `verifyTotp`, `otpauthUri`, `base32Encode`, `base32Decode` | TOTP primitives (RFC 6238). Advanced. |
|
|
285
431
|
| `publicUser(user)` | Converts `AuthUser` → `PublicUser` (removes the hash). |
|
|
286
|
-
| `AUTH`, `API_KEYS` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance. |
|
|
432
|
+
| `AUTH`, `API_KEYS`, `OAUTH` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance; `OAUTH` returns the `OAuth` instance. |
|
|
433
|
+
| `oauthPlugin`, `oauthRoutes` | Social-login plugin (`{ secret, providers }`) and its routes (`{ callbackBaseUrl, successRedirect? }`). |
|
|
434
|
+
| `googleProvider`, `githubProvider`, `oidcProvider`, `discoverOidcProvider` | OAuth 2.0 / OpenID Connect providers. Each takes `{ clientId, clientSecret, scopes? }`. |
|
|
287
435
|
| In-memory stores | `MemoryUserSource`, `MemorySessionStore`, `MemoryRefreshTokenStore`, `MemoryAuthTokenStore`, `MemoryApiKeyStore`, `MemoryMfaStore` — dev/testing. |
|
|
288
436
|
|
|
289
437
|
### Exported errors
|
|
@@ -300,6 +448,9 @@ Options (`ApiKeysPluginOptions`):
|
|
|
300
448
|
| `MfaRequiredError` / `MfaInvalidCodeError` / `MfaNotEnrolledError` | `AUTH_MFA_*` | 401/401/400 |
|
|
301
449
|
| `AccountLockedError` | `AUTH_LOCKED` | 429 |
|
|
302
450
|
| `ScopeRequiredError` | `AUTH_SCOPE_REQUIRED` | 403 |
|
|
451
|
+
| `OAuthProviderUnknownError` | `AUTH_OAUTH_UNKNOWN_PROVIDER` | 404 |
|
|
452
|
+
| `OAuthStateInvalidError` | `AUTH_OAUTH_STATE_INVALID` | 400 |
|
|
453
|
+
| `OAuthExchangeError` | `AUTH_OAUTH_EXCHANGE_FAILED` | 502 |
|
|
303
454
|
|
|
304
455
|
## Common issues and solutions (FAQ)
|
|
305
456
|
|
|
@@ -317,6 +468,8 @@ Options (`ApiKeysPluginOptions`):
|
|
|
317
468
|
|
|
318
469
|
**"My API key doesn't work with authPlugin."** Correct: bearers prefixed with `mk_` are ignored by `authPlugin` and handled by `apiKeysPlugin` — register both.
|
|
319
470
|
|
|
471
|
+
**"OAuth: redirect_uri is not associated with this application."** Your `callbackBaseUrl` must be the app's **base URL** (`https://app.example.com`), *not* the full callback path — the module appends `/auth/oauth/:provider/callback` itself. Passing the full callback URL doubles the path so it no longer matches what you registered. Register exactly `${callbackBaseUrl}/auth/oauth/:provider/callback` with the provider.
|
|
472
|
+
|
|
320
473
|
## How it connects to other modules
|
|
321
474
|
|
|
322
475
|
- **@basaltkit/core** — provides the app, the container, the request context (`ctx()`), and hooks; auth sets `ctx().user` and `ctx().apiKey`.
|
package/dist/index.d.ts
CHANGED
|
@@ -905,4 +905,219 @@ 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
|
+
interface WebAuthnChallengeStore {
|
|
945
|
+
save(key: string, challenge: string, expiresAt: number): Promise<void>;
|
|
946
|
+
/** Return AND consume the challenge (single-use), or null if missing/expired. */
|
|
947
|
+
take(key: string): Promise<string | null>;
|
|
948
|
+
}
|
|
949
|
+
declare class MemoryWebAuthnChallengeStore implements WebAuthnChallengeStore {
|
|
950
|
+
private readonly entries;
|
|
951
|
+
private readonly now;
|
|
952
|
+
constructor(options?: {
|
|
953
|
+
now?: () => number;
|
|
954
|
+
});
|
|
955
|
+
save(key: string, challenge: string, expiresAt: number): Promise<void>;
|
|
956
|
+
take(key: string): Promise<string | null>;
|
|
957
|
+
}
|
|
958
|
+
interface VerifyRegistrationInput {
|
|
959
|
+
/** The `RegistrationResponseJSON` from `@simplewebauthn/browser`. */
|
|
960
|
+
response: unknown;
|
|
961
|
+
expectedChallenge: string;
|
|
962
|
+
expectedOrigin: string | string[];
|
|
963
|
+
expectedRpId: string;
|
|
964
|
+
requireUserVerification: boolean;
|
|
965
|
+
}
|
|
966
|
+
interface VerifiedRegistration {
|
|
967
|
+
verified: boolean;
|
|
968
|
+
credential?: {
|
|
969
|
+
id: string;
|
|
970
|
+
publicKey: string;
|
|
971
|
+
counter: number;
|
|
972
|
+
transports?: string[];
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
interface VerifyAuthenticationInput {
|
|
976
|
+
/** The `AuthenticationResponseJSON` from `@simplewebauthn/browser`. */
|
|
977
|
+
response: unknown;
|
|
978
|
+
expectedChallenge: string;
|
|
979
|
+
expectedOrigin: string | string[];
|
|
980
|
+
expectedRpId: string;
|
|
981
|
+
requireUserVerification: boolean;
|
|
982
|
+
credential: {
|
|
983
|
+
id: string;
|
|
984
|
+
publicKey: string;
|
|
985
|
+
counter: number;
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
interface VerifiedAuthentication {
|
|
989
|
+
verified: boolean;
|
|
990
|
+
newCounter: number;
|
|
991
|
+
}
|
|
992
|
+
/** The cryptographic boundary — implement over a WebAuthn library. */
|
|
993
|
+
interface WebAuthnVerifier {
|
|
994
|
+
verifyRegistration(input: VerifyRegistrationInput): Promise<VerifiedRegistration>;
|
|
995
|
+
verifyAuthentication(input: VerifyAuthenticationInput): Promise<VerifiedAuthentication>;
|
|
996
|
+
}
|
|
997
|
+
interface PublicKeyParam {
|
|
998
|
+
type: 'public-key';
|
|
999
|
+
alg: number;
|
|
1000
|
+
}
|
|
1001
|
+
interface CredentialDescriptor {
|
|
1002
|
+
type: 'public-key';
|
|
1003
|
+
id: string;
|
|
1004
|
+
transports?: string[];
|
|
1005
|
+
}
|
|
1006
|
+
interface RegistrationOptions {
|
|
1007
|
+
challenge: string;
|
|
1008
|
+
rp: {
|
|
1009
|
+
id: string;
|
|
1010
|
+
name: string;
|
|
1011
|
+
};
|
|
1012
|
+
user: {
|
|
1013
|
+
id: string;
|
|
1014
|
+
name: string;
|
|
1015
|
+
displayName: string;
|
|
1016
|
+
};
|
|
1017
|
+
pubKeyCredParams: PublicKeyParam[];
|
|
1018
|
+
timeout: number;
|
|
1019
|
+
attestation: 'none';
|
|
1020
|
+
excludeCredentials: CredentialDescriptor[];
|
|
1021
|
+
authenticatorSelection: {
|
|
1022
|
+
userVerification: string;
|
|
1023
|
+
residentKey: 'preferred';
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
interface AuthenticationOptions {
|
|
1027
|
+
challenge: string;
|
|
1028
|
+
timeout: number;
|
|
1029
|
+
rpId: string;
|
|
1030
|
+
userVerification: string;
|
|
1031
|
+
allowCredentials: CredentialDescriptor[];
|
|
1032
|
+
}
|
|
1033
|
+
declare class WebAuthnChallengeError extends BasaltError {
|
|
1034
|
+
readonly status = 400;
|
|
1035
|
+
constructor();
|
|
1036
|
+
}
|
|
1037
|
+
declare class WebAuthnVerificationError extends BasaltError {
|
|
1038
|
+
readonly status = 400;
|
|
1039
|
+
constructor();
|
|
1040
|
+
}
|
|
1041
|
+
declare class PasskeyNotFoundError extends BasaltError {
|
|
1042
|
+
readonly status = 404;
|
|
1043
|
+
constructor();
|
|
1044
|
+
}
|
|
1045
|
+
declare class PasskeyClonedError extends BasaltError {
|
|
1046
|
+
readonly status = 401;
|
|
1047
|
+
constructor();
|
|
1048
|
+
}
|
|
1049
|
+
interface WebAuthnConfig {
|
|
1050
|
+
/** Relying Party ID — your registrable domain, e.g. 'example.com'. */
|
|
1051
|
+
rpId: string;
|
|
1052
|
+
/** Human-readable RP name shown in the OS prompt. */
|
|
1053
|
+
rpName: string;
|
|
1054
|
+
/** Expected origin(s), e.g. 'https://example.com'. */
|
|
1055
|
+
origin: string | string[];
|
|
1056
|
+
/** Challenge TTL in ms. Default 5 minutes. */
|
|
1057
|
+
challengeTtlMs?: number;
|
|
1058
|
+
/** User-verification requirement. Default 'preferred'. */
|
|
1059
|
+
userVerification?: 'required' | 'preferred' | 'discouraged';
|
|
1060
|
+
/** Ceremony timeout advertised to the browser, ms. Default 60s. */
|
|
1061
|
+
timeoutMs?: number;
|
|
1062
|
+
/** Override the accepted algorithms. Default ES256 + RS256. */
|
|
1063
|
+
pubKeyCredParams?: PublicKeyParam[];
|
|
1064
|
+
}
|
|
1065
|
+
interface WebAuthnServiceOptions {
|
|
1066
|
+
config: WebAuthnConfig;
|
|
1067
|
+
credentials: PasskeyStore;
|
|
1068
|
+
challenges: WebAuthnChallengeStore;
|
|
1069
|
+
verifier: WebAuthnVerifier;
|
|
1070
|
+
now?: () => number;
|
|
1071
|
+
/** Challenge generator (tests). Default: 32 random bytes, base64url. */
|
|
1072
|
+
randomChallenge?: () => string;
|
|
1073
|
+
}
|
|
1074
|
+
declare class WebAuthnService {
|
|
1075
|
+
private readonly config;
|
|
1076
|
+
private readonly credentials;
|
|
1077
|
+
private readonly challenges;
|
|
1078
|
+
private readonly verifier;
|
|
1079
|
+
private readonly now;
|
|
1080
|
+
private readonly randomChallenge;
|
|
1081
|
+
constructor(options: WebAuthnServiceOptions);
|
|
1082
|
+
private get uv();
|
|
1083
|
+
private get timeout();
|
|
1084
|
+
private issueChallenge;
|
|
1085
|
+
/** Registration options for a known user; stores the challenge under `sessionKey`. */
|
|
1086
|
+
startRegistration(sessionKey: string, user: {
|
|
1087
|
+
id: string;
|
|
1088
|
+
name: string;
|
|
1089
|
+
displayName?: string;
|
|
1090
|
+
}): Promise<RegistrationOptions>;
|
|
1091
|
+
/** Verify a registration response and store the new passkey. Throws on failure. */
|
|
1092
|
+
finishRegistration(sessionKey: string, userId: string, response: unknown, deviceName?: string): Promise<PasskeyCredential>;
|
|
1093
|
+
/** Authentication options; `userId` narrows allowCredentials, omit it for discoverable login. */
|
|
1094
|
+
startAuthentication(sessionKey: string, userId?: string): Promise<AuthenticationOptions>;
|
|
1095
|
+
/**
|
|
1096
|
+
* Verify an authentication response. Looks the credential up by its id, checks
|
|
1097
|
+
* the signature counter increased (clone detection), persists the new counter,
|
|
1098
|
+
* and returns whose passkey authenticated. Throws on any failure.
|
|
1099
|
+
*/
|
|
1100
|
+
finishAuthentication(sessionKey: string, response: unknown): Promise<{
|
|
1101
|
+
userId: string;
|
|
1102
|
+
credentialId: string;
|
|
1103
|
+
}>;
|
|
1104
|
+
/** A user's registered passkeys (for a "manage devices" screen). */
|
|
1105
|
+
list(userId: string): Promise<PasskeyCredential[]>;
|
|
1106
|
+
/** Remove a passkey (revoke a device). */
|
|
1107
|
+
remove(credentialId: string): Promise<void>;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
declare const WEBAUTHN: _basaltkit_core.Token<WebAuthnService>;
|
|
1111
|
+
interface WebAuthnPluginOptions {
|
|
1112
|
+
config: WebAuthnConfig;
|
|
1113
|
+
/** The crypto boundary — implement over `@simplewebauthn/server`. Required. */
|
|
1114
|
+
verifier: WebAuthnVerifier;
|
|
1115
|
+
/** Passkey storage. Default: in-memory (swap for a durable store). */
|
|
1116
|
+
credentials?: PasskeyStore;
|
|
1117
|
+
/** Challenge storage. Default: in-memory. */
|
|
1118
|
+
challenges?: WebAuthnChallengeStore;
|
|
1119
|
+
}
|
|
1120
|
+
/** Registers a {@link WebAuthnService} under the {@link WEBAUTHN} token. */
|
|
1121
|
+
declare function webauthnPlugin(options: WebAuthnPluginOptions): _basaltkit_core.BasaltPlugin<unknown>;
|
|
1122
|
+
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -1473,6 +1473,218 @@ 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
|
+
constructor(options = {}) {
|
|
1507
|
+
this.now = options.now ?? (() => Date.now());
|
|
1508
|
+
}
|
|
1509
|
+
async save(key, challenge, expiresAt) {
|
|
1510
|
+
this.entries.set(key, { challenge, expiresAt });
|
|
1511
|
+
}
|
|
1512
|
+
async take(key) {
|
|
1513
|
+
const entry = this.entries.get(key);
|
|
1514
|
+
if (!entry) return null;
|
|
1515
|
+
this.entries.delete(key);
|
|
1516
|
+
return entry.expiresAt > this.now() ? entry.challenge : null;
|
|
1517
|
+
}
|
|
1518
|
+
};
|
|
1519
|
+
var DEFAULT_PUB_KEY_PARAMS = [
|
|
1520
|
+
{ type: "public-key", alg: -7 },
|
|
1521
|
+
{ type: "public-key", alg: -257 }
|
|
1522
|
+
];
|
|
1523
|
+
var WebAuthnChallengeError = class extends BasaltError7 {
|
|
1524
|
+
status = 400;
|
|
1525
|
+
constructor() {
|
|
1526
|
+
super("WEBAUTHN_CHALLENGE_INVALID", "No matching WebAuthn challenge \u2014 it expired or was already used.");
|
|
1527
|
+
}
|
|
1528
|
+
};
|
|
1529
|
+
var WebAuthnVerificationError = class extends BasaltError7 {
|
|
1530
|
+
status = 400;
|
|
1531
|
+
constructor() {
|
|
1532
|
+
super("WEBAUTHN_VERIFICATION_FAILED", "The WebAuthn response could not be verified.");
|
|
1533
|
+
}
|
|
1534
|
+
};
|
|
1535
|
+
var PasskeyNotFoundError = class extends BasaltError7 {
|
|
1536
|
+
status = 404;
|
|
1537
|
+
constructor() {
|
|
1538
|
+
super("PASSKEY_NOT_FOUND", "No passkey matches the presented credential.");
|
|
1539
|
+
}
|
|
1540
|
+
};
|
|
1541
|
+
var PasskeyClonedError = class extends BasaltError7 {
|
|
1542
|
+
status = 401;
|
|
1543
|
+
constructor() {
|
|
1544
|
+
super("PASSKEY_CLONED", "Signature counter did not increase \u2014 the authenticator may be cloned.");
|
|
1545
|
+
}
|
|
1546
|
+
};
|
|
1547
|
+
var WebAuthnService = class {
|
|
1548
|
+
config;
|
|
1549
|
+
credentials;
|
|
1550
|
+
challenges;
|
|
1551
|
+
verifier;
|
|
1552
|
+
now;
|
|
1553
|
+
randomChallenge;
|
|
1554
|
+
constructor(options) {
|
|
1555
|
+
this.config = options.config;
|
|
1556
|
+
this.credentials = options.credentials;
|
|
1557
|
+
this.challenges = options.challenges;
|
|
1558
|
+
this.verifier = options.verifier;
|
|
1559
|
+
this.now = options.now ?? (() => Date.now());
|
|
1560
|
+
this.randomChallenge = options.randomChallenge ?? (() => randomBytes8(32).toString("base64url"));
|
|
1561
|
+
}
|
|
1562
|
+
get uv() {
|
|
1563
|
+
return this.config.userVerification ?? "preferred";
|
|
1564
|
+
}
|
|
1565
|
+
get timeout() {
|
|
1566
|
+
return this.config.timeoutMs ?? 6e4;
|
|
1567
|
+
}
|
|
1568
|
+
async issueChallenge(sessionKey) {
|
|
1569
|
+
const challenge = this.randomChallenge();
|
|
1570
|
+
await this.challenges.save(sessionKey, challenge, this.now() + (this.config.challengeTtlMs ?? 3e5));
|
|
1571
|
+
return challenge;
|
|
1572
|
+
}
|
|
1573
|
+
/** Registration options for a known user; stores the challenge under `sessionKey`. */
|
|
1574
|
+
async startRegistration(sessionKey, user) {
|
|
1575
|
+
const challenge = await this.issueChallenge(sessionKey);
|
|
1576
|
+
const existing = await this.credentials.forUser(user.id);
|
|
1577
|
+
return {
|
|
1578
|
+
challenge,
|
|
1579
|
+
rp: { id: this.config.rpId, name: this.config.rpName },
|
|
1580
|
+
user: { id: user.id, name: user.name, displayName: user.displayName ?? user.name },
|
|
1581
|
+
pubKeyCredParams: this.config.pubKeyCredParams ?? DEFAULT_PUB_KEY_PARAMS,
|
|
1582
|
+
timeout: this.timeout,
|
|
1583
|
+
attestation: "none",
|
|
1584
|
+
excludeCredentials: existing.map((c) => ({
|
|
1585
|
+
type: "public-key",
|
|
1586
|
+
id: c.id,
|
|
1587
|
+
...c.transports ? { transports: c.transports } : {}
|
|
1588
|
+
})),
|
|
1589
|
+
authenticatorSelection: { userVerification: this.uv, residentKey: "preferred" }
|
|
1590
|
+
};
|
|
1591
|
+
}
|
|
1592
|
+
/** Verify a registration response and store the new passkey. Throws on failure. */
|
|
1593
|
+
async finishRegistration(sessionKey, userId, response, deviceName) {
|
|
1594
|
+
const expectedChallenge = await this.challenges.take(sessionKey);
|
|
1595
|
+
if (!expectedChallenge) throw new WebAuthnChallengeError();
|
|
1596
|
+
const result = await this.verifier.verifyRegistration({
|
|
1597
|
+
response,
|
|
1598
|
+
expectedChallenge,
|
|
1599
|
+
expectedOrigin: this.config.origin,
|
|
1600
|
+
expectedRpId: this.config.rpId,
|
|
1601
|
+
requireUserVerification: this.uv === "required"
|
|
1602
|
+
});
|
|
1603
|
+
if (!result.verified || !result.credential) throw new WebAuthnVerificationError();
|
|
1604
|
+
const credential = {
|
|
1605
|
+
id: result.credential.id,
|
|
1606
|
+
userId,
|
|
1607
|
+
publicKey: result.credential.publicKey,
|
|
1608
|
+
counter: result.credential.counter,
|
|
1609
|
+
...result.credential.transports ? { transports: result.credential.transports } : {},
|
|
1610
|
+
...deviceName ? { deviceName } : {},
|
|
1611
|
+
createdAt: this.now()
|
|
1612
|
+
};
|
|
1613
|
+
await this.credentials.add(credential);
|
|
1614
|
+
return credential;
|
|
1615
|
+
}
|
|
1616
|
+
/** Authentication options; `userId` narrows allowCredentials, omit it for discoverable login. */
|
|
1617
|
+
async startAuthentication(sessionKey, userId) {
|
|
1618
|
+
const challenge = await this.issueChallenge(sessionKey);
|
|
1619
|
+
const creds = userId ? await this.credentials.forUser(userId) : [];
|
|
1620
|
+
return {
|
|
1621
|
+
challenge,
|
|
1622
|
+
timeout: this.timeout,
|
|
1623
|
+
rpId: this.config.rpId,
|
|
1624
|
+
userVerification: this.uv,
|
|
1625
|
+
allowCredentials: creds.map((c) => ({
|
|
1626
|
+
type: "public-key",
|
|
1627
|
+
id: c.id,
|
|
1628
|
+
...c.transports ? { transports: c.transports } : {}
|
|
1629
|
+
}))
|
|
1630
|
+
};
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* Verify an authentication response. Looks the credential up by its id, checks
|
|
1634
|
+
* the signature counter increased (clone detection), persists the new counter,
|
|
1635
|
+
* and returns whose passkey authenticated. Throws on any failure.
|
|
1636
|
+
*/
|
|
1637
|
+
async finishAuthentication(sessionKey, response) {
|
|
1638
|
+
const credentialId = response?.id;
|
|
1639
|
+
if (!credentialId) throw new PasskeyNotFoundError();
|
|
1640
|
+
const credential = await this.credentials.get(credentialId);
|
|
1641
|
+
if (!credential) throw new PasskeyNotFoundError();
|
|
1642
|
+
const expectedChallenge = await this.challenges.take(sessionKey);
|
|
1643
|
+
if (!expectedChallenge) throw new WebAuthnChallengeError();
|
|
1644
|
+
const result = await this.verifier.verifyAuthentication({
|
|
1645
|
+
response,
|
|
1646
|
+
expectedChallenge,
|
|
1647
|
+
expectedOrigin: this.config.origin,
|
|
1648
|
+
expectedRpId: this.config.rpId,
|
|
1649
|
+
requireUserVerification: this.uv === "required",
|
|
1650
|
+
credential: { id: credential.id, publicKey: credential.publicKey, counter: credential.counter }
|
|
1651
|
+
});
|
|
1652
|
+
if (!result.verified) throw new WebAuthnVerificationError();
|
|
1653
|
+
if (credential.counter > 0 && result.newCounter <= credential.counter) {
|
|
1654
|
+
throw new PasskeyClonedError();
|
|
1655
|
+
}
|
|
1656
|
+
await this.credentials.updateCounter(credential.id, result.newCounter, this.now());
|
|
1657
|
+
return { userId: credential.userId, credentialId: credential.id };
|
|
1658
|
+
}
|
|
1659
|
+
/** A user's registered passkeys (for a "manage devices" screen). */
|
|
1660
|
+
async list(userId) {
|
|
1661
|
+
return this.credentials.forUser(userId);
|
|
1662
|
+
}
|
|
1663
|
+
/** Remove a passkey (revoke a device). */
|
|
1664
|
+
async remove(credentialId) {
|
|
1665
|
+
await this.credentials.remove(credentialId);
|
|
1666
|
+
}
|
|
1667
|
+
};
|
|
1668
|
+
|
|
1669
|
+
// src/webauthn-plugin.ts
|
|
1670
|
+
import { createToken as createToken4, definePlugin as definePlugin4 } from "@basaltkit/core";
|
|
1671
|
+
var WEBAUTHN = createToken4("auth:webauthn");
|
|
1672
|
+
function webauthnPlugin(options) {
|
|
1673
|
+
return definePlugin4({
|
|
1674
|
+
name: "basalt:auth-webauthn",
|
|
1675
|
+
register({ container }) {
|
|
1676
|
+
container.singleton(
|
|
1677
|
+
WEBAUTHN,
|
|
1678
|
+
() => new WebAuthnService({
|
|
1679
|
+
config: options.config,
|
|
1680
|
+
verifier: options.verifier,
|
|
1681
|
+
credentials: options.credentials ?? new MemoryPasskeyStore(),
|
|
1682
|
+
challenges: options.challenges ?? new MemoryWebAuthnChallengeStore()
|
|
1683
|
+
})
|
|
1684
|
+
);
|
|
1685
|
+
}
|
|
1686
|
+
});
|
|
1687
|
+
}
|
|
1476
1688
|
export {
|
|
1477
1689
|
API_KEYS,
|
|
1478
1690
|
AUTH,
|
|
@@ -1487,10 +1699,12 @@ export {
|
|
|
1487
1699
|
MemoryApiKeyStore,
|
|
1488
1700
|
MemoryAuthTokenStore,
|
|
1489
1701
|
MemoryMfaStore,
|
|
1702
|
+
MemoryPasskeyStore,
|
|
1490
1703
|
MemoryRefreshTokenStore,
|
|
1491
1704
|
MemorySessionStore,
|
|
1492
1705
|
MemoryTokenVersionStore,
|
|
1493
1706
|
MemoryUserSource,
|
|
1707
|
+
MemoryWebAuthnChallengeStore,
|
|
1494
1708
|
MfaInvalidCodeError,
|
|
1495
1709
|
MfaNotEnrolledError,
|
|
1496
1710
|
MfaRequiredError,
|
|
@@ -1499,6 +1713,8 @@ export {
|
|
|
1499
1713
|
OAuthExchangeError,
|
|
1500
1714
|
OAuthProviderUnknownError,
|
|
1501
1715
|
OAuthStateInvalidError,
|
|
1716
|
+
PasskeyClonedError,
|
|
1717
|
+
PasskeyNotFoundError,
|
|
1502
1718
|
RefreshInvalidError,
|
|
1503
1719
|
RefreshReusedError,
|
|
1504
1720
|
ScopeRequiredError,
|
|
@@ -1506,7 +1722,11 @@ export {
|
|
|
1506
1722
|
TokenExpiredError,
|
|
1507
1723
|
TokenInvalidError,
|
|
1508
1724
|
UserUpdateUnsupportedError,
|
|
1725
|
+
WEBAUTHN,
|
|
1509
1726
|
WeakJwtSecretError,
|
|
1727
|
+
WebAuthnChallengeError,
|
|
1728
|
+
WebAuthnService,
|
|
1729
|
+
WebAuthnVerificationError,
|
|
1510
1730
|
apiKeyRoutes,
|
|
1511
1731
|
apiKeysPlugin,
|
|
1512
1732
|
authPlugin,
|
|
@@ -1528,5 +1748,6 @@ export {
|
|
|
1528
1748
|
signJwt,
|
|
1529
1749
|
totp,
|
|
1530
1750
|
verifyJwt,
|
|
1531
|
-
verifyTotp
|
|
1751
|
+
verifyTotp,
|
|
1752
|
+
webauthnPlugin
|
|
1532
1753
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@basaltkit/auth",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.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.0",
|
|
18
|
+
"@basaltkit/fastify": "^1.5.0"
|
|
19
19
|
},
|
|
20
20
|
"peerDependencies": {
|
|
21
21
|
"zod": "^3.24.0 || ^4.0.0"
|