@basaltkit/auth 4.0.0 → 4.2.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
@@ -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
 
@@ -241,7 +242,7 @@ Flow (all routes require login):
241
242
 
242
243
  1. `POST /auth/mfa/enroll` → returns `{ secret, otpauthUri }`; show the `otpauthUri` as a QR code.
243
244
  2. `POST /auth/mfa/activate` with `{ code }` (code from the app) → activates and returns `{ recoveryCodes }` — 10 single-use recovery codes, **shown only once**.
244
- 3. From then on, `POST /auth/login` requires the extra `mfaCode` field (TOTP code or a recovery code). Correct password without a code → `AUTH_MFA_REQUIRED` error.
245
+ 3. From then on, `POST /auth/login` requires the extra `mfaCode` field (TOTP code or a recovery code). Correct password without a code → `AUTH_MFA_REQUIRED` error (counted by the login throttle — see [Brute-force lockout](#brute-force-lockout-loginthrottle)).
245
246
  4. `GET /auth/mfa/status` and `POST /auth/mfa/disable` (with `{ code }`) complete the cycle.
246
247
 
247
248
  **Requiring MFA.** `authPlugin({ requireMfa: true })` — or a policy
@@ -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>.…`
@@ -524,11 +529,34 @@ 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 (`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
 
530
556
  Active by default: 5 failed attempts per email within a 15-minute window → `AUTH_LOCKED` error (HTTP 429). A successful login clears the counter.
531
557
 
558
+ **`AUTH_MFA_REQUIRED` counts as an attempt.** On an MFA account, that answer is only given for the *right* password, so it is a password oracle (the standard two-step MFA login has the same property). To keep it from allowing unthrottled guessing, it spends the per-account and per-IP budgets exactly like a wrong password. A user who then signs in with the code clears the account counter; the IP slot of the first step expires with the window, so under a shared NAT with many MFA users, size `ipLoginThrottle` accordingly.
559
+
532
560
  ```ts
533
561
  import { authPlugin, LoginThrottle, MemoryUserSource } from '@basaltkit/auth'
534
562
 
@@ -554,7 +582,7 @@ lock go (the memory bound is absolute).
554
582
 
555
583
  ### Hooks (events)
556
584
 
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`.
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`.
558
586
 
559
587
  ## API reference
560
588
 
@@ -571,8 +599,9 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
571
599
  | `refreshTokens` | `RefreshTokenStore` | No | `MemoryRefreshTokenStore` | Refresh token storage. `markUsed` must be a **compare-and-swap** — see below. |
572
600
  | `accessTtl` | `DurationInput` | No | `'15m'` | Access token validity. |
573
601
  | `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
574
- | `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
575
- | `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 value is emitted as configured with a boot warning, and is refused from the next major (`AUTH_SESSION_COOKIE_INVALID`). |
576
605
  | `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
577
606
  | `throttleStore` | `ThrottleStore` | No | in-memory, per process | Counters of the default login / per-IP / email-request throttles — `RedisThrottleStore` for one budget across replicas. |
578
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. |
@@ -584,13 +613,15 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
584
613
  | `mfaEncryption` | `{ keys: SecretBoxKey[]; legacy? }` | No | — (plaintext) | Encrypts TOTP secrets at rest with a key ring; see *Encrypting secrets at rest*. |
585
614
  | `mfaEncryptionKey` | `string \| Buffer` | No | — | Shorthand for a one-key ring (`id: 'default'`, ≥ 32 bytes). |
586
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. |
587
617
  | `hooks` | `HookBus` | No | — | Only on the `Auth` class; the plugin injects it. |
588
618
 
589
619
  `Auth` class methods:
590
620
 
591
621
  | Method | Description |
592
622
  |---|---|
593
- | `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. |
594
625
  | `login(email, password, mfaCode?)` | Returns `{ user, tokens, amr }`; applies throttle and MFA. |
595
626
  | `attempt(email, password)` | Checks credentials without side effects; `null` on failure. |
596
627
  | `refresh(refreshToken)` | New token pair; detects reuse and revokes the family. |
@@ -601,12 +632,12 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
601
632
  | `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
602
633
  | `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
603
634
  | `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
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 }`. |
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 }`. |
605
636
  | `reencryptMfaSecret(userId)` | Re-seals a stored TOTP secret under the active `mfaEncryption` key (rotation / legacy migration): `'resealed'`, `'current'` or `'none'`. |
606
637
 
607
638
  ### Ready-made routes
608
639
 
609
- - `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.
610
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.
611
642
  - `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.
612
643
  - `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
@@ -656,6 +687,7 @@ If you implement your own store, do the same. Returning `void` keeps the older r
656
687
  |---|---|---|
657
688
  | `InvalidCredentialsError` | `AUTH_INVALID_CREDENTIALS` | 401 |
658
689
  | `EmailTakenError` | `AUTH_EMAIL_TAKEN` | 409 |
690
+ | `RegistrationClosedError` | `AUTH_REGISTRATION_CLOSED` | 404 (`authRoutes({ register: 'closed' })`, or a `registerPolicy` refused a first social / SSO login) |
659
691
  | `RefreshInvalidError` / `RefreshReusedError` | `AUTH_REFRESH_INVALID` / `AUTH_REFRESH_REUSED` | 401 |
660
692
  | `AuthRequiredError` | `AUTH_REQUIRED` | 401 |
661
693
  | `TokenInvalidError` / `TokenExpiredError` | `AUTH_TOKEN_INVALID` / `AUTH_TOKEN_EXPIRED` | 401 |
@@ -709,5 +741,6 @@ If you implement your own store, do the same. Returning `void` keeps the older r
709
741
  - **Use the browser session cookie for browser UIs.** It is `HttpOnly` by default; keep JWTs out of `localStorage` and use same-origin requests so the browser sends the cookie automatically.
710
742
  - **Don't increase `accessTtl`.** Short access tokens limit the damage from a stolen token; renewal via refresh token already provides convenience for the user.
711
743
  - **Show the API key and recovery codes only once** — that's how the module works; don't store them in plain text on your side.
712
- - **Don't disable `loginThrottle` in production**, and keep the "always 200" responses on the forgot/verify routes (already the default), so as not to reveal which emails have an account.
744
+ - **Don't disable `loginThrottle` / `ipLoginThrottle` in production.** Besides wrong passwords, they bound the `AUTH_MFA_REQUIRED` password oracle on MFA accounts (it is only returned for a correct password and is counted like a failure).
745
+ - **Keep the "always 200" responses** on the forgot/verify routes (already the default), so as not to reveal which emails have an account.
713
746
  - **In a cluster (multiple machines)**, use shared stores (database/Redis) instead of the `Memory*` ones, or sessions and lockouts won't be shared across processes.
@@ -20,11 +20,34 @@ declare module '@basaltkit/core' {
20
20
  * outside the tenant it is bound to (`tenant_mismatch`), used on a
21
21
  * session-only route (`not_allowed`) or beyond its scopes (`scope`). Never
22
22
  * carries the key itself.
23
+ *
24
+ * For an `invalid` key, `prefix` is the presented key's display prefix
25
+ * (`mk_live_` plus six characters, what listings show; never the secret)
26
+ * and `ip` the client address, so an app can throttle or alert per caller.
27
+ * This event is excluded from `auditPlugin`'s default hook capture: any
28
+ * unauthenticated client can trigger it on every request. Refusals of a
29
+ * key that DID verify are also emitted as `auth:apikey_refused`, which is
30
+ * audited by default.
23
31
  */
24
32
  'auth:apikey_rejected': {
25
33
  id?: string;
26
34
  reason: 'invalid' | 'tenant_mismatch' | 'not_allowed' | 'scope';
27
35
  tenantId?: string;
36
+ prefix?: string;
37
+ ip?: string;
38
+ };
39
+ /**
40
+ * A key that verified was refused: used outside its tenant
41
+ * (`tenant_mismatch`), on a session-only route (`not_allowed`) or beyond
42
+ * its scopes (`scope`). Emitted right after the matching
43
+ * `auth:apikey_rejected`. Unlike an unknown key, it is attributable (`id`)
44
+ * and only a key holder can cause it, so `auditPlugin` records it by
45
+ * default (`auth:**`): a cross-tenant probe with a real key leaves a trail.
46
+ */
47
+ 'auth:apikey_refused': {
48
+ id: string;
49
+ reason: 'tenant_mismatch' | 'not_allowed' | 'scope';
50
+ tenantId?: string;
28
51
  };
29
52
  }
30
53
  }
