@basaltkit/auth 2.2.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.
@@ -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
  /**
@@ -18,6 +19,22 @@ export function oauthPlugin(options) {
18
19
  },
19
20
  });
20
21
  }
22
+ const readCookie = (header, name) => {
23
+ if (typeof header !== 'string')
24
+ return undefined;
25
+ for (const part of header.split(';')) {
26
+ const [key, ...rest] = part.trim().split('=');
27
+ if (key === name && rest.length > 0) {
28
+ try {
29
+ return decodeURIComponent(rest.join('='));
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
35
+ }
36
+ return undefined;
37
+ };
21
38
  /**
22
39
  * Ready-made OAuth routes:
23
40
  * - `GET /auth/oauth/:provider` → 302 to the provider's authorize URL.
@@ -27,26 +44,36 @@ export function oauthRoutes(options) {
27
44
  const oauth = () => ctx().container.get(OAUTH);
28
45
  const base = stripTrailingSlashes(options.callbackBaseUrl);
29
46
  const redirectUri = (provider) => `${base}/auth/oauth/${provider}/callback`;
47
+ const secure = options.bindingCookie?.secure ?? process.env['NODE_ENV'] === 'production';
48
+ const cookieName = secure ? '__Host-basalt_oauth' : 'basalt_oauth';
49
+ const maxAge = options.bindingCookie?.maxAgeSeconds ?? 15 * 60;
50
+ // SameSite=Lax: the provider redirects back with a top-level GET, which Lax allows.
51
+ const cookie = (value, age) => `${cookieName}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${age}${secure ? '; Secure' : ''}`;
30
52
  return [
31
53
  route({
32
54
  method: 'GET',
33
55
  url: '/auth/oauth/:provider',
56
+ meta: { ...ACCOUNT_META },
34
57
  params: z.object({ provider: z.string() }),
35
58
  async handler({ params, reply }) {
36
- const url = oauth().authorizeUrl(params.provider, redirectUri(params.provider));
37
- return reply.code(302).header('location', url).send();
59
+ const { url, binding } = oauth().authorize(params.provider, redirectUri(params.provider));
60
+ return reply.code(302).header('set-cookie', cookie(binding, maxAge)).header('location', url).send();
38
61
  },
39
62
  }),
40
63
  route({
41
64
  method: 'GET',
42
65
  url: '/auth/oauth/:provider/callback',
66
+ meta: { ...ACCOUNT_META },
43
67
  params: z.object({ provider: z.string() }),
44
- query: z.object({ code: z.string(), state: z.string() }),
45
- async handler({ params, query, reply }) {
68
+ query: z.object({ code: z.string().max(4096), state: z.string().max(4096) }),
69
+ async handler({ params, query, request, reply }) {
70
+ // Single-use: the binding cookie is cleared whatever the outcome.
71
+ reply.header('set-cookie', cookie('', 0));
46
72
  const { user, tokens } = await oauth().callback(params.provider, {
47
73
  code: query.code,
48
74
  state: query.state,
49
75
  redirectUri: redirectUri(params.provider),
76
+ binding: readCookie(request.headers.cookie, cookieName),
50
77
  });
51
78
  if (options.successRedirect) {
52
79
  const url = new URL(options.successRedirect);
package/dist/oauth.d.ts CHANGED
@@ -79,12 +79,25 @@ export interface OAuthOptions {
79
79
  now?: () => number;
80
80
  /** How long a signed `state` stays valid, in ms. Default: 10 minutes. */
81
81
  stateTtlMs?: number;
82
+ /**
83
+ * MFA for an existing account that has it enabled. `'required'` (default)
84
+ * refuses the social login with `AUTH_MFA_REQUIRED` — the callback cannot
85
+ * collect a code. `'skip'` trusts the provider's own second factor; choose it
86
+ * only for an IdP that enforces MFA.
87
+ */
88
+ mfa?: 'required' | 'skip';
82
89
  }
