@basaltkit/auth 3.0.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -5
- 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/stores.d.ts +21 -0
- package/dist/stores.js +24 -0
- package/dist/throttle.d.ts +95 -27
- package/dist/throttle.js +104 -65
- package/package.json +7 -7
package/dist/oauth-plugin.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createToken, ctx, definePlugin } from '@basaltkit/core';
|
|
|
2
2
|
import { route } from '@basaltkit/http';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { AUTH } from './plugin.js';
|
|
5
|
+
import { ACCOUNT_META } from './routes.js';
|
|
5
6
|
import { OAuth, stripTrailingSlashes } from './oauth.js';
|
|
6
7
|
export const OAUTH = createToken('auth.oauth');
|
|
7
8
|
/**
|
|
@@ -52,6 +53,7 @@ export function oauthRoutes(options) {
|
|
|
52
53
|
route({
|
|
53
54
|
method: 'GET',
|
|
54
55
|
url: '/auth/oauth/:provider',
|
|
56
|
+
meta: { ...ACCOUNT_META },
|
|
55
57
|
params: z.object({ provider: z.string() }),
|
|
56
58
|
async handler({ params, reply }) {
|
|
57
59
|
const { url, binding } = oauth().authorize(params.provider, redirectUri(params.provider));
|
|
@@ -61,6 +63,7 @@ export function oauthRoutes(options) {
|
|
|
61
63
|
route({
|
|
62
64
|
method: 'GET',
|
|
63
65
|
url: '/auth/oauth/:provider/callback',
|
|
66
|
+
meta: { ...ACCOUNT_META },
|
|
64
67
|
params: z.object({ provider: z.string() }),
|
|
65
68
|
query: z.object({ code: z.string().max(4096), state: z.string().max(4096) }),
|
|
66
69
|
async handler({ params, query, request, reply }) {
|
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/stores.d.ts
CHANGED
|
@@ -23,11 +23,32 @@ export interface UserSource {
|
|
|
23
23
|
}): Promise<AuthUser>;
|
|
24
24
|
/** Required for email verification and password reset. Returns the updated user. */
|
|
25
25
|
update?(id: string, patch: UserPatch): Promise<AuthUser | null>;
|
|
26
|
+
/**
|
|
27
|
+
* Bulk counterpart of {@link UserSource.findById}, for resolving the contact
|
|
28
|
+
* details of accounts the caller already knows — e.g. "email every admin of
|
|
29
|
+
* this tenant" (`@basaltkit/teams`' `roleRecipients`). Without it a caller
|
|
30
|
+
* either makes one round trip per id or reads the auth tables directly; the
|
|
31
|
+
* point of this method is that it has to do neither.
|
|
32
|
+
*
|
|
33
|
+
* Contract:
|
|
34
|
+
* - resolves {@link PublicUser}, **never** `AuthUser` — a directory lookup
|
|
35
|
+
* has no business carrying a password hash, and a driver should not even
|
|
36
|
+
* SELECT the credential columns;
|
|
37
|
+
* - one entry per **found** id, in the order of `ids`; ids with no account
|
|
38
|
+
* are omitted, so the result may be shorter than the input;
|
|
39
|
+
* - duplicate ids yield a single entry, and an empty list resolves to `[]`
|
|
40
|
+
* without touching the database.
|
|
41
|
+
*
|
|
42
|
+
* Optional: stores written before it keep compiling, and callers fall back to
|
|
43
|
+
* one `findById` per id.
|
|
44
|
+
*/
|
|
45
|
+
findByIds?(ids: readonly string[]): Promise<PublicUser[]>;
|
|
26
46
|
}
|
|
27
47
|
export declare class MemoryUserSource implements UserSource {
|
|
28
48
|
private readonly users;
|
|
29
49
|
findByEmail(email: string): Promise<AuthUser | null>;
|
|
30
50
|
findById(id: string): Promise<AuthUser | null>;
|
|
51
|
+
findByIds(ids: readonly string[]): Promise<PublicUser[]>;
|
|
31
52
|
create(data: {
|
|
32
53
|
email: string;
|
|
33
54
|
passwordHash: string;
|
package/dist/stores.js
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
2
|
/** SHA-256 of a session id — only this is persisted, never the raw cookie value. */
|
|
3
3
|
const hashSessionId = (id) => createHash('sha256').update(id).digest('hex');
|
|
4
|
+
/**
|
|
5
|
+
* Projects a stored user onto the safe, non-credential shape. Local to this
|
|
6
|
+
* module: the exported `publicUser` lives in `auth.ts`, which imports from
|
|
7
|
+
* here, so stores can't reach for it without a cycle.
|
|
8
|
+
*/
|
|
9
|
+
const contactOf = (user) => ({
|
|
10
|
+
id: user.id,
|
|
11
|
+
email: user.email,
|
|
12
|
+
emailVerified: user.emailVerified ?? false,
|
|
13
|
+
});
|
|
4
14
|
export class MemoryUserSource {
|
|
5
15
|
users = new Map();
|
|
6
16
|
async findByEmail(email) {
|
|
@@ -16,6 +26,20 @@ export class MemoryUserSource {
|
|
|
16
26
|
async findById(id) {
|
|
17
27
|
return this.users.get(id) ?? null;
|
|
18
28
|
}
|
|
29
|
+
async findByIds(ids) {
|
|
30
|
+
const out = [];
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
for (const id of ids) {
|
|
33
|
+
if (seen.has(id))
|
|
34
|
+
continue;
|
|
35
|
+
seen.add(id);
|
|
36
|
+
const user = this.users.get(id);
|
|
37
|
+
// Project, never hand out the live record: this is a contact list.
|
|
38
|
+
if (user)
|
|
39
|
+
out.push(contactOf(user));
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
19
43
|
async create(data) {
|
|
20
44
|
const user = { id: randomUUID(), emailVerified: false, ...data };
|
|
21
45
|
this.users.set(user.id, user);
|