@basaltkit/auth 3.2.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 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. Customize its public attributes when mounting the plugin:
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: 'a-strong-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')
@@ -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. Use `passkeys.list(userId)` / `passkeys.remove(id)`
344
- for a "manage devices" screen.
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`. An **existing** account is only logged into when the provider
398
- verified the email (`SocialLinkRefusedError` otherwise); an existing account that
399
- had never verified its own email has its password, sessions, refresh tokens and
400
- MFA revoked before it is adopted; an account with MFA enabled requires the code
401
- (`MfaRequiredError`) unless `oauthPlugin({ mfa: 'skip' })` is set for an IdP that
402
- enforces its own MFA. `Auth.socialLogin(email, { emailVerified })` is the
403
- underlying primitive for custom providers.
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, authorizationUrl,
407
- tokenUrl, userinfoUrl })`, or let `discoverOidcProvider(issuerUrl, keys)` read the
408
- endpoints from the IdP's `.well-known/openid-configuration`.
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
@@ -473,6 +546,12 @@ login/MFA, per-IP and email-request throttles with one atomic Redis script per
473
546
  attempt. `redis` is any ioredis-compatible client — only `eval` and `del` are
474
547
  used, no Redis dependency. Implement `ThrottleStore` for another backend.
475
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
+
476
555
  ### Hooks (events)
477
556
 
478
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`.
@@ -493,7 +572,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
493
572
  | `accessTtl` | `DurationInput` | No | `'15m'` | Access token validity. |
494
573
  | `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
495
574
  | `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
496
- | `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults to production only. |
575
+ | `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults on unless `NODE_ENV` is explicitly `development`/`test`. |
497
576
  | `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
498
577
  | `throttleStore` | `ThrottleStore` | No | in-memory, per process | Counters of the default login / per-IP / email-request throttles — `RedisThrottleStore` for one budget across replicas. |
499
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. |
@@ -501,6 +580,9 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
501
580
  | `verificationTtl` | `DurationInput` | No | `'24h'` | Email verification link validity. |
502
581
  | `resetTtl` | `DurationInput` | No | `'1h'` | Password reset link validity. |
503
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). |
504
586
  | `mfaIssuer` | `string` | No | `'Basalt'` | Name shown in the authenticator app. |
505
587
  | `hooks` | `HookBus` | No | — | Only on the `Auth` class; the plugin injects it. |
506
588
 
@@ -519,7 +601,8 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
519
601
  | `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
520
602
  | `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
521
603
  | `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 and honours its MFA; returns `{ user, tokens }`. |
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'`. |
523
606
 
524
607
  ### Ready-made routes
525
608
 
@@ -527,7 +610,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
527
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.
528
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.
529
612
  - `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.
613
+ - `oauthRoutes({ callbackBaseUrl, successRedirect?, bindingCookie?, rateLimit? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider (rate-limited by default).
531
614
 
532
615
  ### `apiKeysPlugin(options)` and the `ApiKeys` class
533
616
 
@@ -536,7 +619,7 @@ Options (`ApiKeysPluginOptions`):
536
619
  | Name | Type | Required? | Default | Description |
537
620
  |---|---|---|---|---|
538
621
  | `store` | `ApiKeyStore` | No | `MemoryApiKeyStore` | Key storage. |
539
- | `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`. |
540
623
  | `users` | `UserSource` | No | — | If given, a key with `userId` also populates `ctx().user`. |
541
624
  | `now` | `() => number` | No | `Date.now` | Injectable clock (tests). |
542
625
 
@@ -547,7 +630,7 @@ Options (`ApiKeysPluginOptions`):
547
630
  | Export | Description |
548
631
  |---|---|
549
632
  | `signJwt(claims, { secret, expiresIn? })` / `verifyJwt(token, secret)` | Dependency-free HS256 JWT. Advanced. |
550
- | `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. |
551
634
  | `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `store`, `namespace`, `clock`) | Anti brute-force. |
552
635
  | `ThrottleStore` / `MemoryThrottleStore` / `RedisThrottleStore` (`RedisThrottleClient`: `eval` + `del`) | Where throttle counters live; Redis shares them across replicas. |
553
636
  | `generateTotpSecret`, `totp`, `verifyTotp`, `otpauthUri`, `base32Encode`, `base32Decode` | TOTP primitives (RFC 6238). Advanced. |
@@ -556,7 +639,8 @@ Options (`ApiKeysPluginOptions`):
556
639
  | `AUTH`, `API_KEYS`, `OAUTH` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance; `OAUTH` returns the `OAuth` instance. |
557
640
  | `oauthPlugin`, `oauthRoutes` | Social-login plugin (`{ secret, providers }`) and its routes (`{ callbackBaseUrl, successRedirect? }`). |
558
641
  | `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. |
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. |
560
644
 
561
645
  #### Single-use tokens are consumed with a compare-and-swap
562
646
 
@@ -583,7 +667,14 @@ If you implement your own store, do the same. Returning `void` keeps the older r
583
667
  | `ScopeRequiredError` | `AUTH_SCOPE_REQUIRED` | 403 |
584
668
  | `OAuthProviderUnknownError` | `AUTH_OAUTH_UNKNOWN_PROVIDER` | 404 |
585
669
  | `OAuthStateInvalidError` | `AUTH_OAUTH_STATE_INVALID` | 400 |
586
- | `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 |
587
678
 
588
679
  ## Common issues and solutions (FAQ)
589
680
 
@@ -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
  /**
@@ -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 custom = request.headers[header];
51
- const presented = bearer ?? (typeof custom === 'string' ? custom : undefined);
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 AuthTokenStore, type AuthUser, type MfaStore, type PublicUser, type RefreshTokenStore, type SessionRecord, type SessionStore, type TokenVersionStore, type UserSource } from './stores.js';
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
- /** Whether to require HTTPS. Defaults to production-only. */
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
- * Key for encrypting TOTP secrets at rest (AES-256-GCM). When set, secrets are
179
- * stored as `v1:` envelopes so a database leak can't recover a live second
180
- * factor; existing plaintext records keep working and are encrypted on next
181
- * write. Any length — derived to 32 bytes. Omit to store secrets in plaintext.
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 mfaKey;
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
- * matched by email — find-or-create. A new account is created **passwordless**
215
- * (a random, unusable password hash), so password login won't work for it
216
- * until a password is set. A provider-verified email flips `emailVerified`.
217
- * Returns the tokens and whether the account was just created.
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 MFA are revoked before it is adopted
224
- * (`auth:social_account_adopted`). An account with MFA enabled requires
225
- * `mfaCode` ({@link MfaRequiredError}) unless `mfa: 'skip'` is passed
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;