@lenne.tech/nest-server 11.44.0 → 11.44.2
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/.claude/rules/better-auth.md +50 -4
- package/.claude/rules/configurable-features.md +1 -1
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/config.env.js +2 -2
- package/dist/config.env.js.map +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
- package/dist/core/modules/auth/services/core-auth.service.js +3 -0
- package/dist/core/modules/auth/services/core-auth.service.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth.config.js +32 -4
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +2 -1
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +5 -1
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.d.ts +8 -0
- package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.js +70 -0
- package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.d.ts +2 -0
- package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js +14 -1
- package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.d.ts +3 -1
- package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js +28 -4
- package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +2 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +25 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.controller.js +13 -5
- package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.module.js +2 -0
- package/dist/core/modules/better-auth/core-better-auth.module.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.resolver.js +7 -2
- package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.service.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js +14 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
- package/dist/core/modules/better-auth/index.d.ts +1 -0
- package/dist/core/modules/better-auth/index.js +1 -0
- package/dist/core/modules/better-auth/index.js.map +1 -1
- package/dist/core/modules/error-code/error-codes.d.ts +9 -0
- package/dist/core/modules/error-code/error-codes.js +8 -0
- package/dist/core/modules/error-code/error-codes.js.map +1 -1
- package/dist/core/modules/user/core-user.service.js +5 -1
- package/dist/core/modules/user/core-user.service.js.map +1 -1
- package/dist/server/modules/error-code/error-codes.d.ts +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/docs/REQUEST-LIFECYCLE.md +1 -0
- package/docs/error-codes.md +14 -0
- package/migration-guides/11.41.7-to-11.41.8.md +1 -1
- package/migration-guides/11.44.0-to-11.44.1.md +152 -0
- package/migration-guides/11.44.1-to-11.44.2.md +125 -0
- package/package.json +1 -1
- package/src/config.env.ts +6 -2
- package/src/core/common/interfaces/server-options.interface.ts +16 -0
- package/src/core/modules/auth/services/core-auth.service.ts +8 -0
- package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +3 -0
- package/src/core/modules/better-auth/README.md +34 -4
- package/src/core/modules/better-auth/better-auth.config.ts +72 -5
- package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +8 -3
- package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +18 -1
- package/src/core/modules/better-auth/core-better-auth-path-guard.middleware.ts +85 -0
- package/src/core/modules/better-auth/core-better-auth-rate-limit.middleware.ts +28 -2
- package/src/core/modules/better-auth/core-better-auth-rate-limiter.service.ts +58 -10
- package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +41 -0
- package/src/core/modules/better-auth/core-better-auth.controller.ts +24 -10
- package/src/core/modules/better-auth/core-better-auth.module.ts +12 -2
- package/src/core/modules/better-auth/core-better-auth.resolver.ts +12 -2
- package/src/core/modules/better-auth/core-better-auth.service.ts +28 -0
- package/src/core/modules/better-auth/index.ts +1 -0
- package/src/core/modules/error-code/error-codes.ts +9 -0
- package/src/core/modules/user/core-user.service.ts +10 -2
|
@@ -8,6 +8,7 @@ import { BetterAuthCookieHelper, createCookieHelper } from './core-better-auth-c
|
|
|
8
8
|
import { wrapBetterAuthErrorResponse } from './core-better-auth-error-codes.helper';
|
|
9
9
|
import { isControllerHandledPath } from './core-better-auth-openapi.helper';
|
|
10
10
|
import { runWithResetPassword } from './core-better-auth-password-reset.registry';
|
|
11
|
+
import { canonicalRequestPath } from './core-better-auth-path-guard.middleware';
|
|
11
12
|
import { CoreBetterAuthUserMapper } from './core-better-auth-user.mapper';
|
|
12
13
|
import { extractSessionToken, signCookieValue, toWebRequest } from './core-better-auth-web.helper';
|
|
13
14
|
import { CoreBetterAuthService } from './core-better-auth.service';
|
|
@@ -239,9 +240,13 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
|
|
|
239
240
|
}
|
|
240
241
|
|
|
241
242
|
const basePath = this.betterAuthService.getBasePath();
|
|
242
|
-
//
|
|
243
|
-
//
|
|
244
|
-
|
|
243
|
+
// The path Better-Auth will ROUTE, not the one the client wrote (11.44.1): the forwarded Web Request is built with
|
|
244
|
+
// `new URL(originalUrl, baseUrl)` (toWebRequest()), which resolves `.`, `..` and `%2e` segments. Compared raw,
|
|
245
|
+
// `/iam/sign-up/%2e/email` counted as "not a controller path" while Better-Auth's own sign-up served it — past the
|
|
246
|
+
// controller's checks and every project override. CoreBetterAuthPathGuardMiddleware refuses such a path before this
|
|
247
|
+
// runs; deciding on the canonical path keeps this middleware right where the guard is not registered, as the rate
|
|
248
|
+
// limiter does.
|
|
249
|
+
const requestPath = canonicalRequestPath(req.originalUrl || req.url || req.path);
|
|
245
250
|
|
|
246
251
|
// Only handle requests that start with the Better Auth base path
|
|
247
252
|
if (!requestPath.startsWith(basePath)) {
|
|
@@ -619,6 +619,16 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
619
619
|
return Math.max(1, Math.round(resolved / 60));
|
|
620
620
|
}
|
|
621
621
|
|
|
622
|
+
/**
|
|
623
|
+
* Whether the project switched Better-Auth's origin check off (`betterAuth.options.advanced.disableOriginCheck`):
|
|
624
|
+
* `true`, or a list of paths, which may name the reset route. The framework itself pins `false` (11.44.2), so only a
|
|
625
|
+
* project's own value counts here.
|
|
626
|
+
*/
|
|
627
|
+
protected isOriginCheckDisabled(): boolean {
|
|
628
|
+
const raw = this.configService.getFastButReadOnly<unknown>('betterAuth.options.advanced.disableOriginCheck');
|
|
629
|
+
return raw === true || Array.isArray(raw);
|
|
630
|
+
}
|
|
631
|
+
|
|
622
632
|
protected buildPasswordResetUrl(options: SendPasswordResetEmailOptions): string {
|
|
623
633
|
const configured = this.config.passwordResetLink;
|
|
624
634
|
|
|
@@ -633,7 +643,9 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
633
643
|
// `nuxt-base-starter` sends it on every request (`forgot-password.vue` →
|
|
634
644
|
// `requestPasswordReset({ email, redirectTo: appUrl('/auth/reset-password', siteUrl) })`), and
|
|
635
645
|
// a client that names its page is a better authority on that page than a framework default.
|
|
636
|
-
|
|
646
|
+
// Only while Better-Auth's origin check validated it (see readCallbackUrlFromBetterAuthLink): a project that
|
|
647
|
+
// switched the check off gets the default page, never an unvalidated URL with a valid token in it.
|
|
648
|
+
if (!target && !this.isOriginCheckDisabled()) {
|
|
637
649
|
target = this.readCallbackUrlFromBetterAuthLink(options.url);
|
|
638
650
|
}
|
|
639
651
|
|
|
@@ -687,6 +699,11 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
687
699
|
* knowing before anyone widens it. `cors.allowAll` does not widen it (an origin check has no
|
|
688
700
|
* "allow everything" mode), but an over-broad `allowedOrigins` would.
|
|
689
701
|
*
|
|
702
|
+
* And it makes the origin check itself load-bearing. Until 11.44.2 Better-Auth switched it off on its
|
|
703
|
+
* own under `NODE_ENV=test` (`isTest()`), which is a deployed stage in starter-based projects; the
|
|
704
|
+
* framework now pins `advanced.disableOriginCheck: false`. A project that switches it off itself
|
|
705
|
+
* gets no caller URL here at all ({@link isOriginCheckDisabled}).
|
|
706
|
+
*
|
|
690
707
|
* Returns `undefined` for anything unparseable or absent, so the caller falls through to its own
|
|
691
708
|
* resolution rather than to a half-formed URL.
|
|
692
709
|
*/
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { BadRequestException, Injectable, NestMiddleware } from '@nestjs/common';
|
|
2
|
+
import type { NextFunction, Request, Response } from 'express';
|
|
3
|
+
|
|
4
|
+
import { ErrorCode } from '../error-code/error-codes';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Whether a raw request path contains something URL resolution rewrites: a `.` or `..` segment (also
|
|
8
|
+
* percent-encoded), a backslash (a segment separator for WHATWG URLs), an encoded slash or backslash, or a `#`
|
|
9
|
+
* (Express routes the part before it, the forwarding to Better-Auth reads the whole string).
|
|
10
|
+
*
|
|
11
|
+
* Every check in front of Better-Auth (rate limiter, controller routes, password routes) reads the RAW path, while
|
|
12
|
+
* Better-Auth routes the path `new URL()` resolved. A path the two read differently passes those checks as one route
|
|
13
|
+
* and runs as another. No route under the Better-Auth base path needs any of these, so such a request is refused.
|
|
14
|
+
*
|
|
15
|
+
* A loop over segments, no regex over the whole path: the path comes from an unauthenticated request and may be as
|
|
16
|
+
* long as Node's header limit allows.
|
|
17
|
+
*/
|
|
18
|
+
export function hasNonCanonicalPathSegments(path: string): boolean {
|
|
19
|
+
if (path.includes('\\') || path.includes('#')) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
for (const segment of path.split('/')) {
|
|
23
|
+
if (segment.includes('%')) {
|
|
24
|
+
const lower = segment.toLowerCase();
|
|
25
|
+
if (lower.includes('%2f') || lower.includes('%5c')) {
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
// The longest dot segment is `%2e%2e`
|
|
30
|
+
if (segment.length === 0 || segment.length > 6) {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const dots = segment.replace(/%2e/gi, '.');
|
|
34
|
+
if (dots === '.' || dots === '..') {
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The path as Better-Auth routes it: dot segments resolved (also percent-encoded ones), backslashes read as slashes —
|
|
43
|
+
* what `new URL()` makes of it. Query string and fragment are dropped. A path `new URL()` refuses comes back as given.
|
|
44
|
+
*/
|
|
45
|
+
export function canonicalRequestPath(path: string): string {
|
|
46
|
+
try {
|
|
47
|
+
return new URL(path, 'http://canonical.invalid').pathname;
|
|
48
|
+
} catch {
|
|
49
|
+
return path;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Whether `path` contains the segments of `endpoint` as a contiguous run of WHOLE segments: `/sign-in` matches
|
|
55
|
+
* `/sign-in/email` and `/phone-number/sign-in`, never `/sign-in-legacy`. Segments are compared as they are; pass a
|
|
56
|
+
* {@link canonicalRequestPath} result, so `..` is already resolved.
|
|
57
|
+
*/
|
|
58
|
+
export function pathContainsSegments(path: string, endpoint: string): boolean {
|
|
59
|
+
const wanted = endpoint.split('/').filter(Boolean);
|
|
60
|
+
if (wanted.length === 0) {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
const segments = path.split('/').filter(Boolean);
|
|
64
|
+
for (let start = 0; start + wanted.length <= segments.length; start++) {
|
|
65
|
+
if (wanted.every((segment, offset) => segments[start + offset] === segment)) {
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* First middleware under the Better-Auth base path: refuses a request whose path is not in canonical form (see
|
|
74
|
+
* {@link hasNonCanonicalPathSegments}) with 400, before any check reads that path.
|
|
75
|
+
*/
|
|
76
|
+
@Injectable()
|
|
77
|
+
export class CoreBetterAuthPathGuardMiddleware implements NestMiddleware {
|
|
78
|
+
use(req: Request, _res: Response, next: NextFunction) {
|
|
79
|
+
const path = (req.originalUrl || req.url || '').split('?')[0];
|
|
80
|
+
if (hasNonCanonicalPathSegments(path)) {
|
|
81
|
+
throw new BadRequestException(ErrorCode.INVALID_REQUEST_PATH);
|
|
82
|
+
}
|
|
83
|
+
next();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { HttpException, HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';
|
|
2
2
|
import { NextFunction, Request, Response } from 'express';
|
|
3
3
|
|
|
4
|
+
import { CONTROLLER_HANDLED_PATHS } from './core-better-auth-openapi.helper';
|
|
4
5
|
import { CoreBetterAuthRateLimiter, RateLimitResult } from './core-better-auth-rate-limiter.service';
|
|
5
6
|
import { CoreBetterAuthService } from './core-better-auth.service';
|
|
6
7
|
|
|
@@ -50,9 +51,15 @@ export class CoreBetterAuthRateLimitMiddleware implements NestMiddleware {
|
|
|
50
51
|
// Get client IP
|
|
51
52
|
const ip = this.getClientIp(req);
|
|
52
53
|
|
|
53
|
-
//
|
|
54
|
+
// The path relative to basePath, read from `originalUrl`: Nest mounts this middleware on `${basePath}/*path`, and
|
|
55
|
+
// Express moves the whole match into `req.baseUrl`, so `req.path` is "/" for every request here. Reading it made
|
|
56
|
+
// every IAM request of one client share a single counter with the full limit — no skip list, no strict limit
|
|
54
57
|
const basePath = this.betterAuthService.getBasePath();
|
|
55
|
-
const
|
|
58
|
+
const requestPath = (req.originalUrl || req.url || '').split('?')[0];
|
|
59
|
+
const path = requestPath.startsWith(basePath) ? requestPath.substring(basePath.length) : requestPath;
|
|
60
|
+
|
|
61
|
+
// The route names counters are keyed by, from the running instance (once per instance)
|
|
62
|
+
this.provideKnownEndpoints();
|
|
56
63
|
|
|
57
64
|
// Check rate limit
|
|
58
65
|
const result = await this.rateLimiter.check(ip, path);
|
|
@@ -91,6 +98,25 @@ export class CoreBetterAuthRateLimitMiddleware implements NestMiddleware {
|
|
|
91
98
|
return req.ip || req.socket?.remoteAddress || 'unknown';
|
|
92
99
|
}
|
|
93
100
|
|
|
101
|
+
/** The instance whose routes the limiter knows */
|
|
102
|
+
private knownEndpointsFrom: unknown = null;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Hands the limiter the routes the base path serves: Better-Auth's own (every endpoint of the running instance,
|
|
106
|
+
* plugins included) and the controller's. Counters are keyed by these names only, so unknown paths cannot create
|
|
107
|
+
* counters (see CoreBetterAuthRateLimiter.normalizeEndpoint()).
|
|
108
|
+
*/
|
|
109
|
+
private provideKnownEndpoints(): void {
|
|
110
|
+
// Optional call: a project's stand-in service may not offer it, and the limiter stays bounded without the names
|
|
111
|
+
const instance = this.betterAuthService.getInstance?.() as null | undefined | { api?: Record<string, unknown> };
|
|
112
|
+
if (!instance || instance === this.knownEndpointsFrom) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
this.knownEndpointsFrom = instance;
|
|
116
|
+
const routes = Object.values(instance.api ?? {}).map((endpoint) => (endpoint as { path?: unknown })?.path);
|
|
117
|
+
this.rateLimiter.setKnownEndpoints([...routes, ...CONTROLLER_HANDLED_PATHS]);
|
|
118
|
+
}
|
|
119
|
+
|
|
94
120
|
/**
|
|
95
121
|
* Add standard rate limit headers to response
|
|
96
122
|
*/
|
|
@@ -2,6 +2,7 @@ import { Injectable, Logger, Optional } from '@nestjs/common';
|
|
|
2
2
|
|
|
3
3
|
import { IBetterAuthRateLimit } from '../../common/interfaces/server-options.interface';
|
|
4
4
|
import { CoreRedisService } from '../../common/services/core-redis.service';
|
|
5
|
+
import { canonicalRequestPath, pathContainsSegments } from './core-better-auth-path-guard.middleware';
|
|
5
6
|
import {
|
|
6
7
|
InMemoryRateLimitStore,
|
|
7
8
|
rateLimitKey,
|
|
@@ -134,10 +135,10 @@ export class CoreBetterAuthRateLimiter {
|
|
|
134
135
|
* Check if a request is allowed under the rate limit
|
|
135
136
|
*
|
|
136
137
|
* @param ip - Client IP address
|
|
137
|
-
* @param
|
|
138
|
+
* @param requestPath - Request path (relative to basePath), as sent; dot segments are resolved here
|
|
138
139
|
* @returns Rate limit check result
|
|
139
140
|
*/
|
|
140
|
-
async check(ip: string,
|
|
141
|
+
async check(ip: string, requestPath: string): Promise<RateLimitResult> {
|
|
141
142
|
// If rate limiting is disabled, always allow
|
|
142
143
|
if (!this.config.enabled) {
|
|
143
144
|
return {
|
|
@@ -149,6 +150,13 @@ export class CoreBetterAuthRateLimiter {
|
|
|
149
150
|
};
|
|
150
151
|
}
|
|
151
152
|
|
|
153
|
+
// Decide on the path the request is served under, not the one as sent: `/callback/../sign-in/email` reaches the
|
|
154
|
+
// sign-in handler, so it must not be skipped as a callback (CoreBetterAuthPathGuardMiddleware refuses such paths
|
|
155
|
+
// before they get here; this keeps the limiter correct where that guard is not registered). Lower-cased because
|
|
156
|
+
// Express routes case-insensitively: `/sign-in/EMAIL` is the same sign-in and must share its counter and its
|
|
157
|
+
// strict limit
|
|
158
|
+
const path = canonicalRequestPath(requestPath).toLowerCase();
|
|
159
|
+
|
|
152
160
|
// Check if this endpoint should skip rate limiting
|
|
153
161
|
if (this.shouldSkip(path)) {
|
|
154
162
|
return {
|
|
@@ -249,10 +257,11 @@ export class CoreBetterAuthRateLimiter {
|
|
|
249
257
|
}
|
|
250
258
|
|
|
251
259
|
/**
|
|
252
|
-
* Determine if an endpoint should skip rate limiting
|
|
260
|
+
* Determine if an endpoint should skip rate limiting: an entry matches whole path segments, so `/session` skips
|
|
261
|
+
* `/session` but not `/sessions-export`
|
|
253
262
|
*/
|
|
254
263
|
private shouldSkip(path: string): boolean {
|
|
255
|
-
return this.config.skipEndpoints.some((skip) => path
|
|
264
|
+
return this.config.skipEndpoints.some((skip) => pathContainsSegments(path, skip.toLowerCase()));
|
|
256
265
|
}
|
|
257
266
|
|
|
258
267
|
/**
|
|
@@ -260,9 +269,7 @@ export class CoreBetterAuthRateLimiter {
|
|
|
260
269
|
* Strict endpoints get half the normal limit
|
|
261
270
|
*/
|
|
262
271
|
private getLimit(path: string): number {
|
|
263
|
-
const isStrict = this.config.strictEndpoints.some(
|
|
264
|
-
(strict) => path === strict || path.endsWith(strict) || path.includes(strict),
|
|
265
|
-
);
|
|
272
|
+
const isStrict = this.config.strictEndpoints.some((strict) => pathContainsSegments(path, strict.toLowerCase()));
|
|
266
273
|
|
|
267
274
|
return isStrict ? Math.ceil(this.config.max / 2) : this.config.max;
|
|
268
275
|
}
|
|
@@ -281,7 +288,36 @@ export class CoreBetterAuthRateLimiter {
|
|
|
281
288
|
}
|
|
282
289
|
|
|
283
290
|
/**
|
|
284
|
-
*
|
|
291
|
+
* The route names the base path serves: the last static segment of every route Better-Auth and the controller
|
|
292
|
+
* answer (`/sign-in/email` → `email`, `/two-factor/enable` → `enable`). Set by CoreBetterAuthRateLimitMiddleware from
|
|
293
|
+
* the running instance. A counter is keyed by one of these names, so a client cannot create counters of its own.
|
|
294
|
+
*/
|
|
295
|
+
protected knownEndpoints: null | ReadonlySet<string> = null;
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Record the routes the base path serves (paths relative to it, `:param` segments allowed). Only their last static
|
|
299
|
+
* segment counts.
|
|
300
|
+
*/
|
|
301
|
+
setKnownEndpoints(paths: Iterable<unknown>): void {
|
|
302
|
+
const names = new Set<string>();
|
|
303
|
+
for (const path of paths) {
|
|
304
|
+
if (typeof path !== 'string') {
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
const last = path.split('?')[0].split('/').filter(Boolean).pop();
|
|
308
|
+
if (last && !last.startsWith(':')) {
|
|
309
|
+
names.add(last.toLowerCase());
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
this.knownEndpoints = names;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Normalize endpoint path for consistent grouping. The result comes from a bounded set — a known route name, a
|
|
317
|
+
* configured strict entry, `callback` or `other` — never from the request alone: keyed by the raw last segment, one
|
|
318
|
+
* client sending `/iam/x1`, `/iam/x2`, … created one counter per path, none of them ever reached the limit, and once
|
|
319
|
+
* the store held `maxEntries` counters every new client fell into the overflow buckets the attacker had filled, and
|
|
320
|
+
* was refused at its first sign-in.
|
|
285
321
|
*/
|
|
286
322
|
private normalizeEndpoint(path: string): string {
|
|
287
323
|
// Remove query strings
|
|
@@ -292,9 +328,21 @@ export class CoreBetterAuthRateLimiter {
|
|
|
292
328
|
return 'callback';
|
|
293
329
|
}
|
|
294
330
|
|
|
295
|
-
//
|
|
331
|
+
// The last segment, when it names a route the base path serves
|
|
296
332
|
const segments = cleanPath.split('/').filter(Boolean);
|
|
297
|
-
|
|
333
|
+
const last = segments[segments.length - 1];
|
|
334
|
+
if (last && this.knownEndpoints?.has(last)) {
|
|
335
|
+
return last;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// A strict route under a name nobody serves (`/reset-password/<token>`, `/sign-in/<anything>`) keeps its own counter
|
|
339
|
+
const strict = this.config.strictEndpoints.find((entry) => pathContainsSegments(cleanPath, entry.toLowerCase()));
|
|
340
|
+
if (strict) {
|
|
341
|
+
return `strict:${strict.toLowerCase()}`;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// Everything else of one client shares one counter, as every IAM request did before the per-route split
|
|
345
|
+
return 'other';
|
|
298
346
|
}
|
|
299
347
|
|
|
300
348
|
/**
|
|
@@ -166,6 +166,29 @@ export class CoreBetterAuthUserMapper {
|
|
|
166
166
|
* @param sessionUser - The Better-Auth session user
|
|
167
167
|
* @returns A mapped user with role capabilities
|
|
168
168
|
*/
|
|
169
|
+
/**
|
|
170
|
+
* The mapped user of a Better-Auth user that is stored nowhere, from its own fields only (11.44.1).
|
|
171
|
+
*
|
|
172
|
+
* The placeholder Better-Auth answers a sign-up for an already registered address with (see
|
|
173
|
+
* `CoreBetterAuthService.isPersistedUser()`) must look like a new user: its own id, no roles, not verified. Looking it
|
|
174
|
+
* up by address, as {@link mapSessionUser} does, found the real account and answered its id and roles.
|
|
175
|
+
*/
|
|
176
|
+
mapUnstoredSessionUser(sessionUser: BetterAuthSessionUser): MappedUser | null {
|
|
177
|
+
if (!sessionUser?.id || !sessionUser?.email) {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
return this.createMappedUser({
|
|
181
|
+
email: sessionUser.email,
|
|
182
|
+
emailVerified: sessionUser.emailVerified,
|
|
183
|
+
iamId: sessionUser.id,
|
|
184
|
+
id: sessionUser.id,
|
|
185
|
+
image: sessionUser.image,
|
|
186
|
+
name: sessionUser.name,
|
|
187
|
+
roles: [],
|
|
188
|
+
verified: sessionUser.emailVerified,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
169
192
|
async mapSessionUser(sessionUser: BetterAuthSessionUser): Promise<MappedUser | null> {
|
|
170
193
|
if (!sessionUser?.id || !sessionUser?.email) {
|
|
171
194
|
return null;
|
|
@@ -332,6 +355,24 @@ export class CoreBetterAuthUserMapper {
|
|
|
332
355
|
* @param plainPassword - The plain password to hash with bcrypt
|
|
333
356
|
* @returns true if sync was successful, false otherwise
|
|
334
357
|
*/
|
|
358
|
+
/**
|
|
359
|
+
* Spends the time {@link syncPasswordToLegacy} spends on a password, and writes nothing (11.44.1).
|
|
360
|
+
*
|
|
361
|
+
* A sign-up for an already registered address writes nothing (see `CoreBetterAuthService.isPersistedUser()`).
|
|
362
|
+
* Without this it would answer a bcrypt round faster than a real sign-up, and the response time would tell which
|
|
363
|
+
* addresses have an account — the enumeration Better-Auth's placeholder answer exists to prevent.
|
|
364
|
+
*/
|
|
365
|
+
async equalizeLegacyPasswordSync(plainPassword?: string): Promise<void> {
|
|
366
|
+
if (!plainPassword) {
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
try {
|
|
370
|
+
await bcrypt.hash(this.normalizePasswordForIam(plainPassword), 10);
|
|
371
|
+
} catch {
|
|
372
|
+
// Timing only — nothing depends on the result
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
335
376
|
async syncPasswordToLegacy(iamUserId: string, userEmail: string, plainPassword?: string): Promise<boolean> {
|
|
336
377
|
if (!this.connection) {
|
|
337
378
|
this.logger.warn('No database connection available - cannot sync password to legacy');
|
|
@@ -584,17 +584,31 @@ export class CoreBetterAuthController {
|
|
|
584
584
|
}
|
|
585
585
|
|
|
586
586
|
if (hasUser(response)) {
|
|
587
|
-
//
|
|
588
|
-
//
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
587
|
+
// An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
|
|
588
|
+
// like a new sign-up, with a placeholder user it never stored (enumeration protection). Linking that user
|
|
589
|
+
// re-pointed the real account found by address and overwrote its legacy password with the caller's (11.44.1).
|
|
590
|
+
// The answer below stays that of a new sign-up; only the writes are left out.
|
|
591
|
+
const isPlaceholder = !(await this.betterAuthService.isPersistedUser(response.user.id));
|
|
592
|
+
|
|
593
|
+
if (isPlaceholder) {
|
|
594
|
+
// The same bcrypt round as the legacy sync, so the response time does not tell the address exists
|
|
595
|
+
await this.userMapper.equalizeLegacyPasswordSync(input.password);
|
|
596
|
+
} else {
|
|
597
|
+
// Link or create user in our database
|
|
598
|
+
// Pass termsAndPrivacyAccepted to store the acceptance timestamp
|
|
599
|
+
await this.userMapper.linkOrCreateUser(response.user, {
|
|
600
|
+
termsAndPrivacyAccepted: input.termsAndPrivacyAccepted,
|
|
601
|
+
});
|
|
602
|
+
|
|
603
|
+
// Sync password to legacy (enables IAM Sign-Up → Legacy Sign-In)
|
|
604
|
+
// Pass the plain password so it can be hashed with bcrypt for Legacy Auth
|
|
605
|
+
await this.userMapper.syncPasswordToLegacy(response.user.id, response.user.email, input.password);
|
|
606
|
+
}
|
|
596
607
|
|
|
597
|
-
|
|
608
|
+
// A new user has no roles yet; the placeholder must not carry those of the account it stands for
|
|
609
|
+
const mappedUser = isPlaceholder
|
|
610
|
+
? this.userMapper.mapUnstoredSessionUser(response.user)
|
|
611
|
+
: await this.userMapper.mapSessionUser(response.user);
|
|
598
612
|
|
|
599
613
|
// Get token: JWT accessToken > top-level token > session.token
|
|
600
614
|
// Without this, no session cookies are set after sign-up, causing 401 on
|
|
@@ -32,6 +32,7 @@ import { DefaultBetterAuthResolver } from './better-auth.resolver';
|
|
|
32
32
|
import { CoreBetterAuthApiMiddleware } from './core-better-auth-api.middleware';
|
|
33
33
|
import { CoreBetterAuthChallengeService } from './core-better-auth-challenge.service';
|
|
34
34
|
import { CoreBetterAuthEmailVerificationService } from './core-better-auth-email-verification.service';
|
|
35
|
+
import { CoreBetterAuthPathGuardMiddleware } from './core-better-auth-path-guard.middleware';
|
|
35
36
|
import { CoreBetterAuthRateLimitMiddleware } from './core-better-auth-rate-limit.middleware';
|
|
36
37
|
import { CoreBetterAuthRateLimiter } from './core-better-auth-rate-limiter.service';
|
|
37
38
|
import { revokeApiTokensOfUser } from '../api-token/core-api-token.registry';
|
|
@@ -422,8 +423,10 @@ export class CoreBetterAuthModule implements NestModule, OnModuleInit {
|
|
|
422
423
|
* 1. CoreBetterAuthMiddleware - Session validation and user mapping for all routes
|
|
423
424
|
* Must run FIRST so that req.betterAuthSession is available for downstream middleware.
|
|
424
425
|
* In JWT mode, this resolves the JWT to a real DB session (via getActiveSessionForUser).
|
|
425
|
-
* 2.
|
|
426
|
-
*
|
|
426
|
+
* 2. CoreBetterAuthPathGuardMiddleware - Refuses a non-canonical path under the base path (400), before
|
|
427
|
+
* anything below reads it
|
|
428
|
+
* 3. CoreBetterAuthRateLimitMiddleware - Rate limiting for auth endpoints
|
|
429
|
+
* 4. CoreBetterAuthApiMiddleware - Forwards plugin endpoints (passkey, 2FA, etc.) to Better Auth's native handler
|
|
427
430
|
* Runs AFTER session middleware so it can use req.betterAuthSession.session.token
|
|
428
431
|
* to authenticate requests in JWT mode.
|
|
429
432
|
*/
|
|
@@ -442,6 +445,13 @@ export class CoreBetterAuthModule implements NestModule, OnModuleInit {
|
|
|
442
445
|
consumer.apply(CoreBetterAuthMiddleware).forRoutes('(.*)'); // New path-to-regexp syntax for wildcard
|
|
443
446
|
CoreBetterAuthModule.logger.debug('CoreBetterAuthMiddleware registered for all routes');
|
|
444
447
|
|
|
448
|
+
// Refuse a non-canonical path (`.` / `..` segments, also encoded, backslashes, encoded slashes) before anything
|
|
449
|
+
// under the base path reads it: every check below reads the path as SENT, while Better-Auth routes the one
|
|
450
|
+
// `new URL()` resolved — `/callback/../sign-in/email` would pass the rate limiter as a callback and run as a
|
|
451
|
+
// sign-in. Registered unconditionally and FIRST, so it guards the limiter, the controller routes and the
|
|
452
|
+
// forwarding alike.
|
|
453
|
+
consumer.apply(CoreBetterAuthPathGuardMiddleware).forRoutes(`${basePath}/*path`);
|
|
454
|
+
|
|
445
455
|
// Apply rate limiting to Better-Auth endpoints only.
|
|
446
456
|
// Mirrors the "presence implies enabled" contract `CoreBetterAuthRateLimiter.configure()`
|
|
447
457
|
// implements. Gating the MOUNT on `.enabled` alone made that fix unobservable: the limiter
|
|
@@ -483,10 +483,20 @@ export class CoreBetterAuthResolver {
|
|
|
483
483
|
if (hasUser(response)) {
|
|
484
484
|
const sessionUser: BetterAuthSessionUser = response.user;
|
|
485
485
|
|
|
486
|
+
// An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
|
|
487
|
+
// like a new sign-up, with a placeholder user it never stored (enumeration protection). Linking that user
|
|
488
|
+
// re-pointed the real account found by address, and the answer carried that account's id and roles (11.44.1).
|
|
489
|
+
// The answer stays that of a new sign-up; only the write is left out.
|
|
490
|
+
const isPlaceholder = !(await this.betterAuthService.isPersistedUser(sessionUser.id));
|
|
491
|
+
|
|
486
492
|
// Link or create user in our database
|
|
487
493
|
// Pass termsAndPrivacyAccepted to store the acceptance timestamp
|
|
488
|
-
|
|
489
|
-
|
|
494
|
+
if (!isPlaceholder) {
|
|
495
|
+
await this.userMapper.linkOrCreateUser(sessionUser, { termsAndPrivacyAccepted });
|
|
496
|
+
}
|
|
497
|
+
const mappedUser = isPlaceholder
|
|
498
|
+
? this.userMapper.mapUnstoredSessionUser(sessionUser)
|
|
499
|
+
: await this.userMapper.mapSessionUser(sessionUser);
|
|
490
500
|
|
|
491
501
|
// If email verification is enabled, revoke the session and don't return session data
|
|
492
502
|
// The user must verify their email before they can use any session
|
|
@@ -1068,6 +1068,34 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
|
|
|
1068
1068
|
}
|
|
1069
1069
|
}
|
|
1070
1070
|
|
|
1071
|
+
/**
|
|
1072
|
+
* Whether Better-Auth has stored the user `userId` — false for the placeholder it answers a sign-up with when the
|
|
1073
|
+
* address is already registered (11.44.1).
|
|
1074
|
+
*
|
|
1075
|
+
* With `emailAndPassword.requireEmailVerification: true` or `autoSignIn: false`, Better-Auth answers a sign-up for a
|
|
1076
|
+
* known address like a new one (enumeration protection): `{ token: null, user: <a generated id, the given address> }`.
|
|
1077
|
+
* That user exists nowhere. The sign-up paths linked it to the app user found by address — the real account then
|
|
1078
|
+
* carried the placeholder's id and `verified: false`, its legacy password became the one the caller chose, and the
|
|
1079
|
+
* answer carried its roles. A sign-up therefore writes only for a user this confirms. Asked through Better-Auth's own
|
|
1080
|
+
* adapter (`internalAdapter.findUserById()`), so it reads wherever Better-Auth keeps its users.
|
|
1081
|
+
*
|
|
1082
|
+
* @returns `false` for an unknown id, an empty id, and a failed lookup — a sign-up that cannot confirm the user writes
|
|
1083
|
+
* nothing rather than guessing
|
|
1084
|
+
*/
|
|
1085
|
+
async isPersistedUser(userId: string): Promise<boolean> {
|
|
1086
|
+
if (typeof userId !== 'string' || !userId) {
|
|
1087
|
+
return false;
|
|
1088
|
+
}
|
|
1089
|
+
try {
|
|
1090
|
+
const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
|
|
1091
|
+
const user: unknown = await context?.internalAdapter?.findUserById?.(userId);
|
|
1092
|
+
return !!user && String((user as { id?: unknown }).id) === userId;
|
|
1093
|
+
} catch (error) {
|
|
1094
|
+
this.logger.error(`isPersistedUser error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
1095
|
+
return false;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1071
1099
|
/**
|
|
1072
1100
|
* Revokes a specific session (logout for that session)
|
|
1073
1101
|
*
|
|
@@ -34,6 +34,7 @@ export * from './core-better-auth-email-verification.service';
|
|
|
34
34
|
export * from './core-better-auth-error-codes.helper';
|
|
35
35
|
export * from './core-better-auth-migration-status.model';
|
|
36
36
|
export * from './core-better-auth-models';
|
|
37
|
+
export * from './core-better-auth-path-guard.middleware';
|
|
37
38
|
export * from './core-better-auth-rate-limit.middleware';
|
|
38
39
|
export * from './core-better-auth-rate-limiter.service';
|
|
39
40
|
export * from './core-better-auth-signup-validator.service';
|
|
@@ -493,6 +493,15 @@ export const LtnsErrors = {
|
|
|
493
493
|
},
|
|
494
494
|
},
|
|
495
495
|
|
|
496
|
+
INVALID_REQUEST_PATH: {
|
|
497
|
+
code: 'LTNS_0305',
|
|
498
|
+
message: 'Invalid request path',
|
|
499
|
+
translations: {
|
|
500
|
+
de: 'Der Anfragepfad ist ungültig.',
|
|
501
|
+
en: 'The request path is invalid.',
|
|
502
|
+
},
|
|
503
|
+
},
|
|
504
|
+
|
|
496
505
|
/**
|
|
497
506
|
* An object arrived where the route declares a string, number or boolean (`@Body('token') token: string`) — the
|
|
498
507
|
* shape a MongoDB operator takes (`{ "$ne": null }`). Answered by `MapAndValidatePipe` (11.44.0 / 12.8.0, DEV-4144).
|
|
@@ -697,8 +697,16 @@ export abstract class CoreUserService<
|
|
|
697
697
|
// Perform the update
|
|
698
698
|
const updatedUser = await super.update(id, input, serviceOptions);
|
|
699
699
|
|
|
700
|
-
// Sync email change to IAM if email was changed and mapper is available
|
|
701
|
-
|
|
700
|
+
// Sync email change to IAM if email was changed and mapper is available. Compared the way the address is stored
|
|
701
|
+
// (trimmed, lower case): `Foo@Example.com` for `foo@example.com` changes nothing, and the sync would end every
|
|
702
|
+
// session of the account for it.
|
|
703
|
+
const normalizeEmail = (value: unknown) => (typeof value === 'string' ? value.trim().toLowerCase() : value);
|
|
704
|
+
if (
|
|
705
|
+
this.options?.betterAuthUserMapper &&
|
|
706
|
+
oldEmail &&
|
|
707
|
+
input.email &&
|
|
708
|
+
normalizeEmail(oldEmail) !== normalizeEmail(input.email)
|
|
709
|
+
) {
|
|
702
710
|
try {
|
|
703
711
|
await this.options.betterAuthUserMapper.syncEmailChangeFromLegacy(oldEmail, input.email);
|
|
704
712
|
this.userServiceLogger.debug(`Synced email change from Legacy to IAM: ${oldEmail} → ${input.email}`);
|