@basaltkit/auth 4.1.0 → 5.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
@@ -24,7 +24,7 @@ It also includes, with nothing extra to install: account lockout after too many
24
24
  pnpm add @basaltkit/auth
25
25
  ```
26
26
 
27
- Requirements: `@basaltkit/core` and `@basaltkit/fastify` (installed automatically as dependencies) and `zod` (peer dependency — install with `pnpm add zod`).
27
+ Requirements: `@basaltkit/core` and `@basaltkit/http` (3.x; installed automatically as dependencies) and `zod` (peer dependency — install with `pnpm add zod`). The package is adapter-agnostic: serve its routes with `@basaltkit/fastify`, `@basaltkit/express` or `@basaltkit/hono` 3.x, which must run the same `@basaltkit/http` 3.
28
28
 
29
29
  ## Get started in 5 minutes
30
30
 
@@ -130,14 +130,15 @@ const myRoute = route({
130
130
  The module doesn't impose any database. You provide an object that fulfills the `UserSource` interface:
131
131
 
132
132
  ```ts
133
- import type { UserSource, AuthUser, UserPatch } from '@basaltkit/auth'
133
+ import type { UserSource, AuthUser, UserPatch, NewUser } from '@basaltkit/auth'
134
134
 
135
135
  const users: UserSource = {
136
136
  async findByEmail(email) { /* SELECT ... WHERE email = ? */ return null },
137
137
  async findById(id) { /* SELECT ... WHERE id = ? */ return null },
138
- async create(data) {
139
- // data = { email, passwordHash } — the hash is already computed
140
- return { id: 'new-id', ...data } as AuthUser
138
+ async create(data: NewUser) {
139
+ // data = { email, passwordHash, emailVerified? } — the hash is already computed;
140
+ // persist emailVerified (omitted = false) with the row
141
+ return { id: 'new-id', email: data.email, passwordHash: data.passwordHash, emailVerified: data.emailVerified === true }
141
142
  },
142
143
  // Optional, but required for email verification and password reset:
143
144
  async update(id, patch: UserPatch) { /* UPDATE ... */ return null },
@@ -150,7 +151,7 @@ const users: UserSource = {
150
151
  |---|---|---|---|
151
152
  | `findByEmail(email)` | Yes | `AuthUser \| null` | Sign-in and registration lookups. Emails are case-insensitive identities. |
152
153
  | `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
+ | `create({ email, passwordHash, emailVerified? })` | Yes | `AuthUser` | Registration; the hash arrives already computed. `emailVerified: true` comes only from trusted flows (`register(…, { emailVerified: true })`, a provider-verified social login) and must be persisted with the row. A source that drops it is patched through `update()`; without `update()`, `register(…, { emailVerified: true })` throws `AUTH_UPDATE_UNSUPPORTED` before anything is written and a social login keeps the account unverified (still linked and signed in). |
154
155
  | `update(id, patch)` | No | `AuthUser \| null` | Email verification and password reset need it (`AUTH_UPDATE_UNSUPPORTED` without it). |
155
156
  | `findByIds(ids)` | No | `PublicUser[]` | **Bulk contact lookup** — see below. |
156
157
 
@@ -255,6 +256,10 @@ enroll/activate/status. `meta: { mfa: true }` requires MFA on one route
255
256
  `['pwd', 'mfa']`, `['fed', …]` for social login), refreshes keep it, the
256
257
  session cookie carries it HMAC-signed, and the request exposes it as
257
258
  `ctx().amr`. API-key requests are not subject to the policy. Off by default.
259
+ Listing surfaces (MCP `tools/list`) hide `meta.mfa: true` routes — and, under
260
+ `requireMfa: true`, every authenticated route — from a session without `'mfa'` in
261
+ `ctx().amr`, through a side-effect-free `http:route-visibility` check. A
262
+ `requireMfa` function is never called for a listing.
258
263
 
259
264
  **Encrypting secrets at rest.** `authPlugin({ mfaEncryption: { keys: [{ id, key }] } })`
260
265
  (or the shorthand `mfaEncryptionKey`) stores TOTP secrets as `bka2.<keyId>.…`
@@ -499,7 +504,7 @@ const app = await createApp({
499
504
  fastifyPlugin({
500
505
  routes: [
501
506
  ...authRoutes(),
502
- ...apiKeyRoutes(), // POST/GET /apikeys, DELETE /apikeys/:id
507
+ ...apiKeyRoutes(), // POST/GET /apikeys, PATCH/DELETE /apikeys/:id, POST /apikeys/:id/rotate
503
508
  route({
504
509
  method: 'GET',
505
510
  url: '/reports',
@@ -524,6 +529,27 @@ without `*` is refused on `meta.auth`/`can`/`teamRole`/`audience` routes that do
524
529
  declare `meta.scopes`; opt out with `allowNarrowKeysOnUnscopedRoutes: true`) and
525
530
  **session-only routes** (`meta.apiKey: false` refuses every key with
526
531
  `403 AUTH_APIKEY_NOT_ALLOWED` — `apiKeyRoutes()` and `mfaRoutes()` declare it).
532
+ The plugin also registers a side-effect-free `http:route-visibility` check, so
533
+ listing surfaces (MCP `tools/list`) hide `meta.scopes` routes from callers whose key
534
+ does not hold every scope, `meta.apiKey: false` routes from key holders, and identity-gated routes without
535
+ `meta.scopes` from narrow keys (no `*`). A listing emits no `auth:apikey_rejected`.
536
+
537
+ **Rate limits and OpenAPI.** With `securityPlugin({ rateLimit })` from `@basaltkit/http`,
538
+ `meta.rateLimit: { …, key: 'apiKey' }` budgets each verified key separately (an invalid
539
+ key never gets a bucket of its own), and `rateLimit.prefixes` lifts the per-IP ceiling for
540
+ an API's paths. `openapiPlugin` advertises `meta.scopes` routes with an `apiKeyAuth`
541
+ scheme and `x-required-scopes`; if you change `header` here, pass the same one as
542
+ `openapiPlugin({ apiKey: { header } })`.
543
+
544
+ For machine clients: `rejectInvalid: true` answers a presented key that does not
545
+ verify with `401 AUTH_APIKEY_INVALID` and `WWW-Authenticate: Bearer
546
+ error="invalid_token"` (default: the request continues as anonymous), and
547
+ `touchEveryMs` (default 60 s; `0` = every request) throttles `lastUsedAt` writes.
548
+ `auth:apikey_rejected` carries the display `prefix` and `ip` of an invalid key,
549
+ never the secret; `@basaltkit/audit` does not record it by default. A refusal of
550
+ a key that verified (`ip_not_allowed`, `tenant_mismatch`, `not_allowed`, `scope`) is also emitted
551
+ as `auth:apikey_refused` (`{ id, reason, tenantId? }`), which the audit records
552
+ by default.
527
553
 
528
554
  ### Brute-force lockout (LoginThrottle)
529
555
 
@@ -556,7 +582,7 @@ lock go (the memory bound is absolute).
556
582
 
557
583
  ### Hooks (events)
558
584
 
559
- The application can react to authentication events: `auth:registered`, `auth:login`, `auth:login_failed`, `auth:logout`, `auth:verify_requested`, `auth:email_verified`, `auth:password_reset_requested`, `auth:password_reset`, `auth:mfa_enabled`, `auth:mfa_disabled`, `auth:apikey_issued`, `auth:apikey_revoked`.
585
+ The application can react to authentication events: `auth:registered`, `auth:register_existing_email`, `auth:register_refused` (a registration policy refused a new account: `{ email, tenantId?, source: 'register' | 'social' }`), `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`, `auth:apikey_rotated`, `auth:apikey_updated` (changed field names only).
560
586
 
561
587
  ## API reference
562
588
 
@@ -573,8 +599,9 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
573
599
  | `refreshTokens` | `RefreshTokenStore` | No | `MemoryRefreshTokenStore` | Refresh token storage. `markUsed` must be a **compare-and-swap** — see below. |
574
600
  | `accessTtl` | `DurationInput` | No | `'15m'` | Access token validity. |
575
601
  | `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
576
- | `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
577
- | `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults on unless `NODE_ENV` is explicitly `development`/`test`. |
602
+ | `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity (absolute). |
603
+ | `sessionIdleTtl` | `DurationInput` | No | — | Idle timeout: a session unused for longer is refused and deleted. Needs a session store with `touch` (memory, auth-sqlite, auth-prisma with `trackSessionActivity`); fails at boot otherwise. |
604
+ | `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults on unless `NODE_ENV` is explicitly `development`/`test`. A `__Host-`/`__Secure-` name implies `Secure` (and `Path=/` for `__Host-`); a contradicting `secure: false` or `__Host-` path refuses the boot (`AUTH_SESSION_COOKIE_INVALID`, `SessionCookieConfigError`) — use `name: isProd ? '__Host-sid' : 'sid'`. |
578
605
  | `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
579
606
  | `throttleStore` | `ThrottleStore` | No | in-memory, per process | Counters of the default login / per-IP / email-request throttles — `RedisThrottleStore` for one budget across replicas. |
580
607
  | `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. |
@@ -586,13 +613,15 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
586
613
  | `mfaEncryption` | `{ keys: SecretBoxKey[]; legacy? }` | No | — (plaintext) | Encrypts TOTP secrets at rest with a key ring; see *Encrypting secrets at rest*. |
587
614
  | `mfaEncryptionKey` | `string \| Buffer` | No | — | Shorthand for a one-key ring (`id: 'default'`, ≥ 32 bytes). |
588
615
  | `mfaIssuer` | `string` | No | `'Basalt'` | Name shown in the authenticator app. |
616
+ | `registerPolicy` | `RegisterPolicy` (`({ email, tenantId? }) => boolean \| Promise<boolean>`) | No | — (open) | Who may create a NEW account through `POST /auth/register` (refusal = same `202`, `auth:register_refused`) and the create branch of `socialLogin` (refusal = `RegistrationClosedError`). Logins into existing accounts and `register()` are never gated. `@basaltkit/teams`' `teamsInviteGate(teams)` = invite-only on tenant hosts. |
589
617
  | `hooks` | `HookBus` | No | — | Only on the `Auth` class; the plugin injects it. |
590
618
 
591
619
  `Auth` class methods:
592
620
 
593
621
  | Method | Description |
594
622
  |---|---|
595
- | `register(email, password)` | Creates the account; throws `EmailTakenError` if the email already exists. |
623
+ | `register(email, password, { emailVerified? })` | Trusted, server-side creation; throws `EmailTakenError` if the email already exists; never gated by `registerPolicy`. `emailVerified: true` creates the account already verified (only for a flow that proved the address — never from a request body). |
624
+ | `registerSafely(email, password, { policy?, tenantId? })` | What `POST /auth/register` calls: enumeration-safe, asks the registration policy first (`policy: null` = open); never creates a verified account. |
596
625
  | `login(email, password, mfaCode?)` | Returns `{ user, tokens, amr }`; applies throttle and MFA. |
597
626
  | `attempt(email, password)` | Checks credentials without side effects; `null` on failure. |
598
627
  | `refresh(refreshToken)` | New token pair; detects reuse and revokes the family. |
@@ -603,14 +632,15 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
603
632
  | `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
604
633
  | `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
605
634
  | `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
606
- | `socialLogin(email, { emailVerified?, mfaCode?, mfa?, identity?, subjectConflict? })` | Find-or-create a passwordless account for an OAuth/OIDC identity; with `identity: { provider, subject }` the account link decides, otherwise it links to an existing account only with a provider-verified email; honours MFA; returns `{ user, tokens }`. |
635
+ | `socialLogin(email, { emailVerified?, mfaCode?, mfa?, identity?, subjectConflict?, tenantId? })` | 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; creating a new account asks `registerPolicy` (for `tenantId`, default `ctx().tenant?.id`) and is refused with `RegistrationClosedError`; returns `{ user, tokens }`. |
607
636
  | `reencryptMfaSecret(userId)` | Re-seals a stored TOTP secret under the active `mfaEncryption` key (rotation / legacy migration): `'resealed'`, `'current'` or `'none'`. |
608
637
 
609
638
  ### Ready-made routes
610
639
 
611
- - `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`).
640
+ - `authRoutes({ register?, password?, rateLimit? })`: `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`). `register: 'open' | 'closed' | RegisterPolicy` sets who may sign up (default: the plugin's `registerPolicy`, open without one): `'closed'` answers a static `404 AUTH_REGISTRATION_CLOSED`; a refusing policy answers the same `202` as a success and creates nothing.
612
641
  - 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.
613
- - `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys`, `DELETE /apikeys/:id` (login session only — API keys are refused; scoped to the current tenant/user). `POST /apikeys` accepts an optional `expiresAt` Unix timestamp in milliseconds; expired keys are rejected and omitted from listings.
642
+ - `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys[?includeExpired=true]`, `PATCH /apikeys/:id`, `POST /apikeys/:id/rotate`, `DELETE /apikeys/:id` (login session only — API keys are refused; scoped to the current tenant/user, anything else is 404). `POST /apikeys` accepts an optional `expiresAt` Unix timestamp in milliseconds, `allowedIps` (addresses/CIDRs) and `meta`; expired keys are rejected and omitted from listings unless `includeExpired=true`. `PATCH` changes `name`, `scopes`, `expiresAt` (`null` = never), `allowedIps` and `meta` in one write; rotate takes an optional `graceMs` (0 by default, at most 30 days) and returns the new key once. An expired or revoked key cannot be renewed or rotated. Service keys (`ApiKeys.issue({ serviceId })`, no user, scopes only) are programmatic-only.
643
+ - **Idempotency and API keys.** `idempotencyPlugin` (from `@basaltkit/http`) scopes a replay by the raw bytes of the credential headers, not by the key's id: a `POST` retried after a rotation, or with the key moved from `x-api-key` to `Authorization: Bearer`, runs again instead of replaying. And when the client sends `Idempotency-Key`, the `201` of `POST /apikeys` and `POST /apikeys/:id/rotate`, which carries the plaintext key, is stored in the idempotency store for its `ttlMs` (24 h by default), so protect a shared store (Redis) as secret material, or mint keys without an idempotency key.
614
644
  - `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
615
645
  - `oauthRoutes({ callbackBaseUrl, successRedirect?, bindingCookie?, rateLimit? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider (rate-limited by default).
616
646
 
@@ -658,6 +688,7 @@ If you implement your own store, do the same. Returning `void` keeps the older r
658
688
  |---|---|---|
659
689
  | `InvalidCredentialsError` | `AUTH_INVALID_CREDENTIALS` | 401 |
660
690
  | `EmailTakenError` | `AUTH_EMAIL_TAKEN` | 409 |
691
+ | `RegistrationClosedError` | `AUTH_REGISTRATION_CLOSED` | 404 (`authRoutes({ register: 'closed' })`, or a `registerPolicy` refused a first social / SSO login) |
661
692
  | `RefreshInvalidError` / `RefreshReusedError` | `AUTH_REFRESH_INVALID` / `AUTH_REFRESH_REUSED` | 401 |
662
693
  | `AuthRequiredError` | `AUTH_REQUIRED` | 401 |
663
694
  | `TokenInvalidError` / `TokenExpiredError` | `AUTH_TOKEN_INVALID` / `AUTH_TOKEN_EXPIRED` | 401 |
@@ -1,5 +1,5 @@
1
1
  import { BasaltError } from '@basaltkit/core';
2
- import { ApiKeys, type ApiKeyContext, type ApiKeysOptions } from './apikeys.js';
2
+ import { ApiKeys, type ApiKeyContext, type ApiKeysOptions, type ApiKeyUpdatedField } from './apikeys.js';
3
3
  import type { UserSource } from './stores.js';
4
4
  declare module '@basaltkit/core' {
5
5
  interface RequestContext {
@@ -11,19 +11,61 @@ declare module '@basaltkit/core' {
11
11
  id: string;
12
12
  tenantId?: string;
13
13
  userId?: string;
14
+ serviceId?: string;
14
15
  };
15
16
  'auth:apikey_revoked': {
16
17
  id: string;
17
18
  };
19
+ /** A key's secret was replaced. `graceUntil` (ms) is when the replaced secret stops working, if it was given a grace window. */
20
+ 'auth:apikey_rotated': {
21
+ id: string;
22
+ tenantId?: string;
23
+ userId?: string;
24
+ serviceId?: string;
25
+ graceUntil?: number;
26
+ };
27
+ /** A key's mutable fields changed. `changes` lists field names only, never their values. */
28
+ 'auth:apikey_updated': {
29
+ id: string;
30
+ tenantId?: string;
31
+ userId?: string;
32
+ serviceId?: string;
33
+ changes: ApiKeyUpdatedField[];
34
+ };
18
35
  /**
19
36
  * A presented API key was refused: unknown/revoked/expired (`invalid`), used
37
+ * from an address outside its `allowedIps` (`ip_not_allowed`), used
20
38
  * outside the tenant it is bound to (`tenant_mismatch`), used on a
21
39
  * session-only route (`not_allowed`) or beyond its scopes (`scope`). Never
22
40
  * carries the key itself.
41
+ *
42
+ * For an `invalid` key, `prefix` is the presented key's display prefix
43
+ * (`mk_live_` plus six characters, what listings show; never the secret)
44
+ * and `ip` the client address, so an app can throttle or alert per caller.
45
+ * This event is excluded from `auditPlugin`'s default hook capture: any
46
+ * unauthenticated client can trigger it on every request. Refusals of a
47
+ * key that DID verify are also emitted as `auth:apikey_refused`, which is
48
+ * audited by default.
23
49
  */
24
50
  'auth:apikey_rejected': {
25
51
  id?: string;
26
- reason: 'invalid' | 'tenant_mismatch' | 'not_allowed' | 'scope';
52
+ reason: 'invalid' | 'ip_not_allowed' | 'tenant_mismatch' | 'not_allowed' | 'scope';
53
+ tenantId?: string;
54
+ prefix?: string;
55
+ ip?: string;
56
+ };
57
+ /**
58
+ * A key that verified was refused: used from an address outside its
59
+ * `allowedIps` (`ip_not_allowed`), outside its tenant
60
+ * (`tenant_mismatch`), on a session-only route (`not_allowed`) or beyond
61
+ * its scopes (`scope`). Emitted right after the matching
62
+ * `auth:apikey_rejected`. Unlike an unknown key, it is attributable (`id`)
63
+ * and only a key holder can cause it, so `auditPlugin` records it by
64
+ * default (`auth:**`): a cross-tenant probe with a real key leaves a trail.
65
+ */
66
+ 'auth:apikey_refused': {
67
+ id: string;
68
+ reason: 'ip_not_allowed' | 'tenant_mismatch' | 'not_allowed' | 'scope';
27
69
  tenantId?: string;
28
70
  };
29
71
  }
@@ -52,6 +94,15 @@ export declare class ApiKeyAmbiguousError extends BasaltError {
52
94
  readonly status = 400;
53
95
  constructor();
54
96
  }
97
+ /**
98
+ * A presented API key is unknown, revoked, expired or malformed. Thrown only
99
+ * with `apiKeysPlugin({ rejectInvalid: true })`; by default such a request
100
+ * continues as anonymous.
101
+ */
102
+ export declare class ApiKeyInvalidError extends BasaltError {
103
+ readonly status = 401;
104
+ constructor();
105
+ }
55
106
  /** The route only accepts an interactive session, not an API key. */
56
107
  export declare class ApiKeyNotAllowedError extends BasaltError {
57
108
  readonly status = 403;
@@ -67,7 +118,8 @@ export interface ApiKeysPluginOptions extends ApiKeysOptions {
67
118
  header?: string;
68
119
  /**
69
120
  * When provided, a key that carries a `userId` also populates `ctx().user`,
70
- * so scope-guarded routes can read the acting user.
121
+ * so scope-guarded routes can read the acting user. A service key (one with
122
+ * a `serviceId`) never does.
71
123
  */
72
124
  users?: UserSource;
73
125
  /**
@@ -84,6 +136,16 @@ export interface ApiKeysPluginOptions extends ApiKeysOptions {
84
136
  * old behaviour where any key with a `userId` acts as its owner. Default false.
85
137
  */
86
138
  allowNarrowKeysOnUnscopedRoutes?: boolean;
139
+ /**
140
+ * `true` refuses a request that presents an API key which does not verify
141
+ * (unknown, revoked, expired, malformed) with 401 `AUTH_APIKEY_INVALID` and
142
+ * `WWW-Authenticate: Bearer error="invalid_token"`, before any guard runs. A
143
+ * machine client can then tell "my key is dead" from "this route needs a
144
+ * scope". Default false: the request continues as anonymous and the route's
145
+ * own guards answer (401 `AUTH_REQUIRED`, 403 `AUTH_SCOPE_REQUIRED`, or the
146
+ * public response).
147
+ */
148
+ rejectInvalid?: boolean;
87
149
  }
88
150
  /**
89
151
  * Programmatic access via API keys. Registers an enricher that authenticates
@@ -1,5 +1,5 @@
1
1
  import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
2
- import { ApiKeys, ScopeRequiredError, scopesSatisfy } from './apikeys.js';
2
+ import { ApiKeyIpNotAllowedError, ApiKeys, ScopeRequiredError, apiKeyDisplayPrefix, resolveTouchEveryMs, scopesSatisfy, } from './apikeys.js';
3
3
  import { publicUser } from './auth.js';
4
4
  /** The key is bound to another tenant than the one this request resolved. */
5
5
  export class ApiKeyTenantMismatchError extends BasaltError {
@@ -19,6 +19,19 @@ export class ApiKeyAmbiguousError extends BasaltError {
19
19
  super('AUTH_APIKEY_AMBIGUOUS', 'Two different API keys were presented; send exactly one.');
20
20
  }
21
21
  }
22
+ /**
23
+ * A presented API key is unknown, revoked, expired or malformed. Thrown only
24
+ * with `apiKeysPlugin({ rejectInvalid: true })`; by default such a request
25
+ * continues as anonymous.
26
+ */
27
+ export class ApiKeyInvalidError extends BasaltError {
28
+ status = 401;
29
+ constructor() {
30
+ super('AUTH_APIKEY_INVALID', 'The API key is invalid, revoked or expired.');
31
+ }
32
+ }
33
+ /** RFC 6750 challenge sent with {@link ApiKeyInvalidError}. */
34
+ const INVALID_TOKEN_CHALLENGE = 'Bearer error="invalid_token"';
22
35
  /** The route only accepts an interactive session, not an API key. */
23
36
  export class ApiKeyNotAllowedError extends BasaltError {
24
37
  status = 403;
@@ -45,6 +58,9 @@ export function apiKeysPlugin(options = {}) {
45
58
  return definePlugin({
46
59
  name: 'basalt:apikeys',
47
60
  register({ container, hooks }) {
61
+ // The ApiKeys singleton is built lazily; fail at boot, not on the first
62
+ // request, on an invalid option.
63
+ resolveTouchEveryMs(options.touchEveryMs);
48
64
  container.singleton(API_KEYS, () => new ApiKeys({ ...options, hooks }));
49
65
  // A verified social login that adopts a never-verified account distrusts
50
66
  // whoever registered it: the keys they may have minted die with the rest
@@ -53,7 +69,8 @@ export function apiKeysPlugin(options = {}) {
53
69
  await container.get(API_KEYS).revokeAllForUser(user.id);
54
70
  });
55
71
  const metadata = ensureMetadata(container);
56
- const enricher = async ({ request, context, container: c }) => {
72
+ const enricher = async ({ request, reply, context, container: c }) => {
73
+ const ip = typeof request.ip === 'string' && request.ip.length > 0 ? request.ip : undefined;
57
74
  const authHeader = request.headers.authorization;
58
75
  const bearer = typeof authHeader === 'string' && authHeader.startsWith('Bearer mk_')
59
76
  ? authHeader.slice('Bearer '.length)
@@ -65,15 +82,37 @@ export function apiKeysPlugin(options = {}) {
65
82
  // replaces the key the client meant (and vice versa). Identical values
66
83
  // are harmless and accepted.
67
84
  if (bearer !== undefined && custom !== undefined && bearer !== custom) {
68
- await hooks.emit('auth:apikey_rejected', { reason: 'invalid' });
85
+ await hooks.emit('auth:apikey_rejected', { reason: 'invalid', ...(ip !== undefined ? { ip } : {}) });
69
86
  throw new ApiKeyAmbiguousError();
70
87
  }
71
88
  const presented = bearer ?? custom;
72
89
  if (!presented)
73
90
  return;
74
- const record = await c.get(API_KEYS).verify(presented);
91
+ const result = await c.get(API_KEYS).authenticate(presented, { ip });
92
+ if (!result.ok && result.reason === 'ip_not_allowed') {
93
+ // A genuine key used from the wrong place: always refused, whatever
94
+ // `rejectInvalid` says — silently downgrading to anonymous would hide
95
+ // a misconfiguration (or a stolen key). Nothing is set, nothing touched.
96
+ // Only the key holder can cause it, so it is also the attributable
97
+ // `auth:apikey_refused` the audit records by default.
98
+ const tenantId = result.record.tenantId;
99
+ const scope = { id: result.record.id, reason: 'ip_not_allowed', ...(tenantId !== undefined ? { tenantId } : {}) };
100
+ await hooks.emit('auth:apikey_rejected', { ...scope, ...(ip !== undefined ? { ip } : {}) });
101
+ await hooks.emit('auth:apikey_refused', scope);
102
+ throw new ApiKeyIpNotAllowedError();
103
+ }
104
+ const record = result.ok ? result.record : null;
75
105
  if (!record) {
76
- await hooks.emit('auth:apikey_rejected', { reason: 'invalid' });
106
+ const prefix = apiKeyDisplayPrefix(presented);
107
+ await hooks.emit('auth:apikey_rejected', {
108
+ reason: 'invalid',
109
+ ...(prefix !== undefined ? { prefix } : {}),
110
+ ...(ip !== undefined ? { ip } : {}),
111
+ });
112
+ if (options.rejectInvalid === true) {
113
+ reply?.header('WWW-Authenticate', INVALID_TOKEN_CHALLENGE);
114
+ throw new ApiKeyInvalidError();
115
+ }
77
116
  return;
78
117
  }
79
118
  context.apiKey = {
@@ -81,8 +120,10 @@ export function apiKeysPlugin(options = {}) {
81
120
  scopes: record.scopes,
82
121
  ...(record.tenantId !== undefined ? { tenantId: record.tenantId } : {}),
83
122
  ...(record.userId !== undefined ? { userId: record.userId } : {}),
123
+ ...(record.serviceId !== undefined ? { serviceId: record.serviceId } : {}),
84
124
  };
85
- if (record.userId && options.users) {
125
+ // A service key acts as its service, never as a user.
126
+ if (record.userId && record.serviceId === undefined && options.users) {
86
127
  const user = await options.users.findById(record.userId);
87
128
  if (user)
88
129
  context.user = publicUser(user);
@@ -95,10 +136,17 @@ export function apiKeysPlugin(options = {}) {
95
136
  const guard = async ({ route, context }) => {
96
137
  const key = context.apiKey;
97
138
  const meta = route.meta;
139
+ // A verified key refused: the catch-all event, then the attributable
140
+ // one the audit records by default.
141
+ const refuse = async (id, reason) => {
142
+ const tenantId = tenantOf(context);
143
+ const payload = { id, reason, ...(tenantId !== undefined ? { tenantId } : {}) };
144
+ await hooks.emit('auth:apikey_rejected', payload);
145
+ await hooks.emit('auth:apikey_refused', payload);
146
+ };
98
147
  if (key) {
99
148
  const reject = async (reason, error) => {
100
- const tenantId = tenantOf(context);
101
- await hooks.emit('auth:apikey_rejected', { id: key.id, reason, ...(tenantId !== undefined ? { tenantId } : {}) });
149
+ await refuse(key.id, reason);
102
150
  throw error;
103
151
  };
104
152
  const tenantId = tenantOf(context);
@@ -130,12 +178,36 @@ export function apiKeysPlugin(options = {}) {
130
178
  for (const scope of required) {
131
179
  if (!scopesSatisfy(granted, [scope])) {
132
180
  if (key)
133
- await hooks.emit('auth:apikey_rejected', { id: key.id, reason: 'scope' });
181
+ await refuse(key.id, 'scope');
134
182
  throw new ScopeRequiredError(scope);
135
183
  }
136
184
  }
137
185
  };
138
186
  metadata.add('http:guards', guard);
187
+ // Visibility (e.g. MCP `tools/list`): hide a route whose `meta.scopes`
188
+ // the caller's key does not cover, or that refuses keys (`meta.apiKey:
189
+ // false`) when the caller holds one. Pure — it reads ctx().apiKey, the
190
+ // value the guard reads, and never emits `auth:apikey_rejected`.
191
+ const visibility = ({ route, context }) => {
192
+ const meta = route.meta;
193
+ const key = context['apiKey'];
194
+ if (key && meta?.['apiKey'] === false)
195
+ return false;
196
+ const required = meta?.['scopes'];
197
+ if (!Array.isArray(required) || required.length === 0) {
198
+ // Same rule as the guard: a narrow key (no `*`) never reaches an
199
+ // identity-gated route that declares no scopes. Tenant binding is
200
+ // NOT mirrored — the tenant may only resolve from the tool route's
201
+ // own params, which a listing does not have.
202
+ return !(key &&
203
+ options.allowNarrowKeysOnUnscopedRoutes !== true &&
204
+ !key.scopes.includes('*') &&
205
+ IDENTITY_GATED_META.some((k) => meta?.[k] !== undefined && meta?.[k] !== false));
206
+ }
207
+ const granted = key?.scopes ?? [];
208
+ return required.every((scope) => scopesSatisfy(granted, [scope]));
209
+ };
210
+ metadata.add('http:route-visibility', visibility);
139
211
  // Claim `meta.scopes` for the adapters' boot-time guarded-meta check —
140
212
  // a scope-gated route without this plugin would serve unchecked.
141
213
  metadata.add('http:guarded-meta', 'scopes');
package/dist/apikeys.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { BasaltError, type HookBus } from '@basaltkit/core';
2
+ import { API_KEY_ALLOWED_IPS_MAX } from './ip-allowlist.js';
2
3
  import { type ApiKeyFilter, type ApiKeyInfo, type ApiKeyRecord, type ApiKeyStore } from './stores.js';
4
+ export { API_KEY_ALLOWED_IPS_MAX };
3
5
  /** A route required a scope the presented key does not hold. */
4
6
  export declare class ScopeRequiredError extends BasaltError {
5
7
  readonly status = 403;
@@ -9,42 +11,193 @@ export declare class ApiKeyExpirationError extends BasaltError {
9
11
  readonly status = 400;
10
12
  constructor();
11
13
  }
14
+ /** No key with this id in scope, or it is revoked or expired (an expired key is dead: issue a new one). */
15
+ export declare class ApiKeyNotFoundError extends BasaltError {
16
+ readonly status = 404;
17
+ constructor();
18
+ }
19
+ /**
20
+ * Invalid input to an API key operation: a bad `allowedIps` entry, `meta` over
21
+ * its limits, `userId` together with `serviceId`, a malformed `serviceId` or
22
+ * `scopes`, or a rotation `graceMs` out of range.
23
+ */
24
+ export declare class ApiKeyInputError extends BasaltError {
25
+ readonly status = 400;
26
+ constructor(message: string);
27
+ }
28
+ /** A concurrent rotation or revocation changed the key first; re-read it and retry. */
29
+ export declare class ApiKeyConflictError extends BasaltError {
30
+ readonly status = 409;
31
+ constructor();
32
+ }
33
+ /** The configured `ApiKeyStore` does not implement `update`, which lifecycle operations need. */
34
+ export declare class ApiKeyStoreUnsupportedError extends BasaltError {
35
+ readonly status = 501;
36
+ constructor(operation: string);
37
+ }
38
+ /** The key is valid, but the request comes from an address outside its `allowedIps`. */
39
+ export declare class ApiKeyIpNotAllowedError extends BasaltError {
40
+ readonly status = 403;
41
+ constructor();
42
+ }
43
+ /** Longest rotation grace window {@link ApiKeys.rotate} accepts: 30 days (the webhooks secret-rotation cap). */
44
+ export declare const MAX_API_KEY_ROTATION_GRACE_MS: number;
45
+ /** Limits on a key's `meta`: number of entries, key length, value length. */
46
+ export declare const API_KEY_META_LIMITS: {
47
+ readonly keys: 20;
48
+ readonly keyLength: 40;
49
+ readonly valueLength: 500;
50
+ };
51
+ /**
52
+ * The display prefix of a presented key (`mk_live_` plus the first six secret
53
+ * characters), the same value `ApiKeyRecord.prefix` stores and listings show.
54
+ * Undefined for anything that is not shaped like a Basalt key, so an unrelated
55
+ * secret sent by mistake is never echoed into a hook payload or a log.
56
+ */
57
+ export declare const apiKeyDisplayPrefix: (presented: string) => string | undefined;
12
58
  /** True when `granted` covers `required` (an exact match or the `*` wildcard). */
13
59
  export declare const scopesSatisfy: (granted: readonly string[], required: readonly string[]) => boolean;
14
60
  export interface IssueApiKeyInput {
15
61
  name: string;
16
62
  scopes?: string[] | undefined;
17
63
  tenantId?: string;
64
+ /** The user the key acts as. Mutually exclusive with `serviceId`. */
18
65
  userId?: string;
19
66
  expiresAt?: number | undefined;
67
+ /**
68
+ * The non-human actor the key acts as (opaque, app-defined, 1-128 printable
69
+ * characters without spaces). Mutually exclusive with `userId`; immutable. A
70
+ * service key never sets `ctx().user`: it is authorized by its scopes and
71
+ * tenant binding only.
72
+ */
73
+ serviceId?: string | undefined;
74
+ /** Client addresses or CIDR networks allowed to use the key (at most 32). Absent or empty: any. */
75
+ allowedIps?: string[] | undefined;
76
+ /** Flat app metadata, never used for authorization (see {@link API_KEY_META_LIMITS}). */
77
+ meta?: Record<string, string> | undefined;
78
+ }
79
+ /** The mutable fields {@link ApiKeys.update} accepts. `null` clears a field. */
80
+ export interface UpdateApiKeyInput {
81
+ name?: string | undefined;
82
+ scopes?: string[] | undefined;
83
+ /** A future timestamp (ms), or `null` for "never expires". */
84
+ expiresAt?: number | null | undefined;
85
+ allowedIps?: string[] | null | undefined;
86
+ meta?: Record<string, string> | null | undefined;
20
87
  }
88
+ export interface RotateApiKeyOptions {
89
+ /**
90
+ * How long the replaced secret keeps working, in ms. 0 (the default) kills it
91
+ * now — the answer to a leak. At most {@link MAX_API_KEY_ROTATION_GRACE_MS}.
92
+ */
93
+ graceMs?: number | undefined;
94
+ }
95
+ export interface ListApiKeysOptions extends ApiKeyFilter {
96
+ /** Also list keys past their `expiresAt`. Default false. Revoked keys are never listed. */
97
+ includeExpired?: boolean | undefined;
98
+ }
99
+ export interface AuthenticateApiKeyOptions {
100
+ /** The client address, checked against the key's `allowedIps`. */
101
+ ip?: string | undefined;
102
+ }
103
+ /** The outcome of {@link ApiKeys.authenticate}. */
104
+ export type ApiKeyAuthResult = {
105
+ ok: true;
106
+ record: ApiKeyRecord;
107
+ } | {
108
+ ok: false;
109
+ reason: 'invalid';
110
+ } | {
111
+ ok: false;
112
+ reason: 'ip_not_allowed';
113
+ record: ApiKeyRecord;
114
+ };
115
+ /** The fields an `auth:apikey_updated` event reports as changed (names only, never values). */
116
+ export type ApiKeyUpdatedField = 'name' | 'scopes' | 'expiresAt' | 'allowedIps' | 'meta';
21
117
  export interface ApiKeysOptions {
22
118
  store?: ApiKeyStore;
23
119
  hooks?: HookBus;
24
120
  /** Injectable clock — tests and deterministic runs override it. */
25
121
  now?: () => number;
122
+ /**
123
+ * Minimum interval, in milliseconds, between two `lastUsedAt` writes for the
124
+ * same key. A machine client calling once a second would otherwise cost one
125
+ * store write per request. `lastUsedAt` is therefore accurate to within this
126
+ * window. `0` writes on every verification (the pre-4.2 behaviour).
127
+ * Default 60_000.
128
+ */
129
+ touchEveryMs?: number;
26
130
  }
131
+ export declare class ApiKeyOptionsError extends BasaltError {
132
+ readonly status = 500;
133
+ constructor(message: string);
134
+ }
135
+ /** Default `touchEveryMs`: one `lastUsedAt` write per key per minute. */
136
+ export declare const DEFAULT_API_KEY_TOUCH_EVERY_MS = 60000;
137
+ /** Resolves and validates `touchEveryMs`; throws {@link ApiKeyOptionsError}. */
138
+ export declare function resolveTouchEveryMs(value: number | undefined): number;
27
139
  /**
28
140
  * Issues and verifies API keys. The plaintext key is returned exactly once by
29
- * {@link issue}; only its SHA-256 hash is stored, so a leaked database never
30
- * yields usable keys.
141
+ * {@link issue} (and {@link rotate}); only its SHA-256 hash is stored, so a
142
+ * leaked database never yields usable keys.
31
143
  */
32
144
  export declare class ApiKeys {
33
145
  private readonly store;
34
146
  private readonly hooks;
35
147
  private readonly now;
148
+ private readonly touchEveryMs;
36
149
  constructor(options?: ApiKeysOptions);
37
150
  /** Mints a key. Returns the record plus the plaintext `key` (shown once). */
38
151
  issue(input: IssueApiKeyInput): Promise<{
39
152
  record: ApiKeyInfo;
40
153
  key: string;
41
154
  }>;
155
+ /**
156
+ * Authenticates a presented key. Malformed, unknown, revoked and expired keys
157
+ * are `invalid`; a key whose `allowedIps` does not cover `options.ip` (or
158
+ * that has an allowlist and no ip to check) is `ip_not_allowed`. After a
159
+ * rotation the previous secret is accepted only until
160
+ * `previousHashExpiresAt`, re-checked here and never trusted to the store.
161
+ * Updates `lastUsedAt` on success only, at most once per `touchEveryMs`.
162
+ */
163
+ authenticate(presented: string, options?: AuthenticateApiKeyOptions): Promise<ApiKeyAuthResult>;
42
164
  /**
43
165
  * Resolves a presented key to its record, or null if it's malformed,
44
- * unknown, or revoked. Updates `lastUsedAt` on a hit.
166
+ * unknown, revoked, expired, or used from an address outside its
167
+ * `allowedIps`. Updates `lastUsedAt` on a hit, at most once per
168
+ * `touchEveryMs` per key.
169
+ */
170
+ verify(presented: string, options?: AuthenticateApiKeyOptions): Promise<ApiKeyRecord | null>;
171
+ /**
172
+ * Live keys matching the filter, without hashes. The filter is re-applied
173
+ * here, so a store that ignores one of its fields never widens the result.
174
+ * Expired keys are listed only with `includeExpired`; revoked ones never.
45
175
  */
46
- verify(presented: string): Promise<ApiKeyRecord | null>;
47
- list(filter: ApiKeyFilter): Promise<ApiKeyInfo[]>;
176
+ list(options: ListApiKeysOptions): Promise<ApiKeyInfo[]>;
177
+ /**
178
+ * Changes a key's mutable fields in ONE store write; all input is validated
179
+ * first. An unknown, revoked or expired key is {@link ApiKeyNotFoundError}:
180
+ * an expired key cannot be renewed, issue a new one. Emits
181
+ * `auth:apikey_updated` with the changed field names (never the values).
182
+ */
183
+ update(id: string, input: UpdateApiKeyInput): Promise<ApiKeyInfo>;
184
+ /**
185
+ * Sets when a key expires: a future timestamp (ms), or `null` for never. A
186
+ * thin wrapper over {@link update}; the same "expired is dead" rule applies.
187
+ */
188
+ setExpiry(id: string, expiresAt: number | null): Promise<ApiKeyInfo>;
189
+ /**
190
+ * Replaces a key's secret, keeping its id (so its owner, scopes and audit
191
+ * trail stay). With `graceMs` the replaced secret keeps working that long —
192
+ * never past the key's own expiry or revocation; at most two secrets are ever
193
+ * live, so rotating during a grace window drops the oldest. Compare-and-set:
194
+ * when a concurrent rotation or revocation wins, this one throws
195
+ * {@link ApiKeyConflictError}. Returns the new plaintext `key` (shown once).
196
+ */
197
+ rotate(id: string, options?: RotateApiKeyOptions): Promise<{
198
+ record: ApiKeyInfo;
199
+ key: string;
200
+ }>;
48
201
  /** Revokes a key by id. No-op if unknown or already revoked. */
49
202
  revoke(id: string): Promise<void>;
50
203
  /**
@@ -54,6 +207,9 @@ export declare class ApiKeys {
54
207
  revokeAllForUser(userId: string): Promise<void>;
55
208
  /** Reads a single key's public info (used to authorize a revoke). */
56
209
  get(id: string): Promise<ApiKeyInfo | null>;
210
+ private requireUpdate;
211
+ /** The record behind a lifecycle operation: unknown, revoked and expired keys are all "not found". */
212
+ private live;
57
213
  }
58
214
  /** The value stashed on `ctx().apiKey` after a request authenticates with a key. */
59
215
  export interface ApiKeyContext {
@@ -61,4 +217,6 @@ export interface ApiKeyContext {
61
217
  scopes: string[];
62
218
  tenantId?: string;
63
219
  userId?: string;
220
+ /** Set for a service key: the non-human actor the request acts as. `ctx().user` is then never set. */
221
+ serviceId?: string;
64
222
  }