@lenne.tech/nest-server 12.4.0 → 12.6.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/configurable-features.md +2 -1
- package/.claude/rules/testing.md +5 -4
- package/CLAUDE.md +4 -0
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/helpers/config-endpoint.helper.d.ts +3 -0
- package/dist/core/common/helpers/config-endpoint.helper.js +17 -0
- package/dist/core/common/helpers/config-endpoint.helper.js.map +1 -0
- package/dist/core/common/helpers/redact-secrets.helper.d.ts +3 -0
- package/dist/core/common/helpers/redact-secrets.helper.js +72 -0
- package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -0
- package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
- package/dist/core/common/services/config.service.d.ts +3 -0
- package/dist/core/common/services/config.service.js +17 -3
- package/dist/core/common/services/config.service.js.map +1 -1
- package/dist/core/common/services/rate-limit-store.d.ts +1 -0
- package/dist/core/common/services/rate-limit-store.js +3 -3
- package/dist/core/common/services/rate-limit-store.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +23 -0
- 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 +31 -1
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +96 -14
- 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-openapi.helper.js +8 -1
- package/dist/core/modules/better-auth/core-better-auth-openapi.helper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.d.ts +3 -0
- package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.js +29 -0
- package/dist/core/modules/better-auth/core-better-auth-verification-link.helper.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth.controller.d.ts +8 -0
- package/dist/core/modules/better-auth/core-better-auth.controller.js +51 -0
- package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.module.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth.module.js +10 -1
- package/dist/core/modules/better-auth/core-better-auth.module.js.map +1 -1
- package/dist/core/modules/hub/core-hub.service.js +1 -13
- package/dist/core/modules/hub/core-hub.service.js.map +1 -1
- package/dist/core/modules/hub/helpers/hub-mask.helper.d.ts +1 -1
- package/dist/core/modules/hub/helpers/hub-mask.helper.js +1 -42
- package/dist/core/modules/hub/helpers/hub-mask.helper.js.map +1 -1
- package/dist/core/modules/system-setup/core-system-setup.service.d.ts +59 -2
- package/dist/core/modules/system-setup/core-system-setup.service.js +157 -28
- package/dist/core/modules/system-setup/core-system-setup.service.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/server/server.controller.d.ts +1 -1
- package/dist/server/server.controller.js +2 -2
- package/dist/server/server.controller.js.map +1 -1
- package/migration-guides/12.4.x-to-12.5.x.md +136 -0
- package/migration-guides/12.5.x-to-12.6.x.md +213 -0
- package/package.json +5 -4
- package/src/core/common/helpers/config-endpoint.helper.ts +56 -0
- package/src/core/common/helpers/redact-secrets.helper.ts +175 -0
- package/src/core/common/interfaces/server-options.interface.ts +26 -5
- package/src/core/common/services/config.service.ts +41 -3
- package/src/core/common/services/rate-limit-store.ts +9 -3
- package/src/core/modules/better-auth/README.md +27 -0
- package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +33 -0
- package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +218 -35
- package/src/core/modules/better-auth/core-better-auth-openapi.helper.ts +8 -1
- package/src/core/modules/better-auth/core-better-auth-verification-link.helper.ts +53 -0
- package/src/core/modules/better-auth/core-better-auth.controller.ts +61 -0
- package/src/core/modules/better-auth/core-better-auth.module.ts +18 -2
- package/src/core/modules/hub/README.md +3 -1
- package/src/core/modules/hub/core-hub.service.ts +4 -20
- package/src/core/modules/hub/helpers/hub-mask.helper.ts +4 -92
- package/src/core/modules/system-setup/README.md +20 -4
- package/src/core/modules/system-setup/core-system-setup.service.ts +290 -45
- package/src/index.ts +2 -0
- package/src/server/server.controller.ts +7 -2
|
@@ -1,18 +1,27 @@
|
|
|
1
|
-
import { Inject, Injectable, Logger, Optional } from '@nestjs/common';
|
|
2
|
-
import {
|
|
1
|
+
import { HttpException, HttpStatus, Inject, Injectable, Logger, Optional } from '@nestjs/common';
|
|
2
|
+
import { jwtVerify } from 'jose';
|
|
3
|
+
import { JWTExpired } from 'jose/errors';
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
5
|
import ejs from 'ejs';
|
|
4
6
|
import * as fs from 'fs';
|
|
5
7
|
import * as path from 'path';
|
|
6
8
|
|
|
7
|
-
import { isLocalEnv,
|
|
9
|
+
import { isLocalEnv, resolveAppUrlFromConfig } from '../../common/helpers/cookies.helper.js';
|
|
8
10
|
import { maskEmail } from '../../common/helpers/logging.helper.js';
|
|
9
11
|
import { IBetterAuthEmailVerificationConfig } from '../../common/interfaces/server-options.interface.js';
|
|
10
12
|
import { BrevoService } from '../../common/services/brevo.service.js';
|
|
11
13
|
import { ConfigService } from '../../common/services/config.service.js';
|
|
12
14
|
import { CoreRedisService } from '../../common/services/core-redis.service.js';
|
|
15
|
+
import {
|
|
16
|
+
InMemoryRateLimitStore,
|
|
17
|
+
type RateLimitStore,
|
|
18
|
+
RedisRateLimitStore,
|
|
19
|
+
} from '../../common/services/rate-limit-store.js';
|
|
20
|
+
import { ErrorCode } from '../error-code/error-codes.js';
|
|
13
21
|
import { EmailService } from '../../common/services/email.service.js';
|
|
14
22
|
import { TemplateService } from '../../common/services/template.service.js';
|
|
15
23
|
import { AuthEmailCallbackOptions, formatProjectName } from './better-auth.config.js';
|
|
24
|
+
import { openVerificationToken } from './core-better-auth-verification-link.helper.js';
|
|
16
25
|
import { callerDirectory } from '../../common/helpers/module-location.helper.js';
|
|
17
26
|
|
|
18
27
|
/**
|
|
@@ -226,7 +235,7 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
226
235
|
try {
|
|
227
236
|
// Override URL if callbackURL is configured (frontend-based verification)
|
|
228
237
|
if (this.config.callbackURL) {
|
|
229
|
-
url = this.buildFrontendVerificationUrl(token
|
|
238
|
+
url = this.buildFrontendVerificationUrl(token);
|
|
230
239
|
}
|
|
231
240
|
|
|
232
241
|
this.logAuthUrlForDevelopment('EMAIL VERIFICATION', user.email, url);
|
|
@@ -728,7 +737,7 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
728
737
|
* @param token - The verification token from Better-Auth
|
|
729
738
|
* @returns The full frontend URL with token query parameter
|
|
730
739
|
*/
|
|
731
|
-
protected buildFrontendVerificationUrl(token: string
|
|
740
|
+
protected buildFrontendVerificationUrl(token: string): string {
|
|
732
741
|
let baseUrl = this.config.callbackURL!;
|
|
733
742
|
|
|
734
743
|
// Resolve relative paths against appUrl
|
|
@@ -737,30 +746,189 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
737
746
|
baseUrl = `${appUrl.replace(/\/$/, '')}${baseUrl}`;
|
|
738
747
|
}
|
|
739
748
|
|
|
740
|
-
//
|
|
749
|
+
// The token only — and the token arrives here SEALED (CoreBetterAuthModule's mail callback,
|
|
750
|
+
// core-better-auth-verification-link.helper.ts), because Better-Auth's own token is a readable JWT with the address
|
|
751
|
+
// in it. Until DEV-4056 the address also travelled as `&email=`, so the page could offer "send a new email" for an
|
|
752
|
+
// expired link; it stood in the mail, in the browser history and in every access log the app keeps. The page now
|
|
753
|
+
// asks for a new mail WITH the token (POST /iam/resend-verification-email): the server opens it, reads the address
|
|
754
|
+
// and answers with a masked form, so the address never leaves it.
|
|
741
755
|
const separator = baseUrl.includes('?') ? '&' : '?';
|
|
742
|
-
|
|
756
|
+
return `${baseUrl}${separator}token=${encodeURIComponent(token)}`;
|
|
757
|
+
}
|
|
743
758
|
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
759
|
+
// ===================================================================================================================
|
|
760
|
+
// Resend by token (POST /iam/resend-verification-email)
|
|
761
|
+
// ===================================================================================================================
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* Requests with a VALID token for one address per {@link resendByTokenWindowSeconds}, counted under the address the
|
|
765
|
+
* token names: the sealed and the plain form of a link, and every other link for that address, share the counter
|
|
766
|
+
*/
|
|
767
|
+
protected readonly resendByTokenMaxPerToken = 3;
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* Requests with an INVALID token one client address may make per {@link resendByTokenWindowSeconds}. Valid tokens
|
|
771
|
+
* are not counted here: behind a reverse proxy without `trustProxy` every client has the proxy's address, and a
|
|
772
|
+
* bucket shared by everyone would let one anonymous caller lock the resend for all users with ten junk requests.
|
|
773
|
+
*/
|
|
774
|
+
protected readonly resendByTokenMaxPerIp = 10;
|
|
775
|
+
|
|
776
|
+
protected readonly resendByTokenWindowSeconds = 3600;
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* Keys each resend counter store holds before new keys fold into its shared overflow buckets (see
|
|
780
|
+
* `InMemoryRateLimitStore` / `RedisRateLimitStore`)
|
|
781
|
+
*/
|
|
782
|
+
protected readonly resendLimitStoreCapacity: number = 10_000;
|
|
783
|
+
|
|
784
|
+
/**
|
|
785
|
+
* The counters behind the two limits, one store each, shared through Redis when configured and process-local
|
|
786
|
+
* otherwise. Separate on purpose: invalid tokens cost nothing to make, and in a shared store a flood of them fills
|
|
787
|
+
* the capacity until every valid token lands in an overflow bucket that is already past its limit.
|
|
788
|
+
*/
|
|
789
|
+
protected resendByTokenStore?: RateLimitStore;
|
|
790
|
+
protected resendByAddressStore?: RateLimitStore;
|
|
791
|
+
|
|
792
|
+
/**
|
|
793
|
+
* Send a new verification mail for the address a verification token belongs to — the token of an EXPIRED link
|
|
794
|
+
* included, which is the case this exists for. The caller types nothing, and the address never leaves the server:
|
|
795
|
+
* the answer carries it masked ({@link maskEmailForDisplay}).
|
|
796
|
+
*
|
|
797
|
+
* - The token is the one the link carries: sealed (core-better-auth-verification-link.helper.ts), or plain from a
|
|
798
|
+
* link mailed before the seal. It must carry Better-Auth's signature (HS256 with its secret) once opened; a forged
|
|
799
|
+
* or garbled token sends nothing.
|
|
800
|
+
* - A new mail goes out only through Better-Auth's own `sendVerificationEmail`, which sends to an existing,
|
|
801
|
+
* unverified account and to nothing else; the per-address cooldown of {@link sendVerificationEmail} applies on
|
|
802
|
+
* top. A token of an address change (`updateTo`) sends nothing.
|
|
803
|
+
* - The answer is the same whatever happened: `{ email: <masked address of the token>, success: true }`, `email`
|
|
804
|
+
* null for an invalid token. Whoever holds a valid token received it at that address, so the masked form tells
|
|
805
|
+
* them nothing new, and nothing in the answer says whether an account exists, is verified, or was mailed.
|
|
806
|
+
* - It never verifies, signs in or creates a session.
|
|
807
|
+
*
|
|
808
|
+
* @throws HttpException 429 `RATE_LIMIT_EXCEEDED` past {@link resendByTokenMaxPerToken} requests with valid tokens
|
|
809
|
+
* for one address or past {@link resendByTokenMaxPerIp} invalid tokens from one client address within the window.
|
|
810
|
+
* The token is checked first: an invalid one is counted only per client address, so junk never creates a counter
|
|
811
|
+
* in the store valid tokens use (the answer already says it is invalid, so the order tells nobody anything more)
|
|
812
|
+
*/
|
|
813
|
+
async resendVerificationByToken(
|
|
814
|
+
authInstance:
|
|
815
|
+
| null
|
|
816
|
+
| undefined
|
|
817
|
+
| {
|
|
818
|
+
$context: Promise<{ secret: string }>;
|
|
819
|
+
// Better-Auth's own endpoint function; typed loosely because its declared type is an overload set
|
|
820
|
+
api: { sendVerificationEmail: (request: { body: { email: string } }) => Promise<unknown> };
|
|
821
|
+
},
|
|
822
|
+
token: unknown,
|
|
823
|
+
clientAddress: string | undefined,
|
|
824
|
+
): Promise<{ email: null | string; success: true }> {
|
|
825
|
+
const tokenValue = typeof token === 'string' ? token : '';
|
|
826
|
+
|
|
827
|
+
let claims: undefined | { email: string; updateTo?: string };
|
|
828
|
+
if (authInstance && tokenValue) {
|
|
829
|
+
const { secret } = await authInstance.$context;
|
|
830
|
+
const opened = await openVerificationToken(secret, tokenValue);
|
|
831
|
+
claims = opened ? await this.readVerificationTokenClaims(secret, opened) : undefined;
|
|
832
|
+
}
|
|
833
|
+
if (!claims) {
|
|
834
|
+
// The answer already says the token is invalid (`email: null`), so counting only these per address tells
|
|
835
|
+
// nobody anything more, and a valid token cannot be locked out by a stranger behind the same proxy
|
|
836
|
+
await this.assertResendAddressLimit(clientAddress);
|
|
837
|
+
return { email: null, success: true };
|
|
761
838
|
}
|
|
839
|
+
await this.assertResendTokenLimit(claims.email);
|
|
762
840
|
|
|
763
|
-
|
|
841
|
+
if (!claims.updateTo) {
|
|
842
|
+
try {
|
|
843
|
+
await authInstance.api.sendVerificationEmail({ body: { email: claims.email } });
|
|
844
|
+
} catch (error) {
|
|
845
|
+
// The answer must not differ: a failed send (verification switched off, an SMTP outage) is logged, not told
|
|
846
|
+
this.logger.debug(
|
|
847
|
+
`Resend by token for ${maskEmail(claims.email)} sent nothing: ${
|
|
848
|
+
error instanceof Error ? error.message : 'Unknown error'
|
|
849
|
+
}`,
|
|
850
|
+
);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
return { email: this.maskEmailForDisplay(claims.email), success: true };
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
/** The counter store of one resend limit, created on first use */
|
|
857
|
+
protected resendLimitStore(scope: 'address' | 'token'): RateLimitStore {
|
|
858
|
+
const create = (namespace: string): RateLimitStore =>
|
|
859
|
+
this.coreRedisService?.enabled
|
|
860
|
+
? new RedisRateLimitStore(this.coreRedisService, namespace, this.resendLimitStoreCapacity)
|
|
861
|
+
: new InMemoryRateLimitStore(this.resendLimitStoreCapacity);
|
|
862
|
+
if (scope === 'token') {
|
|
863
|
+
this.resendByTokenStore ??= create('email-verification-resend-token');
|
|
864
|
+
return this.resendByTokenStore;
|
|
865
|
+
}
|
|
866
|
+
this.resendByAddressStore ??= create('email-verification-resend-address');
|
|
867
|
+
return this.resendByAddressStore;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/**
|
|
871
|
+
* Count a request with a valid token against the address it names, by the address's hash (no PII in the key).
|
|
872
|
+
*
|
|
873
|
+
* A count from a shared overflow bucket (the store is full) never refuses: valid tokens cost a sign-up each, so an
|
|
874
|
+
* attacker who signs up ten thousand addresses of their own and replays the links could otherwise fill the store
|
|
875
|
+
* and push every other user's resend into a bucket past its limit. Mail volume stays bounded without it — the
|
|
876
|
+
* per-address cooldown of {@link sendVerificationEmail} applies to every resend.
|
|
877
|
+
*/
|
|
878
|
+
protected async assertResendTokenLimit(email: string): Promise<void> {
|
|
879
|
+
const tokenKey = createHash('sha256').update(email.trim().toLowerCase()).digest('hex');
|
|
880
|
+
const perToken = await this.resendLimitStore('token').hit(`token:${tokenKey}`, this.resendByTokenWindowSeconds);
|
|
881
|
+
if (perToken.count > this.resendByTokenMaxPerToken && !perToken.overflow) {
|
|
882
|
+
throw new HttpException(ErrorCode.RATE_LIMIT_EXCEEDED, HttpStatus.TOO_MANY_REQUESTS);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/** Count an invalid token against the client address it came from */
|
|
887
|
+
protected async assertResendAddressLimit(clientAddress: string | undefined): Promise<void> {
|
|
888
|
+
const key = `ip:${clientAddress || 'unknown'}`;
|
|
889
|
+
const perAddress = await this.resendLimitStore('address').hit(key, this.resendByTokenWindowSeconds);
|
|
890
|
+
if (perAddress.count > this.resendByTokenMaxPerIp) {
|
|
891
|
+
throw new HttpException(ErrorCode.RATE_LIMIT_EXCEEDED, HttpStatus.TOO_MANY_REQUESTS);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* The claims of a verification token Better-Auth signed (`createEmailVerificationToken`: HS256 with its secret,
|
|
897
|
+
* `{ email, updateTo?, userId? }`), expired or not. `undefined` for anything without a valid signature.
|
|
898
|
+
*/
|
|
899
|
+
protected async readVerificationTokenClaims(
|
|
900
|
+
secret: string,
|
|
901
|
+
token: string,
|
|
902
|
+
): Promise<undefined | { email: string; updateTo?: string }> {
|
|
903
|
+
let payload: Record<string, unknown>;
|
|
904
|
+
try {
|
|
905
|
+
({ payload } = await jwtVerify(token, new TextEncoder().encode(secret), { algorithms: ['HS256'] }));
|
|
906
|
+
} catch (error) {
|
|
907
|
+
// jose checks the signature before the expiry, so an expired token carries its verified claims
|
|
908
|
+
if (!(error instanceof JWTExpired)) {
|
|
909
|
+
return undefined;
|
|
910
|
+
}
|
|
911
|
+
payload = error.payload;
|
|
912
|
+
}
|
|
913
|
+
if (typeof payload.email !== 'string' || !payload.email.includes('@')) {
|
|
914
|
+
return undefined;
|
|
915
|
+
}
|
|
916
|
+
return {
|
|
917
|
+
email: payload.email,
|
|
918
|
+
updateTo: typeof payload.updateTo === 'string' && payload.updateTo ? payload.updateTo : undefined,
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
/**
|
|
923
|
+
* The address as the page may show it: the first character, `***`, the domain — `k***@lenne.tech`. Enough to
|
|
924
|
+
* recognise one's own mailbox, not enough to learn an address.
|
|
925
|
+
*/
|
|
926
|
+
protected maskEmailForDisplay(email: string): string {
|
|
927
|
+
const at = email.lastIndexOf('@');
|
|
928
|
+
if (at < 1) {
|
|
929
|
+
return '***';
|
|
930
|
+
}
|
|
931
|
+
return `${email[0]}***${email.slice(at)}`;
|
|
764
932
|
}
|
|
765
933
|
|
|
766
934
|
/**
|
|
@@ -858,32 +1026,47 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
858
1026
|
* passed it and wrote live reset links into their log pipeline, where log access alone was
|
|
859
1027
|
* enough to take over an account.
|
|
860
1028
|
*
|
|
861
|
-
*
|
|
862
|
-
*
|
|
863
|
-
*
|
|
864
|
-
*
|
|
1029
|
+
* Nothing opens it elsewhere (12.6.0): until then `LT_LOG_AUTH_URLS=1` printed it in any
|
|
1030
|
+
* environment but `production` and `staging`, and an environment name says nothing reliable about
|
|
1031
|
+
* whether it is a laptop — `development` names a deployed stage as often as a machine. A live token
|
|
1032
|
+
* and the line's `UserKey` (a pseudonym of the address) must never reach a deployment's logs.
|
|
1033
|
+
* `LT_LOG_AUTH_URLS=0` still suppresses the line in the local environments.
|
|
1034
|
+
*
|
|
1035
|
+
* The process's own `NODE_ENV` must agree (12.6.0): `getEnvironmentConfig()` answers a `NODE_ENV` without a
|
|
1036
|
+
* configuration key (`development`, `dev`, `staging` in a project that defines none of them) with the `local`
|
|
1037
|
+
* block, whose `env` then claims `local` on a deployed stage, and so does an EMPTY `NODE_ENV` (`'' || 'local'`). So
|
|
1038
|
+
* the line needs both a local `env` and a `NODE_ENV` that is unset (not empty: the `local` default) or itself
|
|
1039
|
+
* `local`, `ci` or `e2e`.
|
|
865
1040
|
*
|
|
866
1041
|
* The address is masked (PII, and the rest of this file already masks it); the URL is printed in
|
|
867
|
-
* full because following it without a mail server is the whole point locally.
|
|
1042
|
+
* full because following it without a mail server is the whole point locally. `UserKey` tells a
|
|
1043
|
+
* test which line is its own when many runs sign up in parallel: the first 16 hex characters of
|
|
1044
|
+
* SHA-256 over the trimmed, lower-cased address, so a helper that knows its test address computes
|
|
1045
|
+
* the same key. It replaces reading the address from the token's JWT payload, which the sealed
|
|
1046
|
+
* verification token (DEV-4056) no longer allows. Format:
|
|
1047
|
+
* `[<LABEL>] User: <masked>, UserKey: <16 hex>, URL: <url>`.
|
|
868
1048
|
*
|
|
869
1049
|
* `console.log` rather than the NestJS logger, deliberately and for two reasons: the logger
|
|
870
1050
|
* buffers, which makes interception unreliable under Vitest, and a logger call would route the
|
|
871
1051
|
* token into `HubLogBufferService`'s ring buffer, which is readable over HTTP by any ADMIN.
|
|
872
1052
|
*/
|
|
873
1053
|
protected logAuthUrlForDevelopment(label: string, email: string, url: string): void {
|
|
874
|
-
|
|
875
|
-
if (optIn === '0') {
|
|
1054
|
+
if (process.env.LT_LOG_AUTH_URLS === '0') {
|
|
876
1055
|
return;
|
|
877
1056
|
}
|
|
878
1057
|
const env = this.configService?.getFastButReadOnly<string>('env') ?? process.env.NODE_ENV;
|
|
879
|
-
if (
|
|
1058
|
+
if (!isLocalEnv(env)) {
|
|
880
1059
|
return;
|
|
881
1060
|
}
|
|
882
|
-
|
|
1061
|
+
// `!== undefined`, not truthiness: an empty NODE_ENV (`NODE_ENV=${NODE_ENV}` in a compose file on a host without
|
|
1062
|
+
// the variable) is read as `local` by getEnvironmentConfig(), and `isLocalEnv('')` is false
|
|
1063
|
+
const nodeEnv = process.env.NODE_ENV;
|
|
1064
|
+
if (nodeEnv !== undefined && !isLocalEnv(nodeEnv)) {
|
|
883
1065
|
return;
|
|
884
1066
|
}
|
|
1067
|
+
const userKey = createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 16);
|
|
885
1068
|
// oxlint-disable-next-line no-console
|
|
886
|
-
console.log(`[${label}] User: ${
|
|
1069
|
+
console.log(`[${label}] User: ${maskEmail(email)}, UserKey: ${userKey}, URL: ${url}`);
|
|
887
1070
|
}
|
|
888
1071
|
|
|
889
1072
|
protected getAppName(): string {
|
|
@@ -24,7 +24,14 @@ import type { IBetterAuth } from '../../common/interfaces/server-options.interfa
|
|
|
24
24
|
* - session: custom response format with mapped user
|
|
25
25
|
* - features: nest-server's own feature report
|
|
26
26
|
*/
|
|
27
|
-
export const CONTROLLER_HANDLED_PATHS = [
|
|
27
|
+
export const CONTROLLER_HANDLED_PATHS = [
|
|
28
|
+
'/features',
|
|
29
|
+
'/sign-in/email',
|
|
30
|
+
'/sign-up/email',
|
|
31
|
+
'/sign-out',
|
|
32
|
+
'/session',
|
|
33
|
+
'/resend-verification-email',
|
|
34
|
+
];
|
|
28
35
|
|
|
29
36
|
/**
|
|
30
37
|
* Routes Better-Auth guards with a session check in the HANDLER instead of a session middleware: the
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { CompactEncrypt, compactDecrypt } from 'jose';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The verification link's token, sealed (DEV-4056).
|
|
6
|
+
*
|
|
7
|
+
* Better-Auth's email-verification token is a SIGNED JWT, not an encrypted one: its middle segment is base64url JSON
|
|
8
|
+
* with the address and the user id (`{ email, userId, iat, exp }`). Removing `&email=` from the link therefore removed
|
|
9
|
+
* nothing — anyone reading an access log, the browser history or a mail scanner's URL log decodes the address from the
|
|
10
|
+
* token itself. The link carries the token encrypted instead (compact JWE, `dir` + `A256GCM`, key derived from
|
|
11
|
+
* Better-Auth's secret), and the framework opens it where the token comes back: the API middleware before it forwards
|
|
12
|
+
* `GET /verify-email` to Better-Auth, and `POST /iam/resend-verification-email`. Better-Auth's own verification runs
|
|
13
|
+
* unchanged on the token it signed.
|
|
14
|
+
*
|
|
15
|
+
* A link mailed before the seal carries the plain token, which goes through as it is: {@link openVerificationToken}
|
|
16
|
+
* answers an unsealed value unchanged.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** A sealed token is a compact JWE — five segments; Better-Auth's token is a JWS — three */
|
|
20
|
+
export function isSealedVerificationToken(value: unknown): value is string {
|
|
21
|
+
return typeof value === 'string' && value.split('.').length === 5;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The key of the seal: derived from Better-Auth's secret, so it rotates with it and needs no configuration */
|
|
25
|
+
function sealKey(secret: string): Uint8Array {
|
|
26
|
+
return new Uint8Array(createHash('sha256').update(`lt-email-verification-link:${secret}`).digest());
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Encrypt a verification token for the link */
|
|
30
|
+
export async function sealVerificationToken(secret: string, token: string): Promise<string> {
|
|
31
|
+
return new CompactEncrypt(new TextEncoder().encode(token))
|
|
32
|
+
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
|
|
33
|
+
.encrypt(sealKey(secret));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The token a link carried: decrypted when sealed, unchanged when not (a link mailed before the seal). `undefined`
|
|
38
|
+
* for a sealed value that does not open with this secret — forged, garbled, or sealed under a rotated secret.
|
|
39
|
+
*/
|
|
40
|
+
export async function openVerificationToken(secret: string, value: string): Promise<string | undefined> {
|
|
41
|
+
if (!isSealedVerificationToken(value)) {
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
const { plaintext } = await compactDecrypt(value, sealKey(secret), {
|
|
46
|
+
contentEncryptionAlgorithms: ['A256GCM'],
|
|
47
|
+
keyManagementAlgorithms: ['dir'],
|
|
48
|
+
});
|
|
49
|
+
return new TextDecoder().decode(plaintext);
|
|
50
|
+
} catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -146,6 +146,31 @@ export class CoreBetterAuthSignInInput {
|
|
|
146
146
|
password: string;
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
+
/**
|
|
150
|
+
* Input of `POST /iam/resend-verification-email`: the token of a verification link, an expired one included
|
|
151
|
+
*/
|
|
152
|
+
export class CoreBetterAuthResendVerificationInput {
|
|
153
|
+
@ApiProperty({ description: 'The token of the verification link, also when it has expired' })
|
|
154
|
+
@IsNotEmpty()
|
|
155
|
+
@IsString()
|
|
156
|
+
token: string;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Answer of `POST /iam/resend-verification-email` — the same whatever happened, so it says nothing about the account
|
|
161
|
+
*/
|
|
162
|
+
export class CoreBetterAuthResendVerificationResponse {
|
|
163
|
+
@ApiProperty({
|
|
164
|
+
description: 'The address the token belongs to, masked (k***@example.com); null for an invalid token',
|
|
165
|
+
nullable: true,
|
|
166
|
+
type: String,
|
|
167
|
+
})
|
|
168
|
+
email: null | string;
|
|
169
|
+
|
|
170
|
+
@ApiProperty({ description: 'Always true' })
|
|
171
|
+
success: boolean;
|
|
172
|
+
}
|
|
173
|
+
|
|
149
174
|
/**
|
|
150
175
|
* Sign-up input DTO
|
|
151
176
|
*/
|
|
@@ -321,6 +346,8 @@ export class CoreBetterAuthController {
|
|
|
321
346
|
jwt: this.betterAuthService.isJwtEnabled(),
|
|
322
347
|
passkey: this.betterAuthService.isPasskeyEnabled(),
|
|
323
348
|
resendCooldownSeconds: this.emailVerificationService?.getConfig()?.resendCooldownSeconds ?? 60,
|
|
349
|
+
// POST /iam/resend-verification-email: a page may offer "send a new email" with the token of the link alone
|
|
350
|
+
resendVerificationByToken: this.emailVerificationService?.isEnabled() ?? false,
|
|
324
351
|
signUpChecks: this.signUpValidator?.isEnabled() ?? false,
|
|
325
352
|
signUpEnabled: this.betterAuthService.isSignUpEnabled(),
|
|
326
353
|
socialProviders: this.betterAuthService.getEnabledSocialProviders(),
|
|
@@ -730,6 +757,40 @@ export class CoreBetterAuthController {
|
|
|
730
757
|
*
|
|
731
758
|
* @see README.md "Architecture: Why Custom Controllers?"
|
|
732
759
|
*/
|
|
760
|
+
/**
|
|
761
|
+
* Send a new verification mail for the token of a verification link — an expired one is the case this exists for.
|
|
762
|
+
* The address never travels: the server reads it from the token, and the answer carries it masked.
|
|
763
|
+
*
|
|
764
|
+
* Never verifies, signs in or creates a session. The answer is the same whether the account exists, is already
|
|
765
|
+
* verified, or a mail went out; see `CoreBetterAuthEmailVerificationService.resendVerificationByToken()` for the
|
|
766
|
+
* checks and the rate limits (429 `LTNS_0020`).
|
|
767
|
+
*/
|
|
768
|
+
@ApiBody({ type: CoreBetterAuthResendVerificationInput })
|
|
769
|
+
@ApiOkResponse({
|
|
770
|
+
description: 'Always the same answer; email is the masked address of the token, or null for an invalid token',
|
|
771
|
+
type: CoreBetterAuthResendVerificationResponse,
|
|
772
|
+
})
|
|
773
|
+
@ApiOperation({
|
|
774
|
+
description: 'Send a new verification email for the token of a verification link, also an expired one',
|
|
775
|
+
summary: 'Resend Verification Email by Token',
|
|
776
|
+
})
|
|
777
|
+
@HttpCode(HttpStatus.OK)
|
|
778
|
+
@Post('resend-verification-email')
|
|
779
|
+
@Roles(RoleEnum.S_EVERYONE)
|
|
780
|
+
async resendVerificationEmail(
|
|
781
|
+
@Req() req: Request,
|
|
782
|
+
@Body() input: CoreBetterAuthResendVerificationInput,
|
|
783
|
+
): Promise<CoreBetterAuthResendVerificationResponse> {
|
|
784
|
+
if (!this.emailVerificationService) {
|
|
785
|
+
return { email: null, success: true };
|
|
786
|
+
}
|
|
787
|
+
return this.emailVerificationService.resendVerificationByToken(
|
|
788
|
+
this.betterAuthService.getInstance(),
|
|
789
|
+
input?.token,
|
|
790
|
+
req.ip,
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
|
|
733
794
|
@ApiOkResponse({ description: 'Signed out successfully', type: CoreBetterAuthResponse })
|
|
734
795
|
@ApiOperation({ description: 'Sign out from Better-Auth', summary: 'Sign Out' })
|
|
735
796
|
@Post('sign-out')
|
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
instantiateBetterAuth,
|
|
33
33
|
OnPasswordResetCallback,
|
|
34
34
|
} from './better-auth.config.js';
|
|
35
|
+
import { sealVerificationToken } from './core-better-auth-verification-link.helper.js';
|
|
35
36
|
import { applyBetterAuthSchema } from './better-auth-sql.helper.js';
|
|
36
37
|
import { getBetterAuthSqlStore, setBetterAuthSqlStore } from './core-better-auth-sql.registry.js';
|
|
37
38
|
import { BetterAuthSqlStore } from './core-better-auth-sql.store.js';
|
|
@@ -926,6 +927,20 @@ export class CoreBetterAuthModule implements NestModule, OnModuleInit {
|
|
|
926
927
|
}
|
|
927
928
|
}
|
|
928
929
|
|
|
930
|
+
/**
|
|
931
|
+
* The verification mail's token and link with the token sealed (core-better-auth-verification-link.helper.ts). The
|
|
932
|
+
* API middleware opens it again for `GET /verify-email`, and `POST /iam/resend-verification-email` does too.
|
|
933
|
+
* Without an instance (cannot happen while Better-Auth sends) the mail goes out unsealed rather than not at all.
|
|
934
|
+
*/
|
|
935
|
+
protected static async sealVerificationMail(options: AuthEmailCallbackOptions): Promise<AuthEmailCallbackOptions> {
|
|
936
|
+
const secret = (await this.authInstance?.$context)?.secret;
|
|
937
|
+
if (!secret || !options.token) {
|
|
938
|
+
return options;
|
|
939
|
+
}
|
|
940
|
+
const sealed = await sealVerificationToken(secret, options.token);
|
|
941
|
+
return { ...options, token: sealed, url: options.url?.split(options.token).join(sealed) };
|
|
942
|
+
}
|
|
943
|
+
|
|
929
944
|
/**
|
|
930
945
|
* `protected` rather than `private`: the callbacks it returns include `onPasswordReset`, which
|
|
931
946
|
* decides what mirroring a reset into the legacy store means for a deployment. A project with a
|
|
@@ -1027,9 +1042,10 @@ export class CoreBetterAuthModule implements NestModule, OnModuleInit {
|
|
|
1027
1042
|
}
|
|
1028
1043
|
},
|
|
1029
1044
|
sendVerificationEmail: async (options) => {
|
|
1030
|
-
// Delegate to the NestJS service
|
|
1045
|
+
// Delegate to the NestJS service — with the token sealed, because Better-Auth's own token is a readable JWT
|
|
1046
|
+
// that carries the address, and the link goes into mails, browser histories and access logs (DEV-4056)
|
|
1031
1047
|
if (this.emailVerificationService) {
|
|
1032
|
-
await this.emailVerificationService.sendVerificationEmail(options);
|
|
1048
|
+
await this.emailVerificationService.sendVerificationEmail(await this.sealVerificationMail(options));
|
|
1033
1049
|
} else {
|
|
1034
1050
|
// Same reasoning as the password-reset branch above: the URL carries a token and this
|
|
1035
1051
|
// logger feeds the ADMIN-readable Hub log buffer, so report the breakage instead.
|
|
@@ -123,7 +123,9 @@ Every action writes an audit line: `[HUB-ACTION] <action> by user <id>`.
|
|
|
123
123
|
The messages are centralized in `hub-action-messages.ts` (`HubActionMessage`) so the wording stays
|
|
124
124
|
consistent and reviewable in one place.
|
|
125
125
|
- **CSP**: strict per-request nonce; no `unsafe-inline`; `X-Frame-Options: DENY`; `no-store`.
|
|
126
|
-
- **Secrets**: the config viewer deep-clones and masks by key pattern + `security.secretFields
|
|
126
|
+
- **Secrets**: the config viewer deep-clones and masks by key pattern + `security.secretFields` — since 12.5.0
|
|
127
|
+
through the framework-wide `redactSecrets()` / `ConfigService.getRedactedConfig()`, the same view `GET /config`
|
|
128
|
+
serves (`configEndpointResponse()`).
|
|
127
129
|
- **Interceptor safety**: sidecars return pre-serialized JSON strings, so the global response
|
|
128
130
|
interceptors never walk/mutate live config.
|
|
129
131
|
- **Mailbox guard**: `mode: 'capture'` throws at startup in any **reachable** environment (anything
|
|
@@ -7,25 +7,10 @@ import { ConfigService } from '../../common/services/config.service.js';
|
|
|
7
7
|
|
|
8
8
|
import { HUB_CONFIG } from './hub.constants.js';
|
|
9
9
|
import { HUB_PANEL_GROUPS, HUB_PANELS } from './hub-nav.js';
|
|
10
|
-
import { maskConfigDeep } from './helpers/hub-mask.helper.js';
|
|
11
10
|
import { CoreHubSourcesService } from './services/core-hub-sources.service.js';
|
|
12
11
|
import { HubDashboardData, HubDiagnosticsData, HubSessionData } from './interfaces/hub-panels.interface.js';
|
|
13
12
|
import type { ResolvedHubConfig } from './interfaces/hub-config.interface.js';
|
|
14
13
|
|
|
15
|
-
/**
|
|
16
|
-
* Framework-default secret field names (see CheckSecurityInterceptor). Union with the pattern-based
|
|
17
|
-
* masking in {@link maskConfigDeep} and the project's `security.secretFields`.
|
|
18
|
-
*/
|
|
19
|
-
const FRAMEWORK_SECRET_FIELDS = [
|
|
20
|
-
'password',
|
|
21
|
-
'verificationToken',
|
|
22
|
-
'passwordResetToken',
|
|
23
|
-
'passwordResetTokenExpiresAt',
|
|
24
|
-
'refreshTokens',
|
|
25
|
-
'tempTokens',
|
|
26
|
-
'apiKeyEncrypted',
|
|
27
|
-
];
|
|
28
|
-
|
|
29
14
|
const MONGO_STATES: Record<number, string> = {
|
|
30
15
|
0: 'disconnected',
|
|
31
16
|
1: 'connected',
|
|
@@ -92,13 +77,12 @@ export class CoreHubService {
|
|
|
92
77
|
}
|
|
93
78
|
|
|
94
79
|
/**
|
|
95
|
-
* The full server config with all secrets masked
|
|
96
|
-
* then masked by key heuristics + the framework/project
|
|
80
|
+
* The full server config with all secrets masked — the same view `GET /config` serves
|
|
81
|
+
* (`ConfigService.getRedactedConfig()`): deep-cloned first, then masked by key heuristics + the framework/project
|
|
82
|
+
* secret-field lists.
|
|
97
83
|
*/
|
|
98
84
|
getConfigMasked(): Record<string, unknown> {
|
|
99
|
-
|
|
100
|
-
const projectSecretFields = this.configService.get<string[]>('security.secretFields', []) ?? [];
|
|
101
|
-
return maskConfigDeep(raw, [...FRAMEWORK_SECRET_FIELDS, ...projectSecretFields]);
|
|
85
|
+
return this.configService.getRedactedConfig();
|
|
102
86
|
}
|
|
103
87
|
|
|
104
88
|
/** The resolved Hub config (for controller/actions/gating decisions). */
|