@basaltkit/auth 2.2.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 +25 -11
- package/dist/apikeys-plugin.d.ts +46 -0
- package/dist/apikeys-plugin.js +72 -7
- package/dist/apikeys.d.ts +5 -0
- package/dist/apikeys.js +10 -0
- package/dist/auth.d.ts +59 -7
- package/dist/auth.js +174 -32
- package/dist/index.d.ts +4 -4
- package/dist/index.js +4 -4
- 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 +40 -21
- package/dist/stores.d.ts +14 -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
|
@@ -291,8 +291,9 @@ for a "manage devices" screen.
|
|
|
291
291
|
### Social login (OAuth)
|
|
292
292
|
|
|
293
293
|
Sign in with Google, GitHub, or any OpenID Connect provider via the OAuth 2.0
|
|
294
|
-
authorization-code flow — no SDK
|
|
295
|
-
|
|
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
|
|
296
297
|
your app's **base URL**:
|
|
297
298
|
|
|
298
299
|
```ts
|
|
@@ -305,7 +306,7 @@ createApp({
|
|
|
305
306
|
plugins: [
|
|
306
307
|
authPlugin({ users, secret: process.env.AUTH_SECRET! }),
|
|
307
308
|
oauthPlugin({
|
|
308
|
-
secret: process.env.AUTH_SECRET!, // signs the
|
|
309
|
+
secret: process.env.AUTH_SECRET!, // signs the `state`, derives PKCE verifier + nonce
|
|
309
310
|
providers: [
|
|
310
311
|
googleProvider({ clientId: env.GOOGLE_ID, clientSecret: env.GOOGLE_SECRET }),
|
|
311
312
|
githubProvider({ clientId: env.GITHUB_ID, clientSecret: env.GITHUB_SECRET }),
|
|
@@ -325,8 +326,8 @@ createApp({
|
|
|
325
326
|
|
|
326
327
|
Two routes are added per provider:
|
|
327
328
|
|
|
328
|
-
- `GET /auth/oauth/:provider` → 302 to the provider's consent screen.
|
|
329
|
-
- `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,
|
|
330
331
|
and logs the user in. Returns JSON `{ user, accessToken, refreshToken }`; pass
|
|
331
332
|
`successRedirect` to `oauthRoutes` to bounce the browser back to your SPA with
|
|
332
333
|
the tokens in the URL fragment instead.
|
|
@@ -338,9 +339,13 @@ character-for-character, or the provider rejects it with *"redirect_uri is not
|
|
|
338
339
|
associated with this application"*.
|
|
339
340
|
|
|
340
341
|
New accounts are created **passwordless** and a provider-verified email flips
|
|
341
|
-
`emailVerified`.
|
|
342
|
-
|
|
343
|
-
|
|
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.
|
|
344
349
|
|
|
345
350
|
**Enterprise SSO (OIDC):** any OpenID Connect IdP (Okta, Entra ID, Auth0,
|
|
346
351
|
Keycloak…) plugs in via `oidcProvider({ clientId, clientSecret, authorizationUrl,
|
|
@@ -383,6 +388,15 @@ const app = await createApp({
|
|
|
383
388
|
|
|
384
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? }`.
|
|
385
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
|
+
|
|
386
400
|
### Brute-force lockout (LoginThrottle)
|
|
387
401
|
|
|
388
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.
|
|
@@ -442,12 +456,12 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
442
456
|
| `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
|
|
443
457
|
| `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
|
|
444
458
|
| `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
|
|
445
|
-
| `socialLogin(email, { emailVerified? })` | Find-or-create a passwordless account for an OAuth/OIDC identity; returns `{ user, tokens }`. |
|
|
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 }`. |
|
|
446
460
|
|
|
447
461
|
### Ready-made routes
|
|
448
462
|
|
|
449
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.
|
|
450
|
-
- `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.
|
|
451
465
|
- `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
|
|
452
466
|
- `oauthRoutes({ callbackBaseUrl, successRedirect? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider.
|
|
453
467
|
|
|
@@ -527,7 +541,7 @@ If you implement your own store, do the same. Returning `void` keeps the older r
|
|
|
527
541
|
- **@basaltkit/core** — provides the app, the container, the request context (`ctx()`), and hooks; auth sets `ctx().user` and `ctx().apiKey`.
|
|
528
542
|
- **@basaltkit/fastify** — the HTTP adapter that runs the enrichers/guards and serves the ready-made routes.
|
|
529
543
|
- **@basaltkit/permissions** — answers "what can you do?"; its `meta.can` guard uses the `ctx().user` that auth sets.
|
|
530
|
-
- **@basaltkit/tenancy** — defines `ctx().tenant`; API keys created within a tenant
|
|
544
|
+
- **@basaltkit/tenancy** — defines `ctx().tenant`; API keys created within a tenant only work inside that tenant.
|
|
531
545
|
- **@basaltkit/teams** — the `meta.teamRole` guard combines `ctx().user` (auth) with `ctx().tenant` (tenancy).
|
|
532
546
|
|
|
533
547
|
## Security best practices
|
package/dist/apikeys-plugin.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { BasaltError } from '@basaltkit/core';
|
|
1
2
|
import { ApiKeys, type ApiKeyContext, type ApiKeysOptions } from './apikeys.js';
|
|
2
3
|
import type { UserSource } from './stores.js';
|
|
3
4
|
declare module '@basaltkit/core' {
|
|
@@ -14,8 +15,39 @@ declare module '@basaltkit/core' {
|
|
|
14
15
|
'auth:apikey_revoked': {
|
|
15
16
|
id: string;
|
|
16
17
|
};
|
|
18
|
+
/**
|
|
19
|
+
* A presented API key was refused: unknown/revoked/expired (`invalid`), used
|
|
20
|
+
* outside the tenant it is bound to (`tenant_mismatch`), used on a
|
|
21
|
+
* session-only route (`not_allowed`) or beyond its scopes (`scope`). Never
|
|
22
|
+
* carries the key itself.
|
|
23
|
+
*/
|
|
24
|
+
'auth:apikey_rejected': {
|
|
25
|
+
id?: string;
|
|
26
|
+
reason: 'invalid' | 'tenant_mismatch' | 'not_allowed' | 'scope';
|
|
27
|
+
tenantId?: string;
|
|
28
|
+
};
|
|
17
29
|
}
|
|
18
30
|
}
|
|
31
|
+
declare module '@basaltkit/http' {
|
|
32
|
+
interface RouteMeta {
|
|
33
|
+
/**
|
|
34
|
+
* `false` makes the route session-only: requests authenticated with an API
|
|
35
|
+
* key are refused (403 `AUTH_APIKEY_NOT_ALLOWED`), whatever the key's scopes.
|
|
36
|
+
* Key management and MFA routes declare it.
|
|
37
|
+
*/
|
|
38
|
+
apiKey?: boolean;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** The key is bound to another tenant than the one this request resolved. */
|
|
42
|
+
export declare class ApiKeyTenantMismatchError extends BasaltError {
|
|
43
|
+
readonly status = 403;
|
|
44
|
+
constructor();
|
|
45
|
+
}
|
|
46
|
+
/** The route only accepts an interactive session, not an API key. */
|
|
47
|
+
export declare class ApiKeyNotAllowedError extends BasaltError {
|
|
48
|
+
readonly status = 403;
|
|
49
|
+
constructor();
|
|
50
|
+
}
|
|
19
51
|
export declare const API_KEYS: import("@basaltkit/core").Token<ApiKeys>;
|
|
20
52
|
export interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
21
53
|
/**
|
|
@@ -28,6 +60,20 @@ export interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
|
28
60
|
* so scope-guarded routes can read the acting user.
|
|
29
61
|
*/
|
|
30
62
|
users?: UserSource;
|
|
63
|
+
/**
|
|
64
|
+
* Keys issued without a tenant (machine/platform keys) are refused on any
|
|
65
|
+
* request that resolved a tenant, so they cannot be pointed at an arbitrary
|
|
66
|
+
* tenant through `x-tenant-id`, a subdomain or the Host. Set `true` only for
|
|
67
|
+
* trusted platform keys that must act across tenants. Default false.
|
|
68
|
+
*/
|
|
69
|
+
allowTenantlessKeys?: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* By default a key that does not hold `*` is refused on routes gated by
|
|
72
|
+
* `meta.auth`/`can`/`teamRole`/`audience` unless the route also declares
|
|
73
|
+
* `meta.scopes` — scopes are an upper bound, not a label. `true` restores the
|
|
74
|
+
* old behaviour where any key with a `userId` acts as its owner. Default false.
|
|
75
|
+
*/
|
|
76
|
+
allowNarrowKeysOnUnscopedRoutes?: boolean;
|
|
31
77
|
}
|
|
32
78
|
/**
|
|
33
79
|
* Programmatic access via API keys. Registers an enricher that authenticates
|
package/dist/apikeys-plugin.js
CHANGED
|
@@ -1,7 +1,29 @@
|
|
|
1
|
-
import { createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
|
|
1
|
+
import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
|
|
2
2
|
import { ApiKeys, ScopeRequiredError, scopesSatisfy } from './apikeys.js';
|
|
3
3
|
import { publicUser } from './auth.js';
|
|
4
|
+
/** The key is bound to another tenant than the one this request resolved. */
|
|
5
|
+
export class ApiKeyTenantMismatchError extends BasaltError {
|
|
6
|
+
status = 403;
|
|
7
|
+
constructor() {
|
|
8
|
+
super('AUTH_APIKEY_TENANT_MISMATCH', 'This API key is not valid for this tenant.');
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** The route only accepts an interactive session, not an API key. */
|
|
12
|
+
export class ApiKeyNotAllowedError extends BasaltError {
|
|
13
|
+
status = 403;
|
|
14
|
+
constructor() {
|
|
15
|
+
super('AUTH_APIKEY_NOT_ALLOWED', 'This action requires an interactive session; API keys are not accepted.');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Route-meta keys that gate a route on the *identity* of the caller. A key that
|
|
20
|
+
* does not hold `*` reaches such a route only when the route also declares
|
|
21
|
+
* `meta.scopes` — otherwise a narrow key would inherit its owner's full powers
|
|
22
|
+
* through `ctx().user`.
|
|
23
|
+
*/
|
|
24
|
+
const IDENTITY_GATED_META = ['auth', 'can', 'teamRole', 'audience'];
|
|
4
25
|
export const API_KEYS = createToken('auth:apikeys');
|
|
26
|
+
const tenantOf = (context) => context.tenant?.id;
|
|
5
27
|
/**
|
|
6
28
|
* Programmatic access via API keys. Registers an enricher that authenticates
|
|
7
29
|
* `mk_`-prefixed bearers (or the configured header) and a guard that enforces
|
|
@@ -13,6 +35,12 @@ export function apiKeysPlugin(options = {}) {
|
|
|
13
35
|
name: 'basalt:apikeys',
|
|
14
36
|
register({ container, hooks }) {
|
|
15
37
|
container.singleton(API_KEYS, () => new ApiKeys({ ...options, hooks }));
|
|
38
|
+
// A verified social login that adopts a never-verified account distrusts
|
|
39
|
+
// whoever registered it: the keys they may have minted die with the rest
|
|
40
|
+
// of their credentials (Auth revokes passwords, sessions, tokens and MFA).
|
|
41
|
+
hooks.on('auth:social_account_adopted', async ({ user }) => {
|
|
42
|
+
await container.get(API_KEYS).revokeAllForUser(user.id);
|
|
43
|
+
});
|
|
16
44
|
const metadata = ensureMetadata(container);
|
|
17
45
|
const enricher = async ({ request, context, container: c }) => {
|
|
18
46
|
const authHeader = request.headers.authorization;
|
|
@@ -24,8 +52,10 @@ export function apiKeysPlugin(options = {}) {
|
|
|
24
52
|
if (!presented)
|
|
25
53
|
return;
|
|
26
54
|
const record = await c.get(API_KEYS).verify(presented);
|
|
27
|
-
if (!record)
|
|
55
|
+
if (!record) {
|
|
56
|
+
await hooks.emit('auth:apikey_rejected', { reason: 'invalid' });
|
|
28
57
|
return;
|
|
58
|
+
}
|
|
29
59
|
context.apiKey = {
|
|
30
60
|
id: record.id,
|
|
31
61
|
scopes: record.scopes,
|
|
@@ -39,15 +69,50 @@ export function apiKeysPlugin(options = {}) {
|
|
|
39
69
|
}
|
|
40
70
|
};
|
|
41
71
|
metadata.add('http:enrichers', enricher);
|
|
42
|
-
// Guard
|
|
43
|
-
|
|
44
|
-
|
|
72
|
+
// Guard (runs after every enricher, so ctx().tenant is resolved): binds the
|
|
73
|
+
// key to its tenant, refuses keys on session-only routes, and enforces
|
|
74
|
+
// meta.scopes as an upper bound on what a key may reach.
|
|
75
|
+
const guard = async ({ route, context }) => {
|
|
76
|
+
const key = context.apiKey;
|
|
77
|
+
const meta = route.meta;
|
|
78
|
+
if (key) {
|
|
79
|
+
const reject = async (reason, error) => {
|
|
80
|
+
const tenantId = tenantOf(context);
|
|
81
|
+
await hooks.emit('auth:apikey_rejected', { id: key.id, reason, ...(tenantId !== undefined ? { tenantId } : {}) });
|
|
82
|
+
throw error;
|
|
83
|
+
};
|
|
84
|
+
const tenantId = tenantOf(context);
|
|
85
|
+
if (key.tenantId !== undefined) {
|
|
86
|
+
// A tenant-bound key works only inside that tenant — never in another
|
|
87
|
+
// one picked by the client, and never outside any tenant.
|
|
88
|
+
if (tenantId !== key.tenantId)
|
|
89
|
+
await reject('tenant_mismatch', new ApiKeyTenantMismatchError());
|
|
90
|
+
}
|
|
91
|
+
else if (tenantId !== undefined && options.allowTenantlessKeys !== true) {
|
|
92
|
+
await reject('tenant_mismatch', new ApiKeyTenantMismatchError());
|
|
93
|
+
}
|
|
94
|
+
if (meta?.['apiKey'] === false)
|
|
95
|
+
await reject('not_allowed', new ApiKeyNotAllowedError());
|
|
96
|
+
const declared = meta?.['scopes'];
|
|
97
|
+
const hasScopes = Array.isArray(declared) && declared.length > 0;
|
|
98
|
+
if (!hasScopes &&
|
|
99
|
+
options.allowNarrowKeysOnUnscopedRoutes !== true &&
|
|
100
|
+
!key.scopes.includes('*') &&
|
|
101
|
+
IDENTITY_GATED_META.some((k) => meta?.[k] !== undefined && meta?.[k] !== false)) {
|
|
102
|
+
await reject('scope', new ScopeRequiredError('*'));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// A route declaring meta.scopes needs an API key holding them all.
|
|
106
|
+
const required = meta?.['scopes'];
|
|
45
107
|
if (!Array.isArray(required) || required.length === 0)
|
|
46
108
|
return;
|
|
47
|
-
const granted =
|
|
109
|
+
const granted = key?.scopes ?? [];
|
|
48
110
|
for (const scope of required) {
|
|
49
|
-
if (!scopesSatisfy(granted, [scope]))
|
|
111
|
+
if (!scopesSatisfy(granted, [scope])) {
|
|
112
|
+
if (key)
|
|
113
|
+
await hooks.emit('auth:apikey_rejected', { id: key.id, reason: 'scope' });
|
|
50
114
|
throw new ScopeRequiredError(scope);
|
|
115
|
+
}
|
|
51
116
|
}
|
|
52
117
|
};
|
|
53
118
|
metadata.add('http:guards', guard);
|
package/dist/apikeys.d.ts
CHANGED
|
@@ -47,6 +47,11 @@ export declare class ApiKeys {
|
|
|
47
47
|
list(filter: ApiKeyFilter): Promise<ApiKeyInfo[]>;
|
|
48
48
|
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
49
49
|
revoke(id: string): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Revokes every live key owned by the user — for when the account's previous
|
|
52
|
+
* holder is no longer trusted (e.g. a verified social login adopted it).
|
|
53
|
+
*/
|
|
54
|
+
revokeAllForUser(userId: string): Promise<void>;
|
|
50
55
|
/** Reads a single key's public info (used to authorize a revoke). */
|
|
51
56
|
get(id: string): Promise<ApiKeyInfo | null>;
|
|
52
57
|
}
|
package/dist/apikeys.js
CHANGED
|
@@ -88,6 +88,16 @@ export class ApiKeys {
|
|
|
88
88
|
await this.hooks?.emit('auth:apikey_revoked', { id });
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* Revokes every live key owned by the user — for when the account's previous
|
|
93
|
+
* holder is no longer trusted (e.g. a verified social login adopted it).
|
|
94
|
+
*/
|
|
95
|
+
async revokeAllForUser(userId) {
|
|
96
|
+
for (const record of await this.store.list({ userId })) {
|
|
97
|
+
if (record.userId === userId)
|
|
98
|
+
await this.revoke(record.id);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
91
101
|
/** Reads a single key's public info (used to authorize a revoke). */
|
|
92
102
|
async get(id) {
|
|
93
103
|
const record = await this.store.findById(id);
|
package/dist/auth.d.ts
CHANGED
|
@@ -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;
|