83
90
  /**
84
91
  * OAuth 2.0 authorization-code login. Server-side (confidential-client) flow:
85
92
  * build an authorize URL with a signed, expiring `state`, then exchange the code
86
93
  * for a token, fetch the profile, and log the user in via {@link Auth.socialLogin}.
87
- * The `state` is HMAC-signed and stateless — no server storage, works cookieless.
94
+ *
95
+ * The flow is bound to the browser that started it: {@link authorize} returns a
96
+ * random `binding` the caller stores in an HttpOnly cookie ({@link oauthRoutes}
97
+ * does). The signed `state` carries its hash, the PKCE verifier (S256) and the
98
+ * OIDC nonce are derived from it, and the callback requires it back — so an
99
+ * attacker's callback URL opened in a victim's browser (login CSRF) or an
100
+ * injected authorization code is refused. Each `state` is single-use.
88
101
  */
89
102
  export declare class OAuth {
90
103
  private readonly auth;
@@ -96,18 +109,42 @@ export declare class OAuth {
96
109
  constructor(auth: Auth, providers: OAuthProvider[], options: OAuthOptions);
97
110
  names(): string[];
98
111
  private provider;
99
- /** The provider's authorization URL to redirect the browser to. */
100
- authorizeUrl(name: string, redirectUri: string): string;
101
- /** Verifies `state`, exchanges the code, fetches the profile, and logs in. */
112
+ /**
113
+ * Starts a login: returns the provider's authorization URL to redirect the
114
+ * browser to, and the `binding` to keep in an HttpOnly cookie until the
115
+ * callback (pass it back to {@link callback}).
116
+ */
117
+ authorize(name: string, redirectUri: string): {
118
+ url: string;
119
+ binding: string;
120
+ };
121
+ /**
122
+ * The provider's authorization URL for a caller-managed `binding` (at least
123
+ * 32 characters of randomness, stored where only the initiating browser can
124
+ * present it). Prefer {@link authorize}, which generates one.
125
+ */
126
+ authorizeUrl(name: string, redirectUri: string, binding: string): string;
127
+ /**
128
+ * Verifies `state` against the browser `binding`, consumes it (single-use),
129
+ * exchanges the code with the PKCE verifier, fetches the profile, and logs in.
130
+ */
102
131
  callback(name: string, input: {
103
132
  code: string;
104
133
  state: string | undefined;
105
134
  redirectUri: string;
135
+ binding: string | undefined;
106
136
  }): Promise<{
107
137
  user: PublicUser;
108
138
  tokens: TokenPair;
109
139
  created: boolean;
110
140
  }>;
141
+ /** A per-flow secret derived from the binding (PKCE verifier, OIDC nonce): 43 url-safe chars. */
142
+ private derive;
143
+ /** Single-use: a state nonce is remembered until it expires. */
144
+ private readonly consumed;
145
+ private consumeState;
146
+ /** The id_token (received directly from the token endpoint over TLS) must echo our nonce. */
147
+ private checkNonce;
111
148
  private exchangeCode;
112
149
  private signState;
113
150
  private verifyState;
package/dist/oauth.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
1
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
2
2
  import { BasaltError } from '@basaltkit/core';
3
3
  /** Strip trailing '/' without a backtracking regex (avoids ReDoS on long runs). */
4
4
  export function stripTrailingSlashes(s) {
@@ -136,11 +136,25 @@ export async function discoverOidcProvider(config) {
136
136
  ...(config.scopes ? { scopes: config.scopes } : {}),
137
137
  });
138
138
  }
139
+ const sha256 = (value) => createHash('sha256').update(value).digest('base64url');
140
+ const safeEqual = (a, b) => {
141
+ const x = Buffer.from(a);
142
+ const y = Buffer.from(b);
143
+ return x.length === y.length && timingSafeEqual(x, y);
144
+ };
145
+ /** Cap on remembered (consumed) states; each lives only until its expiry. */
146
+ const MAX_CONSUMED_STATES = 100_000;
139
147
  /**
140
148
  * OAuth 2.0 authorization-code login. Server-side (confidential-client) flow:
141
149
  * build an authorize URL with a signed, expiring `state`, then exchange the code
142
150
  * for a token, fetch the profile, and log the user in via {@link Auth.socialLogin}.
143
- * The `state` is HMAC-signed and stateless — no server storage, works cookieless.
151
+ *
152
+ * The flow is bound to the browser that started it: {@link authorize} returns a
153
+ * random `binding` the caller stores in an HttpOnly cookie ({@link oauthRoutes}
154
+ * does). The signed `state` carries its hash, the PKCE verifier (S256) and the
155
+ * OIDC nonce are derived from it, and the callback requires it back — so an
156
+ * attacker's callback URL opened in a victim's browser (login CSRF) or an
157
+ * injected authorization code is refused. Each `state` is single-use.
144
158
  */
145
159
  export class OAuth {
146
160
  auth;
@@ -166,32 +180,103 @@ export class OAuth {
166
180
  throw new OAuthProviderUnknownError(name);
167
181
  return p;
168
182
  }
169
- /** The provider's authorization URL to redirect the browser to. */
170
- authorizeUrl(name, redirectUri) {
183
+ /**
184
+ * Starts a login: returns the provider's authorization URL to redirect the
185
+ * browser to, and the `binding` to keep in an HttpOnly cookie until the
186
+ * callback (pass it back to {@link callback}).
187
+ */
188
+ authorize(name, redirectUri) {
189
+ const binding = randomBytes(32).toString('base64url');
190
+ return { url: this.authorizeUrl(name, redirectUri, binding), binding };
191
+ }
192
+ /**
193
+ * The provider's authorization URL for a caller-managed `binding` (at least
194
+ * 32 characters of randomness, stored where only the initiating browser can
195
+ * present it). Prefer {@link authorize}, which generates one.
196
+ */
197
+ authorizeUrl(name, redirectUri, binding) {
198
+ if (typeof binding !== 'string' || binding.length < 32)
199
+ throw new OAuthStateInvalidError();
171
200
  const p = this.provider(name);
172
- const state = this.signState({ n: randomBytes(16).toString('hex'), e: this.now() + this.stateTtl, p: name });
201
+ const state = this.signState({
202
+ n: randomBytes(16).toString('hex'),
203
+ e: this.now() + this.stateTtl,
204
+ p: name,
205
+ b: sha256(binding),
206
+ });
173
207
  const params = new URLSearchParams({
174
208
  client_id: p.clientId,
175
209
  redirect_uri: redirectUri,
176
210
  response_type: 'code',
177
211
  scope: p.scopes.join(' '),
178
212
  state,
213
+ code_challenge: sha256(this.derive('pkce', binding)),
214
+ code_challenge_method: 'S256',
179
215
  });
216
+ if (p.scopes.includes('openid'))
217
+ params.set('nonce', this.derive('nonce', binding));
180
218
  return `${p.authorizeUrl}?${params.toString()}`;
181
219
  }
182
- /** Verifies `state`, exchanges the code, fetches the profile, and logs in. */
220
+ /**
221
+ * Verifies `state` against the browser `binding`, consumes it (single-use),
222
+ * exchanges the code with the PKCE verifier, fetches the profile, and logs in.
223
+ */
183
224
  async callback(name, input) {
184
225
  const payload = this.verifyState(input.state);
185
226
  if (payload.p !== name)
186
227
  throw new OAuthStateInvalidError();
228
+ if (!input.binding || typeof payload.b !== 'string' || !safeEqual(sha256(input.binding), payload.b)) {
229
+ throw new OAuthStateInvalidError();
230
+ }
231
+ this.consumeState(payload);
187
232
  const p = this.provider(name);
188
- const accessToken = await this.exchangeCode(p, input.code, input.redirectUri);
233
+ const { accessToken, idToken } = await this.exchangeCode(p, input.code, input.redirectUri, this.derive('pkce', input.binding));
234
+ if (p.scopes.includes('openid') && idToken !== undefined)
235
+ this.checkNonce(idToken, this.derive('nonce', input.binding));
189
236
  const profile = await p.fetchProfile(accessToken, this.doFetch);
190
237
  if (!profile.email)
191
238
  throw new OAuthExchangeError('provider returned no email');
192
- return this.auth.socialLogin(profile.email, { emailVerified: profile.emailVerified === true });
239
+ return this.auth.socialLogin(profile.email, {
240
+ emailVerified: profile.emailVerified === true,
241
+ ...(this.options.mfa ? { mfa: this.options.mfa } : {}),
242
+ });
243
+ }
244
+ /** A per-flow secret derived from the binding (PKCE verifier, OIDC nonce): 43 url-safe chars. */
245
+ derive(label, binding) {
246
+ return createHmac('sha256', this.options.secret).update(`oauth:${label}:${binding}`).digest('base64url');
247
+ }
248
+ /** Single-use: a state nonce is remembered until it expires. */
249
+ consumed = new Map();
250
+ consumeState(payload) {
251
+ const now = this.now();
252
+ if (this.consumed.size >= MAX_CONSUMED_STATES) {
253
+ for (const [n, exp] of this.consumed)
254
+ if (now > exp)
255
+ this.consumed.delete(n);
256
+ for (const n of this.consumed.keys()) {
257
+ if (this.consumed.size < MAX_CONSUMED_STATES)
258
+ break;
259
+ this.consumed.delete(n);
260
+ }
261
+ }
262
+ if (this.consumed.has(payload.n))
263
+ throw new OAuthStateInvalidError();
264
+ this.consumed.set(payload.n, payload.e);
265
+ }
266
+ /** The id_token (received directly from the token endpoint over TLS) must echo our nonce. */
267
+ checkNonce(idToken, expected) {
268
+ let claims;
269
+ try {
270
+ claims = JSON.parse(Buffer.from(idToken.split('.')[1] ?? '', 'base64url').toString('utf8'));
271
+ }
272
+ catch {
273
+ throw new OAuthExchangeError('malformed id_token');
274
+ }
275
+ if (typeof claims.nonce !== 'string' || !safeEqual(claims.nonce, expected)) {
276
+ throw new OAuthExchangeError('id_token nonce mismatch');
277
+ }
193
278
  }
194
- async exchangeCode(p, code, redirectUri) {
279
+ async exchangeCode(p, code, redirectUri, codeVerifier) {
195
280
  const res = await this.doFetch(p.tokenUrl, {
196
281
  method: 'POST',
197
282
  headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
@@ -201,14 +286,17 @@ export class OAuth {
201
286
  redirect_uri: redirectUri,
202
287
  client_id: p.clientId,
203
288
  client_secret: p.clientSecret,
289
+ code_verifier: codeVerifier,
204
290
  }).toString(),
205
291
  });
206
292
  const text = await res.text();
207
- const json = text ? JSON.parse(text) : {};
293
+ const json = text
294
+ ? JSON.parse(text)
295
+ : {};
208
296
  if (!res.ok || !json.access_token) {
209
297
  throw new OAuthExchangeError(json.error_description ?? json.error ?? `token endpoint HTTP ${res.status}`);
210
298
  }
211
- return json.access_token;
299
+ return { accessToken: json.access_token, ...(typeof json.id_token === 'string' ? { idToken: json.id_token } : {}) };
212
300
  }
213
301
  signState(payload) {
214
302
  const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
package/dist/plugin.d.ts CHANGED
@@ -1,9 +1,16 @@
1
+ import { BasaltError, type RequestContext } from '@basaltkit/core';
1
2
  import { Auth, type AuthOptions } from './auth.js';
2
3
  import type { PublicUser } from './stores.js';
3
4
  declare module '@basaltkit/core' {
4
5
  interface RequestContext {
5
6
  /** The authenticated user of the current request, set by auth. */
6
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[];
7
14
  }
8
15
  interface BasaltHooks {
9
16
  'auth:registered': {
@@ -49,8 +56,75 @@ declare module '@basaltkit/core' {
49
56
  'auth:mfa_disabled': {
50
57
  user: PublicUser;
51
58
  };
59
+ /** A wrong MFA code was presented for this user (login or social login). */
60
+ 'auth:mfa_failed': {
61
+ userId: string;
62
+ };
63
+ /** A login was refused because the account (or the client ip) is locked. */
64
+ 'auth:locked_out': {
65
+ email: string;
66
+ ip?: string;
67
+ };
68
+ /** A consumed refresh token came back; its whole family was revoked (theft indicator). */
69
+ 'auth:refresh_reused': {
70
+ userId: string;
71
+ familyId: string;
72
+ };
73
+ /**
74
+ * A provider-verified social login took over an account whose email had
75
+ * never been verified; its previous password, sessions, refresh tokens and
76
+ * MFA were revoked.
77
+ */
78
+ 'auth:social_account_adopted': {
79
+ user: PublicUser;
80
+ };
52
81
  }
53
82
  }
54
83
  export declare const AUTH: import("@basaltkit/core").Token<Auth>;
55
- export type AuthPluginOptions = Omit<AuthOptions, 'hooks'>;
56
- export declare function authPlugin(options: AuthPluginOptions): import("@basaltkit/core").BasaltPlugin<unknown>;
84
+ /** A cookie-authenticated, state-changing request came from another origin. */
85
+ export declare class CsrfRejectedError extends BasaltError {
86
+ readonly status = 403;
87
+ constructor();
88
+ }
89
+ export interface CsrfOptions {
90
+ /**
91
+ * Extra origins (scheme://host[:port]) allowed to send cookie-authenticated
92
+ * unsafe requests — e.g. a front-end on a sibling subdomain. The request's
93
+ * own origin (its Host / X-Forwarded-Host) is always allowed.
94
+ */
95
+ trustedOrigins?: string[];
96
+ }
97
+ export interface AuthPluginOptions extends Omit<AuthOptions, 'hooks'> {
98
+ /**
99
+ * CSRF defence for the session cookie (on by default). A request whose ONLY
100
+ * credential is the ambient session cookie and whose method is not
101
+ * GET/HEAD/OPTIONS is not authenticated when the browser says it is
102
+ * cross-site or same-site (`Sec-Fetch-Site`), or when its `Origin` is neither
103
+ * the request's own host nor a trusted origin; a route requiring auth then
104
+ * answers 403 `AUTH_CSRF_REJECTED`. Bearer tokens, `x-session-id` and API keys
105
+ * are not ambient and are not affected. `false` disables the check.
106
+ */
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>);
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;
130
+ export declare function authPlugin(pluginOptions: AuthPluginOptions): import("@basaltkit/core").BasaltPlugin<unknown>;
package/dist/plugin.js CHANGED
@@ -1,8 +1,63 @@
1
- import { createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
2
- import { Auth, AuthRequiredError } from './auth.js';
1
+ import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
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
- export function authPlugin(options) {
5
+ /** A cookie-authenticated, state-changing request came from another origin. */
6
+ export class CsrfRejectedError extends BasaltError {
7
+ status = 403;
8
+ constructor() {
9
+ super('AUTH_CSRF_REJECTED', 'Cross-site request refused: the session cookie cannot authorize it.');
10
+ }
11
+ }
12
+ const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
13
+ const headerOf = (request, name) => {
14
+ const value = request.headers[name];
15
+ return Array.isArray(value) ? value[0] : value;
16
+ };
17
+ const originOf = (value) => {
18
+ try {
19
+ const url = new URL(value);
20
+ return `${url.protocol}//${url.host}`.toLowerCase();
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ };
26
+ /** Whether a cookie-authenticated request may change state (CSRF check). */
27
+ function sameOriginRequest(request, trusted) {
28
+ if (SAFE_METHODS.has(request.method.toUpperCase()))
29
+ return true;
30
+ const origin = headerOf(request, 'origin');
31
+ const normalized = origin && origin !== 'null' ? originOf(origin) : null;
32
+ if (normalized && trusted.has(normalized))
33
+ return true;
34
+ // Sec-Fetch-Site is set by the browser alone (a page cannot forge it), so it
35
+ // settles the question when present — including behind a proxy that rewrites Host.
36
+ const site = headerOf(request, 'sec-fetch-site')?.toLowerCase();
37
+ if (site === 'same-origin' || site === 'none')
38
+ return true;
39
+ if (site === 'cross-site' || site === 'same-site')
40
+ return false;
41
+ if (origin === undefined)
42
+ return true; // no browser metadata: not a browser-forged request
43
+ if (!normalized)
44
+ return false; // `Origin: null` (sandboxed/opaque) or garbage
45
+ const host = normalized.slice(normalized.indexOf('//') + 2);
46
+ const own = [headerOf(request, 'host'), headerOf(request, 'x-forwarded-host')]
47
+ .filter((h) => typeof h === 'string')
48
+ .map((h) => h.split(',')[0].trim().toLowerCase());
49
+ return own.includes(host);
50
+ }
51
+ /** Requests whose session cookie was ignored by the CSRF check. */
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);
58
+ export function authPlugin(pluginOptions) {
59
+ const { csrf, requireMfa, ...options } = pluginOptions;
60
+ const trustedOrigins = new Set((csrf ? (csrf.trustedOrigins ?? []) : []).map((o) => originOf(o)).filter((o) => o !== null));
6
61
  return definePlugin({
7
62
  name: 'basalt:auth',
8
63
  register({ container, hooks }) {
@@ -13,6 +68,14 @@ export function authPlugin(options) {
13
68
  // credentials just leaves the request anonymous.
14
69
  const enricher = async ({ request, context, container: c }) => {
15
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
+ }
16
79
  const header = request.headers.authorization;
17
80
  const bearer = typeof header === 'string' && header.startsWith('Bearer ')
18
81
  ? header.slice('Bearer '.length)
@@ -21,37 +84,65 @@ export function authPlugin(options) {
21
84
  if (bearer && !bearer.startsWith('mk_')) {
22
85
  const claims = await auth.verifyAccessToken(bearer);
23
86
  const user = await auth.users.findById(claims.sub);
24
- if (user)
87
+ if (user) {
25
88
  context.user = publicUser(user);
89
+ if (isAmr(claims.amr))
90
+ context.amr = claims.amr;
91
+ }
26
92
  return;
27
93
  }
28
94
  const sessionId = request.headers['x-session-id'];
29
95
  if (typeof sessionId === 'string') {
30
- const user = await auth.sessionUser(sessionId);
31
- if (user)
32
- 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
+ }
33
102
  return;
34
103
  }
35
- const cookie = request.headers.cookie;
36
- if (typeof cookie === 'string') {
37
- const cookieSessionId = auth.sessionIdFromCookie(cookie);
38
- if (cookieSessionId) {
39
- const user = await auth.sessionUser(cookieSessionId);
40
- if (user)
41
- 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;
42
111
  }
43
112
  }
44
113
  };
45
114
  metadata.add('http:enrichers', enricher);
46
115
  // Guard: routes declaring meta.auth require an authenticated user.
47
116
  const guard = ({ route, context }) => {
48
- if (route.meta?.['auth'] === true && !context.user)
49
- throw new AuthRequiredError();
117
+ if (route.meta?.['auth'] === true && !context.user) {
118
+ throw csrfRejected.has(context) ? new CsrfRejectedError() : new AuthRequiredError();
119
+ }
50
120
  };
51
121
  metadata.add('http:guards', guard);
52
122
  // Claim `meta.auth` so the adapters' boot check knows this key is
53
123
  // enforced (routes declaring it without this plugin fail loud at boot).
54
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);
55
146
  },
56
147
  });
57
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
+ }