@basaltkit/auth 2.2.0 → 3.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 +52 -15
- package/dist/apikeys-plugin.d.ts +46 -0
- package/dist/apikeys-plugin.js +72 -7
- package/dist/apikeys.d.ts +5 -0
- package/dist/apikeys.js +10 -0
- package/dist/auth.d.ts +117 -9
- package/dist/auth.js +288 -48
- package/dist/index.d.ts +17 -5
- package/dist/index.js +6 -5
- package/dist/jwt.d.ts +5 -0
- package/dist/oauth-plugin.d.ts +9 -0
- package/dist/oauth-plugin.js +31 -4
- package/dist/oauth.d.ts +41 -4
- package/dist/oauth.js +99 -11
- package/dist/plugin.d.ts +76 -2
- package/dist/plugin.js +107 -16
- package/dist/redis-throttle.d.ts +34 -0
- package/dist/redis-throttle.js +69 -0
- package/dist/routes.d.ts +35 -1
- package/dist/routes.js +77 -29
- package/dist/stores.d.ts +14 -0
- package/dist/stores.js +24 -1
- package/dist/throttle.d.ts +107 -10
- package/dist/throttle.js +127 -17
- package/dist/webauthn-plugin.js +9 -1
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -197,6 +197,18 @@ Flow (all routes require login):
|
|
|
197
197
|
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.
|
|
198
198
|
4. `GET /auth/mfa/status` and `POST /auth/mfa/disable` (with `{ code }`) complete the cycle.
|
|
199
199
|
|
|
200
|
+
**Requiring MFA.** `authPlugin({ requireMfa: true })` — or a policy
|
|
201
|
+
`requireMfa: (user, context) => boolean | Promise<boolean>` — refuses every
|
|
202
|
+
authenticated request whose credential was not obtained with a second factor:
|
|
203
|
+
`403 AUTH_MFA_ENROLLMENT_REQUIRED` (no MFA yet: enrol, then sign in again) or
|
|
204
|
+
`403 AUTH_MFA_REQUIRED` (sign in again with a code). Routes with
|
|
205
|
+
`meta.mfa: false` are exempt — all of `authRoutes()` and MFA
|
|
206
|
+
enroll/activate/status. `meta: { mfa: true }` requires MFA on one route
|
|
207
|
+
(step-up) even without the policy. Tokens carry an `amr` claim (`['pwd']`,
|
|
208
|
+
`['pwd', 'mfa']`, `['fed', …]` for social login), refreshes keep it, the
|
|
209
|
+
session cookie carries it HMAC-signed, and the request exposes it as
|
|
210
|
+
`ctx().amr`. API-key requests are not subject to the policy. Off by default.
|
|
211
|
+
|
|
200
212
|
### Passkeys — WebAuthn (`webauthnPlugin`)
|
|
201
213
|
|
|
202
214
|
Passkeys let users sign in with Face ID / Touch ID / a security key — no password.
|
|
@@ -291,8 +303,9 @@ for a "manage devices" screen.
|
|
|
291
303
|
### Social login (OAuth)
|
|
292
304
|
|
|
293
305
|
Sign in with Google, GitHub, or any OpenID Connect provider via the OAuth 2.0
|
|
294
|
-
authorization-code flow — no SDK
|
|
295
|
-
|
|
306
|
+
authorization-code flow — no SDK. The flow is bound to the browser that started
|
|
307
|
+
it (an HttpOnly binding cookie whose hash is in the HMAC-signed, single-use
|
|
308
|
+
`state`), and the code exchange uses PKCE (S256) plus an OIDC `nonce`. Register `oauthPlugin` with your providers and `oauthRoutes` with
|
|
296
309
|
your app's **base URL**:
|
|
297
310
|
|
|
298
311
|
```ts
|
|
@@ -305,7 +318,7 @@ createApp({
|
|
|
305
318
|
plugins: [
|
|
306
319
|
authPlugin({ users, secret: process.env.AUTH_SECRET! }),
|
|
307
320
|
oauthPlugin({
|
|
308
|
-
secret: process.env.AUTH_SECRET!, // signs the
|
|
321
|
+
secret: process.env.AUTH_SECRET!, // signs the `state`, derives PKCE verifier + nonce
|
|
309
322
|
providers: [
|
|
310
323
|
googleProvider({ clientId: env.GOOGLE_ID, clientSecret: env.GOOGLE_SECRET }),
|
|
311
324
|
githubProvider({ clientId: env.GITHUB_ID, clientSecret: env.GITHUB_SECRET }),
|
|
@@ -325,8 +338,8 @@ createApp({
|
|
|
325
338
|
|
|
326
339
|
Two routes are added per provider:
|
|
327
340
|
|
|
328
|
-
- `GET /auth/oauth/:provider` → 302 to the provider's consent screen.
|
|
329
|
-
- `GET /auth/oauth/:provider/callback` → verifies the `state
|
|
341
|
+
- `GET /auth/oauth/:provider` → sets the binding cookie, 302 to the provider's consent screen.
|
|
342
|
+
- `GET /auth/oauth/:provider/callback` → verifies the `state` against the cookie, exchanges the code,
|
|
330
343
|
and logs the user in. Returns JSON `{ user, accessToken, refreshToken }`; pass
|
|
331
344
|
`successRedirect` to `oauthRoutes` to bounce the browser back to your SPA with
|
|
332
345
|
the tokens in the URL fragment instead.
|
|
@@ -338,9 +351,13 @@ character-for-character, or the provider rejects it with *"redirect_uri is not
|
|
|
338
351
|
associated with this application"*.
|
|
339
352
|
|
|
340
353
|
New accounts are created **passwordless** and a provider-verified email flips
|
|
341
|
-
`emailVerified`.
|
|
342
|
-
|
|
343
|
-
|
|
354
|
+
`emailVerified`. An **existing** account is only logged into when the provider
|
|
355
|
+
verified the email (`SocialLinkRefusedError` otherwise); an existing account that
|
|
356
|
+
had never verified its own email has its password, sessions, refresh tokens and
|
|
357
|
+
MFA revoked before it is adopted; an account with MFA enabled requires the code
|
|
358
|
+
(`MfaRequiredError`) unless `oauthPlugin({ mfa: 'skip' })` is set for an IdP that
|
|
359
|
+
enforces its own MFA. `Auth.socialLogin(email, { emailVerified })` is the
|
|
360
|
+
underlying primitive for custom providers.
|
|
344
361
|
|
|
345
362
|
**Enterprise SSO (OIDC):** any OpenID Connect IdP (Okta, Entra ID, Auth0,
|
|
346
363
|
Keycloak…) plugs in via `oidcProvider({ clientId, clientSecret, authorizationUrl,
|
|
@@ -383,6 +400,15 @@ const app = await createApp({
|
|
|
383
400
|
|
|
384
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? }`.
|
|
385
402
|
|
|
403
|
+
The guard enforces, on every key-authenticated request: **tenant binding** (a key
|
|
404
|
+
issued in a tenant is refused with `403 AUTH_APIKEY_TENANT_MISMATCH` on any request
|
|
405
|
+
resolving another tenant or none; tenantless keys are refused on tenant-scoped
|
|
406
|
+
requests unless `allowTenantlessKeys: true`), **scopes as an upper bound** (a key
|
|
407
|
+
without `*` is refused on `meta.auth`/`can`/`teamRole`/`audience` routes that do not
|
|
408
|
+
declare `meta.scopes`; opt out with `allowNarrowKeysOnUnscopedRoutes: true`) and
|
|
409
|
+
**session-only routes** (`meta.apiKey: false` refuses every key with
|
|
410
|
+
`403 AUTH_APIKEY_NOT_ALLOWED` — `apiKeyRoutes()` and `mfaRoutes()` declare it).
|
|
411
|
+
|
|
386
412
|
### Brute-force lockout (LoginThrottle)
|
|
387
413
|
|
|
388
414
|
Active by default: 5 failed attempts per email within a 15-minute window → `AUTH_LOCKED` error (HTTP 429). A successful login clears the counter.
|
|
@@ -398,6 +424,12 @@ authPlugin({
|
|
|
398
424
|
})
|
|
399
425
|
```
|
|
400
426
|
|
|
427
|
+
Counters live in memory per process by default. For several replicas, share
|
|
428
|
+
them: `authPlugin({ throttleStore: new RedisThrottleStore(redis) })` backs the
|
|
429
|
+
login/MFA, per-IP and email-request throttles with one atomic Redis script per
|
|
430
|
+
attempt. `redis` is any ioredis-compatible client — only `eval` and `del` are
|
|
431
|
+
used, no Redis dependency. Implement `ThrottleStore` for another backend.
|
|
432
|
+
|
|
401
433
|
### Hooks (events)
|
|
402
434
|
|
|
403
435
|
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`.
|
|
@@ -420,6 +452,8 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
420
452
|
| `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
|
|
421
453
|
| `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults to production only. |
|
|
422
454
|
| `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
|
|
455
|
+
| `throttleStore` | `ThrottleStore` | No | in-memory, per process | Counters of the default login / per-IP / email-request throttles — `RedisThrottleStore` for one budget across replicas. |
|
|
456
|
+
| `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. |
|
|
423
457
|
| `tokens` | `AuthTokenStore` | No | `MemoryAuthTokenStore` | Verification/reset tokens. `markUsed` must be a **compare-and-swap** — see below. |
|
|
424
458
|
| `verificationTtl` | `DurationInput` | No | `'24h'` | Email verification link validity. |
|
|
425
459
|
| `resetTtl` | `DurationInput` | No | `'1h'` | Password reset link validity. |
|
|
@@ -432,22 +466,23 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
432
466
|
| Method | Description |
|
|
433
467
|
|---|---|
|
|
434
468
|
| `register(email, password)` | Creates the account; throws `EmailTakenError` if the email already exists. |
|
|
435
|
-
| `login(email, password, mfaCode?)` | Returns `{ user, tokens }`; applies throttle and MFA. |
|
|
469
|
+
| `login(email, password, mfaCode?)` | Returns `{ user, tokens, amr }`; applies throttle and MFA. |
|
|
436
470
|
| `attempt(email, password)` | Checks credentials without side effects; `null` on failure. |
|
|
437
471
|
| `refresh(refreshToken)` | New token pair; detects reuse and revokes the family. |
|
|
438
472
|
| `revoke(refreshToken)` | Logout for token-based clients. |
|
|
439
473
|
| `verifyAccess(accessToken)` | Validates the JWT and returns the claims. |
|
|
440
|
-
| `createSession(userId)` / `sessionUser(sessionId)` / `logout(sessionId)` | Cookie/header-based sessions
|
|
474
|
+
| `createSession(userId, { amr? })` / `sessionUser(sessionId)` / `sessionAuth(sessionId)` / `logout(sessionId)` | Cookie/header-based sessions; `amr` is carried HMAC-signed in the session id, `sessionAuth` returns `{ user, amr? }`. |
|
|
441
475
|
| `requestEmailVerification(email)` / `verifyEmail(token)` | Email verification. |
|
|
442
476
|
| `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
|
|
443
477
|
| `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
|
|
444
478
|
| `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
|
|
445
|
-
| `socialLogin(email, { emailVerified? })` | Find-or-create a passwordless account for an OAuth/OIDC identity; returns `{ user, tokens }`. |
|
|
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 and honours its MFA; returns `{ user, tokens }`. |
|
|
446
480
|
|
|
447
481
|
### Ready-made routes
|
|
448
482
|
|
|
449
|
-
- `authRoutes()`: `POST /auth/register`, `POST /auth/login`, `POST /auth/refresh`, `POST /auth/logout`, `GET /auth/me`, `POST /auth/verify/request`, `POST /auth/verify`, `POST /auth/password/forgot`, `POST /auth/password/reset`. These are regular routes — you can omit or replace any of them.
|
|
450
|
-
- `
|
|
483
|
+
- `authRoutes()`: `POST /auth/register`, `POST /auth/login`, `POST /auth/refresh`, `POST /auth/logout`, `GET /auth/me`, `POST /auth/verify/request`, `POST /auth/verify`, `POST /auth/password/forgot`, `POST /auth/password/reset`. These are regular routes — you can omit or replace any of them. `POST /auth/logout` takes an optional `{ refreshToken }`: with none (or no body) it ends the cookie / `x-session-id` session and expires the cookie — a cross-site cookie-only logout is refused (`403 AUTH_CSRF_REJECTED`).
|
|
484
|
+
- 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
|
+
- `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.
|
|
451
486
|
- `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
|
|
452
487
|
- `oauthRoutes({ callbackBaseUrl, successRedirect? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider.
|
|
453
488
|
|
|
@@ -470,7 +505,8 @@ Options (`ApiKeysPluginOptions`):
|
|
|
470
505
|
|---|---|
|
|
471
506
|
| `signJwt(claims, { secret, expiresIn? })` / `verifyJwt(token, secret)` | Dependency-free HS256 JWT. Advanced. |
|
|
472
507
|
| `ScryptPasswordHasher` / `PasswordHasher` | Password hashing (scrypt, memory-hard). Advanced. |
|
|
473
|
-
| `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `clock`) | Anti brute-force. |
|
|
508
|
+
| `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `store`, `namespace`, `clock`) | Anti brute-force. |
|
|
509
|
+
| `ThrottleStore` / `MemoryThrottleStore` / `RedisThrottleStore` (`RedisThrottleClient`: `eval` + `del`) | Where throttle counters live; Redis shares them across replicas. |
|
|
474
510
|
| `generateTotpSecret`, `totp`, `verifyTotp`, `otpauthUri`, `base32Encode`, `base32Decode` | TOTP primitives (RFC 6238). Advanced. |
|
|
475
511
|
| `publicUser(user)` | Converts `AuthUser` → `PublicUser` (removes the hash). |
|
|
476
512
|
| `AUTH`, `API_KEYS`, `OAUTH` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance; `OAUTH` returns the `OAuth` instance. |
|
|
@@ -498,6 +534,7 @@ If you implement your own store, do the same. Returning `void` keeps the older r
|
|
|
498
534
|
| `AuthTokenInvalidError` (verification/reset links) | `AUTH_TOKEN_INVALID` | 400 |
|
|
499
535
|
| `UserUpdateUnsupportedError` | `AUTH_UPDATE_UNSUPPORTED` | 500 |
|
|
500
536
|
| `MfaRequiredError` / `MfaInvalidCodeError` / `MfaNotEnrolledError` | `AUTH_MFA_*` | 401/401/400 |
|
|
537
|
+
| `MfaStepUpRequiredError` / `MfaEnrollmentRequiredError` | `AUTH_MFA_REQUIRED` / `AUTH_MFA_ENROLLMENT_REQUIRED` | 403/403 |
|
|
501
538
|
| `AccountLockedError` | `AUTH_LOCKED` | 429 |
|
|
502
539
|
| `ScopeRequiredError` | `AUTH_SCOPE_REQUIRED` | 403 |
|
|
503
540
|
| `OAuthProviderUnknownError` | `AUTH_OAUTH_UNKNOWN_PROVIDER` | 404 |
|
|
@@ -527,7 +564,7 @@ If you implement your own store, do the same. Returning `void` keeps the older r
|
|
|
527
564
|
- **@basaltkit/core** — provides the app, the container, the request context (`ctx()`), and hooks; auth sets `ctx().user` and `ctx().apiKey`.
|
|
528
565
|
- **@basaltkit/fastify** — the HTTP adapter that runs the enrichers/guards and serves the ready-made routes.
|
|
529
566
|
- **@basaltkit/permissions** — answers "what can you do?"; its `meta.can` guard uses the `ctx().user` that auth sets.
|
|
530
|
-
- **@basaltkit/tenancy** — defines `ctx().tenant`; API keys created within a tenant
|
|
567
|
+
- **@basaltkit/tenancy** — defines `ctx().tenant`; API keys created within a tenant only work inside that tenant.
|
|
531
568
|
- **@basaltkit/teams** — the `meta.teamRole` guard combines `ctx().user` (auth) with `ctx().tenant` (tenancy).
|
|
532
569
|
|
|
533
570
|
## Security best practices
|
package/dist/apikeys-plugin.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { BasaltError } from '@basaltkit/core';
|
|
1
2
|
import { ApiKeys, type ApiKeyContext, type ApiKeysOptions } from './apikeys.js';
|
|
2
3
|
import type { UserSource } from './stores.js';
|
|
3
4
|
declare module '@basaltkit/core' {
|
|
@@ -14,8 +15,39 @@ declare module '@basaltkit/core' {
|
|
|
14
15
|
'auth:apikey_revoked': {
|
|
15
16
|
id: string;
|
|
16
17
|
};
|
|
18
|
+
/**
|
|
19
|
+
* A presented API key was refused: unknown/revoked/expired (`invalid`), used
|
|
20
|
+
* outside the tenant it is bound to (`tenant_mismatch`), used on a
|
|
21
|
+
* session-only route (`not_allowed`) or beyond its scopes (`scope`). Never
|
|
22
|
+
* carries the key itself.
|
|
23
|
+
*/
|
|
24
|
+
'auth:apikey_rejected': {
|
|
25
|
+
id?: string;
|
|
26
|
+
reason: 'invalid' | 'tenant_mismatch' | 'not_allowed' | 'scope';
|
|
27
|
+
tenantId?: string;
|
|
28
|
+
};
|
|
17
29
|
}
|
|
18
30
|
}
|
|
31
|
+
declare module '@basaltkit/http' {
|
|
32
|
+
interface RouteMeta {
|
|
33
|
+
/**
|
|
34
|
+
* `false` makes the route session-only: requests authenticated with an API
|
|
35
|
+
* key are refused (403 `AUTH_APIKEY_NOT_ALLOWED`), whatever the key's scopes.
|
|
36
|
+
* Key management and MFA routes declare it.
|
|
37
|
+
*/
|
|
38
|
+
apiKey?: boolean;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** The key is bound to another tenant than the one this request resolved. */
|
|
42
|
+
export declare class ApiKeyTenantMismatchError extends BasaltError {
|
|
43
|
+
readonly status = 403;
|
|
44
|
+
constructor();
|
|
45
|
+
}
|
|
46
|
+
/** The route only accepts an interactive session, not an API key. */
|
|
47
|
+
export declare class ApiKeyNotAllowedError extends BasaltError {
|
|
48
|
+
readonly status = 403;
|
|
49
|
+
constructor();
|
|
50
|
+
}
|
|
19
51
|
export declare const API_KEYS: import("@basaltkit/core").Token<ApiKeys>;
|
|
20
52
|
export interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
21
53
|
/**
|
|
@@ -28,6 +60,20 @@ export interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
|
28
60
|
* so scope-guarded routes can read the acting user.
|
|
29
61
|
*/
|
|
30
62
|
users?: UserSource;
|
|
63
|
+
/**
|
|
64
|
+
* Keys issued without a tenant (machine/platform keys) are refused on any
|
|
65
|
+
* request that resolved a tenant, so they cannot be pointed at an arbitrary
|
|
66
|
+
* tenant through `x-tenant-id`, a subdomain or the Host. Set `true` only for
|
|
67
|
+
* trusted platform keys that must act across tenants. Default false.
|
|
68
|
+
*/
|
|
69
|
+
allowTenantlessKeys?: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* By default a key that does not hold `*` is refused on routes gated by
|
|
72
|
+
* `meta.auth`/`can`/`teamRole`/`audience` unless the route also declares
|
|
73
|
+
* `meta.scopes` — scopes are an upper bound, not a label. `true` restores the
|
|
74
|
+
* old behaviour where any key with a `userId` acts as its owner. Default false.
|
|
75
|
+
*/
|
|
76
|
+
allowNarrowKeysOnUnscopedRoutes?: boolean;
|
|
31
77
|
}
|
|
32
78
|
/**
|
|
33
79
|
* Programmatic access via API keys. Registers an enricher that authenticates
|
package/dist/apikeys-plugin.js
CHANGED
|
@@ -1,7 +1,29 @@
|
|
|
1
|
-
import { createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
|
|
1
|
+
import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
|
|
2
2
|
import { ApiKeys, ScopeRequiredError, scopesSatisfy } from './apikeys.js';
|
|
3
3
|
import { publicUser } from './auth.js';
|
|
4
|
+
/** The key is bound to another tenant than the one this request resolved. */
|
|
5
|
+
export class ApiKeyTenantMismatchError extends BasaltError {
|
|
6
|
+
status = 403;
|
|
7
|
+
constructor() {
|
|
8
|
+
super('AUTH_APIKEY_TENANT_MISMATCH', 'This API key is not valid for this tenant.');
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** The route only accepts an interactive session, not an API key. */
|
|
12
|
+
export class ApiKeyNotAllowedError extends BasaltError {
|
|
13
|
+
status = 403;
|
|
14
|
+
constructor() {
|
|
15
|
+
super('AUTH_APIKEY_NOT_ALLOWED', 'This action requires an interactive session; API keys are not accepted.');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Route-meta keys that gate a route on the *identity* of the caller. A key that
|
|
20
|
+
* does not hold `*` reaches such a route only when the route also declares
|
|
21
|
+
* `meta.scopes` — otherwise a narrow key would inherit its owner's full powers
|
|
22
|
+
* through `ctx().user`.
|
|
23
|
+
*/
|
|
24
|
+
const IDENTITY_GATED_META = ['auth', 'can', 'teamRole', 'audience'];
|
|
4
25
|
export const API_KEYS = createToken('auth:apikeys');
|
|
26
|
+
const tenantOf = (context) => context.tenant?.id;
|
|
5
27
|
/**
|
|
6
28
|
* Programmatic access via API keys. Registers an enricher that authenticates
|
|
7
29
|
* `mk_`-prefixed bearers (or the configured header) and a guard that enforces
|
|
@@ -13,6 +35,12 @@ export function apiKeysPlugin(options = {}) {
|
|
|
13
35
|
name: 'basalt:apikeys',
|
|
14
36
|
register({ container, hooks }) {
|
|
15
37
|
container.singleton(API_KEYS, () => new ApiKeys({ ...options, hooks }));
|
|
38
|
+
// A verified social login that adopts a never-verified account distrusts
|
|
39
|
+
// whoever registered it: the keys they may have minted die with the rest
|
|
40
|
+
// of their credentials (Auth revokes passwords, sessions, tokens and MFA).
|
|
41
|
+
hooks.on('auth:social_account_adopted', async ({ user }) => {
|
|
42
|
+
await container.get(API_KEYS).revokeAllForUser(user.id);
|
|
43
|
+
});
|
|
16
44
|
const metadata = ensureMetadata(container);
|
|
17
45
|
const enricher = async ({ request, context, container: c }) => {
|
|
18
46
|
const authHeader = request.headers.authorization;
|
|
@@ -24,8 +52,10 @@ export function apiKeysPlugin(options = {}) {
|
|
|
24
52
|
if (!presented)
|
|
25
53
|
return;
|
|
26
54
|
const record = await c.get(API_KEYS).verify(presented);
|
|
27
|
-
if (!record)
|
|
55
|
+
if (!record) {
|
|
56
|
+
await hooks.emit('auth:apikey_rejected', { reason: 'invalid' });
|
|
28
57
|
return;
|
|
58
|
+
}
|
|
29
59
|
context.apiKey = {
|
|
30
60
|
id: record.id,
|
|
31
61
|
scopes: record.scopes,
|
|
@@ -39,15 +69,50 @@ export function apiKeysPlugin(options = {}) {
|
|
|
39
69
|
}
|
|
40
70
|
};
|
|
41
71
|
metadata.add('http:enrichers', enricher);
|
|
42
|
-
// Guard
|
|
43
|
-
|
|
44
|
-
|
|
72
|
+
// Guard (runs after every enricher, so ctx().tenant is resolved): binds the
|
|
73
|
+
// key to its tenant, refuses keys on session-only routes, and enforces
|
|
74
|
+
// meta.scopes as an upper bound on what a key may reach.
|
|
75
|
+
const guard = async ({ route, context }) => {
|
|
76
|
+
const key = context.apiKey;
|
|
77
|
+
const meta = route.meta;
|
|
78
|
+
if (key) {
|
|
79
|
+
const reject = async (reason, error) => {
|
|
80
|
+
const tenantId = tenantOf(context);
|
|
81
|
+
await hooks.emit('auth:apikey_rejected', { id: key.id, reason, ...(tenantId !== undefined ? { tenantId } : {}) });
|
|
82
|
+
throw error;
|
|
83
|
+
};
|
|
84
|
+
const tenantId = tenantOf(context);
|
|
85
|
+
if (key.tenantId !== undefined) {
|
|
86
|
+
// A tenant-bound key works only inside that tenant — never in another
|
|
87
|
+
// one picked by the client, and never outside any tenant.
|
|
88
|
+
if (tenantId !== key.tenantId)
|
|
89
|
+
await reject('tenant_mismatch', new ApiKeyTenantMismatchError());
|
|
90
|
+
}
|
|
91
|
+
else if (tenantId !== undefined && options.allowTenantlessKeys !== true) {
|
|
92
|
+
await reject('tenant_mismatch', new ApiKeyTenantMismatchError());
|
|
93
|
+
}
|
|
94
|
+
if (meta?.['apiKey'] === false)
|
|
95
|
+
await reject('not_allowed', new ApiKeyNotAllowedError());
|
|
96
|
+
const declared = meta?.['scopes'];
|
|
97
|
+
const hasScopes = Array.isArray(declared) && declared.length > 0;
|
|
98
|
+
if (!hasScopes &&
|
|
99
|
+
options.allowNarrowKeysOnUnscopedRoutes !== true &&
|
|
100
|
+
!key.scopes.includes('*') &&
|
|
101
|
+
IDENTITY_GATED_META.some((k) => meta?.[k] !== undefined && meta?.[k] !== false)) {
|
|
102
|
+
await reject('scope', new ScopeRequiredError('*'));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// A route declaring meta.scopes needs an API key holding them all.
|
|
106
|
+
const required = meta?.['scopes'];
|
|
45
107
|
if (!Array.isArray(required) || required.length === 0)
|
|
46
108
|
return;
|
|
47
|
-
const granted =
|
|
109
|
+
const granted = key?.scopes ?? [];
|
|
48
110
|
for (const scope of required) {
|
|
49
|
-
if (!scopesSatisfy(granted, [scope]))
|
|
111
|
+
if (!scopesSatisfy(granted, [scope])) {
|
|
112
|
+
if (key)
|
|
113
|
+
await hooks.emit('auth:apikey_rejected', { id: key.id, reason: 'scope' });
|
|
50
114
|
throw new ScopeRequiredError(scope);
|
|
115
|
+
}
|
|
51
116
|
}
|
|
52
117
|
};
|
|
53
118
|
metadata.add('http:guards', guard);
|
package/dist/apikeys.d.ts
CHANGED
|
@@ -47,6 +47,11 @@ export declare class ApiKeys {
|
|
|
47
47
|
list(filter: ApiKeyFilter): Promise<ApiKeyInfo[]>;
|
|
48
48
|
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
49
49
|
revoke(id: string): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Revokes every live key owned by the user — for when the account's previous
|
|
52
|
+
* holder is no longer trusted (e.g. a verified social login adopted it).
|
|
53
|
+
*/
|
|
54
|
+
revokeAllForUser(userId: string): Promise<void>;
|
|
50
55
|
/** Reads a single key's public info (used to authorize a revoke). */
|
|
51
56
|
get(id: string): Promise<ApiKeyInfo | null>;
|
|
52
57
|
}
|
package/dist/apikeys.js
CHANGED
|
@@ -88,6 +88,16 @@ export class ApiKeys {
|
|
|
88
88
|
await this.hooks?.emit('auth:apikey_revoked', { id });
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* Revokes every live key owned by the user — for when the account's previous
|
|
93
|
+
* holder is no longer trusted (e.g. a verified social login adopted it).
|
|
94
|
+
*/
|
|
95
|
+
async revokeAllForUser(userId) {
|
|
96
|
+
for (const record of await this.store.list({ userId })) {
|
|
97
|
+
if (record.userId === userId)
|
|
98
|
+
await this.revoke(record.id);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
91
101
|
/** Reads a single key's public info (used to authorize a revoke). */
|
|
92
102
|
async get(id) {
|
|
93
103
|
const record = await this.store.findById(id);
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BasaltError, type DurationInput, type HookBus } from '@basaltkit/core';
|
|
2
2
|
import { type PasswordHasher } from './hashing.js';
|
|
3
|
-
import { LoginThrottle } from './throttle.js';
|
|
3
|
+
import { LoginThrottle, type ThrottleStore } from './throttle.js';
|
|
4
4
|
import { type JwtClaims } from './jwt.js';
|
|
5
5
|
import { type AuthTokenStore, type AuthUser, type MfaStore, type PublicUser, type RefreshTokenStore, type SessionRecord, type SessionStore, type TokenVersionStore, type UserSource } from './stores.js';
|
|
6
6
|
export declare class InvalidCredentialsError extends BasaltError {
|
|
@@ -48,11 +48,49 @@ export declare class MfaRequiredError extends BasaltError {
|
|
|
48
48
|
readonly status = 401;
|
|
49
49
|
constructor();
|
|
50
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* The route needs a credential obtained with a second factor (MFA policy or
|
|
53
|
+
* `meta.mfa: true`), and the account has MFA enabled: sign in again with a
|
|
54
|
+
* code. Distinct from the 401 {@link MfaRequiredError} of the login itself.
|
|
55
|
+
*/
|
|
56
|
+
export declare class MfaStepUpRequiredError extends BasaltError {
|
|
57
|
+
readonly status = 403;
|
|
58
|
+
constructor();
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The route needs a credential obtained with a second factor, and the account
|
|
62
|
+
* has not enabled MFA yet: enrol (`/auth/mfa/enroll` + `/activate`), then sign
|
|
63
|
+
* in again with a code.
|
|
64
|
+
*/
|
|
65
|
+
export declare class MfaEnrollmentRequiredError extends BasaltError {
|
|
66
|
+
readonly status = 403;
|
|
67
|
+
constructor();
|
|
68
|
+
}
|
|
51
69
|
/** The supplied MFA (or recovery) code was wrong. */
|
|
52
70
|
export declare class MfaInvalidCodeError extends BasaltError {
|
|
53
71
|
readonly status = 401;
|
|
54
72
|
constructor();
|
|
55
73
|
}
|
|
74
|
+
/** MFA is already active: re-enrolling would silently switch it off. Disable it (with a code) first. */
|
|
75
|
+
export declare class MfaAlreadyEnabledError extends BasaltError {
|
|
76
|
+
readonly status = 409;
|
|
77
|
+
constructor();
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A social / SSO login matched an existing account by email, but the provider
|
|
81
|
+
* did not vouch for that email (unverified), so linking would let anyone who
|
|
82
|
+
* can create an IdP account with the address take the account over.
|
|
83
|
+
*/
|
|
84
|
+
export declare class SocialLinkRefusedError extends BasaltError {
|
|
85
|
+
readonly status = 403;
|
|
86
|
+
constructor();
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Canonical form of an email identity: trimmed and lowercased. Every lookup,
|
|
90
|
+
* create and throttle key goes through it, so `Bob@acme.test` and
|
|
91
|
+
* `bob@acme.test` are one account.
|
|
92
|
+
*/
|
|
93
|
+
export declare const canonicalEmail: (email: string) => string;
|
|
56
94
|
/** An MFA action needed an enrollment that doesn't exist. */
|
|
57
95
|
export declare class MfaNotEnrolledError extends BasaltError {
|
|
58
96
|
readonly status = 400;
|
|
@@ -62,6 +100,8 @@ export interface TokenPair {
|
|
|
62
100
|
accessToken: string;
|
|
63
101
|
refreshToken: string;
|
|
64
102
|
}
|
|
103
|
+
/** Whether a value is a well-formed `amr` list (non-empty, short lowercase words). */
|
|
104
|
+
export declare const isAmr: (value: unknown) => value is string[];
|
|
65
105
|
export interface SessionCookieOptions {
|
|
66
106
|
/** Cookie name. Default: `basalt_session`. */
|
|
67
107
|
name?: string;
|
|
@@ -94,6 +134,23 @@ export interface AuthOptions {
|
|
|
94
134
|
* Only applies when the caller passes the client ip to `login`.
|
|
95
135
|
*/
|
|
96
136
|
ipLoginThrottle?: LoginThrottle | false;
|
|
137
|
+
/**
|
|
138
|
+
* Per-account throttle on password-reset and email-verification requests.
|
|
139
|
+
* Over budget, a request is silently dropped (no new token, no hook, the live
|
|
140
|
+
* link keeps working) — so the endpoints cannot be used to mail-bomb a user or
|
|
141
|
+
* keep invalidating their reset link. Default: 3 per 15 minutes per account
|
|
142
|
+
* and purpose; pass `false` to disable.
|
|
143
|
+
*/
|
|
144
|
+
emailRequestThrottle?: LoginThrottle | false;
|
|
145
|
+
/**
|
|
146
|
+
* Where the DEFAULT throttles above (login, per-ip login, email requests)
|
|
147
|
+
* keep their counters. Default: in memory, per process — each replica then
|
|
148
|
+
* grants its own budget. Pass a shared store (e.g. `RedisThrottleStore`) so a
|
|
149
|
+
* cluster enforces one budget; each throttle uses its own namespace
|
|
150
|
+
* (`login`, `login-ip`, `email-request`). Ignored for a throttle passed
|
|
151
|
+
* explicitly (give that one its own `store`).
|
|
152
|
+
*/
|
|
153
|
+
throttleStore?: ThrottleStore;
|
|
97
154
|
/**
|
|
98
155
|
* Make the public registration endpoint enumeration-safe: a request for an
|
|
99
156
|
* email that already exists returns the same response (and does equivalent
|
|
@@ -141,6 +198,7 @@ export declare class Auth {
|
|
|
141
198
|
private readonly hooks;
|
|
142
199
|
private readonly throttle;
|
|
143
200
|
private readonly ipThrottle;
|
|
201
|
+
private readonly requestThrottle;
|
|
144
202
|
private readonly tokens;
|
|
145
203
|
private readonly verificationTtl;
|
|
146
204
|
private readonly resetTtl;
|
|
@@ -150,21 +208,39 @@ export declare class Auth {
|
|
|
150
208
|
private readonly tokenVersions;
|
|
151
209
|
private readonly enumerationSafeRegister;
|
|
152
210
|
constructor(options: AuthOptions);
|
|
153
|
-
register(
|
|
211
|
+
register(rawEmail: string, password: string): Promise<PublicUser>;
|
|
154
212
|
/**
|
|
155
213
|
* Logs in an externally-authenticated user (e.g. from an OAuth provider),
|
|
156
214
|
* matched by email — find-or-create. A new account is created **passwordless**
|
|
157
215
|
* (a random, unusable password hash), so password login won't work for it
|
|
158
216
|
* until a password is set. A provider-verified email flips `emailVerified`.
|
|
159
217
|
* Returns the tokens and whether the account was just created.
|
|
218
|
+
*
|
|
219
|
+
* Linking to an EXISTING account is refused ({@link SocialLinkRefusedError})
|
|
220
|
+
* unless `emailVerified` is `true` — an unverified provider email proves
|
|
221
|
+
* nothing about who owns the address. When the existing account had never
|
|
222
|
+
* 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).
|
|
160
227
|
*/
|
|
161
|
-
socialLogin(
|
|
228
|
+
socialLogin(rawEmail: string, options?: {
|
|
162
229
|
emailVerified?: boolean;
|
|
230
|
+
mfaCode?: string;
|
|
231
|
+
mfa?: 'required' | 'skip';
|
|
163
232
|
}): Promise<{
|
|
164
233
|
user: PublicUser;
|
|
165
234
|
tokens: TokenPair;
|
|
166
235
|
created: boolean;
|
|
236
|
+
amr: string[];
|
|
167
237
|
}>;
|
|
238
|
+
/**
|
|
239
|
+
* A provider-verified login is taking over an account whose email was never
|
|
240
|
+
* verified: whoever registered it could be anyone (pre-account hijacking), so
|
|
241
|
+
* every credential they may hold is revoked before the verified owner gets in.
|
|
242
|
+
*/
|
|
243
|
+
private adoptUnverifiedAccount;
|
|
168
244
|
/**
|
|
169
245
|
* Enumeration-safe registration for the public endpoint: creates the account
|
|
170
246
|
* for a new email, or — when the email is already taken — does equivalent work
|
|
@@ -175,7 +251,7 @@ export declare class Auth {
|
|
|
175
251
|
* With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
|
|
176
252
|
* duplicate instead (the classic, enumerable behavior).
|
|
177
253
|
*/
|
|
178
|
-
registerSafely(
|
|
254
|
+
registerSafely(rawEmail: string, password: string): Promise<void>;
|
|
179
255
|
/** Verifies credentials without side effects. Null on failure. */
|
|
180
256
|
attempt(email: string, password: string): Promise<AuthUser | null>;
|
|
181
257
|
private dummyHashPromise?;
|
|
@@ -190,12 +266,18 @@ export declare class Auth {
|
|
|
190
266
|
* required: a correct password with a missing code throws
|
|
191
267
|
* {@link MfaRequiredError} (without counting as a failed attempt), and a
|
|
192
268
|
* wrong code throws {@link MfaInvalidCodeError}.
|
|
269
|
+
*
|
|
270
|
+
* `amr` lists the authentication methods used — `['pwd']`, or
|
|
271
|
+
* `['pwd', 'mfa']` when a second factor was verified. It is also embedded in
|
|
272
|
+
* the access token (`amr` claim) and carried by every refresh of this login;
|
|
273
|
+
* pass it to {@link createSession} so a cookie session carries it too.
|
|
193
274
|
*/
|
|
194
275
|
login(email: string, password: string, mfaCode?: string, context?: {
|
|
195
276
|
ip?: string;
|
|
196
277
|
}): Promise<{
|
|
197
278
|
user: PublicUser;
|
|
198
279
|
tokens: TokenPair;
|
|
280
|
+
amr: string[];
|
|
199
281
|
}>;
|
|
200
282
|
/**
|
|
201
283
|
* Refresh rotation with reuse detection: every refresh consumes the token
|
|
@@ -203,6 +285,7 @@ export declare class Auth {
|
|
|
203
285
|
* (theft indicator), the whole family is revoked.
|
|
204
286
|
*/
|
|
205
287
|
refresh(refreshToken: string): Promise<TokenPair>;
|
|
288
|
+
private reuseDetected;
|
|
206
289
|
/** Revokes a refresh family — logout for token-based clients. */
|
|
207
290
|
revoke(refreshToken: string): Promise<void>;
|
|
208
291
|
/** Structural JWT verification only (signature + expiry). */
|
|
@@ -216,15 +299,37 @@ export declare class Auth {
|
|
|
216
299
|
verifyAccessToken(accessToken: string): Promise<JwtClaims>;
|
|
217
300
|
/**
|
|
218
301
|
* Revokes every access token issued so far for the user (logout-everywhere),
|
|
219
|
-
*
|
|
220
|
-
*
|
|
302
|
+
* revoking every refresh token and server-side session (when the stores
|
|
303
|
+
* implement `revokeAllForUser` / `deleteAllForUser`, as the bundled ones do)
|
|
304
|
+
* and bumping the token version so outstanding access tokens die too (needs a
|
|
305
|
+
* {@link TokenVersionStore}; without one, access tokens live until their TTL).
|
|
221
306
|
*/
|
|
222
307
|
revokeAllTokens(userId: string): Promise<void>;
|
|
223
|
-
|
|
308
|
+
/**
|
|
309
|
+
* Creates a server-side session. With `amr` (from {@link login}), the
|
|
310
|
+
* returned id — the value to put in the cookie — also carries those
|
|
311
|
+
* authentication methods, HMAC-signed with the auth secret so a client cannot
|
|
312
|
+
* add `mfa` to a password-only session. Stores are unaffected: they only
|
|
313
|
+
* ever see the random part.
|
|
314
|
+
*/
|
|
315
|
+
createSession(userId: string, options?: {
|
|
316
|
+
amr?: readonly string[];
|
|
317
|
+
}): Promise<SessionRecord>;
|
|
318
|
+
private sessionTagSignature;
|
|
319
|
+
/** Splits a session id minted by {@link createSession} into the store id and its signed `amr`. */
|
|
320
|
+
private parseSessionId;
|
|
224
321
|
sessionCookieHeader(sessionId: string): string;
|
|
225
322
|
sessionIdFromCookie(cookieHeader?: string): string | null;
|
|
226
323
|
expiredSessionCookieHeader(): string;
|
|
227
324
|
sessionUser(sessionId: string): Promise<AuthUser | null>;
|
|
325
|
+
/**
|
|
326
|
+
* The user of a session plus the authentication methods it was created with
|
|
327
|
+
* (`amr` is absent for sessions created without them, e.g. before this option).
|
|
328
|
+
*/
|
|
329
|
+
sessionAuth(sessionId: string): Promise<{
|
|
330
|
+
user: AuthUser;
|
|
331
|
+
amr?: string[];
|
|
332
|
+
} | null>;
|
|
228
333
|
logout(sessionId: string): Promise<void>;
|
|
229
334
|
/**
|
|
230
335
|
* Starts email verification: mints a single-use token and emits
|
|
@@ -238,10 +343,13 @@ export declare class Auth {
|
|
|
238
343
|
} | null>;
|
|
239
344
|
/** Consumes a verification token and marks the user's email verified. */
|
|
240
345
|
verifyEmail(token: string): Promise<PublicUser>;
|
|
346
|
+
/** Per-account budget for reset/verification mails; false = drop silently. */
|
|
347
|
+
private allowEmailRequest;
|
|
241
348
|
/**
|
|
242
349
|
* Starts a password reset: mints a single-use token and emits
|
|
243
|
-
* `auth:password_reset_requested`. Returns null when no account matches
|
|
244
|
-
* the
|
|
350
|
+
* `auth:password_reset_requested`. Returns null when no account matches (or
|
|
351
|
+
* the per-account request budget is spent — the live link then stays valid),
|
|
352
|
+
* so the caller always responds 200 (no account enumeration).
|
|
245
353
|
*/
|
|
246
354
|
requestPasswordReset(email: string): Promise<{
|
|
247
355
|
user: PublicUser;
|