@basaltkit/auth 3.1.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +159 -24
- package/dist/apikeys-plugin.d.ts +11 -1
- package/dist/apikeys-plugin.js +22 -2
- package/dist/auth.d.ts +108 -20
- package/dist/auth.js +170 -41
- package/dist/hashing.d.ts +3 -1
- package/dist/hashing.js +29 -7
- package/dist/index.d.ts +6 -5
- package/dist/index.js +6 -5
- package/dist/jwt.js +13 -1
- package/dist/oauth-plugin.d.ts +12 -1
- package/dist/oauth-plugin.js +6 -5
- package/dist/oauth.d.ts +81 -2
- package/dist/oauth.js +221 -40
- package/dist/plugin.d.ts +6 -1
- package/dist/secret-box.d.ts +80 -8
- package/dist/secret-box.js +178 -27
- package/dist/stores.d.ts +60 -0
- package/dist/stores.js +52 -0
- package/dist/throttle.d.ts +12 -4
- package/dist/throttle.js +16 -4
- package/dist/webauthn-plugin.js +1 -1
- package/dist/webauthn.d.ts +49 -8
- package/dist/webauthn.js +70 -11
- package/package.json +4 -4
package/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({
|
|
@@ -137,9 +141,52 @@ const users: UserSource = {
|
|
|
137
141
|
},
|
|
138
142
|
// Optional, but required for email verification and password reset:
|
|
139
143
|
async update(id, patch: UserPatch) { /* UPDATE ... */ return null },
|
|
144
|
+
// Optional: bulk contact lookup (see below).
|
|
145
|
+
async findByIds(ids) { /* SELECT id, email, email_verified WHERE id IN (...) */ return [] },
|
|
140
146
|
}
|
|
141
147
|
```
|
|
142
148
|
|
|
149
|
+
| Method | Required? | Returns | Purpose |
|
|
150
|
+
|---|---|---|---|
|
|
151
|
+
| `findByEmail(email)` | Yes | `AuthUser \| null` | Sign-in and registration lookups. Emails are case-insensitive identities. |
|
|
152
|
+
| `findById(id)` | Yes | `AuthUser \| null` | Resolving the user behind a token, session or API key. |
|
|
153
|
+
| `create({ email, passwordHash })` | Yes | `AuthUser` | Registration; the hash arrives already computed. |
|
|
154
|
+
| `update(id, patch)` | No | `AuthUser \| null` | Email verification and password reset need it (`AUTH_UPDATE_UNSUPPORTED` without it). |
|
|
155
|
+
| `findByIds(ids)` | No | `PublicUser[]` | **Bulk contact lookup** — see below. |
|
|
156
|
+
|
|
157
|
+
#### `findByIds` — one lookup instead of N
|
|
158
|
+
|
|
159
|
+
`findById` resolves one account at a time, which pushes anything that needs the
|
|
160
|
+
*contact details of a group* ("email every admin of this tenant") into either N
|
|
161
|
+
round trips or — worse — reading the auth tables directly from application code,
|
|
162
|
+
coupling the product to the auth schema.
|
|
163
|
+
|
|
164
|
+
`findByIds` is the bulk counterpart, and its contract is deliberately narrower
|
|
165
|
+
than `findById`'s:
|
|
166
|
+
|
|
167
|
+
- it resolves **`PublicUser`**, never `AuthUser` — a directory lookup has no
|
|
168
|
+
business carrying a password hash, and the shipped drivers do not even
|
|
169
|
+
`SELECT` the credential columns;
|
|
170
|
+
- one entry per **found** id, **in the order of `ids`**; ids with no account are
|
|
171
|
+
omitted, so the result may be shorter than the input;
|
|
172
|
+
- duplicate ids collapse to one entry, and an empty list resolves to `[]`
|
|
173
|
+
without touching the database.
|
|
174
|
+
|
|
175
|
+
It is optional: stores written before it keep compiling, and callers fall back
|
|
176
|
+
to one `findById` per id. `@basaltkit/teams` does exactly that — pass the same
|
|
177
|
+
`UserSource` to `teamsPlugin({ users })` and `teams.roleRecipients(tenantId,
|
|
178
|
+
'admin')` returns the admins' contacts, taking the batched path automatically
|
|
179
|
+
when your driver has one.
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
const contacts = await users.findByIds?.(['u1', 'u2', 'ghost'])
|
|
183
|
+
// → [{ id: 'u1', email: 'ada@acme.test', emailVerified: true }, { id: 'u2', ... }]
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
The shipped drivers (`@basaltkit/auth-prisma`, `@basaltkit/auth-sqlite`) and
|
|
187
|
+
`MemoryUserSource` all implement it; the SQL ones chunk the id list so a large
|
|
188
|
+
tenant can't exceed the driver's bind-parameter limit.
|
|
189
|
+
|
|
143
190
|
### Register, login, and logout (by code)
|
|
144
191
|
|
|
145
192
|
All operations are also available programmatically through the `Auth` class:
|
|
@@ -147,7 +194,7 @@ All operations are also available programmatically through the `Auth` class:
|
|
|
147
194
|
```ts
|
|
148
195
|
import { Auth, MemoryUserSource } from '@basaltkit/auth'
|
|
149
196
|
|
|
150
|
-
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
|
|
151
198
|
|
|
152
199
|
const user = await auth.register('ada@example.com', 'secretpassword1')
|
|
153
200
|
const { tokens } = await auth.login('ada@example.com', 'secretpassword1')
|
|
@@ -209,6 +256,17 @@ enroll/activate/status. `meta: { mfa: true }` requires MFA on one route
|
|
|
209
256
|
session cookie carries it HMAC-signed, and the request exposes it as
|
|
210
257
|
`ctx().amr`. API-key requests are not subject to the policy. Off by default.
|
|
211
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
|
+
|
|
212
270
|
### Passkeys — WebAuthn (`webauthnPlugin`)
|
|
213
271
|
|
|
214
272
|
Passkeys let users sign in with Face ID / Touch ID / a security key — no password.
|
|
@@ -296,9 +354,27 @@ const { userId } = await passkeys.finishAuthentication(sessionKey, browserRespon
|
|
|
296
354
|
> credential id is rejected (`PASSKEY_EXISTS`) rather than overwriting an existing one.
|
|
297
355
|
|
|
298
356
|
`finishAuthentication` looks the credential up by id, verifies it, checks the
|
|
299
|
-
signature counter **increased** (a non-increasing counter throws `PasskeyClonedError
|
|
300
|
-
and persists the new counter
|
|
301
|
-
|
|
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'`.
|
|
302
378
|
|
|
303
379
|
### Social login (OAuth)
|
|
304
380
|
|
|
@@ -351,18 +427,58 @@ character-for-character, or the provider rejects it with *"redirect_uri is not
|
|
|
351
427
|
associated with this application"*.
|
|
352
428
|
|
|
353
429
|
New accounts are created **passwordless** and a provider-verified email flips
|
|
354
|
-
`emailVerified`.
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
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.
|
|
361
444
|
|
|
362
445
|
**Enterprise SSO (OIDC):** any OpenID Connect IdP (Okta, Entra ID, Auth0,
|
|
363
|
-
Keycloak…) plugs in via `oidcProvider({ clientId, clientSecret,
|
|
364
|
-
tokenUrl,
|
|
365
|
-
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).
|
|
366
482
|
|
|
367
483
|
### API keys
|
|
368
484
|
|
|
@@ -398,7 +514,7 @@ const app = await createApp({
|
|
|
398
514
|
|
|
399
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.
|
|
400
516
|
|
|
401
|
-
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? }`.
|
|
402
518
|
|
|
403
519
|
The guard enforces, on every key-authenticated request: **tenant binding** (a key
|
|
404
520
|
issued in a tenant is refused with `403 AUTH_APIKEY_TENANT_MISMATCH` on any request
|
|
@@ -430,6 +546,12 @@ login/MFA, per-IP and email-request throttles with one atomic Redis script per
|
|
|
430
546
|
attempt. `redis` is any ioredis-compatible client — only `eval` and `del` are
|
|
431
547
|
used, no Redis dependency. Implement `ThrottleStore` for another backend.
|
|
432
548
|
|
|
549
|
+
The in-memory store is bounded (`maxEntries`, default 100 000): when full it
|
|
550
|
+
sweeps expired entries, then evicts the oldest *unlocked* ones — a flood of junk
|
|
551
|
+
identifiers cannot flush a locked account out of the store and hand the
|
|
552
|
+
attacker a fresh budget. Only when every tracked entry is locked does the oldest
|
|
553
|
+
lock go (the memory bound is absolute).
|
|
554
|
+
|
|
433
555
|
### Hooks (events)
|
|
434
556
|
|
|
435
557
|
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`.
|
|
@@ -442,7 +564,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
442
564
|
|
|
443
565
|
| Name | Type | Required? | Default | Description |
|
|
444
566
|
|---|---|---|---|---|
|
|
445
|
-
| `users` | `UserSource` | Yes | — | Where users come from (your DB). |
|
|
567
|
+
| `users` | `UserSource` | Yes | — | Where users come from (your DB). Implement the optional `findByIds` for batched contact lookups. |
|
|
446
568
|
| `secret` | `string` | Yes | — | Secret that signs the JWTs (HS256). |
|
|
447
569
|
| `hasher` | `PasswordHasher` | No | `ScryptPasswordHasher` | Password hashing algorithm. |
|
|
448
570
|
| `sessions` | `SessionStore` | No | `MemorySessionStore` | Session storage. |
|
|
@@ -450,7 +572,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
450
572
|
| `accessTtl` | `DurationInput` | No | `'15m'` | Access token validity. |
|
|
451
573
|
| `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
|
|
452
574
|
| `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
|
|
453
|
-
| `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults
|
|
575
|
+
| `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults on unless `NODE_ENV` is explicitly `development`/`test`. |
|
|
454
576
|
| `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
|
|
455
577
|
| `throttleStore` | `ThrottleStore` | No | in-memory, per process | Counters of the default login / per-IP / email-request throttles — `RedisThrottleStore` for one budget across replicas. |
|
|
456
578
|
| `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. |
|
|
@@ -458,6 +580,9 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
458
580
|
| `verificationTtl` | `DurationInput` | No | `'24h'` | Email verification link validity. |
|
|
459
581
|
| `resetTtl` | `DurationInput` | No | `'1h'` | Password reset link validity. |
|
|
460
582
|
| `mfa` | `MfaStore` | No | `MemoryMfaStore` | Per-user MFA state. |
|
|
583
|
+
| `accountLinks` | `AccountLinkStore` | No | `MemoryAccountLinkStore` | OAuth/OIDC account links (provider + subject → user). `create` must be atomic on the pair. |
|
|
584
|
+
| `mfaEncryption` | `{ keys: SecretBoxKey[]; legacy? }` | No | — (plaintext) | Encrypts TOTP secrets at rest with a key ring; see *Encrypting secrets at rest*. |
|
|
585
|
+
| `mfaEncryptionKey` | `string \| Buffer` | No | — | Shorthand for a one-key ring (`id: 'default'`, ≥ 32 bytes). |
|
|
461
586
|
| `mfaIssuer` | `string` | No | `'Basalt'` | Name shown in the authenticator app. |
|
|
462
587
|
| `hooks` | `HookBus` | No | — | Only on the `Auth` class; the plugin injects it. |
|
|
463
588
|
|
|
@@ -476,7 +601,8 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
476
601
|
| `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
|
|
477
602
|
| `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
|
|
478
603
|
| `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
|
|
479
|
-
| `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
|
|
604
|
+
| `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 }`. |
|
|
605
|
+
| `reencryptMfaSecret(userId)` | Re-seals a stored TOTP secret under the active `mfaEncryption` key (rotation / legacy migration): `'resealed'`, `'current'` or `'none'`. |
|
|
480
606
|
|
|
481
607
|
### Ready-made routes
|
|
482
608
|
|
|
@@ -484,7 +610,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
484
610
|
- 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.
|
|
485
611
|
- `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.
|
|
486
612
|
- `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
|
|
487
|
-
- `oauthRoutes({ callbackBaseUrl, successRedirect? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider.
|
|
613
|
+
- `oauthRoutes({ callbackBaseUrl, successRedirect?, bindingCookie?, rateLimit? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider (rate-limited by default).
|
|
488
614
|
|
|
489
615
|
### `apiKeysPlugin(options)` and the `ApiKeys` class
|
|
490
616
|
|
|
@@ -493,7 +619,7 @@ Options (`ApiKeysPluginOptions`):
|
|
|
493
619
|
| Name | Type | Required? | Default | Description |
|
|
494
620
|
|---|---|---|---|---|
|
|
495
621
|
| `store` | `ApiKeyStore` | No | `MemoryApiKeyStore` | Key storage. |
|
|
496
|
-
| `header` | `string` | No | `'x-api-key'` | Alternative header to Bearer. |
|
|
622
|
+
| `header` | `string` | No | `'x-api-key'` | Alternative header to Bearer. Two different keys (Bearer + header) → 400 `AUTH_APIKEY_AMBIGUOUS`. |
|
|
497
623
|
| `users` | `UserSource` | No | — | If given, a key with `userId` also populates `ctx().user`. |
|
|
498
624
|
| `now` | `() => number` | No | `Date.now` | Injectable clock (tests). |
|
|
499
625
|
|
|
@@ -504,15 +630,17 @@ Options (`ApiKeysPluginOptions`):
|
|
|
504
630
|
| Export | Description |
|
|
505
631
|
|---|---|
|
|
506
632
|
| `signJwt(claims, { secret, expiresIn? })` / `verifyJwt(token, secret)` | Dependency-free HS256 JWT. Advanced. |
|
|
507
|
-
| `ScryptPasswordHasher` / `PasswordHasher` | Password hashing (scrypt, memory-hard). Advanced. |
|
|
633
|
+
| `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. |
|
|
508
634
|
| `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `store`, `namespace`, `clock`) | Anti brute-force. |
|
|
509
635
|
| `ThrottleStore` / `MemoryThrottleStore` / `RedisThrottleStore` (`RedisThrottleClient`: `eval` + `del`) | Where throttle counters live; Redis shares them across replicas. |
|
|
510
636
|
| `generateTotpSecret`, `totp`, `verifyTotp`, `otpauthUri`, `base32Encode`, `base32Decode` | TOTP primitives (RFC 6238). Advanced. |
|
|
511
637
|
| `publicUser(user)` | Converts `AuthUser` → `PublicUser` (removes the hash). |
|
|
638
|
+
| `UserSource.findByIds(ids)` | Optional bulk contact lookup: `PublicUser[]`, in the order of `ids`, missing ids omitted. Powers `@basaltkit/teams`' `roleRecipients`. |
|
|
512
639
|
| `AUTH`, `API_KEYS`, `OAUTH` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance; `OAUTH` returns the `OAuth` instance. |
|
|
513
640
|
| `oauthPlugin`, `oauthRoutes` | Social-login plugin (`{ secret, providers }`) and its routes (`{ callbackBaseUrl, successRedirect? }`). |
|
|
514
641
|
| `googleProvider`, `githubProvider`, `oidcProvider`, `discoverOidcProvider` | OAuth 2.0 / OpenID Connect providers. Each takes `{ clientId, clientSecret, scopes? }`. |
|
|
515
|
-
| In-memory stores | `MemoryUserSource`, `MemorySessionStore`, `MemoryRefreshTokenStore`, `MemoryAuthTokenStore`, `MemoryApiKeyStore`, `MemoryMfaStore` — dev/testing. |
|
|
642
|
+
| In-memory stores | `MemoryUserSource`, `MemorySessionStore`, `MemoryRefreshTokenStore`, `MemoryAuthTokenStore`, `MemoryApiKeyStore`, `MemoryMfaStore`, `MemoryAccountLinkStore`, `MemoryPasskeyStore` — dev/testing. |
|
|
643
|
+
| `SecretBox` | The at-rest envelope behind `mfaEncryption` (`seal` / `open` / `reseal` with a `{ purpose, subject }` context), for your own secrets. |
|
|
516
644
|
|
|
517
645
|
#### Single-use tokens are consumed with a compare-and-swap
|
|
518
646
|
|
|
@@ -539,7 +667,14 @@ If you implement your own store, do the same. Returning `void` keeps the older r
|
|
|
539
667
|
| `ScopeRequiredError` | `AUTH_SCOPE_REQUIRED` | 403 |
|
|
540
668
|
| `OAuthProviderUnknownError` | `AUTH_OAUTH_UNKNOWN_PROVIDER` | 404 |
|
|
541
669
|
| `OAuthStateInvalidError` | `AUTH_OAUTH_STATE_INVALID` | 400 |
|
|
542
|
-
| `OAuthExchangeError` | `AUTH_OAUTH_EXCHANGE_FAILED` | 502 |
|
|
670
|
+
| `OAuthExchangeError` | `AUTH_OAUTH_EXCHANGE_FAILED` | 502 (message kept for the log; the client gets `Bad gateway.`) |
|
|
671
|
+
| `OAuthProviderConfigError` | `AUTH_OAUTH_PROVIDER_CONFIG` | boot (several providers with an unrestricted enterprise IdP, an invalid domain entry, a duplicate name) |
|
|
672
|
+
| `ApiKeyAmbiguousError` | `AUTH_APIKEY_AMBIGUOUS` | 400 |
|
|
673
|
+
| `PasskeyNotFoundError` / `WebAuthnSubjectMismatchError` | `PASSKEY_NOT_FOUND` / `WEBAUTHN_SUBJECT_MISMATCH` | 404/403 |
|
|
674
|
+
| `PasskeyClonedError` / `PasskeyStoreOutdatedError` | `PASSKEY_CLONED` / `PASSKEY_STORE_OUTDATED` | 401 / boot |
|
|
675
|
+
| `AccountLinkConflictError` | `AUTH_ACCOUNT_LINK_CONFLICT` | 409 |
|
|
676
|
+
| `AccountEmailAmbiguousError` | `AUTH_EMAIL_AMBIGUOUS` | 500 (not exposed; several rows differ only in email case) |
|
|
677
|
+
| `SecretUnreadableError` / `SecretBoxKeyError` | `AUTH_SECRET_UNREADABLE` / `AUTH_SECRET_BOX_KEY_INVALID` | 500 / boot |
|
|
543
678
|
|
|
544
679
|
## Common issues and solutions (FAQ)
|
|
545
680
|
|
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
|
|
@@ -365,15 +440,28 @@ export declare class Auth {
|
|
|
365
440
|
enabled: boolean;
|
|
366
441
|
pending: boolean;
|
|
367
442
|
}>;
|
|
443
|
+
/** Encrypt a TOTP secret for storage, bound to its user (no-op when no key is configured). */
|
|
444
|
+
private encryptMfaSecret;
|
|
445
|
+
/**
|
|
446
|
+
* Decrypt a stored TOTP secret. With encryption configured, only an envelope
|
|
447
|
+
* sealed for this user opens; plaintext and `v1:` values need the explicit
|
|
448
|
+
* legacy opt-in (otherwise `AUTH_SECRET_UNREADABLE`, failing closed).
|
|
449
|
+
*/
|
|
450
|
+
private decryptMfaSecret;
|
|
451
|
+
/**
|
|
452
|
+
* Re-encrypts one user's stored TOTP secret under the active key of
|
|
453
|
+
* `mfaEncryption` — for key rotation, and to migrate `v1:` envelopes or
|
|
454
|
+
* plaintext secrets (reading those needs the matching `legacy` opt-in).
|
|
455
|
+
* Returns `'resealed'` when the row was rewritten, `'current'` when it was
|
|
456
|
+
* already sealed with the active key, `'none'` when the user has no MFA
|
|
457
|
+
* record. Run it over every user id with an MFA row, then drop `legacy`.
|
|
458
|
+
*/
|
|
459
|
+
reencryptMfaSecret(userId: string): Promise<'resealed' | 'current' | 'none'>;
|
|
368
460
|
/**
|
|
369
461
|
* Begins MFA enrollment: generates a fresh secret (not yet active) and
|
|
370
462
|
* returns it plus an `otpauth://` URI to render as a QR code. Call
|
|
371
463
|
* {@link activateMfa} with a code from the app to switch it on.
|
|
372
464
|
*/
|
|
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
465
|
enrollMfa(userId: string): Promise<{
|
|
378
466
|
secret: string;
|
|
379
467
|
otpauthUri: string;
|