@basaltkit/auth 2.1.0 → 3.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 +57 -12
- package/dist/apikeys-plugin.d.ts +46 -0
- package/dist/apikeys-plugin.js +72 -7
- package/dist/apikeys.d.ts +10 -0
- package/dist/apikeys.js +22 -2
- package/dist/auth.d.ts +59 -7
- package/dist/auth.js +174 -32
- package/dist/index.d.ts +5 -5
- package/dist/index.js +5 -5
- package/dist/oauth-plugin.d.ts +9 -0
- package/dist/oauth-plugin.js +28 -4
- package/dist/oauth.d.ts +41 -4
- package/dist/oauth.js +99 -11
- package/dist/plugin.d.ts +49 -2
- package/dist/plugin.js +60 -4
- package/dist/routes.d.ts +25 -1
- package/dist/routes.js +41 -21
- package/dist/stores.d.ts +16 -0
- package/dist/stores.js +24 -1
- package/dist/throttle.d.ts +29 -0
- package/dist/throttle.js +79 -8
- package/dist/webauthn-plugin.js +9 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -65,6 +65,35 @@ curl -X POST http://localhost:3000/auth/login \
|
|
|
65
65
|
# → { "user": {...}, "accessToken": "...", "refreshToken": "..." }
|
|
66
66
|
```
|
|
67
67
|
|
|
68
|
+
For browser clients, the same login response also sets an `HttpOnly` session
|
|
69
|
+
cookie named `basalt_session`. Browsers send it automatically on same-origin
|
|
70
|
+
requests, so browser code does not need to read or store the JWT in
|
|
71
|
+
`localStorage`:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
curl -c cookies.txt -X POST http://localhost:3000/auth/login \
|
|
75
|
+
-H 'content-type: application/json' \
|
|
76
|
+
-d '{"email":"ada@example.com","password":"secretpassword1"}'
|
|
77
|
+
|
|
78
|
+
curl -b cookies.txt http://localhost:3000/auth/me
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The cookie defaults to `HttpOnly`, `SameSite=Lax`, `Path=/`, and `Secure` in
|
|
82
|
+
production. Customize its public attributes when mounting the plugin:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
authPlugin({
|
|
86
|
+
users,
|
|
87
|
+
secret: process.env.AUTH_SECRET!,
|
|
88
|
+
sessionCookie: {
|
|
89
|
+
name: 'app_session',
|
|
90
|
+
path: '/app',
|
|
91
|
+
sameSite: 'Strict',
|
|
92
|
+
secure: true,
|
|
93
|
+
},
|
|
94
|
+
})
|
|
95
|
+
```
|
|
96
|
+
|
|
68
97
|
4. **Use the access token** to reach protected routes:
|
|
69
98
|
|
|
70
99
|
```bash
|
|
@@ -130,7 +159,7 @@ await auth.revoke(renewed.refreshToken) // logout: invalidates the token family
|
|
|
130
159
|
|
|
131
160
|
`authPlugin` automatically registers:
|
|
132
161
|
|
|
133
|
-
- An **enricher** that reads the `Authorization: Bearer <jwt
|
|
162
|
+
- An **enricher** that reads the `Authorization: Bearer <jwt>`, the configured session cookie, or `x-session-id` and places the user in `ctx().user` (of type `PublicUser` — never includes the password hash).
|
|
134
163
|
- A **guard** that rejects with 401 any route with `meta: { auth: true }` without an authenticated user.
|
|
135
164
|
|
|
136
165
|
A request with no credentials stays anonymous (no error); an explicit invalid token returns 401.
|
|
@@ -262,8 +291,9 @@ for a "manage devices" screen.
|
|
|
262
291
|
### Social login (OAuth)
|
|
263
292
|
|
|
264
293
|
Sign in with Google, GitHub, or any OpenID Connect provider via the OAuth 2.0
|
|
265
|
-
authorization-code flow — no SDK
|
|
266
|
-
|
|
294
|
+
authorization-code flow — no SDK. The flow is bound to the browser that started
|
|
295
|
+
it (an HttpOnly binding cookie whose hash is in the HMAC-signed, single-use
|
|
296
|
+
`state`), and the code exchange uses PKCE (S256) plus an OIDC `nonce`. Register `oauthPlugin` with your providers and `oauthRoutes` with
|
|
267
297
|
your app's **base URL**:
|
|
268
298
|
|
|
269
299
|
```ts
|
|
@@ -276,7 +306,7 @@ createApp({
|
|
|
276
306
|
plugins: [
|
|
277
307
|
authPlugin({ users, secret: process.env.AUTH_SECRET! }),
|
|
278
308
|
oauthPlugin({
|
|
279
|
-
secret: process.env.AUTH_SECRET!, // signs the
|
|
309
|
+
secret: process.env.AUTH_SECRET!, // signs the `state`, derives PKCE verifier + nonce
|
|
280
310
|
providers: [
|
|
281
311
|
googleProvider({ clientId: env.GOOGLE_ID, clientSecret: env.GOOGLE_SECRET }),
|
|
282
312
|
githubProvider({ clientId: env.GITHUB_ID, clientSecret: env.GITHUB_SECRET }),
|
|
@@ -296,8 +326,8 @@ createApp({
|
|
|
296
326
|
|
|
297
327
|
Two routes are added per provider:
|
|
298
328
|
|
|
299
|
-
- `GET /auth/oauth/:provider` → 302 to the provider's consent screen.
|
|
300
|
-
- `GET /auth/oauth/:provider/callback` → verifies the `state
|
|
329
|
+
- `GET /auth/oauth/:provider` → sets the binding cookie, 302 to the provider's consent screen.
|
|
330
|
+
- `GET /auth/oauth/:provider/callback` → verifies the `state` against the cookie, exchanges the code,
|
|
301
331
|
and logs the user in. Returns JSON `{ user, accessToken, refreshToken }`; pass
|
|
302
332
|
`successRedirect` to `oauthRoutes` to bounce the browser back to your SPA with
|
|
303
333
|
the tokens in the URL fragment instead.
|
|
@@ -309,9 +339,13 @@ character-for-character, or the provider rejects it with *"redirect_uri is not
|
|
|
309
339
|
associated with this application"*.
|
|
310
340
|
|
|
311
341
|
New accounts are created **passwordless** and a provider-verified email flips
|
|
312
|
-
`emailVerified`.
|
|
313
|
-
|
|
314
|
-
|
|
342
|
+
`emailVerified`. An **existing** account is only logged into when the provider
|
|
343
|
+
verified the email (`SocialLinkRefusedError` otherwise); an existing account that
|
|
344
|
+
had never verified its own email has its password, sessions, refresh tokens and
|
|
345
|
+
MFA revoked before it is adopted; an account with MFA enabled requires the code
|
|
346
|
+
(`MfaRequiredError`) unless `oauthPlugin({ mfa: 'skip' })` is set for an IdP that
|
|
347
|
+
enforces its own MFA. `Auth.socialLogin(email, { emailVerified })` is the
|
|
348
|
+
underlying primitive for custom providers.
|
|
315
349
|
|
|
316
350
|
**Enterprise SSO (OIDC):** any OpenID Connect IdP (Okta, Entra ID, Auth0,
|
|
317
351
|
Keycloak…) plugs in via `oidcProvider({ clientId, clientSecret, authorizationUrl,
|
|
@@ -354,6 +388,15 @@ const app = await createApp({
|
|
|
354
388
|
|
|
355
389
|
The key is presented in the `Authorization: Bearer mk_live_...` or `x-api-key` header. A **scope** is a granular permission on the key (e.g. `reports:read`); `*` means all. After authenticating, `ctx().apiKey` contains `{ id, scopes, tenantId?, userId? }`.
|
|
356
390
|
|
|
391
|
+
The guard enforces, on every key-authenticated request: **tenant binding** (a key
|
|
392
|
+
issued in a tenant is refused with `403 AUTH_APIKEY_TENANT_MISMATCH` on any request
|
|
393
|
+
resolving another tenant or none; tenantless keys are refused on tenant-scoped
|
|
394
|
+
requests unless `allowTenantlessKeys: true`), **scopes as an upper bound** (a key
|
|
395
|
+
without `*` is refused on `meta.auth`/`can`/`teamRole`/`audience` routes that do not
|
|
396
|
+
declare `meta.scopes`; opt out with `allowNarrowKeysOnUnscopedRoutes: true`) and
|
|
397
|
+
**session-only routes** (`meta.apiKey: false` refuses every key with
|
|
398
|
+
`403 AUTH_APIKEY_NOT_ALLOWED` — `apiKeyRoutes()` and `mfaRoutes()` declare it).
|
|
399
|
+
|
|
357
400
|
### Brute-force lockout (LoginThrottle)
|
|
358
401
|
|
|
359
402
|
Active by default: 5 failed attempts per email within a 15-minute window → `AUTH_LOCKED` error (HTTP 429). A successful login clears the counter.
|
|
@@ -389,6 +432,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
389
432
|
| `accessTtl` | `DurationInput` | No | `'15m'` | Access token validity. |
|
|
390
433
|
| `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
|
|
391
434
|
| `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
|
|
435
|
+
| `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults to production only. |
|
|
392
436
|
| `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
|
|
393
437
|
| `tokens` | `AuthTokenStore` | No | `MemoryAuthTokenStore` | Verification/reset tokens. `markUsed` must be a **compare-and-swap** — see below. |
|
|
394
438
|
| `verificationTtl` | `DurationInput` | No | `'24h'` | Email verification link validity. |
|
|
@@ -412,12 +456,12 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
412
456
|
| `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
|
|
413
457
|
| `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
|
|
414
458
|
| `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
|
|
415
|
-
| `socialLogin(email, { emailVerified? })` | Find-or-create a passwordless account for an OAuth/OIDC identity; returns `{ user, tokens }`. |
|
|
459
|
+
| `socialLogin(email, { emailVerified?, mfaCode?, mfa? })` | Find-or-create a passwordless account for an OAuth/OIDC identity; links to an existing account only with a provider-verified email and honours its MFA; returns `{ user, tokens }`. |
|
|
416
460
|
|
|
417
461
|
### Ready-made routes
|
|
418
462
|
|
|
419
463
|
- `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.
|
|
420
|
-
- `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys`, `DELETE /apikeys/:id` (
|
|
464
|
+
- `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.
|
|
421
465
|
- `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
|
|
422
466
|
- `oauthRoutes({ callbackBaseUrl, successRedirect? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider.
|
|
423
467
|
|
|
@@ -497,13 +541,14 @@ If you implement your own store, do the same. Returning `void` keeps the older r
|
|
|
497
541
|
- **@basaltkit/core** — provides the app, the container, the request context (`ctx()`), and hooks; auth sets `ctx().user` and `ctx().apiKey`.
|
|
498
542
|
- **@basaltkit/fastify** — the HTTP adapter that runs the enrichers/guards and serves the ready-made routes.
|
|
499
543
|
- **@basaltkit/permissions** — answers "what can you do?"; its `meta.can` guard uses the `ctx().user` that auth sets.
|
|
500
|
-
- **@basaltkit/tenancy** — defines `ctx().tenant`; API keys created within a tenant
|
|
544
|
+
- **@basaltkit/tenancy** — defines `ctx().tenant`; API keys created within a tenant only work inside that tenant.
|
|
501
545
|
- **@basaltkit/teams** — the `meta.teamRole` guard combines `ctx().user` (auth) with `ctx().tenant` (tenancy).
|
|
502
546
|
|
|
503
547
|
## Security best practices
|
|
504
548
|
|
|
505
549
|
- **The `secret` is the vault's key.** Use a long, random value (e.g. `openssl rand -base64 48`), store it in an environment variable, and never put it in code or in git. If it leaks, anyone can forge tokens.
|
|
506
550
|
- **Always use HTTPS.** Plain-text tokens on an unencrypted connection can be intercepted.
|
|
551
|
+
- **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.
|
|
507
552
|
- **Don't increase `accessTtl`.** Short access tokens limit the damage from a stolen token; renewal via refresh token already provides convenience for the user.
|
|
508
553
|
- **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.
|
|
509
554
|
- **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.
|
package/dist/apikeys-plugin.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { BasaltError } from '@basaltkit/core';
|
|
1
2
|
import { ApiKeys, type ApiKeyContext, type ApiKeysOptions } from './apikeys.js';
|
|
2
3
|
import type { UserSource } from './stores.js';
|
|
3
4
|
declare module '@basaltkit/core' {
|
|
@@ -14,8 +15,39 @@ declare module '@basaltkit/core' {
|
|
|
14
15
|
'auth:apikey_revoked': {
|
|
15
16
|
id: string;
|
|
16
17
|
};
|
|
18
|
+
/**
|
|
19
|
+
* A presented API key was refused: unknown/revoked/expired (`invalid`), used
|
|
20
|
+
* outside the tenant it is bound to (`tenant_mismatch`), used on a
|
|
21
|
+
* session-only route (`not_allowed`) or beyond its scopes (`scope`). Never
|
|
22
|
+
* carries the key itself.
|
|
23
|
+
*/
|
|
24
|
+
'auth:apikey_rejected': {
|
|
25
|
+
id?: string;
|
|
26
|
+
reason: 'invalid' | 'tenant_mismatch' | 'not_allowed' | 'scope';
|
|
27
|
+
tenantId?: string;
|
|
28
|
+
};
|
|
17
29
|
}
|
|
18
30
|
}
|
|
31
|
+
declare module '@basaltkit/http' {
|
|
32
|
+
interface RouteMeta {
|
|
33
|
+
/**
|
|
34
|
+
* `false` makes the route session-only: requests authenticated with an API
|
|
35
|
+
* key are refused (403 `AUTH_APIKEY_NOT_ALLOWED`), whatever the key's scopes.
|
|
36
|
+
* Key management and MFA routes declare it.
|
|
37
|
+
*/
|
|
38
|
+
apiKey?: boolean;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** The key is bound to another tenant than the one this request resolved. */
|
|
42
|
+
export declare class ApiKeyTenantMismatchError extends BasaltError {
|
|
43
|
+
readonly status = 403;
|
|
44
|
+
constructor();
|
|
45
|
+
}
|
|
46
|
+
/** The route only accepts an interactive session, not an API key. */
|
|
47
|
+
export declare class ApiKeyNotAllowedError extends BasaltError {
|
|
48
|
+
readonly status = 403;
|
|
49
|
+
constructor();
|
|
50
|
+
}
|
|
19
51
|
export declare const API_KEYS: import("@basaltkit/core").Token<ApiKeys>;
|
|
20
52
|
export interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
21
53
|
/**
|
|
@@ -28,6 +60,20 @@ export interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
|
28
60
|
* so scope-guarded routes can read the acting user.
|
|
29
61
|
*/
|
|
30
62
|
users?: UserSource;
|
|
63
|
+
/**
|
|
64
|
+
* Keys issued without a tenant (machine/platform keys) are refused on any
|
|
65
|
+
* request that resolved a tenant, so they cannot be pointed at an arbitrary
|
|
66
|
+
* tenant through `x-tenant-id`, a subdomain or the Host. Set `true` only for
|
|
67
|
+
* trusted platform keys that must act across tenants. Default false.
|
|
68
|
+
*/
|
|
69
|
+
allowTenantlessKeys?: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* By default a key that does not hold `*` is refused on routes gated by
|
|
72
|
+
* `meta.auth`/`can`/`teamRole`/`audience` unless the route also declares
|
|
73
|
+
* `meta.scopes` — scopes are an upper bound, not a label. `true` restores the
|
|
74
|
+
* old behaviour where any key with a `userId` acts as its owner. Default false.
|
|
75
|
+
*/
|
|
76
|
+
allowNarrowKeysOnUnscopedRoutes?: boolean;
|
|
31
77
|
}
|
|
32
78
|
/**
|
|
33
79
|
* Programmatic access via API keys. Registers an enricher that authenticates
|
package/dist/apikeys-plugin.js
CHANGED
|
@@ -1,7 +1,29 @@
|
|
|
1
|
-
import { createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
|
|
1
|
+
import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
|
|
2
2
|
import { ApiKeys, ScopeRequiredError, scopesSatisfy } from './apikeys.js';
|
|
3
3
|
import { publicUser } from './auth.js';
|
|
4
|
+
/** The key is bound to another tenant than the one this request resolved. */
|
|
5
|
+
export class ApiKeyTenantMismatchError extends BasaltError {
|
|
6
|
+
status = 403;
|
|
7
|
+
constructor() {
|
|
8
|
+
super('AUTH_APIKEY_TENANT_MISMATCH', 'This API key is not valid for this tenant.');
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** The route only accepts an interactive session, not an API key. */
|
|
12
|
+
export class ApiKeyNotAllowedError extends BasaltError {
|
|
13
|
+
status = 403;
|
|
14
|
+
constructor() {
|
|
15
|
+
super('AUTH_APIKEY_NOT_ALLOWED', 'This action requires an interactive session; API keys are not accepted.');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Route-meta keys that gate a route on the *identity* of the caller. A key that
|
|
20
|
+
* does not hold `*` reaches such a route only when the route also declares
|
|
21
|
+
* `meta.scopes` — otherwise a narrow key would inherit its owner's full powers
|
|
22
|
+
* through `ctx().user`.
|
|
23
|
+
*/
|
|
24
|
+
const IDENTITY_GATED_META = ['auth', 'can', 'teamRole', 'audience'];
|
|
4
25
|
export const API_KEYS = createToken('auth:apikeys');
|
|
26
|
+
const tenantOf = (context) => context.tenant?.id;
|
|
5
27
|
/**
|
|
6
28
|
* Programmatic access via API keys. Registers an enricher that authenticates
|
|
7
29
|
* `mk_`-prefixed bearers (or the configured header) and a guard that enforces
|
|
@@ -13,6 +35,12 @@ export function apiKeysPlugin(options = {}) {
|
|
|
13
35
|
name: 'basalt:apikeys',
|
|
14
36
|
register({ container, hooks }) {
|
|
15
37
|
container.singleton(API_KEYS, () => new ApiKeys({ ...options, hooks }));
|
|
38
|
+
// A verified social login that adopts a never-verified account distrusts
|
|
39
|
+
// whoever registered it: the keys they may have minted die with the rest
|
|
40
|
+
// of their credentials (Auth revokes passwords, sessions, tokens and MFA).
|
|
41
|
+
hooks.on('auth:social_account_adopted', async ({ user }) => {
|
|
42
|
+
await container.get(API_KEYS).revokeAllForUser(user.id);
|
|
43
|
+
});
|
|
16
44
|
const metadata = ensureMetadata(container);
|
|
17
45
|
const enricher = async ({ request, context, container: c }) => {
|
|
18
46
|
const authHeader = request.headers.authorization;
|
|
@@ -24,8 +52,10 @@ export function apiKeysPlugin(options = {}) {
|
|
|
24
52
|
if (!presented)
|
|
25
53
|
return;
|
|
26
54
|
const record = await c.get(API_KEYS).verify(presented);
|
|
27
|
-
if (!record)
|
|
55
|
+
if (!record) {
|
|
56
|
+
await hooks.emit('auth:apikey_rejected', { reason: 'invalid' });
|
|
28
57
|
return;
|
|
58
|
+
}
|
|
29
59
|
context.apiKey = {
|
|
30
60
|
id: record.id,
|
|
31
61
|
scopes: record.scopes,
|
|
@@ -39,15 +69,50 @@ export function apiKeysPlugin(options = {}) {
|
|
|
39
69
|
}
|
|
40
70
|
};
|
|
41
71
|
metadata.add('http:enrichers', enricher);
|
|
42
|
-
// Guard
|
|
43
|
-
|
|
44
|
-
|
|
72
|
+
// Guard (runs after every enricher, so ctx().tenant is resolved): binds the
|
|
73
|
+
// key to its tenant, refuses keys on session-only routes, and enforces
|
|
74
|
+
// meta.scopes as an upper bound on what a key may reach.
|
|
75
|
+
const guard = async ({ route, context }) => {
|
|
76
|
+
const key = context.apiKey;
|
|
77
|
+
const meta = route.meta;
|
|
78
|
+
if (key) {
|
|
79
|
+
const reject = async (reason, error) => {
|
|
80
|
+
const tenantId = tenantOf(context);
|
|
81
|
+
await hooks.emit('auth:apikey_rejected', { id: key.id, reason, ...(tenantId !== undefined ? { tenantId } : {}) });
|
|
82
|
+
throw error;
|
|
83
|
+
};
|
|
84
|
+
const tenantId = tenantOf(context);
|
|
85
|
+
if (key.tenantId !== undefined) {
|
|
86
|
+
// A tenant-bound key works only inside that tenant — never in another
|
|
87
|
+
// one picked by the client, and never outside any tenant.
|
|
88
|
+
if (tenantId !== key.tenantId)
|
|
89
|
+
await reject('tenant_mismatch', new ApiKeyTenantMismatchError());
|
|
90
|
+
}
|
|
91
|
+
else if (tenantId !== undefined && options.allowTenantlessKeys !== true) {
|
|
92
|
+
await reject('tenant_mismatch', new ApiKeyTenantMismatchError());
|
|
93
|
+
}
|
|
94
|
+
if (meta?.['apiKey'] === false)
|
|
95
|
+
await reject('not_allowed', new ApiKeyNotAllowedError());
|
|
96
|
+
const declared = meta?.['scopes'];
|
|
97
|
+
const hasScopes = Array.isArray(declared) && declared.length > 0;
|
|
98
|
+
if (!hasScopes &&
|
|
99
|
+
options.allowNarrowKeysOnUnscopedRoutes !== true &&
|
|
100
|
+
!key.scopes.includes('*') &&
|
|
101
|
+
IDENTITY_GATED_META.some((k) => meta?.[k] !== undefined && meta?.[k] !== false)) {
|
|
102
|
+
await reject('scope', new ScopeRequiredError('*'));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// A route declaring meta.scopes needs an API key holding them all.
|
|
106
|
+
const required = meta?.['scopes'];
|
|
45
107
|
if (!Array.isArray(required) || required.length === 0)
|
|
46
108
|
return;
|
|
47
|
-
const granted =
|
|
109
|
+
const granted = key?.scopes ?? [];
|
|
48
110
|
for (const scope of required) {
|
|
49
|
-
if (!scopesSatisfy(granted, [scope]))
|
|
111
|
+
if (!scopesSatisfy(granted, [scope])) {
|
|
112
|
+
if (key)
|
|
113
|
+
await hooks.emit('auth:apikey_rejected', { id: key.id, reason: 'scope' });
|
|
50
114
|
throw new ScopeRequiredError(scope);
|
|
115
|
+
}
|
|
51
116
|
}
|
|
52
117
|
};
|
|
53
118
|
metadata.add('http:guards', guard);
|
package/dist/apikeys.d.ts
CHANGED
|
@@ -5,6 +5,10 @@ export declare class ScopeRequiredError extends BasaltError {
|
|
|
5
5
|
readonly status = 403;
|
|
6
6
|
constructor(scope: string);
|
|
7
7
|
}
|
|
8
|
+
export declare class ApiKeyExpirationError extends BasaltError {
|
|
9
|
+
readonly status = 400;
|
|
10
|
+
constructor();
|
|
11
|
+
}
|
|
8
12
|
/** True when `granted` covers `required` (an exact match or the `*` wildcard). */
|
|
9
13
|
export declare const scopesSatisfy: (granted: readonly string[], required: readonly string[]) => boolean;
|
|
10
14
|
export interface IssueApiKeyInput {
|
|
@@ -12,6 +16,7 @@ export interface IssueApiKeyInput {
|
|
|
12
16
|
scopes?: string[] | undefined;
|
|
13
17
|
tenantId?: string;
|
|
14
18
|
userId?: string;
|
|
19
|
+
expiresAt?: number | undefined;
|
|
15
20
|
}
|
|
16
21
|
export interface ApiKeysOptions {
|
|
17
22
|
store?: ApiKeyStore;
|
|
@@ -42,6 +47,11 @@ export declare class ApiKeys {
|
|
|
42
47
|
list(filter: ApiKeyFilter): Promise<ApiKeyInfo[]>;
|
|
43
48
|
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
44
49
|
revoke(id: string): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Revokes every live key owned by the user — for when the account's previous
|
|
52
|
+
* holder is no longer trusted (e.g. a verified social login adopted it).
|
|
53
|
+
*/
|
|
54
|
+
revokeAllForUser(userId: string): Promise<void>;
|
|
45
55
|
/** Reads a single key's public info (used to authorize a revoke). */
|
|
46
56
|
get(id: string): Promise<ApiKeyInfo | null>;
|
|
47
57
|
}
|
package/dist/apikeys.js
CHANGED
|
@@ -8,6 +8,12 @@ export class ScopeRequiredError extends BasaltError {
|
|
|
8
8
|
super('AUTH_SCOPE_REQUIRED', `This action requires the "${scope}" scope.`);
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
|
+
export class ApiKeyExpirationError extends BasaltError {
|
|
12
|
+
status = 400;
|
|
13
|
+
constructor() {
|
|
14
|
+
super('AUTH_APIKEY_EXPIRATION_INVALID', 'API key expiration must be a future timestamp.');
|
|
15
|
+
}
|
|
16
|
+
}
|
|
11
17
|
/** The prefix on every key. `mk` = Basalt key, `live` = environment. */
|
|
12
18
|
const KEY_PREFIX = 'mk_live_';
|
|
13
19
|
/** SHA-256 is safe here: API keys are high-entropy, so no slow hash is needed. */
|
|
@@ -34,6 +40,9 @@ export class ApiKeys {
|
|
|
34
40
|
}
|
|
35
41
|
/** Mints a key. Returns the record plus the plaintext `key` (shown once). */
|
|
36
42
|
async issue(input) {
|
|
43
|
+
if (input.expiresAt !== undefined && (!Number.isInteger(input.expiresAt) || input.expiresAt <= this.now())) {
|
|
44
|
+
throw new ApiKeyExpirationError();
|
|
45
|
+
}
|
|
37
46
|
const secret = randomBytes(24).toString('base64url');
|
|
38
47
|
const key = `${KEY_PREFIX}${secret}`;
|
|
39
48
|
const record = {
|
|
@@ -43,6 +52,7 @@ export class ApiKeys {
|
|
|
43
52
|
hash: hashKey(key),
|
|
44
53
|
scopes: input.scopes ?? ['*'],
|
|
45
54
|
createdAt: this.now(),
|
|
55
|
+
...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),
|
|
46
56
|
...(input.tenantId !== undefined ? { tenantId: input.tenantId } : {}),
|
|
47
57
|
...(input.userId !== undefined ? { userId: input.userId } : {}),
|
|
48
58
|
};
|
|
@@ -62,13 +72,13 @@ export class ApiKeys {
|
|
|
62
72
|
if (!presented.startsWith(KEY_PREFIX))
|
|
63
73
|
return null;
|
|
64
74
|
const record = await this.store.findByHash(hashKey(presented));
|
|
65
|
-
if (!record || record.revokedAt !== undefined)
|
|
75
|
+
if (!record || record.revokedAt !== undefined || (record.expiresAt !== undefined && record.expiresAt <= this.now()))
|
|
66
76
|
return null;
|
|
67
77
|
await this.store.touch(record.id, this.now());
|
|
68
78
|
return record;
|
|
69
79
|
}
|
|
70
80
|
async list(filter) {
|
|
71
|
-
return (await this.store.list(filter)).map(strip);
|
|
81
|
+
return (await this.store.list(filter)).filter((record) => record.expiresAt === undefined || record.expiresAt > this.now()).map(strip);
|
|
72
82
|
}
|
|
73
83
|
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
74
84
|
async revoke(id) {
|
|
@@ -78,6 +88,16 @@ export class ApiKeys {
|
|
|
78
88
|
await this.hooks?.emit('auth:apikey_revoked', { id });
|
|
79
89
|
}
|
|
80
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* Revokes every live key owned by the user — for when the account's previous
|
|
93
|
+
* holder is no longer trusted (e.g. a verified social login adopted it).
|
|
94
|
+
*/
|
|
95
|
+
async revokeAllForUser(userId) {
|
|
96
|
+
for (const record of await this.store.list({ userId })) {
|
|
97
|
+
if (record.userId === userId)
|
|
98
|
+
await this.revoke(record.id);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
81
101
|
/** Reads a single key's public info (used to authorize a revoke). */
|
|
82
102
|
async get(id) {
|
|
83
103
|
const record = await this.store.findById(id);
|
package/dist/auth.d.ts
CHANGED
|
@@ -53,6 +53,26 @@ export declare class MfaInvalidCodeError extends BasaltError {
|
|
|
53
53
|
readonly status = 401;
|
|
54
54
|
constructor();
|
|
55
55
|
}
|
|
56
|
+
/** MFA is already active: re-enrolling would silently switch it off. Disable it (with a code) first. */
|
|
57
|
+
export declare class MfaAlreadyEnabledError extends BasaltError {
|
|
58
|
+
readonly status = 409;
|
|
59
|
+
constructor();
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* A social / SSO login matched an existing account by email, but the provider
|
|
63
|
+
* did not vouch for that email (unverified), so linking would let anyone who
|
|
64
|
+
* can create an IdP account with the address take the account over.
|
|
65
|
+
*/
|
|
66
|
+
export declare class SocialLinkRefusedError extends BasaltError {
|
|
67
|
+
readonly status = 403;
|
|
68
|
+
constructor();
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Canonical form of an email identity: trimmed and lowercased. Every lookup,
|
|
72
|
+
* create and throttle key goes through it, so `Bob@acme.test` and
|
|
73
|
+
* `bob@acme.test` are one account.
|
|
74
|
+
*/
|
|
75
|
+
export declare const canonicalEmail: (email: string) => string;
|
|
56
76
|
/** An MFA action needed an enrollment that doesn't exist. */
|
|
57
77
|
export declare class MfaNotEnrolledError extends BasaltError {
|
|
58
78
|
readonly status = 400;
|
|
@@ -94,6 +114,14 @@ export interface AuthOptions {
|
|
|
94
114
|
* Only applies when the caller passes the client ip to `login`.
|
|
95
115
|
*/
|
|
96
116
|
ipLoginThrottle?: LoginThrottle | false;
|
|
117
|
+
/**
|
|
118
|
+
* Per-account throttle on password-reset and email-verification requests.
|
|
119
|
+
* Over budget, a request is silently dropped (no new token, no hook, the live
|
|
120
|
+
* link keeps working) — so the endpoints cannot be used to mail-bomb a user or
|
|
121
|
+
* keep invalidating their reset link. Default: 3 per 15 minutes per account
|
|
122
|
+
* and purpose; pass `false` to disable.
|
|
123
|
+
*/
|
|
124
|
+
emailRequestThrottle?: LoginThrottle | false;
|
|
97
125
|
/**
|
|
98
126
|
* Make the public registration endpoint enumeration-safe: a request for an
|
|
99
127
|
* email that already exists returns the same response (and does equivalent
|
|
@@ -141,6 +169,7 @@ export declare class Auth {
|
|
|
141
169
|
private readonly hooks;
|
|
142
170
|
private readonly throttle;
|
|
143
171
|
private readonly ipThrottle;
|
|
172
|
+
private readonly requestThrottle;
|
|
144
173
|
private readonly tokens;
|
|
145
174
|
private readonly verificationTtl;
|
|
146
175
|
private readonly resetTtl;
|
|
@@ -150,21 +179,38 @@ export declare class Auth {
|
|
|
150
179
|
private readonly tokenVersions;
|
|
151
180
|
private readonly enumerationSafeRegister;
|
|
152
181
|
constructor(options: AuthOptions);
|
|
153
|
-
register(
|
|
182
|
+
register(rawEmail: string, password: string): Promise<PublicUser>;
|
|
154
183
|
/**
|
|
155
184
|
* Logs in an externally-authenticated user (e.g. from an OAuth provider),
|
|
156
185
|
* matched by email — find-or-create. A new account is created **passwordless**
|
|
157
186
|
* (a random, unusable password hash), so password login won't work for it
|
|
158
187
|
* until a password is set. A provider-verified email flips `emailVerified`.
|
|
159
188
|
* Returns the tokens and whether the account was just created.
|
|
189
|
+
*
|
|
190
|
+
* Linking to an EXISTING account is refused ({@link SocialLinkRefusedError})
|
|
191
|
+
* unless `emailVerified` is `true` — an unverified provider email proves
|
|
192
|
+
* nothing about who owns the address. When the existing account had never
|
|
193
|
+
* verified its email, whoever registered it first is not trusted either: its
|
|
194
|
+
* password, sessions, refresh tokens and MFA are revoked before it is adopted
|
|
195
|
+
* (`auth:social_account_adopted`). An account with MFA enabled requires
|
|
196
|
+
* `mfaCode` ({@link MfaRequiredError}) unless `mfa: 'skip'` is passed
|
|
197
|
+
* explicitly (only for an IdP that enforces its own second factor).
|
|
160
198
|
*/
|
|
161
|
-
socialLogin(
|
|
199
|
+
socialLogin(rawEmail: string, options?: {
|
|
162
200
|
emailVerified?: boolean;
|
|
201
|
+
mfaCode?: string;
|
|
202
|
+
mfa?: 'required' | 'skip';
|
|
163
203
|
}): Promise<{
|
|
164
204
|
user: PublicUser;
|
|
165
205
|
tokens: TokenPair;
|
|
166
206
|
created: boolean;
|
|
167
207
|
}>;
|
|
208
|
+
/**
|
|
209
|
+
* A provider-verified login is taking over an account whose email was never
|
|
210
|
+
* verified: whoever registered it could be anyone (pre-account hijacking), so
|
|
211
|
+
* every credential they may hold is revoked before the verified owner gets in.
|
|
212
|
+
*/
|
|
213
|
+
private adoptUnverifiedAccount;
|
|
168
214
|
/**
|
|
169
215
|
* Enumeration-safe registration for the public endpoint: creates the account
|
|
170
216
|
* for a new email, or — when the email is already taken — does equivalent work
|
|
@@ -175,7 +221,7 @@ export declare class Auth {
|
|
|
175
221
|
* With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
|
|
176
222
|
* duplicate instead (the classic, enumerable behavior).
|
|
177
223
|
*/
|
|
178
|
-
registerSafely(
|
|
224
|
+
registerSafely(rawEmail: string, password: string): Promise<void>;
|
|
179
225
|
/** Verifies credentials without side effects. Null on failure. */
|
|
180
226
|
attempt(email: string, password: string): Promise<AuthUser | null>;
|
|
181
227
|
private dummyHashPromise?;
|
|
@@ -203,6 +249,7 @@ export declare class Auth {
|
|
|
203
249
|
* (theft indicator), the whole family is revoked.
|
|
204
250
|
*/
|
|
205
251
|
refresh(refreshToken: string): Promise<TokenPair>;
|
|
252
|
+
private reuseDetected;
|
|
206
253
|
/** Revokes a refresh family — logout for token-based clients. */
|
|
207
254
|
revoke(refreshToken: string): Promise<void>;
|
|
208
255
|
/** Structural JWT verification only (signature + expiry). */
|
|
@@ -216,8 +263,10 @@ export declare class Auth {
|
|
|
216
263
|
verifyAccessToken(accessToken: string): Promise<JwtClaims>;
|
|
217
264
|
/**
|
|
218
265
|
* Revokes every access token issued so far for the user (logout-everywhere),
|
|
219
|
-
*
|
|
220
|
-
*
|
|
266
|
+
* revoking every refresh token and server-side session (when the stores
|
|
267
|
+
* implement `revokeAllForUser` / `deleteAllForUser`, as the bundled ones do)
|
|
268
|
+
* and bumping the token version so outstanding access tokens die too (needs a
|
|
269
|
+
* {@link TokenVersionStore}; without one, access tokens live until their TTL).
|
|
221
270
|
*/
|
|
222
271
|
revokeAllTokens(userId: string): Promise<void>;
|
|
223
272
|
createSession(userId: string): Promise<SessionRecord>;
|
|
@@ -238,10 +287,13 @@ export declare class Auth {
|
|
|
238
287
|
} | null>;
|
|
239
288
|
/** Consumes a verification token and marks the user's email verified. */
|
|
240
289
|
verifyEmail(token: string): Promise<PublicUser>;
|
|
290
|
+
/** Per-account budget for reset/verification mails; false = drop silently. */
|
|
291
|
+
private allowEmailRequest;
|
|
241
292
|
/**
|
|
242
293
|
* Starts a password reset: mints a single-use token and emits
|
|
243
|
-
* `auth:password_reset_requested`. Returns null when no account matches
|
|
244
|
-
* the
|
|
294
|
+
* `auth:password_reset_requested`. Returns null when no account matches (or
|
|
295
|
+
* the per-account request budget is spent — the live link then stays valid),
|
|
296
|
+
* so the caller always responds 200 (no account enumeration).
|
|
245
297
|
*/
|
|
246
298
|
requestPasswordReset(email: string): Promise<{
|
|
247
299
|
user: PublicUser;
|