@basaltkit/auth 3.2.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -25
- package/dist/apikeys-plugin.d.ts +11 -1
- package/dist/apikeys-plugin.js +22 -2
- package/dist/auth.d.ts +112 -22
- package/dist/auth.js +179 -49
- 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 +39 -0
- package/dist/stores.js +28 -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/README.md
CHANGED
|
@@ -79,7 +79,11 @@ curl -b cookies.txt http://localhost:3000/auth/me
|
|
|
79
79
|
```
|
|
80
80
|
|
|
81
81
|
The cookie defaults to `HttpOnly`, `SameSite=Lax`, `Path=/`, and `Secure` in
|
|
82
|
-
production
|
|
82
|
+
production — anything but an explicit `NODE_ENV=development` or `test` (an
|
|
83
|
+
unset `NODE_ENV` counts as production, as in `@basaltkit/env`). The same rule
|
|
84
|
+
gates the 32-character minimum on `secret` (`AUTH_WEAK_SECRET`). A cookie whose
|
|
85
|
+
value cannot be decoded (malformed percent-encoding) is ignored: the request is
|
|
86
|
+
simply anonymous. Customize its public attributes when mounting the plugin:
|
|
83
87
|
|
|
84
88
|
```ts
|
|
85
89
|
authPlugin({
|
|
@@ -190,7 +194,7 @@ All operations are also available programmatically through the `Auth` class:
|
|
|
190
194
|
```ts
|
|
191
195
|
import { Auth, MemoryUserSource } from '@basaltkit/auth'
|
|
192
196
|
|
|
193
|
-
const auth = new Auth({ users: new MemoryUserSource(), secret:
|
|
197
|
+
const auth = new Auth({ users: new MemoryUserSource(), secret: process.env.AUTH_SECRET! }) // >= 32 chars in production
|
|
194
198
|
|
|
195
199
|
const user = await auth.register('ada@example.com', 'secretpassword1')
|
|
196
200
|
const { tokens } = await auth.login('ada@example.com', 'secretpassword1')
|
|
@@ -237,7 +241,7 @@ Flow (all routes require login):
|
|
|
237
241
|
|
|
238
242
|
1. `POST /auth/mfa/enroll` → returns `{ secret, otpauthUri }`; show the `otpauthUri` as a QR code.
|
|
239
243
|
2. `POST /auth/mfa/activate` with `{ code }` (code from the app) → activates and returns `{ recoveryCodes }` — 10 single-use recovery codes, **shown only once**.
|
|
240
|
-
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.
|
|
244
|
+
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 (counted by the login throttle — see [Brute-force lockout](#brute-force-lockout-loginthrottle)).
|
|
241
245
|
4. `GET /auth/mfa/status` and `POST /auth/mfa/disable` (with `{ code }`) complete the cycle.
|
|
242
246
|
|
|
243
247
|
**Requiring MFA.** `authPlugin({ requireMfa: true })` — or a policy
|
|
@@ -252,6 +256,17 @@ enroll/activate/status. `meta: { mfa: true }` requires MFA on one route
|
|
|
252
256
|
session cookie carries it HMAC-signed, and the request exposes it as
|
|
253
257
|
`ctx().amr`. API-key requests are not subject to the policy. Off by default.
|
|
254
258
|
|
|
259
|
+
**Encrypting secrets at rest.** `authPlugin({ mfaEncryption: { keys: [{ id, key }] } })`
|
|
260
|
+
(or the shorthand `mfaEncryptionKey`) stores TOTP secrets as `bka2.<keyId>.…`
|
|
261
|
+
envelopes: AES-256-GCM, HKDF-SHA256-derived keys (≥ 32 bytes of material), bound
|
|
262
|
+
to the user as associated data. The first key of the ring seals, the others stay
|
|
263
|
+
readable (rotation); `auth.reencryptMfaSecret(userId)` moves a row to the active
|
|
264
|
+
key. A value that is not an envelope sealed for that user is refused
|
|
265
|
+
(`AUTH_SECRET_UNREADABLE`) — a database write cannot swap in a plaintext secret.
|
|
266
|
+
Old `v1:` envelopes and plaintext rows are read only with an explicit
|
|
267
|
+
`legacy: { v1Keys: [oldKey], plaintext: true }`, for the migration window.
|
|
268
|
+
`SecretBox` is exported for other secrets.
|
|
269
|
+
|
|
255
270
|
### Passkeys — WebAuthn (`webauthnPlugin`)
|
|
256
271
|
|
|
257
272
|
Passkeys let users sign in with Face ID / Touch ID / a security key — no password.
|
|
@@ -339,9 +354,27 @@ const { userId } = await passkeys.finishAuthentication(sessionKey, browserRespon
|
|
|
339
354
|
> credential id is rejected (`PASSKEY_EXISTS`) rather than overwriting an existing one.
|
|
340
355
|
|
|
341
356
|
`finishAuthentication` looks the credential up by id, verifies it, checks the
|
|
342
|
-
signature counter **increased** (a non-increasing counter throws `PasskeyClonedError
|
|
343
|
-
and persists the new counter
|
|
344
|
-
|
|
357
|
+
signature counter **increased** (a non-increasing counter throws `PasskeyClonedError`;
|
|
358
|
+
a non-integer counter from the verifier is refused), and persists the new counter
|
|
359
|
+
with `PasskeyStore.compareAndSetCounter(id, expected, next, lastUsedAt)` — a
|
|
360
|
+
conditional update, so two concurrent assertions presenting the same counter (a
|
|
361
|
+
cloned authenticator racing the genuine one) cannot both pass: the loser gets
|
|
362
|
+
`PasskeyClonedError`. A custom store must implement it (`PASSKEY_STORE_OUTDATED`
|
|
363
|
+
at construction otherwise); `@basaltkit/auth-sqlite` and `@basaltkit/auth-prisma`
|
|
364
|
+
ship durable `passkeys` stores.
|
|
365
|
+
When `startAuthentication(sessionKey, userId)` names a user (step-up,
|
|
366
|
+
re-authentication), only **that user's** passkey satisfies the challenge — any
|
|
367
|
+
other account's passkey throws `WEBAUTHN_SUBJECT_MISMATCH`.
|
|
368
|
+
|
|
369
|
+
Use `passkeys.list(userId)` / `passkeys.remove(userId, credentialId)` for a "manage
|
|
370
|
+
devices" screen. `remove` only deletes a passkey that belongs to `userId` (an unknown
|
|
371
|
+
or foreign id throws `PASSKEY_NOT_FOUND`), so pass the id of the **authenticated**
|
|
372
|
+
user, never one from the request.
|
|
373
|
+
|
|
374
|
+
> **User verification:** the default `userVerification: 'preferred'` lets an
|
|
375
|
+
> authenticator without a PIN/biometric sign, so the assertion proves possession
|
|
376
|
+
> only. When a passkey is the only factor (passwordless login), set
|
|
377
|
+
> `userVerification: 'required'`.
|
|
345
378
|
|
|
346
379
|
### Social login (OAuth)
|
|
347
380
|
|
|
@@ -394,18 +427,58 @@ character-for-character, or the provider rejects it with *"redirect_uri is not
|
|
|
394
427
|
associated with this application"*.
|
|
395
428
|
|
|
396
429
|
New accounts are created **passwordless** and a provider-verified email flips
|
|
397
|
-
`emailVerified`.
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
430
|
+
`emailVerified`. Logins are bound to the provider's **subject**: the first login
|
|
431
|
+
of a provider account records an account link (provider + `sub` → account) in the
|
|
432
|
+
`accountLinks` store (`authPlugin({ accountLinks })`, durable ones in
|
|
433
|
+
`auth-sqlite` / `auth-prisma`). Once linked, an email change at the IdP still
|
|
434
|
+
reaches the same account, and a different subject of that provider asserting the
|
|
435
|
+
account's email is refused (`AccountLinkConflictError`, 409) unless
|
|
436
|
+
`oauthPlugin({ subjectConflict: 'link' })`. A first login links an **existing**
|
|
437
|
+
account only when the provider verified the email (`SocialLinkRefusedError`
|
|
438
|
+
otherwise); an existing account that had never verified its own email has its
|
|
439
|
+
password, sessions, refresh tokens, MFA and account links revoked before it is
|
|
440
|
+
adopted; an account with MFA enabled requires the code (`MfaRequiredError`)
|
|
441
|
+
unless `oauthPlugin({ mfa: 'skip' })` is set for an IdP that enforces its own
|
|
442
|
+
MFA. `Auth.socialLogin(email, { emailVerified, identity: { provider, subject } })`
|
|
443
|
+
is the underlying primitive for custom providers.
|
|
404
444
|
|
|
405
445
|
**Enterprise SSO (OIDC):** any OpenID Connect IdP (Okta, Entra ID, Auth0,
|
|
406
|
-
Keycloak…) plugs in via `oidcProvider({ clientId, clientSecret,
|
|
407
|
-
tokenUrl,
|
|
408
|
-
endpoints from the IdP's
|
|
446
|
+
Keycloak…) plugs in via `oidcProvider({ name, clientId, clientSecret, authorizeUrl,
|
|
447
|
+
tokenUrl, userInfoUrl, issuer? })`, or let `await discoverOidcProvider({ name, issuer,
|
|
448
|
+
clientId, clientSecret })` read the endpoints from the IdP's
|
|
449
|
+
`.well-known/openid-configuration` (the document's `issuer` must equal yours and every
|
|
450
|
+
endpoint must be `https:` — plain `http:` only to a loopback host).
|
|
451
|
+
|
|
452
|
+
**Restrict each enterprise IdP to its email domains.** A customer's IdP admin
|
|
453
|
+
decides which emails it asserts as verified; without a restriction, Acme's IdP could
|
|
454
|
+
assert `ceo@globex.com` and log into Globex's CEO account (any verified email links
|
|
455
|
+
to the existing account). Pass `allowedEmailDomains`:
|
|
456
|
+
|
|
457
|
+
```ts
|
|
458
|
+
oidcProvider({ name: 'acme', /* …endpoints, keys… */ allowedEmailDomains: ['acme.com'] })
|
|
459
|
+
await discoverOidcProvider({ name: 'globex', issuer, clientId, clientSecret, allowedEmailDomains: ['globex.com'] })
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
A login for any other domain fails with `AUTH_OAUTH_EXCHANGE_FAILED` before an
|
|
463
|
+
account is looked up (exact, case-insensitive match; list subdomains explicitly). With
|
|
464
|
+
**more than one provider configured**, every `oidcProvider` / `discoverOidcProvider`
|
|
465
|
+
entry must declare `allowedEmailDomains` or `allowAnyEmailDomain: true` (only for an
|
|
466
|
+
IdP you fully control) — otherwise `OAuth` refuses to start with
|
|
467
|
+
`AUTH_OAUTH_PROVIDER_CONFIG`. Google and GitHub are not affected (they only assert
|
|
468
|
+
emails they verified themselves); any custom `OAuthProvider` can opt in with
|
|
469
|
+
`enterprise: true` or set `allowedEmailDomains` directly.
|
|
470
|
+
|
|
471
|
+
Accounts are matched by **email**, not by the provider's `subject`: a verified email
|
|
472
|
+
from any configured provider logs into the account holding it. Keep that in mind
|
|
473
|
+
when you add a provider — the domain allowlist is what scopes it.
|
|
474
|
+
|
|
475
|
+
**Provider replies are validated:** a profile without a string `sub`/`email` (or an
|
|
476
|
+
email that is not a single-`@` address) fails the login; an `openid` flow must return
|
|
477
|
+
an `id_token` whose `nonce`, `aud` (your client id), `exp` and — when the provider
|
|
478
|
+
declares an `issuer` — `iss` match; a non-JSON token-endpoint reply is an exchange
|
|
479
|
+
error; every provider call has a deadline (`oauthPlugin({ timeoutMs })`, default 10 s).
|
|
480
|
+
`oauthRoutes` carry `meta.rateLimit` (10 per minute per ip and route by default,
|
|
481
|
+
enforced by the http `securityPlugin`; `oauthRoutes({ rateLimit: false })` removes it).
|
|
409
482
|
|
|
410
483
|
### API keys
|
|
411
484
|
|
|
@@ -441,7 +514,7 @@ const app = await createApp({
|
|
|
441
514
|
|
|
442
515
|
`apiKeysPlugin` claims the `scopes` key in the adapters' boot-time guarded-meta check, so a route declaring `meta.scopes` **without** the plugin registered fails loud at boot (`UnguardedRouteMetaError`) instead of serving unchecked.
|
|
443
516
|
|
|
444
|
-
The key is presented in the `Authorization: Bearer mk_live_...` or `x-api-key` header. A **scope** is a granular permission on the key (e.g. `reports:read`); `*` means all. After authenticating, `ctx().apiKey` contains `{ id, scopes, tenantId?, userId? }`.
|
|
517
|
+
The key is presented in the `Authorization: Bearer mk_live_...` or `x-api-key` header — one of them: a request carrying two **different** keys (one in each) is refused with 400 `AUTH_APIKEY_AMBIGUOUS` rather than letting one silently win. A **scope** is a granular permission on the key (e.g. `reports:read`); `*` means all. After authenticating, `ctx().apiKey` contains `{ id, scopes, tenantId?, userId? }`.
|
|
445
518
|
|
|
446
519
|
The guard enforces, on every key-authenticated request: **tenant binding** (a key
|
|
447
520
|
issued in a tenant is refused with `403 AUTH_APIKEY_TENANT_MISMATCH` on any request
|
|
@@ -456,6 +529,8 @@ declare `meta.scopes`; opt out with `allowNarrowKeysOnUnscopedRoutes: true`) and
|
|
|
456
529
|
|
|
457
530
|
Active by default: 5 failed attempts per email within a 15-minute window → `AUTH_LOCKED` error (HTTP 429). A successful login clears the counter.
|
|
458
531
|
|
|
532
|
+
**`AUTH_MFA_REQUIRED` counts as an attempt.** On an MFA account, that answer is only given for the *right* password, so it is a password oracle (the standard two-step MFA login has the same property). To keep it from allowing unthrottled guessing, it spends the per-account and per-IP budgets exactly like a wrong password. A user who then signs in with the code clears the account counter; the IP slot of the first step expires with the window, so under a shared NAT with many MFA users, size `ipLoginThrottle` accordingly.
|
|
533
|
+
|
|
459
534
|
```ts
|
|
460
535
|
import { authPlugin, LoginThrottle, MemoryUserSource } from '@basaltkit/auth'
|
|
461
536
|
|
|
@@ -473,6 +548,12 @@ login/MFA, per-IP and email-request throttles with one atomic Redis script per
|
|
|
473
548
|
attempt. `redis` is any ioredis-compatible client — only `eval` and `del` are
|
|
474
549
|
used, no Redis dependency. Implement `ThrottleStore` for another backend.
|
|
475
550
|
|
|
551
|
+
The in-memory store is bounded (`maxEntries`, default 100 000): when full it
|
|
552
|
+
sweeps expired entries, then evicts the oldest *unlocked* ones — a flood of junk
|
|
553
|
+
identifiers cannot flush a locked account out of the store and hand the
|
|
554
|
+
attacker a fresh budget. Only when every tracked entry is locked does the oldest
|
|
555
|
+
lock go (the memory bound is absolute).
|
|
556
|
+
|
|
476
557
|
### Hooks (events)
|
|
477
558
|
|
|
478
559
|
The application can react to authentication events: `auth:registered`, `auth:login`, `auth:login_failed`, `auth:logout`, `auth:verify_requested`, `auth:email_verified`, `auth:password_reset_requested`, `auth:password_reset`, `auth:mfa_enabled`, `auth:mfa_disabled`, `auth:apikey_issued`, `auth:apikey_revoked`.
|
|
@@ -493,7 +574,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
493
574
|
| `accessTtl` | `DurationInput` | No | `'15m'` | Access token validity. |
|
|
494
575
|
| `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
|
|
495
576
|
| `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
|
|
496
|
-
| `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults
|
|
577
|
+
| `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults on unless `NODE_ENV` is explicitly `development`/`test`. |
|
|
497
578
|
| `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
|
|
498
579
|
| `throttleStore` | `ThrottleStore` | No | in-memory, per process | Counters of the default login / per-IP / email-request throttles — `RedisThrottleStore` for one budget across replicas. |
|
|
499
580
|
| `requireMfa` | `boolean \| (user, context) => boolean \| Promise<boolean>` | No | off | Plugin only. Require a sign-in with MFA on every authenticated route except `meta.mfa: false` ones. |
|
|
@@ -501,6 +582,9 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
501
582
|
| `verificationTtl` | `DurationInput` | No | `'24h'` | Email verification link validity. |
|
|
502
583
|
| `resetTtl` | `DurationInput` | No | `'1h'` | Password reset link validity. |
|
|
503
584
|
| `mfa` | `MfaStore` | No | `MemoryMfaStore` | Per-user MFA state. |
|
|
585
|
+
| `accountLinks` | `AccountLinkStore` | No | `MemoryAccountLinkStore` | OAuth/OIDC account links (provider + subject → user). `create` must be atomic on the pair. |
|
|
586
|
+
| `mfaEncryption` | `{ keys: SecretBoxKey[]; legacy? }` | No | — (plaintext) | Encrypts TOTP secrets at rest with a key ring; see *Encrypting secrets at rest*. |
|
|
587
|
+
| `mfaEncryptionKey` | `string \| Buffer` | No | — | Shorthand for a one-key ring (`id: 'default'`, ≥ 32 bytes). |
|
|
504
588
|
| `mfaIssuer` | `string` | No | `'Basalt'` | Name shown in the authenticator app. |
|
|
505
589
|
| `hooks` | `HookBus` | No | — | Only on the `Auth` class; the plugin injects it. |
|
|
506
590
|
|
|
@@ -519,7 +603,8 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
519
603
|
| `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
|
|
520
604
|
| `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
|
|
521
605
|
| `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
|
|
522
|
-
| `socialLogin(email, { emailVerified?, mfaCode?, mfa? })` | Find-or-create a passwordless account for an OAuth/OIDC identity; links to an existing account only with a provider-verified email
|
|
606
|
+
| `socialLogin(email, { emailVerified?, mfaCode?, mfa?, identity?, subjectConflict? })` | Find-or-create a passwordless account for an OAuth/OIDC identity; with `identity: { provider, subject }` the account link decides, otherwise it links to an existing account only with a provider-verified email; honours MFA; returns `{ user, tokens }`. |
|
|
607
|
+
| `reencryptMfaSecret(userId)` | Re-seals a stored TOTP secret under the active `mfaEncryption` key (rotation / legacy migration): `'resealed'`, `'current'` or `'none'`. |
|
|
523
608
|
|
|
524
609
|
### Ready-made routes
|
|
525
610
|
|
|
@@ -527,7 +612,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
527
612
|
- Every `authRoutes()`, `mfaRoutes()` and `oauthRoutes()` route declares `meta.account: true` (about the caller, not a tenant's data — `@basaltkit/teams`' membership guard lets non-members through) and, except MFA disable, `meta.mfa: false` (reachable under `requireMfa`). `ACCOUNT_META` exports the pair for your own profile routes.
|
|
528
613
|
- `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys`, `DELETE /apikeys/:id` (login session only — API keys are refused; scoped to the current tenant/user). `POST /apikeys` accepts an optional `expiresAt` Unix timestamp in milliseconds; expired keys are rejected and omitted from listings.
|
|
529
614
|
- `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
|
|
530
|
-
- `oauthRoutes({ callbackBaseUrl, successRedirect? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider.
|
|
615
|
+
- `oauthRoutes({ callbackBaseUrl, successRedirect?, bindingCookie?, rateLimit? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider (rate-limited by default).
|
|
531
616
|
|
|
532
617
|
### `apiKeysPlugin(options)` and the `ApiKeys` class
|
|
533
618
|
|
|
@@ -536,7 +621,7 @@ Options (`ApiKeysPluginOptions`):
|
|
|
536
621
|
| Name | Type | Required? | Default | Description |
|
|
537
622
|
|---|---|---|---|---|
|
|
538
623
|
| `store` | `ApiKeyStore` | No | `MemoryApiKeyStore` | Key storage. |
|
|
539
|
-
| `header` | `string` | No | `'x-api-key'` | Alternative header to Bearer. |
|
|
624
|
+
| `header` | `string` | No | `'x-api-key'` | Alternative header to Bearer. Two different keys (Bearer + header) → 400 `AUTH_APIKEY_AMBIGUOUS`. |
|
|
540
625
|
| `users` | `UserSource` | No | — | If given, a key with `userId` also populates `ctx().user`. |
|
|
541
626
|
| `now` | `() => number` | No | `Date.now` | Injectable clock (tests). |
|
|
542
627
|
|
|
@@ -547,7 +632,7 @@ Options (`ApiKeysPluginOptions`):
|
|
|
547
632
|
| Export | Description |
|
|
548
633
|
|---|---|
|
|
549
634
|
| `signJwt(claims, { secret, expiresIn? })` / `verifyJwt(token, secret)` | Dependency-free HS256 JWT. Advanced. |
|
|
550
|
-
| `ScryptPasswordHasher` / `PasswordHasher` | Password hashing (scrypt, memory-hard). Advanced. |
|
|
635
|
+
| `ScryptPasswordHasher` / `PasswordHasher` | Password hashing (scrypt, memory-hard). Advanced. A stored hash declaring more than N=2^20, r=32, p=16 (or 512 MiB) never verifies, so a tampered row cannot pin the CPU. |
|
|
551
636
|
| `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `store`, `namespace`, `clock`) | Anti brute-force. |
|
|
552
637
|
| `ThrottleStore` / `MemoryThrottleStore` / `RedisThrottleStore` (`RedisThrottleClient`: `eval` + `del`) | Where throttle counters live; Redis shares them across replicas. |
|
|
553
638
|
| `generateTotpSecret`, `totp`, `verifyTotp`, `otpauthUri`, `base32Encode`, `base32Decode` | TOTP primitives (RFC 6238). Advanced. |
|
|
@@ -556,7 +641,8 @@ Options (`ApiKeysPluginOptions`):
|
|
|
556
641
|
| `AUTH`, `API_KEYS`, `OAUTH` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance; `OAUTH` returns the `OAuth` instance. |
|
|
557
642
|
| `oauthPlugin`, `oauthRoutes` | Social-login plugin (`{ secret, providers }`) and its routes (`{ callbackBaseUrl, successRedirect? }`). |
|
|
558
643
|
| `googleProvider`, `githubProvider`, `oidcProvider`, `discoverOidcProvider` | OAuth 2.0 / OpenID Connect providers. Each takes `{ clientId, clientSecret, scopes? }`. |
|
|
559
|
-
| In-memory stores | `MemoryUserSource`, `MemorySessionStore`, `MemoryRefreshTokenStore`, `MemoryAuthTokenStore`, `MemoryApiKeyStore`, `MemoryMfaStore` — dev/testing. |
|
|
644
|
+
| In-memory stores | `MemoryUserSource`, `MemorySessionStore`, `MemoryRefreshTokenStore`, `MemoryAuthTokenStore`, `MemoryApiKeyStore`, `MemoryMfaStore`, `MemoryAccountLinkStore`, `MemoryPasskeyStore` — dev/testing. |
|
|
645
|
+
| `SecretBox` | The at-rest envelope behind `mfaEncryption` (`seal` / `open` / `reseal` with a `{ purpose, subject }` context), for your own secrets. |
|
|
560
646
|
|
|
561
647
|
#### Single-use tokens are consumed with a compare-and-swap
|
|
562
648
|
|
|
@@ -583,7 +669,14 @@ If you implement your own store, do the same. Returning `void` keeps the older r
|
|
|
583
669
|
| `ScopeRequiredError` | `AUTH_SCOPE_REQUIRED` | 403 |
|
|
584
670
|
| `OAuthProviderUnknownError` | `AUTH_OAUTH_UNKNOWN_PROVIDER` | 404 |
|
|
585
671
|
| `OAuthStateInvalidError` | `AUTH_OAUTH_STATE_INVALID` | 400 |
|
|
586
|
-
| `OAuthExchangeError` | `AUTH_OAUTH_EXCHANGE_FAILED` | 502 |
|
|
672
|
+
| `OAuthExchangeError` | `AUTH_OAUTH_EXCHANGE_FAILED` | 502 (message kept for the log; the client gets `Bad gateway.`) |
|
|
673
|
+
| `OAuthProviderConfigError` | `AUTH_OAUTH_PROVIDER_CONFIG` | boot (several providers with an unrestricted enterprise IdP, an invalid domain entry, a duplicate name) |
|
|
674
|
+
| `ApiKeyAmbiguousError` | `AUTH_APIKEY_AMBIGUOUS` | 400 |
|
|
675
|
+
| `PasskeyNotFoundError` / `WebAuthnSubjectMismatchError` | `PASSKEY_NOT_FOUND` / `WEBAUTHN_SUBJECT_MISMATCH` | 404/403 |
|
|
676
|
+
| `PasskeyClonedError` / `PasskeyStoreOutdatedError` | `PASSKEY_CLONED` / `PASSKEY_STORE_OUTDATED` | 401 / boot |
|
|
677
|
+
| `AccountLinkConflictError` | `AUTH_ACCOUNT_LINK_CONFLICT` | 409 |
|
|
678
|
+
| `AccountEmailAmbiguousError` | `AUTH_EMAIL_AMBIGUOUS` | 500 (not exposed; several rows differ only in email case) |
|
|
679
|
+
| `SecretUnreadableError` / `SecretBoxKeyError` | `AUTH_SECRET_UNREADABLE` / `AUTH_SECRET_BOX_KEY_INVALID` | 500 / boot |
|
|
587
680
|
|
|
588
681
|
## Common issues and solutions (FAQ)
|
|
589
682
|
|
|
@@ -618,5 +711,6 @@ If you implement your own store, do the same. Returning `void` keeps the older r
|
|
|
618
711
|
- **Use the browser session cookie for browser UIs.** It is `HttpOnly` by default; keep JWTs out of `localStorage` and use same-origin requests so the browser sends the cookie automatically.
|
|
619
712
|
- **Don't increase `accessTtl`.** Short access tokens limit the damage from a stolen token; renewal via refresh token already provides convenience for the user.
|
|
620
713
|
- **Show the API key and recovery codes only once** — that's how the module works; don't store them in plain text on your side.
|
|
621
|
-
- **Don't disable `loginThrottle` in production
|
|
714
|
+
- **Don't disable `loginThrottle` / `ipLoginThrottle` in production.** Besides wrong passwords, they bound the `AUTH_MFA_REQUIRED` password oracle on MFA accounts (it is only returned for a correct password and is counted like a failure).
|
|
715
|
+
- **Keep the "always 200" responses** on the forgot/verify routes (already the default), so as not to reveal which emails have an account.
|
|
622
716
|
- **In a cluster (multiple machines)**, use shared stores (database/Redis) instead of the `Memory*` ones, or sessions and lockouts won't be shared across processes.
|
package/dist/apikeys-plugin.d.ts
CHANGED
|
@@ -43,6 +43,15 @@ export declare class ApiKeyTenantMismatchError extends BasaltError {
|
|
|
43
43
|
readonly status = 403;
|
|
44
44
|
constructor();
|
|
45
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* The request presented two DIFFERENT API keys (`Authorization: Bearer mk_…`
|
|
48
|
+
* and the key header). Neither is picked: which credential authorizes a
|
|
49
|
+
* request must never depend on header precedence.
|
|
50
|
+
*/
|
|
51
|
+
export declare class ApiKeyAmbiguousError extends BasaltError {
|
|
52
|
+
readonly status = 400;
|
|
53
|
+
constructor();
|
|
54
|
+
}
|
|
46
55
|
/** The route only accepts an interactive session, not an API key. */
|
|
47
56
|
export declare class ApiKeyNotAllowedError extends BasaltError {
|
|
48
57
|
readonly status = 403;
|
|
@@ -52,7 +61,8 @@ export declare const API_KEYS: import("@basaltkit/core").Token<ApiKeys>;
|
|
|
52
61
|
export interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
53
62
|
/**
|
|
54
63
|
* Header carrying the key, besides `Authorization: Bearer mk_...`.
|
|
55
|
-
* Default `x-api-key`.
|
|
64
|
+
* Default `x-api-key`. A request carrying two different keys (one in each)
|
|
65
|
+
* is refused with 400 `AUTH_APIKEY_AMBIGUOUS`.
|
|
56
66
|
*/
|
|
57
67
|
header?: string;
|
|
58
68
|
/**
|
package/dist/apikeys-plugin.js
CHANGED
|
@@ -8,6 +8,17 @@ export class ApiKeyTenantMismatchError extends BasaltError {
|
|
|
8
8
|
super('AUTH_APIKEY_TENANT_MISMATCH', 'This API key is not valid for this tenant.');
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
|
+
/**
|
|
12
|
+
* The request presented two DIFFERENT API keys (`Authorization: Bearer mk_…`
|
|
13
|
+
* and the key header). Neither is picked: which credential authorizes a
|
|
14
|
+
* request must never depend on header precedence.
|
|
15
|
+
*/
|
|
16
|
+
export class ApiKeyAmbiguousError extends BasaltError {
|
|
17
|
+
status = 400;
|
|
18
|
+
constructor() {
|
|
19
|
+
super('AUTH_APIKEY_AMBIGUOUS', 'Two different API keys were presented; send exactly one.');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
11
22
|
/** The route only accepts an interactive session, not an API key. */
|
|
12
23
|
export class ApiKeyNotAllowedError extends BasaltError {
|
|
13
24
|
status = 403;
|
|
@@ -47,8 +58,17 @@ export function apiKeysPlugin(options = {}) {
|
|
|
47
58
|
const bearer = typeof authHeader === 'string' && authHeader.startsWith('Bearer mk_')
|
|
48
59
|
? authHeader.slice('Bearer '.length)
|
|
49
60
|
: undefined;
|
|
50
|
-
const
|
|
51
|
-
const
|
|
61
|
+
const rawCustom = request.headers[header];
|
|
62
|
+
const custom = typeof rawCustom === 'string' && rawCustom.length > 0 ? rawCustom : undefined;
|
|
63
|
+
// Both carriers present and disagreeing is refused outright: letting one
|
|
64
|
+
// shadow the other means a stray or injected `Bearer mk_…` silently
|
|
65
|
+
// replaces the key the client meant (and vice versa). Identical values
|
|
66
|
+
// are harmless and accepted.
|
|
67
|
+
if (bearer !== undefined && custom !== undefined && bearer !== custom) {
|
|
68
|
+
await hooks.emit('auth:apikey_rejected', { reason: 'invalid' });
|
|
69
|
+
throw new ApiKeyAmbiguousError();
|
|
70
|
+
}
|
|
71
|
+
const presented = bearer ?? custom;
|
|
52
72
|
if (!presented)
|
|
53
73
|
return;
|
|
54
74
|
const record = await c.get(API_KEYS).verify(presented);
|
package/dist/auth.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { BasaltError, type DurationInput, type HookBus } from '@basaltkit/core';
|
|
|
2
2
|
import { type PasswordHasher } from './hashing.js';
|
|
3
3
|
import { LoginThrottle, type ThrottleStore } from './throttle.js';
|
|
4
4
|
import { type JwtClaims } from './jwt.js';
|
|
5
|
-
import { type
|
|
5
|
+
import { type SecretBoxKey, type SecretBoxLegacyOptions } from './secret-box.js';
|
|
6
|
+
import { type AccountLinkStore, type AuthTokenStore, type AuthUser, type MfaStore, type PublicUser, type RefreshTokenStore, type SessionRecord, type SessionStore, type TokenVersionStore, type UserSource } from './stores.js';
|
|
6
7
|
export declare class InvalidCredentialsError extends BasaltError {
|
|
7
8
|
readonly status = 401;
|
|
8
9
|
constructor();
|
|
@@ -85,6 +86,29 @@ export declare class SocialLinkRefusedError extends BasaltError {
|
|
|
85
86
|
readonly status = 403;
|
|
86
87
|
constructor();
|
|
87
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* A social / SSO login's provider account conflicts with an existing link: the
|
|
91
|
+
* local account is already linked to a different subject of the same provider
|
|
92
|
+
* (another IdP account asserting the same email), or the subject was bound to
|
|
93
|
+
* another account concurrently.
|
|
94
|
+
*/
|
|
95
|
+
export declare class AccountLinkConflictError extends BasaltError {
|
|
96
|
+
readonly status = 409;
|
|
97
|
+
constructor();
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* A user store holds more than one account whose email differs only in letter
|
|
101
|
+
* case (rows written before emails were canonicalised), so an email lookup
|
|
102
|
+
* cannot tell which account is meant. Stores throw it instead of guessing:
|
|
103
|
+
* resolve the duplicates (e.g. `normalizeAuthUserEmails()` of
|
|
104
|
+
* `@basaltkit/auth-prisma` / `@basaltkit/auth-sqlite` reports them), then the
|
|
105
|
+
* lookup works again. Not exposed to the client.
|
|
106
|
+
*/
|
|
107
|
+
export declare class AccountEmailAmbiguousError extends BasaltError {
|
|
108
|
+
readonly status = 500;
|
|
109
|
+
readonly expose = false;
|
|
110
|
+
constructor(email: string);
|
|
111
|
+
}
|
|
88
112
|
/**
|
|
89
113
|
* Canonical form of an email identity: trimmed and lowercased. Every lookup,
|
|
90
114
|
* create and throttle key goes through it, so `Bob@acme.test` and
|
|
@@ -111,7 +135,10 @@ export interface SessionCookieOptions {
|
|
|
111
135
|
httpOnly?: boolean;
|
|
112
136
|
/** SameSite policy. Default: `Lax`. */
|
|
113
137
|
sameSite?: 'Strict' | 'Lax' | 'None';
|
|
114
|
-
/**
|
|
138
|
+
/**
|
|
139
|
+
* Whether to require HTTPS. Defaults to true unless `NODE_ENV` is explicitly
|
|
140
|
+
* `development` or `test` (an unset NODE_ENV counts as production).
|
|
141
|
+
*/
|
|
115
142
|
secure?: boolean;
|
|
116
143
|
}
|
|
117
144
|
export interface AuthOptions {
|
|
@@ -167,6 +194,13 @@ export interface AuthOptions {
|
|
|
167
194
|
resetTtl?: DurationInput;
|
|
168
195
|
/** Store for MFA (TOTP) enrollment state. Default: in-memory. */
|
|
169
196
|
mfa?: MfaStore;
|
|
197
|
+
/**
|
|
198
|
+
* Store binding provider subjects to accounts ({@link Auth.socialLogin}).
|
|
199
|
+
* Default: in-memory — use a durable one (`@basaltkit/auth-prisma`,
|
|
200
|
+
* `@basaltkit/auth-sqlite`) with OAuth, or links are forgotten on restart and
|
|
201
|
+
* logins fall back to the email match.
|
|
202
|
+
*/
|
|
203
|
+
accountLinks?: AccountLinkStore;
|
|
170
204
|
/**
|
|
171
205
|
* Enables access-token revocation. When set, access tokens carry a version
|
|
172
206
|
* (`tv`) and `resetPassword`/`revokeAllTokens` bump it — invalidating every
|
|
@@ -175,10 +209,25 @@ export interface AuthOptions {
|
|
|
175
209
|
*/
|
|
176
210
|
tokenVersions?: TokenVersionStore;
|
|
177
211
|
/**
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
*
|
|
212
|
+
* Encrypts TOTP secrets at rest (AES-256-GCM, HKDF-derived keys, each
|
|
213
|
+
* ciphertext bound to its user). `keys` is a ring: the first key seals new
|
|
214
|
+
* secrets, the others stay readable (rotation). A stored value that is not an
|
|
215
|
+
* envelope sealed for that user is refused — a database write cannot swap in
|
|
216
|
+
* a plaintext secret the writer knows. `legacy` reads `v1:` envelopes and/or
|
|
217
|
+
* plaintext during a migration only; move rows over with
|
|
218
|
+
* {@link Auth.reencryptMfaSecret}, then remove it.
|
|
219
|
+
*
|
|
220
|
+
* Omit (and omit {@link mfaEncryptionKey}) to store secrets in plaintext.
|
|
221
|
+
*/
|
|
222
|
+
mfaEncryption?: {
|
|
223
|
+
keys: SecretBoxKey[];
|
|
224
|
+
legacy?: SecretBoxLegacyOptions;
|
|
225
|
+
};
|
|
226
|
+
/**
|
|
227
|
+
* Shorthand for `mfaEncryption: { keys: [{ id: 'default', key }] }` (at least
|
|
228
|
+
* 32 bytes). It does **not** read the old `v1:` envelopes or plaintext: to
|
|
229
|
+
* migrate from a pre-4.0 `mfaEncryptionKey`, use `mfaEncryption` with
|
|
230
|
+
* `legacy: { v1Keys: [oldKey] }`.
|
|
182
231
|
*/
|
|
183
232
|
mfaEncryptionKey?: string | Buffer;
|
|
184
233
|
/** Issuer name shown in authenticator apps. Default 'Basalt'. */
|
|
@@ -203,38 +252,64 @@ export declare class Auth {
|
|
|
203
252
|
private readonly verificationTtl;
|
|
204
253
|
private readonly resetTtl;
|
|
205
254
|
private readonly mfa;
|
|
255
|
+
private readonly accountLinks;
|
|
206
256
|
private readonly mfaIssuer;
|
|
207
|
-
private readonly
|
|
257
|
+
private readonly mfaBox;
|
|
208
258
|
private readonly tokenVersions;
|
|
209
259
|
private readonly enumerationSafeRegister;
|
|
210
260
|
constructor(options: AuthOptions);
|
|
211
261
|
register(rawEmail: string, password: string): Promise<PublicUser>;
|
|
212
262
|
/**
|
|
213
|
-
* Logs in an externally-authenticated user (e.g. from an OAuth provider)
|
|
214
|
-
*
|
|
215
|
-
*
|
|
216
|
-
*
|
|
217
|
-
*
|
|
263
|
+
* Logs in an externally-authenticated user (e.g. from an OAuth provider) —
|
|
264
|
+
* find-or-create. A new account is created **passwordless** (a random,
|
|
265
|
+
* unusable password hash), so password login won't work for it until a
|
|
266
|
+
* password is set. A provider-verified email flips `emailVerified`. Returns
|
|
267
|
+
* the tokens and whether the account was just created.
|
|
268
|
+
*
|
|
269
|
+
* With an `identity` (the provider name and its stable `subject`, which
|
|
270
|
+
* {@link OAuth} always passes) the account is matched by that link first
|
|
271
|
+
* (see {@link AccountLinkStore}): a linked provider account reaches its local
|
|
272
|
+
* account whatever email it asserts today. Without a link, the account is
|
|
273
|
+
* matched by email and the link is recorded — for an existing account only
|
|
274
|
+
* under the rules below. Once an account is linked to a provider, a
|
|
275
|
+
* **different** subject of that provider asserting the same email is refused
|
|
276
|
+
* ({@link AccountLinkConflictError}) unless `subjectConflict: 'link'`.
|
|
218
277
|
*
|
|
219
278
|
* Linking to an EXISTING account is refused ({@link SocialLinkRefusedError})
|
|
220
279
|
* unless `emailVerified` is `true` — an unverified provider email proves
|
|
221
280
|
* nothing about who owns the address. When the existing account had never
|
|
222
281
|
* verified its email, whoever registered it first is not trusted either: its
|
|
223
|
-
* password, sessions, refresh tokens and
|
|
224
|
-
* (`auth:social_account_adopted`). An account with MFA
|
|
225
|
-
* `mfaCode` ({@link MfaRequiredError}) unless `mfa: 'skip'`
|
|
226
|
-
* explicitly (only for an IdP that enforces its own second factor).
|
|
282
|
+
* password, sessions, refresh tokens, MFA and account links are revoked
|
|
283
|
+
* before it is adopted (`auth:social_account_adopted`). An account with MFA
|
|
284
|
+
* enabled requires `mfaCode` ({@link MfaRequiredError}) unless `mfa: 'skip'`
|
|
285
|
+
* is passed explicitly (only for an IdP that enforces its own second factor).
|
|
227
286
|
*/
|
|
228
287
|
socialLogin(rawEmail: string, options?: {
|
|
229
288
|
emailVerified?: boolean;
|
|
230
289
|
mfaCode?: string;
|
|
231
290
|
mfa?: 'required' | 'skip';
|
|
291
|
+
/** The provider account behind this login; matched before the email. */
|
|
292
|
+
identity?: {
|
|
293
|
+
provider: string;
|
|
294
|
+
subject: string;
|
|
295
|
+
};
|
|
296
|
+
/**
|
|
297
|
+
* An account already linked to another subject of the same provider:
|
|
298
|
+
* `'refuse'` (default) or `'link'` this subject as well. Only for an IdP
|
|
299
|
+
* that legitimately re-issues subjects (a directory migration).
|
|
300
|
+
*/
|
|
301
|
+
subjectConflict?: 'refuse' | 'link';
|
|
232
302
|
}): Promise<{
|
|
233
303
|
user: PublicUser;
|
|
234
304
|
tokens: TokenPair;
|
|
235
305
|
created: boolean;
|
|
236
306
|
amr: string[];
|
|
237
307
|
}>;
|
|
308
|
+
/** Records the link; a concurrent first login that bound the subject elsewhere wins. */
|
|
309
|
+
private linkIdentity;
|
|
310
|
+
/** MFA gate of a social login into an existing account (see {@link socialLogin}). */
|
|
311
|
+
private requireMfaForSocial;
|
|
312
|
+
private finishSocialLogin;
|
|
238
313
|
/**
|
|
239
314
|
* A provider-verified login is taking over an account whose email was never
|
|
240
315
|
* verified: whoever registered it could be anyone (pre-account hijacking), so
|
|
@@ -264,8 +339,10 @@ export declare class Auth {
|
|
|
264
339
|
*
|
|
265
340
|
* When the account has MFA enabled, `mfaCode` (a TOTP or recovery code) is
|
|
266
341
|
* required: a correct password with a missing code throws
|
|
267
|
-
* {@link MfaRequiredError}
|
|
268
|
-
*
|
|
342
|
+
* {@link MfaRequiredError}, and a wrong code throws {@link MfaInvalidCodeError}.
|
|
343
|
+
* Because `MfaRequiredError` reveals that the password was right, it counts
|
|
344
|
+
* against the per-account and per-IP login budgets exactly like a failure
|
|
345
|
+
* (a later successful login with the code clears the account counter).
|
|
269
346
|
*
|
|
270
347
|
* `amr` lists the authentication methods used — `['pwd']`, or
|
|
271
348
|
* `['pwd', 'mfa']` when a second factor was verified. It is also embedded in
|
|
@@ -365,15 +442,28 @@ export declare class Auth {
|
|
|
365
442
|
enabled: boolean;
|
|
366
443
|
pending: boolean;
|
|
367
444
|
}>;
|
|
445
|
+
/** Encrypt a TOTP secret for storage, bound to its user (no-op when no key is configured). */
|
|
446
|
+
private encryptMfaSecret;
|
|
447
|
+
/**
|
|
448
|
+
* Decrypt a stored TOTP secret. With encryption configured, only an envelope
|
|
449
|
+
* sealed for this user opens; plaintext and `v1:` values need the explicit
|
|
450
|
+
* legacy opt-in (otherwise `AUTH_SECRET_UNREADABLE`, failing closed).
|
|
451
|
+
*/
|
|
452
|
+
private decryptMfaSecret;
|
|
453
|
+
/**
|
|
454
|
+
* Re-encrypts one user's stored TOTP secret under the active key of
|
|
455
|
+
* `mfaEncryption` — for key rotation, and to migrate `v1:` envelopes or
|
|
456
|
+
* plaintext secrets (reading those needs the matching `legacy` opt-in).
|
|
457
|
+
* Returns `'resealed'` when the row was rewritten, `'current'` when it was
|
|
458
|
+
* already sealed with the active key, `'none'` when the user has no MFA
|
|
459
|
+
* record. Run it over every user id with an MFA row, then drop `legacy`.
|
|
460
|
+
*/
|
|
461
|
+
reencryptMfaSecret(userId: string): Promise<'resealed' | 'current' | 'none'>;
|
|
368
462
|
/**
|
|
369
463
|
* Begins MFA enrollment: generates a fresh secret (not yet active) and
|
|
370
464
|
* returns it plus an `otpauth://` URI to render as a QR code. Call
|
|
371
465
|
* {@link activateMfa} with a code from the app to switch it on.
|
|
372
466
|
*/
|
|
373
|
-
/** Encrypt a TOTP secret for storage (no-op when no key is configured). */
|
|
374
|
-
private encryptMfaSecret;
|
|
375
|
-
/** Decrypt a stored TOTP secret (passes plaintext/legacy values through). */
|
|
376
|
-
private decryptMfaSecret;
|
|
377
467
|
enrollMfa(userId: string): Promise<{
|
|
378
468
|
secret: string;
|
|
379
469
|
otpauthUri: string;
|