@basaltkit/auth 4.2.0 → 5.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 +23 -6
- package/dist/apikeys-plugin.d.ts +25 -5
- package/dist/apikeys-plugin.js +18 -3
- package/dist/apikeys.d.ts +138 -5
- package/dist/apikeys.js +272 -23
- package/dist/auth.d.ts +21 -8
- package/dist/auth.js +49 -24
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/ip-allowlist.d.ts +22 -0
- package/dist/ip-allowlist.js +118 -0
- package/dist/plugin.d.ts +10 -0
- package/dist/plugin.js +6 -1
- package/dist/routes.d.ts +17 -4
- package/dist/routes.js +68 -17
- package/dist/stores.d.ts +70 -2
- package/dist/stores.js +48 -5
- package/dist/token-claims.d.ts +75 -0
- package/dist/token-claims.js +83 -0
- package/package.json +7 -7
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/
|
|
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
|
|
|
@@ -212,6 +212,20 @@ await auth.revoke(renewed.refreshToken) // logout: invalidates the token family
|
|
|
212
212
|
|
|
213
213
|
A request with no credentials stays anonymous (no error); an explicit invalid token returns 401.
|
|
214
214
|
|
|
215
|
+
### Custom token claims and tenant-bound tokens
|
|
216
|
+
|
|
217
|
+
`tokenClaims` adds your own claims to every access token (login, MFA completion, social login, every refresh — re-derived on each refresh); `verifyClaims` (plugin) checks them on each bearer request, before the user lookup — `false` answers `401 AUTH_TOKEN_CLAIMS_REJECTED`. Reserved names (`sub`, `tv`, `amr`, `iat`, `exp`, `nbf`, `iss`, `aud`, `jti`) fail the sign-in with `AUTH_TOKEN_CLAIM_RESERVED`.
|
|
218
|
+
|
|
219
|
+
With schema-per-tenant and one secret, a token is otherwise kept out of another tenant only because its `sub` is missing there. `tenantBoundTokens()` binds it to its plane: tokens carry `tid` (the `ctx().tenant` id, `null` on the central plane) and are refused wherever the resolved tenant differs. Auth reads `ctx().tenant` structurally — no dependency on `@basaltkit/tenancy`; register `tenancyPlugin` first.
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
import { authPlugin, tenantBoundTokens } from '@basaltkit/auth'
|
|
223
|
+
|
|
224
|
+
authPlugin({ users, secret, ...tenantBoundTokens() })
|
|
225
|
+
// or with claims of your own:
|
|
226
|
+
authPlugin({ users, secret, ...tenantBoundTokens({ tokenClaims: (user) => ({ org: orgOf(user) }) }) })
|
|
227
|
+
```
|
|
228
|
+
|
|
215
229
|
### Password recovery
|
|
216
230
|
|
|
217
231
|
The flow has two steps. The module generates a **single-use token** (valid for 1 hour by default) and emits a hook — your application sends the email with the link:
|
|
@@ -504,7 +518,7 @@ const app = await createApp({
|
|
|
504
518
|
fastifyPlugin({
|
|
505
519
|
routes: [
|
|
506
520
|
...authRoutes(),
|
|
507
|
-
...apiKeyRoutes(), // POST/GET /apikeys, DELETE /apikeys/:id
|
|
521
|
+
...apiKeyRoutes(), // POST/GET /apikeys, PATCH/DELETE /apikeys/:id, POST /apikeys/:id/rotate
|
|
508
522
|
route({
|
|
509
523
|
method: 'GET',
|
|
510
524
|
url: '/reports',
|
|
@@ -547,7 +561,7 @@ error="invalid_token"` (default: the request continues as anonymous), and
|
|
|
547
561
|
`touchEveryMs` (default 60 s; `0` = every request) throttles `lastUsedAt` writes.
|
|
548
562
|
`auth:apikey_rejected` carries the display `prefix` and `ip` of an invalid key,
|
|
549
563
|
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
|
|
564
|
+
a key that verified (`ip_not_allowed`, `tenant_mismatch`, `not_allowed`, `scope`) is also emitted
|
|
551
565
|
as `auth:apikey_refused` (`{ id, reason, tenantId? }`), which the audit records
|
|
552
566
|
by default.
|
|
553
567
|
|
|
@@ -582,7 +596,7 @@ lock go (the memory bound is absolute).
|
|
|
582
596
|
|
|
583
597
|
### Hooks (events)
|
|
584
598
|
|
|
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
|
|
599
|
+
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).
|
|
586
600
|
|
|
587
601
|
## API reference
|
|
588
602
|
|
|
@@ -601,7 +615,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
601
615
|
| `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
|
|
602
616
|
| `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity (absolute). |
|
|
603
617
|
| `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
|
|
618
|
+
| `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'`. |
|
|
605
619
|
| `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
|
|
606
620
|
| `throttleStore` | `ThrottleStore` | No | in-memory, per process | Counters of the default login / per-IP / email-request throttles — `RedisThrottleStore` for one budget across replicas. |
|
|
607
621
|
| `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. |
|
|
@@ -614,6 +628,8 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
614
628
|
| `mfaEncryptionKey` | `string \| Buffer` | No | — | Shorthand for a one-key ring (`id: 'default'`, ≥ 32 bytes). |
|
|
615
629
|
| `mfaIssuer` | `string` | No | `'Basalt'` | Name shown in the authenticator app. |
|
|
616
630
|
| `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. |
|
|
631
|
+
| `tokenClaims` | `(user, { reason, amr?, request? }) => Record<string, unknown> \| Promise<…>` | No | — | Extra access-token claims on every sign-in and refresh (re-derived). Reserved names throw `ReservedTokenClaimError`. |
|
|
632
|
+
| `verifyClaims` | `(claims, context) => boolean \| Promise<boolean>` | No | — | Plugin only. Checks a bearer token's claims before the user lookup; `false` → `401 AUTH_TOKEN_CLAIMS_REJECTED`. `tenantBoundTokens()` supplies it with `tokenClaims`. |
|
|
617
633
|
| `hooks` | `HookBus` | No | — | Only on the `Auth` class; the plugin injects it. |
|
|
618
634
|
|
|
619
635
|
`Auth` class methods:
|
|
@@ -639,7 +655,8 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
639
655
|
|
|
640
656
|
- `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.
|
|
641
657
|
- 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.
|
|
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
|
|
658
|
+
- `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.
|
|
659
|
+
- **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.
|
|
643
660
|
- `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
|
|
644
661
|
- `oauthRoutes({ callbackBaseUrl, successRedirect?, bindingCookie?, rateLimit? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider (rate-limited by default).
|
|
645
662
|
|
package/dist/apikeys-plugin.d.ts
CHANGED
|
@@ -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,12 +11,30 @@ 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.
|
|
@@ -31,13 +49,14 @@ declare module '@basaltkit/core' {
|
|
|
31
49
|
*/
|
|
32
50
|
'auth:apikey_rejected': {
|
|
33
51
|
id?: string;
|
|
34
|
-
reason: 'invalid' | 'tenant_mismatch' | 'not_allowed' | 'scope';
|
|
52
|
+
reason: 'invalid' | 'ip_not_allowed' | 'tenant_mismatch' | 'not_allowed' | 'scope';
|
|
35
53
|
tenantId?: string;
|
|
36
54
|
prefix?: string;
|
|
37
55
|
ip?: string;
|
|
38
56
|
};
|
|
39
57
|
/**
|
|
40
|
-
* A key that verified was refused: used outside its
|
|
58
|
+
* A key that verified was refused: used from an address outside its
|
|
59
|
+
* `allowedIps` (`ip_not_allowed`), outside its tenant
|
|
41
60
|
* (`tenant_mismatch`), on a session-only route (`not_allowed`) or beyond
|
|
42
61
|
* its scopes (`scope`). Emitted right after the matching
|
|
43
62
|
* `auth:apikey_rejected`. Unlike an unknown key, it is attributable (`id`)
|
|
@@ -46,7 +65,7 @@ declare module '@basaltkit/core' {
|
|
|
46
65
|
*/
|
|
47
66
|
'auth:apikey_refused': {
|
|
48
67
|
id: string;
|
|
49
|
-
reason: 'tenant_mismatch' | 'not_allowed' | 'scope';
|
|
68
|
+
reason: 'ip_not_allowed' | 'tenant_mismatch' | 'not_allowed' | 'scope';
|
|
50
69
|
tenantId?: string;
|
|
51
70
|
};
|
|
52
71
|
}
|
|
@@ -99,7 +118,8 @@ export interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
|
99
118
|
header?: string;
|
|
100
119
|
/**
|
|
101
120
|
* When provided, a key that carries a `userId` also populates `ctx().user`,
|
|
102
|
-
* 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.
|
|
103
123
|
*/
|
|
104
124
|
users?: UserSource;
|
|
105
125
|
/**
|
package/dist/apikeys-plugin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
|
|
2
|
-
import { ApiKeys, ScopeRequiredError, apiKeyDisplayPrefix, resolveTouchEveryMs, 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 {
|
|
@@ -88,7 +88,20 @@ export function apiKeysPlugin(options = {}) {
|
|
|
88
88
|
const presented = bearer ?? custom;
|
|
89
89
|
if (!presented)
|
|
90
90
|
return;
|
|
91
|
-
const
|
|
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;
|
|
92
105
|
if (!record) {
|
|
93
106
|
const prefix = apiKeyDisplayPrefix(presented);
|
|
94
107
|
await hooks.emit('auth:apikey_rejected', {
|
|
@@ -107,8 +120,10 @@ export function apiKeysPlugin(options = {}) {
|
|
|
107
120
|
scopes: record.scopes,
|
|
108
121
|
...(record.tenantId !== undefined ? { tenantId: record.tenantId } : {}),
|
|
109
122
|
...(record.userId !== undefined ? { userId: record.userId } : {}),
|
|
123
|
+
...(record.serviceId !== undefined ? { serviceId: record.serviceId } : {}),
|
|
110
124
|
};
|
|
111
|
-
|
|
125
|
+
// A service key acts as its service, never as a user.
|
|
126
|
+
if (record.userId && record.serviceId === undefined && options.users) {
|
|
112
127
|
const user = await options.users.findById(record.userId);
|
|
113
128
|
if (user)
|
|
114
129
|
context.user = publicUser(user);
|
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,6 +11,43 @@ 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
|
+
};
|
|
12
51
|
/**
|
|
13
52
|
* The display prefix of a presented key (`mk_live_` plus the first six secret
|
|
14
53
|
* characters), the same value `ApiKeyRecord.prefix` stores and listings show.
|
|
@@ -22,9 +61,59 @@ export interface IssueApiKeyInput {
|
|
|
22
61
|
name: string;
|
|
23
62
|
scopes?: string[] | undefined;
|
|
24
63
|
tenantId?: string;
|
|
64
|
+
/** The user the key acts as. Mutually exclusive with `serviceId`. */
|
|
25
65
|
userId?: string;
|
|
26
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;
|
|
27
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';
|
|
28
117
|
export interface ApiKeysOptions {
|
|
29
118
|
store?: ApiKeyStore;
|
|
30
119
|
hooks?: HookBus;
|
|
@@ -49,8 +138,8 @@ export declare const DEFAULT_API_KEY_TOUCH_EVERY_MS = 60000;
|
|
|
49
138
|
export declare function resolveTouchEveryMs(value: number | undefined): number;
|
|
50
139
|
/**
|
|
51
140
|
* Issues and verifies API keys. The plaintext key is returned exactly once by
|
|
52
|
-
* {@link issue}; only its SHA-256 hash is stored, so a
|
|
53
|
-
* 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.
|
|
54
143
|
*/
|
|
55
144
|
export declare class ApiKeys {
|
|
56
145
|
private readonly store;
|
|
@@ -63,13 +152,52 @@ export declare class ApiKeys {
|
|
|
63
152
|
record: ApiKeyInfo;
|
|
64
153
|
key: string;
|
|
65
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>;
|
|
66
164
|
/**
|
|
67
165
|
* Resolves a presented key to its record, or null if it's malformed,
|
|
68
|
-
* unknown,
|
|
166
|
+
* unknown, revoked, expired, or used from an address outside its
|
|
167
|
+
* `allowedIps`. Updates `lastUsedAt` on a hit, at most once per
|
|
69
168
|
* `touchEveryMs` per key.
|
|
70
169
|
*/
|
|
71
|
-
verify(presented: string): Promise<ApiKeyRecord | null>;
|
|
72
|
-
|
|
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.
|
|
175
|
+
*/
|
|
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
|
+
}>;
|
|
73
201
|
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
74
202
|
revoke(id: string): Promise<void>;
|
|
75
203
|
/**
|
|
@@ -79,6 +207,9 @@ export declare class ApiKeys {
|
|
|
79
207
|
revokeAllForUser(userId: string): Promise<void>;
|
|
80
208
|
/** Reads a single key's public info (used to authorize a revoke). */
|
|
81
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;
|
|
82
213
|
}
|
|
83
214
|
/** The value stashed on `ctx().apiKey` after a request authenticates with a key. */
|
|
84
215
|
export interface ApiKeyContext {
|
|
@@ -86,4 +217,6 @@ export interface ApiKeyContext {
|
|
|
86
217
|
scopes: string[];
|
|
87
218
|
tenantId?: string;
|
|
88
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;
|
|
89
222
|
}
|