@lenne.tech/nest-server 12.14.0 → 12.15.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/.claude/rules/better-auth.md +6 -3
- package/.claude/rules/configurable-features.md +1 -0
- package/.claude/rules/persistence.md +23 -0
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/persistence/sql/mysql/mysql-executor.js +6 -1
- package/dist/core/common/persistence/sql/mysql/mysql-executor.js.map +1 -1
- package/dist/core/common/persistence/sql/mysql/mysql-transport.d.ts +9 -0
- package/dist/core/common/persistence/sql/mysql/mysql-transport.js +42 -0
- package/dist/core/common/persistence/sql/mysql/mysql-transport.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.d.ts +21 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.js +106 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-rejection.helper.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth.service.d.ts +4 -1
- package/dist/core/modules/better-auth/core-better-auth.service.js +25 -7
- 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/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/docs/choosing-a-database.md +8 -0
- package/migration-guides/12.13.x-to-12.14.x.md +3 -3
- package/migration-guides/12.14.0-to-12.14.1.md +63 -0
- package/migration-guides/12.14.x-to-12.15.x.md +102 -0
- package/package.json +9 -9
- package/src/core/common/helpers/meta.helper.ts +2 -2
- package/src/core/common/persistence/sql/mysql/mysql-executor.ts +8 -1
- package/src/core/common/persistence/sql/mysql/mysql-transport.ts +91 -0
- package/src/core/modules/better-auth/README.md +4 -1
- package/src/core/modules/better-auth/core-better-auth-jwt-rejection.helper.ts +164 -0
- package/src/core/modules/better-auth/core-better-auth.service.ts +50 -6
- package/src/core/modules/better-auth/index.ts +1 -0
- package/src/index.ts +1 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { isLocalEnv } from '../../../helpers/cookies.helper.js';
|
|
2
|
+
import { ConfigService } from '../../../services/config.service.js';
|
|
3
|
+
import { redactUrl } from '../../data-source.config.js';
|
|
4
|
+
import type { MysqlVariant } from './mysql-session.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* How the password travels on a MySQL connection without TLS (12.15.0).
|
|
8
|
+
*
|
|
9
|
+
* MySQL 8.4 signs accounts in with `caching_sha2_password`. While the server holds the account in its cache, a scrambled
|
|
10
|
+
* proof suffices; the first login after a restart (or `FLUSH PRIVILEGES`, a password change) needs the password itself.
|
|
11
|
+
* Without TLS the client encrypts it with the server's RSA public key — and mysql2 up to 3.25 fetched that key from
|
|
12
|
+
* whoever answered, so a host in the network path could hand out its own key and read the password
|
|
13
|
+
* (GHSA-cc6q-ch5m-cffx). mysql2 3.26 refuses the fetch unless TLS, a socket path, a pinned key (`serverPublicKey`) or
|
|
14
|
+
* `allowPublicKeyRetrieval: true` allows it, and the login fails with `PUBLIC_KEY_RETRIEVAL_NOT_ALLOWED`. While the
|
|
15
|
+
* cache is warm everything works, so the failure surfaces only after the next MySQL restart.
|
|
16
|
+
*
|
|
17
|
+
* The framework therefore decides once, for every connection it opens:
|
|
18
|
+
*
|
|
19
|
+
* | The URL says … | `local` / `ci` / `e2e` | every other environment |
|
|
20
|
+
* |---|---|---|
|
|
21
|
+
* | `ssl`, `socketPath`, `serverPublicKey` or `allowPublicKeyRetrieval` | the URL decides | the URL decides |
|
|
22
|
+
* | nothing | key retrieval allowed (no one sits in the path of a developer's or a runner's own network) | **refused at once** on MySQL, naming the ways out; MariaDB (`mysql_native_password` by default) is left alone |
|
|
23
|
+
*
|
|
24
|
+
* `?allowPublicKeyRetrieval=false` is the explicit answer for an account that needs no RSA key
|
|
25
|
+
* (`mysql_native_password`): it silences the refusal and allows nothing.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** URL parameters with which a project states how the password travels on a connection without TLS */
|
|
29
|
+
export const MYSQL_TRANSPORT_PARAMETERS = ['allowPublicKeyRetrieval', 'serverPublicKey', 'socketPath', 'ssl'] as const;
|
|
30
|
+
|
|
31
|
+
/** A deployed MySQL source whose URL does not say how the password travels (12.15.0) */
|
|
32
|
+
export class MysqlTransportUndecidedError extends Error {
|
|
33
|
+
override readonly name = 'MysqlTransportUndecidedError';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The environment the running configuration names, else `NODE_ENV` (the migrate CLI runs without a configuration); an
|
|
38
|
+
* unset `NODE_ENV` means `local`, as in `getEnvironmentConfig()`
|
|
39
|
+
*/
|
|
40
|
+
export function currentMysqlEnvironment(): string {
|
|
41
|
+
return ConfigService.configFastButReadOnly?.env || process.env.NODE_ENV || 'local';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The option the framework adds to a connection's options: `allowPublicKeyRetrieval: true` in `local` / `ci` / `e2e`
|
|
46
|
+
* when the URL states nothing, otherwise none — the URL's own parameters reach mysql2 unchanged and decide. Throws
|
|
47
|
+
* `MysqlTransportUndecidedError` for a MySQL URL that states nothing on any other environment.
|
|
48
|
+
*
|
|
49
|
+
* @param url - the source's URL (`mysql://` or `mariadb://`)
|
|
50
|
+
* @param variant - the server the URL reaches
|
|
51
|
+
* @param env - the configured environment; defaults to the running one
|
|
52
|
+
*/
|
|
53
|
+
export function mysqlKeyRetrievalOption(
|
|
54
|
+
url: string,
|
|
55
|
+
variant: MysqlVariant,
|
|
56
|
+
env: string | undefined = currentMysqlEnvironment(),
|
|
57
|
+
): { allowPublicKeyRetrieval?: true } {
|
|
58
|
+
const stated = statedTransportParameters(url);
|
|
59
|
+
if (stated === null || stated.length > 0) {
|
|
60
|
+
// The URL decides (an unparsable URL fails in the driver with its own message)
|
|
61
|
+
return {};
|
|
62
|
+
}
|
|
63
|
+
if (isLocalEnv(env)) {
|
|
64
|
+
return { allowPublicKeyRetrieval: true };
|
|
65
|
+
}
|
|
66
|
+
if (variant === 'mysql') {
|
|
67
|
+
throw new MysqlTransportUndecidedError(
|
|
68
|
+
`The MySQL source ${redactUrl(url)} does not say how the password travels, and the environment ` +
|
|
69
|
+
`"${env ?? ''}" is not local. mysql2 fetches the server's RSA key over a connection without TLS only when ` +
|
|
70
|
+
'allowed, so the first login after the next MySQL restart would fail with PUBLIC_KEY_RETRIEVAL_NOT_ALLOWED. ' +
|
|
71
|
+
'Add one parameter to the URL: ?ssl={"rejectUnauthorized":true,"verifyIdentity":true} (TLS, recommended: verifyIdentity makes mysql2 ' +
|
|
72
|
+
'check that the certificate names the URL host, which must be a DNS name; with your CA add "ca":"<PEM>"), ' +
|
|
73
|
+
"?serverPublicKey=<PEM of the server's RSA public key>, " +
|
|
74
|
+
'?allowPublicKeyRetrieval=true (accepts that a host in the network path can read the password), or ' +
|
|
75
|
+
'?allowPublicKeyRetrieval=false when the account does not use caching_sha2_password. ' +
|
|
76
|
+
'See migration-guides/12.14.x-to-12.15.x.md.',
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
return {};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The transport parameters the URL carries, or `null` when it cannot be parsed */
|
|
83
|
+
function statedTransportParameters(url: string): null | string[] {
|
|
84
|
+
let parameters: URLSearchParams;
|
|
85
|
+
try {
|
|
86
|
+
parameters = new URL(url).searchParams;
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
return MYSQL_TRANSPORT_PARAMETERS.filter((name) => parameters.has(name));
|
|
91
|
+
}
|
|
@@ -221,8 +221,11 @@ Read the security section below for production deployments.
|
|
|
221
221
|
https://your-domain.com/iam/callback/google
|
|
222
222
|
```
|
|
223
223
|
- **CORS Origin Validation**: If no `trustedOrigins` are set, `baseUrl` is used as the trusted origin
|
|
224
|
+
- **JWT issuer and audience**: Bearer JWTs are accepted only with this origin as `iss` and `aud`. A token issued for
|
|
225
|
+
another base URL (an old domain, another stage) is rejected; since 12.14.1 the rejection logs a warning naming the
|
|
226
|
+
expected and the received issuer, at most once per hour and issuer (`core-better-auth-jwt-rejection.helper.ts`)
|
|
224
227
|
|
|
225
|
-
**Impact of incorrect value:** Email links point to wrong server, OAuth callbacks fail.
|
|
228
|
+
**Impact of incorrect value:** Email links point to wrong server, OAuth callbacks fail, Bearer JWTs are rejected.
|
|
226
229
|
|
|
227
230
|
### Base Path (`basePath`)
|
|
228
231
|
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import type { Request } from 'express';
|
|
2
|
+
import { decodeJwt } from 'jose';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Facts about the request that carried a JWT, used to find the source of a rejected token. Never the token itself and
|
|
6
|
+
* never the user it names.
|
|
7
|
+
*/
|
|
8
|
+
export interface JwtVerificationContext {
|
|
9
|
+
method?: string;
|
|
10
|
+
origin?: string;
|
|
11
|
+
path?: string;
|
|
12
|
+
userAgent?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Why a JWT was rejected, for the cases worth a warning (an expired token is routine and stays at debug level). */
|
|
16
|
+
export type JwtRejectionKind = 'invalid signature' | 'issuer or audience mismatch' | 'unknown signing key';
|
|
17
|
+
|
|
18
|
+
const USER_AGENT_MAX_LENGTH = 120;
|
|
19
|
+
const CLAIM_MAX_LENGTH = 200;
|
|
20
|
+
const KID_MAX_LENGTH = 40;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Whether a character can steer a terminal or a log viewer: C0 controls and DEL, the C1 controls (U+0080–U+009F, an
|
|
24
|
+
* 8-bit CSI/OSC moves the cursor, erases lines or injects a hyperlink in xterm-like terminals), the line and paragraph
|
|
25
|
+
* separators and the bidi controls (they reorder what an operator reads). Node hands header bytes 0x80–0x9F through as
|
|
26
|
+
* these characters, and a JSON `\u009b` in a token header decodes to one.
|
|
27
|
+
*/
|
|
28
|
+
function isUnsafeLogCharacter(code: number): boolean {
|
|
29
|
+
return (
|
|
30
|
+
code < 0x20 ||
|
|
31
|
+
(code >= 0x7f && code <= 0x9f) ||
|
|
32
|
+
code === 0x2028 ||
|
|
33
|
+
code === 0x2029 ||
|
|
34
|
+
(code >= 0x202a && code <= 0x202e) ||
|
|
35
|
+
(code >= 0x2066 && code <= 0x2069)
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Token claims and request headers are client-controlled: no control characters (log injection), bounded length. */
|
|
40
|
+
function clean(value: unknown, maxLength: number): string {
|
|
41
|
+
let result = '';
|
|
42
|
+
for (const char of String(value)) {
|
|
43
|
+
if (result.length >= maxLength) {
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
const code = char.codePointAt(0) ?? 0;
|
|
47
|
+
result += isUnsafeLogCharacter(code) ? '?' : char;
|
|
48
|
+
}
|
|
49
|
+
return result.slice(0, maxLength);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function header(req: Request, name: string): string | undefined {
|
|
53
|
+
const value = req.headers?.[name];
|
|
54
|
+
return Array.isArray(value) ? value[0] : value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The context of a request: method, path without query string, origin and a shortened user agent. */
|
|
58
|
+
export function jwtVerificationContextFromRequest(req: Request | undefined): JwtVerificationContext | undefined {
|
|
59
|
+
if (!req) {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
const url = req.originalUrl || req.url || '';
|
|
63
|
+
return {
|
|
64
|
+
method: req.method,
|
|
65
|
+
origin: header(req, 'origin'),
|
|
66
|
+
path: url.split('?')[0] || undefined,
|
|
67
|
+
userAgent: header(req, 'user-agent')?.slice(0, USER_AGENT_MAX_LENGTH),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function isoFromEpoch(seconds: unknown): string {
|
|
72
|
+
return typeof seconds === 'number' ? new Date(seconds * 1000).toISOString() : '-';
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The warning line for a rejected JWT and the key it is throttled under (12.14.1).
|
|
77
|
+
*
|
|
78
|
+
* For an issuer or audience mismatch it names the expected and the received issuer and audience, when the token was
|
|
79
|
+
* issued and when it expires, because those tell where a foreign token comes from. For a signature or key failure it
|
|
80
|
+
* names the key id. It never contains the token, the subject or any other claim.
|
|
81
|
+
*
|
|
82
|
+
* The key never holds a value the caller can choose freely, or rotating it would write one warning per request: the
|
|
83
|
+
* issuer is reported only for a token one of our keys signed, the key id of a signature failure is one of our stored
|
|
84
|
+
* keys, and an unknown key id is the caller's invention, so that kind is throttled as a whole.
|
|
85
|
+
*/
|
|
86
|
+
export function describeRejectedJwt(
|
|
87
|
+
kind: JwtRejectionKind,
|
|
88
|
+
token: string,
|
|
89
|
+
expected: string,
|
|
90
|
+
context?: JwtVerificationContext,
|
|
91
|
+
kid?: string,
|
|
92
|
+
): { key: string; message: string } {
|
|
93
|
+
const parts = [`JWT rejected (${kind})`];
|
|
94
|
+
let key: string;
|
|
95
|
+
if (kind === 'issuer or audience mismatch') {
|
|
96
|
+
let claims: Record<string, unknown> = {};
|
|
97
|
+
try {
|
|
98
|
+
claims = decodeJwt(token);
|
|
99
|
+
} catch {
|
|
100
|
+
// Undecodable payload: report what is known
|
|
101
|
+
}
|
|
102
|
+
const iss = claims.iss === undefined ? '-' : clean(claims.iss, CLAIM_MAX_LENGTH);
|
|
103
|
+
const aud = Array.isArray(claims.aud) ? claims.aud.join(',') : (claims.aud ?? '-');
|
|
104
|
+
const expired = typeof claims.exp === 'number' && claims.exp * 1000 < Date.now();
|
|
105
|
+
parts.push(`expected "${expected}", got iss "${iss}", aud "${clean(aud, CLAIM_MAX_LENGTH)}"`);
|
|
106
|
+
parts.push(`issued ${isoFromEpoch(claims.iat)}, expires ${isoFromEpoch(claims.exp)}${expired ? ' (expired)' : ''}`);
|
|
107
|
+
key = `${kind}|${iss}`;
|
|
108
|
+
} else {
|
|
109
|
+
const safeKid = kid === undefined ? '-' : clean(kid, KID_MAX_LENGTH);
|
|
110
|
+
parts.push(`kid "${safeKid}"`);
|
|
111
|
+
key = kind === 'unknown signing key' ? kind : `${kind}|${safeKid}`;
|
|
112
|
+
}
|
|
113
|
+
if (context?.method || context?.path) {
|
|
114
|
+
parts.push(`${clean(context.method ?? '?', 10)} ${clean(context.path ?? '?', CLAIM_MAX_LENGTH)}`);
|
|
115
|
+
}
|
|
116
|
+
if (context?.origin) {
|
|
117
|
+
parts.push(`origin ${clean(context.origin, CLAIM_MAX_LENGTH)}`);
|
|
118
|
+
}
|
|
119
|
+
if (context?.userAgent) {
|
|
120
|
+
parts.push(`ua "${clean(context.userAgent, USER_AGENT_MAX_LENGTH)}"`);
|
|
121
|
+
}
|
|
122
|
+
return { key, message: parts.join('; ') };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Lets one warning per key through per window and counts the ones it holds back, so a client that sends the same bad
|
|
127
|
+
* token with every request cannot flood the log. The map is capped: when it is full, entries whose window has passed
|
|
128
|
+
* are dropped, and a key that still finds no room shares one overflow entry. A full map never resets the keys it holds,
|
|
129
|
+
* so nobody can reopen the warning of a real issuer by filling the map with others.
|
|
130
|
+
*/
|
|
131
|
+
export class JwtRejectionThrottle {
|
|
132
|
+
private static readonly OVERFLOW_KEY = '*';
|
|
133
|
+
private readonly seen = new Map<string, { lastAt: number; suppressed: number }>();
|
|
134
|
+
|
|
135
|
+
constructor(
|
|
136
|
+
private readonly windowMs = 60 * 60 * 1000,
|
|
137
|
+
private readonly maxKeys = 500,
|
|
138
|
+
) {}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @returns the number of occurrences held back since the last warning for this key, or `null` when this one is
|
|
142
|
+
* held back as well
|
|
143
|
+
*/
|
|
144
|
+
take(key: string): null | number {
|
|
145
|
+
const now = Date.now();
|
|
146
|
+
if (!this.seen.has(key) && this.seen.size >= this.maxKeys) {
|
|
147
|
+
for (const [seenKey, seenEntry] of this.seen) {
|
|
148
|
+
if (now - seenEntry.lastAt >= this.windowMs) {
|
|
149
|
+
this.seen.delete(seenKey);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (this.seen.size >= this.maxKeys) {
|
|
153
|
+
key = JwtRejectionThrottle.OVERFLOW_KEY;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const entry = this.seen.get(key);
|
|
157
|
+
if (entry && now - entry.lastAt < this.windowMs) {
|
|
158
|
+
entry.suppressed += 1;
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
this.seen.set(key, { lastAt: now, suppressed: 0 });
|
|
162
|
+
return entry?.suppressed ?? 0;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
} from 'better-auth/api';
|
|
18
18
|
import { Request } from 'express';
|
|
19
19
|
import type { Response as ExpressResponse } from 'express';
|
|
20
|
-
import { importJWK, jwtVerify } from 'jose';
|
|
20
|
+
import { errors as joseErrors, importJWK, jwtVerify } from 'jose';
|
|
21
21
|
import type { Connection } from 'mongoose';
|
|
22
22
|
|
|
23
23
|
import {
|
|
@@ -48,6 +48,13 @@ import {
|
|
|
48
48
|
isPasskeyConfigured,
|
|
49
49
|
isTwoFactorConfigured,
|
|
50
50
|
} from './core-better-auth-sign-in-factors.helper.js';
|
|
51
|
+
import {
|
|
52
|
+
describeRejectedJwt,
|
|
53
|
+
type JwtRejectionKind,
|
|
54
|
+
JwtRejectionThrottle,
|
|
55
|
+
type JwtVerificationContext,
|
|
56
|
+
jwtVerificationContextFromRequest,
|
|
57
|
+
} from './core-better-auth-jwt-rejection.helper.js';
|
|
51
58
|
import { isJwtShaped } from './core-better-auth-token.helper.js';
|
|
52
59
|
import { BetterAuthSessionUser } from './core-better-auth-user.mapper.js';
|
|
53
60
|
import { presentSessionTokens } from './core-better-auth-session-token.helper.js';
|
|
@@ -135,6 +142,8 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
135
142
|
// this cache a test or fork that mutates `process.env.COOKIE_PREFIX` after
|
|
136
143
|
// boot would push the service and the Better-Auth instance out of lockstep.
|
|
137
144
|
private cachedCookiePrefix: null | string = null;
|
|
145
|
+
// Rejected JWTs are warned about at most once per hour and issuer or stored key (12.14.1)
|
|
146
|
+
protected readonly jwtRejectionThrottle = new JwtRejectionThrottle();
|
|
138
147
|
|
|
139
148
|
constructor(
|
|
140
149
|
@Optional() @Inject(BETTER_AUTH_INSTANCE) private readonly authInstance: BetterAuthInstance | null,
|
|
@@ -1515,6 +1524,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1515
1524
|
* This enables stateless JWT verification without requiring a session cookie.
|
|
1516
1525
|
*
|
|
1517
1526
|
* @param token - The JWT token to verify (from Authorization header)
|
|
1527
|
+
* @param context - Optional facts about the request, named in the warning when the token is rejected (12.14.1)
|
|
1518
1528
|
* @returns The JWT payload with user info, or null if verification fails
|
|
1519
1529
|
*
|
|
1520
1530
|
* @example
|
|
@@ -1528,7 +1538,10 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1528
1538
|
* }
|
|
1529
1539
|
* ```
|
|
1530
1540
|
*/
|
|
1531
|
-
async verifyJwtToken(
|
|
1541
|
+
async verifyJwtToken(
|
|
1542
|
+
token: string,
|
|
1543
|
+
context?: JwtVerificationContext,
|
|
1544
|
+
): Promise<null | {
|
|
1532
1545
|
[key: string]: any;
|
|
1533
1546
|
email?: string;
|
|
1534
1547
|
sub: string;
|
|
@@ -1557,7 +1570,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1557
1570
|
payload = await this.verifyHs256Token(token);
|
|
1558
1571
|
} else if (kid) {
|
|
1559
1572
|
// For asymmetric algorithms (EdDSA, RS256, ES256), use JWKS — from MongoDB or the SQL source, whichever holds them
|
|
1560
|
-
payload = await this.verifyJwksToken(token, kid, alg);
|
|
1573
|
+
payload = await this.verifyJwksToken(token, kid, alg, context);
|
|
1561
1574
|
} else {
|
|
1562
1575
|
this.logger.debug(`JWT verification: unsupported algorithm=${alg} or missing kid`);
|
|
1563
1576
|
return null;
|
|
@@ -1739,6 +1752,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1739
1752
|
token: string,
|
|
1740
1753
|
kid: string,
|
|
1741
1754
|
alg: string,
|
|
1755
|
+
context?: JwtVerificationContext,
|
|
1742
1756
|
): Promise<null | {
|
|
1743
1757
|
[key: string]: any;
|
|
1744
1758
|
email?: string;
|
|
@@ -1756,7 +1770,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1756
1770
|
let keyRecord = sql ? await sql.findJwk(kid) : await jwksCollection?.findOne({ id: kid });
|
|
1757
1771
|
|
|
1758
1772
|
if (!keyRecord && sql) {
|
|
1759
|
-
this.
|
|
1773
|
+
this.reportRejectedJwt('unknown signing key', token, context, kid);
|
|
1760
1774
|
return null;
|
|
1761
1775
|
}
|
|
1762
1776
|
if (!keyRecord && jwksCollection) {
|
|
@@ -1764,7 +1778,7 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1764
1778
|
const allKeys = await jwksCollection.find({}).toArray();
|
|
1765
1779
|
const matchingKey = allKeys.find((k) => k.id === kid || k._id?.toString() === kid);
|
|
1766
1780
|
if (!matchingKey) {
|
|
1767
|
-
this.
|
|
1781
|
+
this.reportRejectedJwt('unknown signing key', token, context, kid);
|
|
1768
1782
|
return null;
|
|
1769
1783
|
}
|
|
1770
1784
|
keyRecord = matchingKey;
|
|
@@ -1794,11 +1808,41 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1794
1808
|
|
|
1795
1809
|
return payload as { [key: string]: any; email?: string; sub: string };
|
|
1796
1810
|
} catch (error) {
|
|
1811
|
+
// A token signed by our own key but issued for another address, a forged signature, or a token from an unknown
|
|
1812
|
+
// key points at a misconfiguration or an attack, so it is a warning. An expired token is routine (12.14.1).
|
|
1813
|
+
if (error instanceof joseErrors.JWTClaimValidationFailed && (error.claim === 'iss' || error.claim === 'aud')) {
|
|
1814
|
+
this.reportRejectedJwt('issuer or audience mismatch', token, context);
|
|
1815
|
+
return null;
|
|
1816
|
+
}
|
|
1817
|
+
if (error instanceof joseErrors.JWSSignatureVerificationFailed) {
|
|
1818
|
+
this.reportRejectedJwt('invalid signature', token, context, kid);
|
|
1819
|
+
return null;
|
|
1820
|
+
}
|
|
1797
1821
|
this.logger.debug(`JWKS verification error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
1798
1822
|
return null;
|
|
1799
1823
|
}
|
|
1800
1824
|
}
|
|
1801
1825
|
|
|
1826
|
+
/**
|
|
1827
|
+
* Warns about a rejected JWT with the facts needed to find its source (12.14.1): never the token, the subject or any
|
|
1828
|
+
* other claim beyond issuer, audience and times. Throttled to one warning per hour and issuer or stored key, and one
|
|
1829
|
+
* per hour in all for unknown key ids (the caller chooses those); the next warning names how many were held back. Before 12.14.1 every rejection was logged at debug level only, so a client
|
|
1830
|
+
* holding tokens of another issuer stayed invisible in production.
|
|
1831
|
+
*/
|
|
1832
|
+
protected reportRejectedJwt(
|
|
1833
|
+
kind: JwtRejectionKind,
|
|
1834
|
+
token: string,
|
|
1835
|
+
context?: JwtVerificationContext,
|
|
1836
|
+
kid?: string,
|
|
1837
|
+
): void {
|
|
1838
|
+
const { key, message } = describeRejectedJwt(kind, token, this.getBaseUrl(), context, kid);
|
|
1839
|
+
const suppressed = this.jwtRejectionThrottle.take(key);
|
|
1840
|
+
if (suppressed === null) {
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
this.logger.warn(suppressed > 0 ? `${message} (${suppressed} more since the last warning)` : message);
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1802
1846
|
/**
|
|
1803
1847
|
* Extracts and verifies a JWT token from a request's Authorization header,
|
|
1804
1848
|
* or verifies a directly provided token.
|
|
@@ -1823,6 +1867,6 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1823
1867
|
token = authHeader.substring(7);
|
|
1824
1868
|
}
|
|
1825
1869
|
|
|
1826
|
-
return this.verifyJwtToken(token);
|
|
1870
|
+
return this.verifyJwtToken(token, jwtVerificationContextFromRequest(req));
|
|
1827
1871
|
}
|
|
1828
1872
|
}
|
|
@@ -32,6 +32,7 @@ export * from './core-better-auth-auth.model.js';
|
|
|
32
32
|
export * from './core-better-auth-cookie.helper.js';
|
|
33
33
|
export * from './core-better-auth-email-verification.service.js';
|
|
34
34
|
export * from './core-better-auth-error-codes.helper.js';
|
|
35
|
+
export * from './core-better-auth-jwt-rejection.helper.js';
|
|
35
36
|
export * from './core-better-auth-migration-status.model.js';
|
|
36
37
|
export * from './core-better-auth-models.js';
|
|
37
38
|
export * from './core-better-auth-path-guard.middleware.js';
|
package/src/index.ts
CHANGED
|
@@ -113,6 +113,7 @@ export * from './core/common/persistence/sync-model.js';
|
|
|
113
113
|
export * from './core/common/persistence/unsupported-capability.error.js';
|
|
114
114
|
export * from './core/common/persistence/sql/mysql/mysql-data-store.js';
|
|
115
115
|
export * from './core/common/persistence/sql/mysql/mysql-lock-store.js';
|
|
116
|
+
export * from './core/common/persistence/sql/mysql/mysql-transport.js';
|
|
116
117
|
export * from './core/common/persistence/sql/postgres/postgres-lock-store.js';
|
|
117
118
|
export * from './core/common/persistence/sql/sql-data-store.js';
|
|
118
119
|
export * from './core/common/persistence/sql/sql-errors.js';
|