@@ -52,6 +75,15 @@ export declare class ApiKeyAmbiguousError extends BasaltError {
52
75
  readonly status = 400;
53
76
  constructor();
54
77
  }
78
+ /**
79
+ * A presented API key is unknown, revoked, expired or malformed. Thrown only
80
+ * with `apiKeysPlugin({ rejectInvalid: true })`; by default such a request
81
+ * continues as anonymous.
82
+ */
83
+ export declare class ApiKeyInvalidError extends BasaltError {
84
+ readonly status = 401;
85
+ constructor();
86
+ }
55
87
  /** The route only accepts an interactive session, not an API key. */
56
88
  export declare class ApiKeyNotAllowedError extends BasaltError {
57
89
  readonly status = 403;
@@ -84,6 +116,16 @@ export interface ApiKeysPluginOptions extends ApiKeysOptions {
84
116
  * old behaviour where any key with a `userId` acts as its owner. Default false.
85
117
  */
86
118
  allowNarrowKeysOnUnscopedRoutes?: boolean;
119
+ /**
120
+ * `true` refuses a request that presents an API key which does not verify
121
+ * (unknown, revoked, expired, malformed) with 401 `AUTH_APIKEY_INVALID` and
122
+ * `WWW-Authenticate: Bearer error="invalid_token"`, before any guard runs. A
123
+ * machine client can then tell "my key is dead" from "this route needs a
124
+ * scope". Default false: the request continues as anonymous and the route's
125
+ * own guards answer (401 `AUTH_REQUIRED`, 403 `AUTH_SCOPE_REQUIRED`, or the
126
+ * public response).
127
+ */
128
+ rejectInvalid?: boolean;
87
129
  }
88
130
  /**
89
131
  * 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 { 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,7 +82,7 @@ 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;
@@ -73,7 +90,16 @@ export function apiKeysPlugin(options = {}) {
73
90
  return;
74
91
  const record = await c.get(API_KEYS).verify(presented);
75
92
  if (!record) {
76
- await hooks.emit('auth:apikey_rejected', { reason: 'invalid' });
93
+ const prefix = apiKeyDisplayPrefix(presented);
94
+ await hooks.emit('auth:apikey_rejected', {
95
+ reason: 'invalid',
96
+ ...(prefix !== undefined ? { prefix } : {}),
97
+ ...(ip !== undefined ? { ip } : {}),
98
+ });
99
+ if (options.rejectInvalid === true) {
100
+ reply?.header('WWW-Authenticate', INVALID_TOKEN_CHALLENGE);
101
+ throw new ApiKeyInvalidError();
102
+ }
77
103
  return;
78
104
  }
79
105
  context.apiKey = {
@@ -95,10 +121,17 @@ export function apiKeysPlugin(options = {}) {
95
121
  const guard = async ({ route, context }) => {
96
122
  const key = context.apiKey;
97
123
  const meta = route.meta;
124
+ // A verified key refused: the catch-all event, then the attributable
125
+ // one the audit records by default.
126
+ const refuse = async (id, reason) => {
127
+ const tenantId = tenantOf(context);
128
+ const payload = { id, reason, ...(tenantId !== undefined ? { tenantId } : {}) };
129
+ await hooks.emit('auth:apikey_rejected', payload);
130
+ await hooks.emit('auth:apikey_refused', payload);
131
+ };
98
132
  if (key) {
99
133
  const reject = async (reason, error) => {
100
- const tenantId = tenantOf(context);
101
- await hooks.emit('auth:apikey_rejected', { id: key.id, reason, ...(tenantId !== undefined ? { tenantId } : {}) });
134
+ await refuse(key.id, reason);
102
135
  throw error;
103
136
  };
104
137
  const tenantId = tenantOf(context);
@@ -130,12 +163,36 @@ export function apiKeysPlugin(options = {}) {
130
163
  for (const scope of required) {
131
164
  if (!scopesSatisfy(granted, [scope])) {
132
165
  if (key)
133
- await hooks.emit('auth:apikey_rejected', { id: key.id, reason: 'scope' });
166
+ await refuse(key.id, 'scope');
134
167
  throw new ScopeRequiredError(scope);
135
168
  }
136
169
  }
137
170
  };
138
171
  metadata.add('http:guards', guard);
172
+ // Visibility (e.g. MCP `tools/list`): hide a route whose `meta.scopes`
173
+ // the caller's key does not cover, or that refuses keys (`meta.apiKey:
174
+ // false`) when the caller holds one. Pure — it reads ctx().apiKey, the
175
+ // value the guard reads, and never emits `auth:apikey_rejected`.
176
+ const visibility = ({ route, context }) => {
177
+ const meta = route.meta;
178
+ const key = context['apiKey'];
179
+ if (key && meta?.['apiKey'] === false)
180
+ return false;
181
+ const required = meta?.['scopes'];
182
+ if (!Array.isArray(required) || required.length === 0) {
183
+ // Same rule as the guard: a narrow key (no `*`) never reaches an
184
+ // identity-gated route that declares no scopes. Tenant binding is
185
+ // NOT mirrored — the tenant may only resolve from the tool route's
186
+ // own params, which a listing does not have.
187
+ return !(key &&
188
+ options.allowNarrowKeysOnUnscopedRoutes !== true &&
189
+ !key.scopes.includes('*') &&
190
+ IDENTITY_GATED_META.some((k) => meta?.[k] !== undefined && meta?.[k] !== false));
191
+ }
192
+ const granted = key?.scopes ?? [];
193
+ return required.every((scope) => scopesSatisfy(granted, [scope]));
194
+ };
195
+ metadata.add('http:route-visibility', visibility);
139
196
  // Claim `meta.scopes` for the adapters' boot-time guarded-meta check —
140
197
  // a scope-gated route without this plugin would serve unchecked.
141
198
  metadata.add('http:guarded-meta', 'scopes');
package/dist/apikeys.d.ts CHANGED
@@ -9,6 +9,13 @@ export declare class ApiKeyExpirationError extends BasaltError {
9
9
  readonly status = 400;
10
10
  constructor();
11
11
  }
12
+ /**
13
+ * The display prefix of a presented key (`mk_live_` plus the first six secret
14
+ * characters), the same value `ApiKeyRecord.prefix` stores and listings show.
15
+ * Undefined for anything that is not shaped like a Basalt key, so an unrelated
16
+ * secret sent by mistake is never echoed into a hook payload or a log.
17
+ */
18
+ export declare const apiKeyDisplayPrefix: (presented: string) => string | undefined;
12
19
  /** True when `granted` covers `required` (an exact match or the `*` wildcard). */
13
20
  export declare const scopesSatisfy: (granted: readonly string[], required: readonly string[]) => boolean;
14
21
  export interface IssueApiKeyInput {
@@ -23,7 +30,23 @@ export interface ApiKeysOptions {
23
30
  hooks?: HookBus;
24
31
  /** Injectable clock — tests and deterministic runs override it. */
25
32
  now?: () => number;
33
+ /**
34
+ * Minimum interval, in milliseconds, between two `lastUsedAt` writes for the
35
+ * same key. A machine client calling once a second would otherwise cost one
36
+ * store write per request. `lastUsedAt` is therefore accurate to within this
37
+ * window. `0` writes on every verification (the pre-4.2 behaviour).
38
+ * Default 60_000.
39
+ */
40
+ touchEveryMs?: number;
41
+ }
42
+ export declare class ApiKeyOptionsError extends BasaltError {
43
+ readonly status = 500;
44
+ constructor(message: string);
26
45
  }
46
+ /** Default `touchEveryMs`: one `lastUsedAt` write per key per minute. */
47
+ export declare const DEFAULT_API_KEY_TOUCH_EVERY_MS = 60000;
48
+ /** Resolves and validates `touchEveryMs`; throws {@link ApiKeyOptionsError}. */
49
+ export declare function resolveTouchEveryMs(value: number | undefined): number;
27
50
  /**
28
51
  * Issues and verifies API keys. The plaintext key is returned exactly once by
29
52
  * {@link issue}; only its SHA-256 hash is stored, so a leaked database never
@@ -33,6 +56,7 @@ export declare class ApiKeys {
33
56
  private readonly store;
34
57
  private readonly hooks;
35
58
  private readonly now;
59
+ private readonly touchEveryMs;
36
60
  constructor(options?: ApiKeysOptions);
37
61
  /** Mints a key. Returns the record plus the plaintext `key` (shown once). */
38
62
  issue(input: IssueApiKeyInput): Promise<{
@@ -41,7 +65,8 @@ export declare class ApiKeys {
41
65
  }>;
42
66
  /**
43
67
  * Resolves a presented key to its record, or null if it's malformed,
44
- * unknown, or revoked. Updates `lastUsedAt` on a hit.
68
+ * unknown, or revoked. Updates `lastUsedAt` on a hit, at most once per
69
+ * `touchEveryMs` per key.
45
70
  */
46
71
  verify(presented: string): Promise<ApiKeyRecord | null>;
47
72
  list(filter: ApiKeyFilter): Promise<ApiKeyInfo[]>;
package/dist/apikeys.js CHANGED
@@ -16,6 +16,17 @@ export class ApiKeyExpirationError extends BasaltError {
16
16
  }
17
17
  /** The prefix on every key. `mk` = Basalt key, `live` = environment. */
18
18
  const KEY_PREFIX = 'mk_live_';
19
+ /** Secret characters kept in the display prefix (`ApiKeyRecord.prefix`). */
20
+ const DISPLAY_SECRET_CHARS = 6;
21
+ /**
22
+ * The display prefix of a presented key (`mk_live_` plus the first six secret
23
+ * characters), the same value `ApiKeyRecord.prefix` stores and listings show.
24
+ * Undefined for anything that is not shaped like a Basalt key, so an unrelated
25
+ * secret sent by mistake is never echoed into a hook payload or a log.
26
+ */
27
+ export const apiKeyDisplayPrefix = (presented) => presented.startsWith(KEY_PREFIX) && presented.length >= KEY_PREFIX.length + DISPLAY_SECRET_CHARS
28
+ ? presented.slice(0, KEY_PREFIX.length + DISPLAY_SECRET_CHARS)
29
+ : undefined;
19
30
  /** SHA-256 is safe here: API keys are high-entropy, so no slow hash is needed. */
20
31
  const hashKey = (key) => createHash('sha256').update(key).digest('hex');
21
32
  const strip = (record) => {
@@ -24,6 +35,22 @@ const strip = (record) => {
24
35
  };
25
36
  /** True when `granted` covers `required` (an exact match or the `*` wildcard). */
26
37
  export const scopesSatisfy = (granted, required) => granted.includes('*') || required.every((scope) => granted.includes(scope));
38
+ export class ApiKeyOptionsError extends BasaltError {
39
+ status = 500;
40
+ constructor(message) {
41
+ super('AUTH_APIKEY_OPTIONS_INVALID', message);
42
+ }
43
+ }
44
+ /** Default `touchEveryMs`: one `lastUsedAt` write per key per minute. */
45
+ export const DEFAULT_API_KEY_TOUCH_EVERY_MS = 60_000;
46
+ /** Resolves and validates `touchEveryMs`; throws {@link ApiKeyOptionsError}. */
47
+ export function resolveTouchEveryMs(value) {
48
+ const touchEveryMs = value ?? DEFAULT_API_KEY_TOUCH_EVERY_MS;
49
+ if (typeof touchEveryMs !== 'number' || !Number.isFinite(touchEveryMs) || touchEveryMs < 0) {
50
+ throw new ApiKeyOptionsError(`apiKeys: touchEveryMs must be a finite number >= 0 (got ${String(touchEveryMs)}).`);
51
+ }
52
+ return touchEveryMs;
53
+ }
27
54
  /**
28
55
  * Issues and verifies API keys. The plaintext key is returned exactly once by
29
56
  * {@link issue}; only its SHA-256 hash is stored, so a leaked database never
@@ -33,10 +60,12 @@ export class ApiKeys {
33
60
  store;
34
61
  hooks;
35
62
  now;
63
+ touchEveryMs;
36
64
  constructor(options = {}) {
37
65
  this.store = options.store ?? new MemoryApiKeyStore();
38
66
  this.hooks = options.hooks;
39
67
  this.now = options.now ?? Date.now;
68
+ this.touchEveryMs = resolveTouchEveryMs(options.touchEveryMs);
40
69
  }
41
70
  /** Mints a key. Returns the record plus the plaintext `key` (shown once). */
42
71
  async issue(input) {
@@ -48,7 +77,7 @@ export class ApiKeys {
48
77
  const record = {
49
78
  id: randomUUID(),
50
79
  name: input.name,
51
- prefix: `${KEY_PREFIX}${secret.slice(0, 6)}`,
80
+ prefix: `${KEY_PREFIX}${secret.slice(0, DISPLAY_SECRET_CHARS)}`,
52
81
  hash: hashKey(key),
53
82
  scopes: input.scopes ?? ['*'],
54
83
  createdAt: this.now(),
@@ -66,15 +95,19 @@ export class ApiKeys {
66
95
  }
67
96
  /**
68
97
  * Resolves a presented key to its record, or null if it's malformed,
69
- * unknown, or revoked. Updates `lastUsedAt` on a hit.
98
+ * unknown, or revoked. Updates `lastUsedAt` on a hit, at most once per
99
+ * `touchEveryMs` per key.
70
100
  */
71
101
  async verify(presented) {
72
102
  if (!presented.startsWith(KEY_PREFIX))
73
103
  return null;
74
104
  const record = await this.store.findByHash(hashKey(presented));
75
- if (!record || record.revokedAt !== undefined || (record.expiresAt !== undefined && record.expiresAt <= this.now()))
105
+ const now = this.now();
106
+ if (!record || record.revokedAt !== undefined || (record.expiresAt !== undefined && record.expiresAt <= now))
76
107
  return null;
77
- await this.store.touch(record.id, this.now());
108
+ if (record.lastUsedAt === undefined || now - record.lastUsedAt >= this.touchEveryMs) {
109
+ await this.store.touch(record.id, now);
110
+ }
78
111
  return record;
79
112
  }
80
113
  async list(filter) {