@basaltkit/auth 3.0.0 → 3.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 +27 -4
- package/dist/auth.d.ts +58 -2
- package/dist/auth.js +130 -32
- package/dist/index.d.ts +15 -3
- package/dist/index.js +4 -3
- package/dist/jwt.d.ts +5 -0
- package/dist/oauth-plugin.js +3 -0
- package/dist/plugin.d.ts +28 -1
- package/dist/plugin.js +53 -18
- package/dist/redis-throttle.d.ts +34 -0
- package/dist/redis-throttle.js +69 -0
- package/dist/routes.d.ts +10 -0
- package/dist/routes.js +47 -18
- package/dist/throttle.d.ts +95 -27
- package/dist/throttle.js +104 -65
- package/package.json +7 -7
package/dist/plugin.d.ts
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
|
-
import { BasaltError } from '@basaltkit/core';
|
|
1
|
+
import { BasaltError, type RequestContext } from '@basaltkit/core';
|
|
2
2
|
import { Auth, type AuthOptions } from './auth.js';
|
|
3
3
|
import type { PublicUser } from './stores.js';
|
|
4
4
|
declare module '@basaltkit/core' {
|
|
5
5
|
interface RequestContext {
|
|
6
6
|
/** The authenticated user of the current request, set by auth. */
|
|
7
7
|
user?: PublicUser;
|
|
8
|
+
/**
|
|
9
|
+
* Authentication methods of the current credential (`pwd`, `fed`, `mfa`),
|
|
10
|
+
* from the access token's `amr` claim or the session. Absent for API keys
|
|
11
|
+
* and for tokens / sessions issued without it.
|
|
12
|
+
*/
|
|
13
|
+
amr?: string[];
|
|
8
14
|
}
|
|
9
15
|
interface BasaltHooks {
|
|
10
16
|
'auth:registered': {
|
|
@@ -99,5 +105,26 @@ export interface AuthPluginOptions extends Omit<AuthOptions, 'hooks'> {
|
|
|
99
105
|
* are not ambient and are not affected. `false` disables the check.
|
|
100
106
|
*/
|
|
101
107
|
csrf?: CsrfOptions | false;
|
|
108
|
+
/**
|
|
109
|
+
* Require multi-factor authentication. `true` for every user, or a policy
|
|
110
|
+
* `(user, context) => boolean | Promise<boolean>` (e.g. only admins, only
|
|
111
|
+
* some tenants). An authenticated request whose credential was not obtained
|
|
112
|
+
* with a second factor (`ctx().amr` lacks `mfa`) is refused with 403
|
|
113
|
+
* `AUTH_MFA_ENROLLMENT_REQUIRED` (the account has no MFA yet — enrol, then
|
|
114
|
+
* sign in again) or `AUTH_MFA_REQUIRED` (sign in again with a code).
|
|
115
|
+
*
|
|
116
|
+
* Routes declaring `meta.mfa: false` are exempt — every `authRoutes()` route
|
|
117
|
+
* and the enrol / activate / status routes of `mfaRoutes()`, so a user can
|
|
118
|
+
* still sign in, read `/auth/me`, enrol and log out. API-key requests are not
|
|
119
|
+
* subject to the policy (a key is a machine credential; minting one needs an
|
|
120
|
+
* MFA session under the policy). Independently of the policy, `meta.mfa: true`
|
|
121
|
+
* requires MFA on a single route (step-up). Default: off.
|
|
122
|
+
*/
|
|
123
|
+
requireMfa?: boolean | ((user: PublicUser, context: RequestContext) => boolean | Promise<boolean>);
|
|
102
124
|
}
|
|
125
|
+
/**
|
|
126
|
+
* Whether the request's session cookie failed the CSRF check (so it must not
|
|
127
|
+
* be acted upon — e.g. by `POST /auth/logout`). Internal to the package.
|
|
128
|
+
*/
|
|
129
|
+
export declare const isCsrfRejected: (context: RequestContext) => boolean;
|
|
103
130
|
export declare function authPlugin(pluginOptions: AuthPluginOptions): import("@basaltkit/core").BasaltPlugin<unknown>;
|
package/dist/plugin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
|
|
2
|
-
import { Auth, AuthRequiredError } from './auth.js';
|
|
2
|
+
import { Auth, AuthRequiredError, isAmr, MfaEnrollmentRequiredError, MfaStepUpRequiredError, } from './auth.js';
|
|
3
3
|
import { publicUser } from './auth.js';
|
|
4
4
|
export const AUTH = createToken('auth');
|
|
5
5
|
/** A cookie-authenticated, state-changing request came from another origin. */
|
|
@@ -50,8 +50,13 @@ function sameOriginRequest(request, trusted) {
|
|
|
50
50
|
}
|
|
51
51
|
/** Requests whose session cookie was ignored by the CSRF check. */
|
|
52
52
|
const csrfRejected = new WeakSet();
|
|
53
|
+
/**
|
|
54
|
+
* Whether the request's session cookie failed the CSRF check (so it must not
|
|
55
|
+
* be acted upon — e.g. by `POST /auth/logout`). Internal to the package.
|
|
56
|
+
*/
|
|
57
|
+
export const isCsrfRejected = (context) => csrfRejected.has(context);
|
|
53
58
|
export function authPlugin(pluginOptions) {
|
|
54
|
-
const { csrf, ...options } = pluginOptions;
|
|
59
|
+
const { csrf, requireMfa, ...options } = pluginOptions;
|
|
55
60
|
const trustedOrigins = new Set((csrf ? (csrf.trustedOrigins ?? []) : []).map((o) => originOf(o)).filter((o) => o !== null));
|
|
56
61
|
return definePlugin({
|
|
57
62
|
name: 'basalt:auth',
|
|
@@ -63,6 +68,14 @@ export function authPlugin(pluginOptions) {
|
|
|
63
68
|
// credentials just leaves the request anonymous.
|
|
64
69
|
const enricher = async ({ request, context, container: c }) => {
|
|
65
70
|
const auth = c.get(AUTH);
|
|
71
|
+
// Evaluate the ambient cookie's CSRF standing up front, whatever other
|
|
72
|
+
// credential the request carries, so routes that act on the cookie
|
|
73
|
+
// itself (logout) can refuse a cross-site one.
|
|
74
|
+
const cookie = request.headers.cookie;
|
|
75
|
+
const cookieSessionId = typeof cookie === 'string' ? auth.sessionIdFromCookie(cookie) : null;
|
|
76
|
+
if (cookieSessionId && csrf !== false && !sameOriginRequest(request, trustedOrigins)) {
|
|
77
|
+
csrfRejected.add(context);
|
|
78
|
+
}
|
|
66
79
|
const header = request.headers.authorization;
|
|
67
80
|
const bearer = typeof header === 'string' && header.startsWith('Bearer ')
|
|
68
81
|
? header.slice('Bearer '.length)
|
|
@@ -71,29 +84,30 @@ export function authPlugin(pluginOptions) {
|
|
|
71
84
|
if (bearer && !bearer.startsWith('mk_')) {
|
|
72
85
|
const claims = await auth.verifyAccessToken(bearer);
|
|
73
86
|
const user = await auth.users.findById(claims.sub);
|
|
74
|
-
if (user)
|
|
87
|
+
if (user) {
|
|
75
88
|
context.user = publicUser(user);
|
|
89
|
+
if (isAmr(claims.amr))
|
|
90
|
+
context.amr = claims.amr;
|
|
91
|
+
}
|
|
76
92
|
return;
|
|
77
93
|
}
|
|
78
94
|
const sessionId = request.headers['x-session-id'];
|
|
79
95
|
if (typeof sessionId === 'string') {
|
|
80
|
-
const
|
|
81
|
-
if (
|
|
82
|
-
context.user = publicUser(user);
|
|
96
|
+
const session = await auth.sessionAuth(sessionId);
|
|
97
|
+
if (session) {
|
|
98
|
+
context.user = publicUser(session.user);
|
|
99
|
+
if (session.amr)
|
|
100
|
+
context.amr = session.amr;
|
|
101
|
+
}
|
|
83
102
|
return;
|
|
84
103
|
}
|
|
85
|
-
|
|
86
|
-
if (
|
|
87
|
-
const
|
|
88
|
-
if (
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
}
|
|
93
|
-
if (cookieSessionId) {
|
|
94
|
-
const user = await auth.sessionUser(cookieSessionId);
|
|
95
|
-
if (user)
|
|
96
|
-
context.user = publicUser(user);
|
|
104
|
+
// Ambient credential on a cross-origin state change: do not use it.
|
|
105
|
+
if (cookieSessionId && !csrfRejected.has(context)) {
|
|
106
|
+
const session = await auth.sessionAuth(cookieSessionId);
|
|
107
|
+
if (session) {
|
|
108
|
+
context.user = publicUser(session.user);
|
|
109
|
+
if (session.amr)
|
|
110
|
+
context.amr = session.amr;
|
|
97
111
|
}
|
|
98
112
|
}
|
|
99
113
|
};
|
|
@@ -108,6 +122,27 @@ export function authPlugin(pluginOptions) {
|
|
|
108
122
|
// Claim `meta.auth` so the adapters' boot check knows this key is
|
|
109
123
|
// enforced (routes declaring it without this plugin fail loud at boot).
|
|
110
124
|
metadata.add('http:guarded-meta', 'auth');
|
|
125
|
+
metadata.add('http:guarded-meta', 'mfa');
|
|
126
|
+
// Guard: MFA by policy (`requireMfa`) or per route (`meta.mfa: true`).
|
|
127
|
+
const mfaGuard = async ({ route, context, container: c }) => {
|
|
128
|
+
const declared = route.meta?.['mfa'];
|
|
129
|
+
if (declared === false)
|
|
130
|
+
return;
|
|
131
|
+
const user = context.user;
|
|
132
|
+
if (!user)
|
|
133
|
+
return;
|
|
134
|
+
let required = declared === true;
|
|
135
|
+
if (!required && requireMfa !== undefined && requireMfa !== false) {
|
|
136
|
+
// A machine credential: the policy is about interactive sign-ins.
|
|
137
|
+
if (context.apiKey !== undefined)
|
|
138
|
+
return;
|
|
139
|
+
required = requireMfa === true ? true : (await requireMfa(user, context)) === true;
|
|
140
|
+
}
|
|
141
|
+
if (!required || context.amr?.includes('mfa'))
|
|
142
|
+
return;
|
|
143
|
+
throw (await c.get(AUTH).isMfaEnabled(user.id)) ? new MfaStepUpRequiredError() : new MfaEnrollmentRequiredError();
|
|
144
|
+
};
|
|
145
|
+
metadata.add('http:guards', mfaGuard);
|
|
111
146
|
},
|
|
112
147
|
});
|
|
113
148
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { ThrottleStore, ThrottleWindow } from './throttle.js';
|
|
2
|
+
/**
|
|
3
|
+
* The minimal ioredis-compatible surface {@link RedisThrottleStore} needs —
|
|
4
|
+
* inject your client (ioredis, or node-redis behind a two-method adapter); no
|
|
5
|
+
* dependency on any Redis library.
|
|
6
|
+
*/
|
|
7
|
+
export interface RedisThrottleClient {
|
|
8
|
+
eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
|
|
9
|
+
del(...keys: string[]): Promise<number>;
|
|
10
|
+
}
|
|
11
|
+
export interface RedisThrottleStoreOptions {
|
|
12
|
+
/** Key prefix. Default: `basalt:throttle`. */
|
|
13
|
+
prefix?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Redis-backed {@link ThrottleStore}: the login, MFA and email-request
|
|
17
|
+
* throttles of every replica share one budget, and a lockout survives a
|
|
18
|
+
* restart. Each operation is one atomic Lua script (fixed window).
|
|
19
|
+
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* import Redis from 'ioredis'
|
|
22
|
+
* authPlugin({ users, secret, throttleStore: new RedisThrottleStore(new Redis(url)) })
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export declare class RedisThrottleStore implements ThrottleStore {
|
|
26
|
+
private readonly redis;
|
|
27
|
+
private readonly prefix;
|
|
28
|
+
constructor(redis: RedisThrottleClient, options?: RedisThrottleStoreOptions);
|
|
29
|
+
private key;
|
|
30
|
+
hit(key: string, windowMs: number): Promise<ThrottleWindow>;
|
|
31
|
+
peek(key: string): Promise<ThrottleWindow | null>;
|
|
32
|
+
release(key: string): Promise<void>;
|
|
33
|
+
reset(key: string): Promise<void>;
|
|
34
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* INCR + a first-hit PEXPIRE in one script: concurrent attempts on every
|
|
3
|
+
* replica share one count and can never read-then-write past the budget.
|
|
4
|
+
* KEYS[1] = counter · ARGV[1] = windowMs · returns {count, ttlMs}
|
|
5
|
+
*/
|
|
6
|
+
const HIT_SCRIPT = `
|
|
7
|
+
local count = redis.call('INCR', KEYS[1])
|
|
8
|
+
local ttl
|
|
9
|
+
if count == 1 then
|
|
10
|
+
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
|
11
|
+
ttl = tonumber(ARGV[1])
|
|
12
|
+
else
|
|
13
|
+
ttl = redis.call('PTTL', KEYS[1])
|
|
14
|
+
if ttl < 0 then
|
|
15
|
+
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
|
16
|
+
ttl = tonumber(ARGV[1])
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
return {count, ttl}
|
|
20
|
+
`.trim();
|
|
21
|
+
/** KEYS[1] = counter · returns {count, ttlMs} ({0, 0} when absent). */
|
|
22
|
+
const PEEK_SCRIPT = `
|
|
23
|
+
local count = redis.call('GET', KEYS[1])
|
|
24
|
+
if not count then return {0, 0} end
|
|
25
|
+
return {tonumber(count), redis.call('PTTL', KEYS[1])}
|
|
26
|
+
`.trim();
|
|
27
|
+
/** KEYS[1] = counter · decrements, deleting the key once it reaches zero. */
|
|
28
|
+
const RELEASE_SCRIPT = `
|
|
29
|
+
if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
|
|
30
|
+
local count = redis.call('DECR', KEYS[1])
|
|
31
|
+
if count <= 0 then redis.call('DEL', KEYS[1]) end
|
|
32
|
+
return count
|
|
33
|
+
`.trim();
|
|
34
|
+
/**
|
|
35
|
+
* Redis-backed {@link ThrottleStore}: the login, MFA and email-request
|
|
36
|
+
* throttles of every replica share one budget, and a lockout survives a
|
|
37
|
+
* restart. Each operation is one atomic Lua script (fixed window).
|
|
38
|
+
*
|
|
39
|
+
* ```ts
|
|
40
|
+
* import Redis from 'ioredis'
|
|
41
|
+
* authPlugin({ users, secret, throttleStore: new RedisThrottleStore(new Redis(url)) })
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export class RedisThrottleStore {
|
|
45
|
+
redis;
|
|
46
|
+
prefix;
|
|
47
|
+
constructor(redis, options = {}) {
|
|
48
|
+
this.redis = redis;
|
|
49
|
+
this.prefix = options.prefix ?? 'basalt:throttle';
|
|
50
|
+
}
|
|
51
|
+
key(key) {
|
|
52
|
+
return `${this.prefix}:${key}`;
|
|
53
|
+
}
|
|
54
|
+
async hit(key, windowMs) {
|
|
55
|
+
const reply = (await this.redis.eval(HIT_SCRIPT, 1, this.key(key), windowMs));
|
|
56
|
+
return { count: Number(reply[0]), retryAfterMs: Math.max(0, Number(reply[1])) };
|
|
57
|
+
}
|
|
58
|
+
async peek(key) {
|
|
59
|
+
const reply = (await this.redis.eval(PEEK_SCRIPT, 1, this.key(key)));
|
|
60
|
+
const count = Number(reply[0]);
|
|
61
|
+
return count > 0 ? { count, retryAfterMs: Math.max(0, Number(reply[1])) } : null;
|
|
62
|
+
}
|
|
63
|
+
async release(key) {
|
|
64
|
+
await this.redis.eval(RELEASE_SCRIPT, 1, this.key(key));
|
|
65
|
+
}
|
|
66
|
+
async reset(key) {
|
|
67
|
+
await this.redis.del(this.key(key));
|
|
68
|
+
}
|
|
69
|
+
}
|
package/dist/routes.d.ts
CHANGED
|
@@ -35,6 +35,16 @@ export interface AuthRoutesOptions {
|
|
|
35
35
|
windowMs: number;
|
|
36
36
|
} | false;
|
|
37
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Route meta shared by the account routes (sign-in, profile, MFA self-service):
|
|
40
|
+
* `account: true` exempts them from tenant-membership guards (they are about
|
|
41
|
+
* the caller, not a tenant's data — `@basaltkit/teams` honours it) and
|
|
42
|
+
* `mfa: false` keeps them reachable before MFA under `requireMfa`.
|
|
43
|
+
*/
|
|
44
|
+
export declare const ACCOUNT_META: {
|
|
45
|
+
readonly account: true;
|
|
46
|
+
readonly mfa: false;
|
|
47
|
+
};
|
|
38
48
|
/** RFC 5321 caps a forward path at 254 characters. */
|
|
39
49
|
export declare const MAX_EMAIL_LENGTH = 254;
|
|
40
50
|
/** Far above any passphrase; bounds the work an unauthenticated body can cause. */
|
package/dist/routes.js
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
import { ctx, BasaltError } from '@basaltkit/core';
|
|
2
2
|
import { route } from '@basaltkit/http';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import { AUTH } from './plugin.js';
|
|
4
|
+
import { AUTH, CsrfRejectedError, isCsrfRejected } from './plugin.js';
|
|
5
5
|
import { API_KEYS } from './apikeys-plugin.js';
|
|
6
|
+
/**
|
|
7
|
+
* Route meta shared by the account routes (sign-in, profile, MFA self-service):
|
|
8
|
+
* `account: true` exempts them from tenant-membership guards (they are about
|
|
9
|
+
* the caller, not a tenant's data — `@basaltkit/teams` honours it) and
|
|
10
|
+
* `mfa: false` keeps them reachable before MFA under `requireMfa`.
|
|
11
|
+
*/
|
|
12
|
+
export const ACCOUNT_META = { account: true, mfa: false };
|
|
6
13
|
/** RFC 5321 caps a forward path at 254 characters. */
|
|
7
14
|
export const MAX_EMAIL_LENGTH = 254;
|
|
8
15
|
/** Far above any passphrase; bounds the work an unauthenticated body can cause. */
|
|
@@ -34,11 +41,14 @@ export function authRoutes(options = {}) {
|
|
|
34
41
|
const password = passwordSchema(options.password);
|
|
35
42
|
const credentials = z.object({ email: email(), password });
|
|
36
43
|
const limit = options.rateLimit === false ? {} : { rateLimit: options.rateLimit ?? { ...DEFAULT_AUTH_RATE_LIMIT } };
|
|
44
|
+
// Every route here is about the caller's own account: exempt from the
|
|
45
|
+
// tenant-membership guard (`account`) and reachable before MFA (`mfa: false`).
|
|
46
|
+
const account = ACCOUNT_META;
|
|
37
47
|
return [
|
|
38
48
|
route({
|
|
39
49
|
method: 'POST',
|
|
40
50
|
url: '/auth/register',
|
|
41
|
-
meta: { ...limit },
|
|
51
|
+
meta: { ...account, ...limit },
|
|
42
52
|
body: credentials,
|
|
43
53
|
// Enumeration-safe: the same 202 whether the email is new or already taken
|
|
44
54
|
// (a collision is signalled out-of-band via auth:register_existing_email).
|
|
@@ -50,11 +60,11 @@ export function authRoutes(options = {}) {
|
|
|
50
60
|
route({
|
|
51
61
|
method: 'POST',
|
|
52
62
|
url: '/auth/login',
|
|
53
|
-
meta: { ...limit },
|
|
63
|
+
meta: { ...account, ...limit },
|
|
54
64
|
body: credentials.extend({ mfaCode: z.string().max(64).optional() }),
|
|
55
65
|
async handler({ body, request, reply }) {
|
|
56
|
-
const { user, tokens } = await auth().login(body.email, body.password, body.mfaCode, request.ip ? { ip: request.ip } : {});
|
|
57
|
-
const session = await auth().createSession(user.id);
|
|
66
|
+
const { user, tokens, amr } = await auth().login(body.email, body.password, body.mfaCode, request.ip ? { ip: request.ip } : {});
|
|
67
|
+
const session = await auth().createSession(user.id, { amr });
|
|
58
68
|
const sessionCookie = auth().sessionCookieHeader(session.id);
|
|
59
69
|
if (sessionCookie)
|
|
60
70
|
reply.header('set-cookie', sessionCookie);
|
|
@@ -64,6 +74,7 @@ export function authRoutes(options = {}) {
|
|
|
64
74
|
route({
|
|
65
75
|
method: 'POST',
|
|
66
76
|
url: '/auth/refresh',
|
|
77
|
+
meta: { ...account },
|
|
67
78
|
body: z.object({ refreshToken: token() }),
|
|
68
79
|
async handler({ body }) {
|
|
69
80
|
return auth().refresh(body.refreshToken);
|
|
@@ -72,12 +83,27 @@ export function authRoutes(options = {}) {
|
|
|
72
83
|
route({
|
|
73
84
|
method: 'POST',
|
|
74
85
|
url: '/auth/logout',
|
|
75
|
-
|
|
86
|
+
meta: { ...account },
|
|
87
|
+
// The refresh token is optional: a SPA on the HttpOnly session cookie
|
|
88
|
+
// alone never sees one, and ends its session with an empty body.
|
|
89
|
+
body: z.object({ refreshToken: token().optional() }).optional(),
|
|
76
90
|
async handler({ body, request, reply }) {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
91
|
+
const refreshToken = body?.refreshToken;
|
|
92
|
+
if (refreshToken)
|
|
93
|
+
await auth().revoke(refreshToken);
|
|
94
|
+
const headerSession = request.headers['x-session-id'];
|
|
95
|
+
if (typeof headerSession === 'string')
|
|
96
|
+
await auth().logout(headerSession);
|
|
97
|
+
const cookieSession = auth().sessionIdFromCookie(request.headers.cookie);
|
|
98
|
+
if (cookieSession && isCsrfRejected(ctx())) {
|
|
99
|
+
// A cross-site request must not end the cookie session (logout CSRF).
|
|
100
|
+
// With nothing else to act on, say so instead of a silent 204.
|
|
101
|
+
if (!refreshToken && typeof headerSession !== 'string')
|
|
102
|
+
throw new CsrfRejectedError();
|
|
103
|
+
return reply.code(204).send();
|
|
104
|
+
}
|
|
105
|
+
if (cookieSession)
|
|
106
|
+
await auth().logout(cookieSession);
|
|
81
107
|
const expiredCookie = auth().expiredSessionCookieHeader();
|
|
82
108
|
if (expiredCookie)
|
|
83
109
|
reply.header('set-cookie', expiredCookie);
|
|
@@ -87,7 +113,7 @@ export function authRoutes(options = {}) {
|
|
|
87
113
|
route({
|
|
88
114
|
method: 'GET',
|
|
89
115
|
url: '/auth/me',
|
|
90
|
-
meta: { auth: true },
|
|
116
|
+
meta: { auth: true, ...account },
|
|
91
117
|
async handler() {
|
|
92
118
|
return ctx().user;
|
|
93
119
|
},
|
|
@@ -96,7 +122,7 @@ export function authRoutes(options = {}) {
|
|
|
96
122
|
route({
|
|
97
123
|
method: 'POST',
|
|
98
124
|
url: '/auth/verify/request',
|
|
99
|
-
meta: { ...limit },
|
|
125
|
+
meta: { ...account, ...limit },
|
|
100
126
|
body: z.object({ email: email() }),
|
|
101
127
|
async handler({ body }) {
|
|
102
128
|
// The app emails the token (via the auth:verify_requested hook). Always
|
|
@@ -108,6 +134,7 @@ export function authRoutes(options = {}) {
|
|
|
108
134
|
route({
|
|
109
135
|
method: 'POST',
|
|
110
136
|
url: '/auth/verify',
|
|
137
|
+
meta: { ...account },
|
|
111
138
|
body: z.object({ token: token() }),
|
|
112
139
|
async handler({ body }) {
|
|
113
140
|
return { user: await auth().verifyEmail(body.token) };
|
|
@@ -117,7 +144,7 @@ export function authRoutes(options = {}) {
|
|
|
117
144
|
route({
|
|
118
145
|
method: 'POST',
|
|
119
146
|
url: '/auth/password/forgot',
|
|
120
|
-
meta: { ...limit },
|
|
147
|
+
meta: { ...account, ...limit },
|
|
121
148
|
body: z.object({ email: email() }),
|
|
122
149
|
async handler({ body }) {
|
|
123
150
|
await auth().requestPasswordReset(body.email);
|
|
@@ -130,7 +157,7 @@ export function authRoutes(options = {}) {
|
|
|
130
157
|
// The same policy as register. Covering register and leaving reset behind
|
|
131
158
|
// would let anyone walk a strong password back down to eight characters
|
|
132
159
|
// through "forgot password" — a loophole worse than having no option.
|
|
133
|
-
meta: { ...limit },
|
|
160
|
+
meta: { ...account, ...limit },
|
|
134
161
|
body: z.object({ token: token(), password }),
|
|
135
162
|
async handler({ body }) {
|
|
136
163
|
await auth().resetPassword(body.token, body.password);
|
|
@@ -230,7 +257,7 @@ export function mfaRoutes() {
|
|
|
230
257
|
route({
|
|
231
258
|
method: 'POST',
|
|
232
259
|
url: '/auth/mfa/enroll',
|
|
233
|
-
meta: { auth: true, apiKey: false },
|
|
260
|
+
meta: { auth: true, apiKey: false, ...ACCOUNT_META },
|
|
234
261
|
async handler() {
|
|
235
262
|
return auth().enrollMfa(currentUserId());
|
|
236
263
|
},
|
|
@@ -238,7 +265,7 @@ export function mfaRoutes() {
|
|
|
238
265
|
route({
|
|
239
266
|
method: 'POST',
|
|
240
267
|
url: '/auth/mfa/activate',
|
|
241
|
-
meta: { auth: true, apiKey: false },
|
|
268
|
+
meta: { auth: true, apiKey: false, ...ACCOUNT_META },
|
|
242
269
|
body: z.object({ code: z.string().min(6).max(64) }),
|
|
243
270
|
async handler({ body }) {
|
|
244
271
|
return auth().activateMfa(currentUserId(), body.code);
|
|
@@ -247,7 +274,7 @@ export function mfaRoutes() {
|
|
|
247
274
|
route({
|
|
248
275
|
method: 'GET',
|
|
249
276
|
url: '/auth/mfa/status',
|
|
250
|
-
meta: { auth: true, apiKey: false },
|
|
277
|
+
meta: { auth: true, apiKey: false, ...ACCOUNT_META },
|
|
251
278
|
async handler() {
|
|
252
279
|
return auth().mfaStatus(currentUserId());
|
|
253
280
|
},
|
|
@@ -255,7 +282,9 @@ export function mfaRoutes() {
|
|
|
255
282
|
route({
|
|
256
283
|
method: 'POST',
|
|
257
284
|
url: '/auth/mfa/disable',
|
|
258
|
-
|
|
285
|
+
// Account route, but NOT exempt from `requireMfa`: switching MFA off
|
|
286
|
+
// under the policy needs an MFA sign-in.
|
|
287
|
+
meta: { auth: true, apiKey: false, account: true },
|
|
259
288
|
body: z.object({ code: z.string().min(6).max(64) }),
|
|
260
289
|
async handler({ body, reply }) {
|
|
261
290
|
await auth().disableMfa(currentUserId(), body.code);
|
package/dist/throttle.d.ts
CHANGED
|
@@ -5,57 +5,125 @@ export declare class AccountLockedError extends BasaltError {
|
|
|
5
5
|
readonly status = 429;
|
|
6
6
|
constructor(retryAfterMs: number);
|
|
7
7
|
}
|
|
8
|
+
/** A throttle counter's state within its current window. */
|
|
9
|
+
export interface ThrottleWindow {
|
|
10
|
+
/** Attempts counted in the current window. */
|
|
11
|
+
count: number;
|
|
12
|
+
/** Milliseconds until the window closes and the counter starts over. */
|
|
13
|
+
retryAfterMs: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Where throttle counters live. The default {@link MemoryThrottleStore} is per
|
|
17
|
+
* process; pass a shared one ({@link RedisThrottleStore}) so every replica of a
|
|
18
|
+
* cluster spends ONE budget — otherwise an attacker gets `maxAttempts` guesses
|
|
19
|
+
* per replica, and a lockout on one replica is not seen by the others.
|
|
20
|
+
*
|
|
21
|
+
* Methods may be sync or async: an in-process store stays synchronous (so the
|
|
22
|
+
* count moves before any await), a network store returns promises. `hit` MUST
|
|
23
|
+
* be atomic — increment and read in one step — since it is what bounds a
|
|
24
|
+
* parallel burst. Keys arrive already digested (never a raw email).
|
|
25
|
+
*/
|
|
26
|
+
export interface ThrottleStore {
|
|
27
|
+
/**
|
|
28
|
+
* Atomically counts one attempt and returns the new state. The first hit of
|
|
29
|
+
* a key opens a fixed window of `windowMs`; later hits do not extend it.
|
|
30
|
+
*/
|
|
31
|
+
hit(key: string, windowMs: number): ThrottleWindow | Promise<ThrottleWindow>;
|
|
32
|
+
/** The current state without counting; null when the key has no live window. */
|
|
33
|
+
peek(key: string): ThrottleWindow | null | Promise<ThrottleWindow | null>;
|
|
34
|
+
/** Gives one attempt back (a successful attempt must not consume budget). */
|
|
35
|
+
release(key: string): void | Promise<void>;
|
|
36
|
+
/** Forgets the key. */
|
|
37
|
+
reset(key: string): void | Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
export interface MemoryThrottleStoreOptions {
|
|
40
|
+
/**
|
|
41
|
+
* Upper bound on tracked keys. When full, expired entries are swept and then
|
|
42
|
+
* the oldest ones are evicted, so failed logins with unique identifiers
|
|
43
|
+
* cannot grow the heap without limit. Default 100 000.
|
|
44
|
+
*/
|
|
45
|
+
maxEntries?: number;
|
|
46
|
+
/** Injectable clock for tests. */
|
|
47
|
+
clock?: () => number;
|
|
48
|
+
}
|
|
49
|
+
/** In-process {@link ThrottleStore} (the default): synchronous and bounded. */
|
|
50
|
+
export declare class MemoryThrottleStore implements ThrottleStore {
|
|
51
|
+
private readonly entries;
|
|
52
|
+
private readonly maxEntries;
|
|
53
|
+
private readonly clock;
|
|
54
|
+
constructor(options?: MemoryThrottleStoreOptions);
|
|
55
|
+
/** Number of keys currently tracked. */
|
|
56
|
+
get size(): number;
|
|
57
|
+
/** Total characters retained in keys — diagnostics for memory bounds. */
|
|
58
|
+
retainedKeyChars(): number;
|
|
59
|
+
private live;
|
|
60
|
+
private store;
|
|
61
|
+
hit(key: string, windowMs: number): ThrottleWindow;
|
|
62
|
+
peek(key: string): ThrottleWindow | null;
|
|
63
|
+
release(key: string): void;
|
|
64
|
+
reset(key: string): void;
|
|
65
|
+
}
|
|
8
66
|
export interface LoginThrottleOptions {
|
|
9
67
|
/** Failed attempts allowed within the window. Default 5. */
|
|
10
68
|
maxAttempts?: number;
|
|
11
|
-
/**
|
|
69
|
+
/** Fixed window in ms, opened by the first attempt. Default 15 minutes. */
|
|
12
70
|
windowMs?: number;
|
|
13
71
|
/**
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
72
|
+
* Where the counters live. Default: a private {@link MemoryThrottleStore}
|
|
73
|
+
* (per process). Pass a shared store — e.g. {@link RedisThrottleStore} — to
|
|
74
|
+
* enforce one budget across every replica.
|
|
75
|
+
*/
|
|
76
|
+
store?: ThrottleStore;
|
|
77
|
+
/**
|
|
78
|
+
* Key prefix separating this throttle's counters from others sharing the
|
|
79
|
+
* same store (Auth uses `login`, `login-ip` and `email-request`).
|
|
17
80
|
*/
|
|
81
|
+
namespace?: string;
|
|
82
|
+
/** Bound of the default in-memory store (ignored with `store`). Default 100 000. */
|
|
18
83
|
maxEntries?: number;
|
|
19
|
-
/** Injectable clock for
|
|
84
|
+
/** Injectable clock for the default in-memory store (ignored with `store`). */
|
|
20
85
|
clock?: () => number;
|
|
21
86
|
}
|
|
87
|
+
type Awaitable<T> = T | Promise<T>;
|
|
22
88
|
/**
|
|
23
89
|
* Brute-force guard: counts failed logins per identifier (email) within a
|
|
24
|
-
*
|
|
25
|
-
* login clears the counter.
|
|
26
|
-
*
|
|
90
|
+
* fixed window and locks the account once the budget is spent. A successful
|
|
91
|
+
* login clears the counter. Counters live in a {@link ThrottleStore}: in memory
|
|
92
|
+
* per process by default, or shared across replicas (Redis).
|
|
27
93
|
*
|
|
28
|
-
* Identifiers are
|
|
29
|
-
*
|
|
94
|
+
* Identifiers are handed to the store as SHA-256 digests (fixed size, never
|
|
95
|
+
* the raw email).
|
|
30
96
|
*
|
|
31
97
|
* Use {@link reserve} before verifying credentials: it counts the attempt
|
|
32
|
-
* synchronously
|
|
98
|
+
* atomically (synchronously with the memory store, in one Redis script with a
|
|
99
|
+
* shared one), so a parallel burst cannot run more verifications than the
|
|
33
100
|
* budget allows. {@link release} gives the reservation back on success.
|
|
101
|
+
*
|
|
102
|
+
* Every method returns synchronously with a synchronous store (the default)
|
|
103
|
+
* and a promise otherwise; `await` the result when the store may be async.
|
|
34
104
|
*/
|
|
35
105
|
export declare class LoginThrottle {
|
|
36
|
-
private readonly
|
|
106
|
+
private readonly store;
|
|
37
107
|
private readonly maxAttempts;
|
|
38
108
|
private readonly windowMs;
|
|
39
|
-
private readonly
|
|
40
|
-
private readonly clock;
|
|
109
|
+
private readonly prefix;
|
|
41
110
|
constructor(options?: LoginThrottleOptions);
|
|
42
|
-
/** Number of identifiers currently tracked. */
|
|
111
|
+
/** Number of identifiers currently tracked (in-memory store only; 0 otherwise). */
|
|
43
112
|
get size(): number;
|
|
44
|
-
/** Total characters retained in keys — diagnostics for memory bounds. */
|
|
113
|
+
/** Total characters retained in keys — diagnostics for memory bounds (in-memory store only). */
|
|
45
114
|
retainedKeyChars(): number;
|
|
46
|
-
private
|
|
47
|
-
private live;
|
|
48
|
-
private store;
|
|
115
|
+
private key;
|
|
49
116
|
/** Throws {@link AccountLockedError} when the key is currently locked. */
|
|
50
|
-
assertAllowed(key: string): void
|
|
51
|
-
recordFailure(key: string): void
|
|
117
|
+
assertAllowed(key: string): Awaitable<void>;
|
|
118
|
+
recordFailure(key: string): Awaitable<void>;
|
|
52
119
|
/**
|
|
53
|
-
* Atomically
|
|
54
|
-
*
|
|
55
|
-
*
|
|
120
|
+
* Atomically counts this attempt and throws {@link AccountLockedError} when
|
|
121
|
+
* it exceeds the budget. Pair with {@link release} on success; a failure
|
|
122
|
+
* simply keeps the reservation.
|
|
56
123
|
*/
|
|
57
|
-
reserve(key: string): void
|
|
124
|
+
reserve(key: string): Awaitable<void>;
|
|
58
125
|
/** Returns one reservation (a successful attempt must not consume budget). */
|
|
59
|
-
release(key: string): void
|
|
60
|
-
reset(key: string): void
|
|
126
|
+
release(key: string): Awaitable<void>;
|
|
127
|
+
reset(key: string): Awaitable<void>;
|
|
61
128
|
}
|
|
129
|
+
export {};
|