@lenne.tech/nest-server 11.42.11 → 11.42.12

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.
Files changed (39) hide show
  1. package/.claude/rules/configurable-features.md +1 -1
  2. package/.claude/rules/package-management.md +12 -5
  3. package/.claude/rules/testing.md +3 -3
  4. package/FRAMEWORK-API.md +1 -1
  5. package/dist/core/common/helpers/cookies.helper.d.ts +3 -2
  6. package/dist/core/common/helpers/cookies.helper.js +13 -4
  7. package/dist/core/common/helpers/cookies.helper.js.map +1 -1
  8. package/dist/core/common/helpers/outbound-url.helper.js +2 -5
  9. package/dist/core/common/helpers/outbound-url.helper.js.map +1 -1
  10. package/dist/core/modules/auth/core-auth.controller.js +2 -1
  11. package/dist/core/modules/auth/core-auth.controller.js.map +1 -1
  12. package/dist/core/modules/auth/core-auth.resolver.js +2 -1
  13. package/dist/core/modules/auth/core-auth.resolver.js.map +1 -1
  14. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +1 -0
  15. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  16. package/dist/core/modules/better-auth/core-better-auth-cookie.helper.d.ts +2 -0
  17. package/dist/core/modules/better-auth/core-better-auth-cookie.helper.js +2 -1
  18. package/dist/core/modules/better-auth/core-better-auth-cookie.helper.js.map +1 -1
  19. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +7 -2
  20. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  21. package/dist/core/modules/better-auth/core-better-auth.controller.js +1 -0
  22. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  23. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +1 -0
  24. package/dist/core/modules/better-auth/core-better-auth.service.js +4 -0
  25. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  26. package/dist/tsconfig.build.tsbuildinfo +1 -1
  27. package/migration-guides/11.42.10-to-11.42.11.md +18 -2
  28. package/migration-guides/11.42.11-to-11.42.12.md +142 -0
  29. package/package.json +1 -1
  30. package/src/core/common/helpers/cookies.helper.ts +50 -6
  31. package/src/core/common/helpers/outbound-url.helper.ts +4 -10
  32. package/src/core/modules/auth/core-auth.controller.ts +2 -1
  33. package/src/core/modules/auth/core-auth.resolver.ts +2 -1
  34. package/src/core/modules/better-auth/README.md +1 -0
  35. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +1 -0
  36. package/src/core/modules/better-auth/core-better-auth-cookie.helper.ts +24 -5
  37. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +20 -10
  38. package/src/core/modules/better-auth/core-better-auth.controller.ts +4 -0
  39. package/src/core/modules/better-auth/core-better-auth.service.ts +24 -0
@@ -6,7 +6,7 @@
6
6
  | -------------------- | -------------------------------------------------------------------------------------------------------- |
7
7
  | **Framework API** | No change |
8
8
  | **Test tooling** | e2e low-resource cap fixed for Vitest 4, e2e run governor hardened, two `check.mjs` false greens closed (§1–§3) — reaches your project only through this guide |
9
- | **Tests** | A race in tests that upload to a route a role guard refuses (§4) |
9
+ | **Tests** | A race in tests that upload to a route a role guard refuses (§4); a red unit file in starter-derived monorepos (§7) |
10
10
  | **Documentation** | `lt dev` exports `NSC__MONGOOSE__URI`, never `MONGODB_URI`; two older guides corrected (§5) |
11
11
  | **Dependencies** | `nodemailer` 10.1.0 (minor, no API change); dev tooling (§6) |
12
12
  | **Breaking Changes** | None |
@@ -88,7 +88,9 @@ release.
88
88
 
89
89
  ## 4. Tests that upload to a refused route: send no file
90
90
 
91
- Already in projects generated from **starter 11.41.9 or later** (for the avatar upload test).
91
+ For the avatar upload test, already in projects generated from **starter 11.41.9 or later**. The two upload
92
+ refusals in `tests/modules/file-rest.e2e-spec.ts` (401 and 403 on `/files/upload`) still attached a file until
93
+ **starter 11.42.11**.
92
94
 
93
95
  When a role guard refuses a multipart upload route, it answers before the file interceptor reads the body. A
94
96
  test that still attaches a file races that answer: the 401/403 arrives while the client is writing the
@@ -137,6 +139,20 @@ redoing unless you adapted a script to the wrong name.
137
139
  Unchanged on purpose: `express` stays 5.2.1, because `@nestjs/platform-express` 11.2.7 pins it exactly — a
138
140
  direct bump would put two copies of express into your tree. `better-auth` stays on 1.7.7, the current release.
139
141
 
142
+ ## 7. Starter-derived monorepos: a red `audit-suppression-scope.spec.ts`
143
+
144
+ Fixed in **starter 11.42.11**; affects projects generated from **starter 11.41.7 or later** inside a
145
+ fullstack monorepo.
146
+
147
+ `tests/unit/audit-suppression-scope.spec.ts` read `pnpm-workspace.yaml` from the API project at COLLECTION
148
+ time. In a monorepo the API has no `pnpm-workspace.yaml` of its own (it lives at the workspace root), so the
149
+ whole file failed to load with `ENOENT` and the unit suite went red without a single test running. The
150
+ starter now reads the file inside the test and guards the monorepo layout with
151
+ `tests/unit/hoisted-layout.spec.ts`; copy both from the current starter.
152
+
153
+ Optional, also new in starter 11.42.11: its `scripts/check.mjs` ends a hanging `pnpm audit` after a timeout
154
+ (`CHECK_AUDIT_TIMEOUT`) and reports it as not checked, instead of stalling the whole `check`.
155
+
140
156
  ## Compatibility Notes
141
157
 
142
158
  | Pattern | Status |
@@ -0,0 +1,142 @@
1
+ # Migration Guide: 11.42.11 → 11.42.12
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ | -------------------- | -------------------------------------------------------------------------------------------------------- |
7
+ | **Security** | Password-reset and verification links are no longer printed on deployed `develop` / `test` stages (§1); auth cookies carry `Secure` on every https deployment, whatever the environment is called (§2) |
8
+ | **Framework API** | Additive only: `isLocalEnv()`, `CoreBetterAuthService.usesSecureCookies()`, optional `secureTransport` / `baseUrl` arguments on the cookie helpers |
9
+ | **Dependencies** | None for the package. The repository's own audit suppression for GHSA-ch52-4w7c-c8xp is gone (§3) |
10
+ | **Breaking Changes** | None |
11
+ | **Migration Effort** | None for most projects. Check §1 if you read auth links from a log outside `local` / `ci` / `e2e`, and §2 if you override a cookie-writing method |
12
+
13
+ ## Quick Migration
14
+
15
+ ```bash
16
+ pnpm update @lenne.tech/nest-server
17
+ ```
18
+
19
+ Vendor-mode projects pick it up with the core update. No code or configuration change is required unless one
20
+ of the checks in §1 or §2 applies to you.
21
+
22
+ ## 1. Auth links are printed only in local environments
23
+
24
+ `CoreBetterAuthEmailVerificationService.logAuthUrlForDevelopment()` prints the verification and password-reset
25
+ link to stdout so a developer can follow it without a mail server. The URL carries a live bearer token — a reset
26
+ link changes the password outright.
27
+
28
+ Until this release the link was printed everywhere except `production` and `staging`. The deployed `develop` and
29
+ `test` stages of a starter-based project are neither, so they wrote live reset links into their log pipeline,
30
+ where read access to the logs was enough to take over an account.
31
+
32
+ | Environment (`env`, else `NODE_ENV`) | Before | After |
33
+ | ------------------------------------ | ------ | ----- |
34
+ | `local`, `ci`, `e2e` | printed | printed |
35
+ | `develop`, `test`, `development`, any other name, none at all | printed | **not printed** |
36
+ | `production`, `staging`, `NODE_ENV=production` | not printed | not printed |
37
+
38
+ `LT_LOG_AUTH_URLS` gained a value:
39
+
40
+ | Value | Effect |
41
+ | ----- | ------ |
42
+ | unset | the table above |
43
+ | `1` | also print in an environment that is not in the list — for a developer machine with a different environment name |
44
+ | `0` | print nowhere, not even locally |
45
+
46
+ `production` and `staging` never print, whatever the variable says.
47
+
48
+ **What to check:**
49
+
50
+ - **Your local environment has another name** (e.g. `development`): set `LT_LOG_AUTH_URLS=1` in your local
51
+ `.env`. Never set it on a deployment.
52
+ - **A script or CI job reads `[EMAIL VERIFICATION]` / `[PASSWORD RESET]` from the API log** — fine as long as it
53
+ runs the API as `local`, `ci` or `e2e` (`lt dev up`, `lt dev test` and the starter's e2e scripts do). Against a
54
+ deployed stage, read the mail instead (Hub mailbox, Mailpit), which is what that stage should have been doing.
55
+
56
+ The decision uses the new exported helper `isLocalEnv(env)`, which reads the existing `LOCALHOST_URL_ENVS`
57
+ (`local`, `ci`, `e2e`). The SSRF guard's private-target allowance (`privateOutboundTargetsAllowed()`) now reads
58
+ the same helper; its behaviour is unchanged.
59
+
60
+ ## 2. Auth cookies carry `Secure` on every https deployment
61
+
62
+ The session cookie is written by two paths: Better-Auth's own handlers (2FA, social callback, passkey) and the
63
+ framework's cookie helper (sign-in and sign-up through `CoreBetterAuthController`, the API middleware, and the
64
+ legacy `token` / `refreshToken` cookies). Better-Auth sets `Secure` from an `https://` base URL. The framework
65
+ helper set it only for `production` / `staging` — so on an https `develop` or `test` stage the cookie that
66
+ establishes the session went out without `Secure`, while Better-Auth's handlers set it on the same deployment.
67
+
68
+ Now:
69
+
70
+ | Cookie | `Secure` when |
71
+ | ------ | ------------- |
72
+ | Better-Auth session cookie written by the framework | Better-Auth's own cookies are secure (read off the instance: `CoreBetterAuthService.usesSecureCookies()`), or the environment is production-like |
73
+ | Legacy `token` / `refreshToken` | `baseUrl` starts with `https://`, or the environment is production-like |
74
+
75
+ `Secure` is only ever added, never removed. A project that switched it off on purpose
76
+ (`betterAuth.options.advanced.defaultCookieAttributes.secure: false`) keeps that outside production and staging.
77
+
78
+ **What to check:**
79
+
80
+ - **A deployment whose `baseUrl` says `https://` but whose browsers reach the API over plain http** now loses the
81
+ framework-written session cookie too — browsers drop a `Secure` cookie received over http. Better-Auth's own
82
+ handlers already behaved this way, so such a deployment had broken 2FA and social sign-in before. Fix the
83
+ `baseUrl` or serve https.
84
+ - **You override a cookie-writing method.** The new inputs reach the helpers only if the caller passes them:
85
+
86
+ ```typescript
87
+ // A CoreAuthController / CoreAuthResolver subclass that overrides processCookies()
88
+ const baseUrl = this.configService.getFastButReadOnly<string>('baseUrl');
89
+ return setLegacyAuthCookies(res, result, cookiesConfig, env, baseUrl);
90
+
91
+ // Code that builds its own Better-Auth cookie helper
92
+ createCookieHelper(basePath, { ...options, secureTransport: this.betterAuthService.usesSecureCookies() });
93
+ ```
94
+
95
+ Without the argument the helper keeps the previous, environment-only rule — nothing breaks, the fix just does
96
+ not reach that path.
97
+ - **Your tests stub `CoreBetterAuthService`**: no change needed. The controller calls `usesSecureCookies()`
98
+ optionally, so a stub without it keeps the previous behaviour.
99
+
100
+ ## 3. Audit suppression GHSA-ch52-4w7c-c8xp removed (repository only)
101
+
102
+ This repository no longer lists GHSA-ch52-4w7c-c8xp (`http-cache-semantics <= 4.2.0`, dev tooling only:
103
+ `@swc/cli` > … > `cacheable-request`) in `auditConfig.ignoreGhsas`. Its lockfile now resolves 4.3.0, which
104
+ `cacheable-request`'s `^4.2.0` takes on any fresh resolve. Nothing here reaches the published package.
105
+
106
+ 4.3.0 is **not a fix**: its max-stale code is identical to 4.2.0's. It only lies outside the advisory's declared
107
+ range, because the advisory was written as "up to the newest release" and never followed. The maintainer disputes
108
+ the report (kornelski/http-cache-semantics#56); a withdrawal request is open (github/advisory-database#10139),
109
+ and an independent re-test there reproduces the behaviour through 4.3.0, so a range extension is possible.
110
+
111
+ **For starter-derived projects** that carry the same entry (nest-server-starter 11.41.7 – 11.42.11):
112
+
113
+ - Lockfile on 4.3.0 (`pnpm why http-cache-semantics`): remove the entry from `ignoreGhsas` together with its row in
114
+ `tests/unit/audit-suppression-scope.spec.ts`. On 4.3.0 the entry hides nothing and would swallow the advisory
115
+ unseen the day its range is extended; without it, that day turns `pnpm audit` red, which is the moment to
116
+ re-argue the dev-only case.
117
+ - Lockfile still on 4.2.0: `pnpm update http-cache-semantics` first, then as above. Keep the entry instead if
118
+ your resolve cannot move.
119
+
120
+ ## Compatibility Notes
121
+
122
+ | Pattern | Status |
123
+ | ------- | ------ |
124
+ | npm-mode and vendor-mode projects without cookie-related overrides | Nothing to do |
125
+ | `lt dev up` / `lt dev test` / starter e2e scripts reading auth links from the log | Unchanged — they run as `local` / `e2e` |
126
+ | Subclass overriding `processCookies()` (legacy) | Pass `baseUrl` (§2), otherwise unchanged behaviour |
127
+ | Custom `createCookieHelper()` call | Pass `secureTransport` (§2), otherwise unchanged behaviour |
128
+ | Test stubs of `CoreBetterAuthService` | Compatible |
129
+
130
+ ## Troubleshooting
131
+
132
+ **The `[PASSWORD RESET]` / `[EMAIL VERIFICATION]` line disappeared from your local log**
133
+ Your environment is not named `local`, `ci` or `e2e`. Set `LT_LOG_AUTH_URLS=1` locally (§1).
134
+
135
+ **After the update, sign-in succeeds but the next request is anonymous on a non-production stage**
136
+ The browser dropped the now-`Secure` session cookie because the page or API is served over http while `baseUrl`
137
+ says https. Serve https or correct `baseUrl` (§2).
138
+
139
+ ## Module Documentation
140
+
141
+ - [Better-Auth module README](../src/core/modules/better-auth/README.md) — `usesSecureCookies()`
142
+ - [Configurable features](../.claude/rules/configurable-features.md) — Cookies row, Outbound URL Guard row
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.42.11",
3
+ "version": "11.42.12",
4
4
  "description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
5
5
  "keywords": [
6
6
  "node",
@@ -51,23 +51,37 @@ export interface AuthCookieDefaultOptions {
51
51
  *
52
52
  * - `httpOnly: true` — prevents JavaScript access (XSS mitigation)
53
53
  * - `sameSite: 'lax'` — CSRF mitigation
54
- * - `secure: isProductionLikeEnv(env)` — HTTPS-only in production/staging
54
+ * - `secure` — HTTPS-only on an `https://` `baseUrl`, and always in production/staging
55
55
  *
56
- * Used by both Legacy Auth and BetterAuth cookie helpers for consistent security.
56
+ * Used by the Legacy Auth cookie helper. (The BetterAuth helper decides `secure` the same way, but
57
+ * reads the https half off the Better-Auth instance.)
57
58
  *
58
59
  * @param env - App-level environment from `IServerOptions.env` (e.g. `'production'`, `'staging'`, `'ci'`).
59
60
  * Falls back to `process.env.NODE_ENV === 'production'` if absent.
61
+ * @param baseUrl - The server's `IServerOptions.baseUrl`. An `https://` value sets `secure` whatever
62
+ * the environment is called — since 11.42.12, because the deployed `develop` / `test`
63
+ * stages of a starter-based project are not production-like and got cookies without it.
60
64
  *
61
65
  * @since 11.25.0
62
66
  */
63
- export function getDefaultAuthCookieOptions(env?: string): AuthCookieDefaultOptions {
67
+ export function getDefaultAuthCookieOptions(env?: string, baseUrl?: string): AuthCookieDefaultOptions {
64
68
  return {
65
69
  httpOnly: true,
66
70
  sameSite: 'lax',
67
- secure: isProductionLikeEnv(env),
71
+ secure: isProductionLikeEnv(env) || isHttpsUrl(baseUrl),
68
72
  };
69
73
  }
70
74
 
75
+ /**
76
+ * Whether a URL uses https, the transport signal for the `Secure` cookie attribute (Better-Auth
77
+ * derives its own the same way). Trimmed and case-insensitive; anything that is not a string is not.
78
+ *
79
+ * @since 11.42.12
80
+ */
81
+ function isHttpsUrl(url: unknown): boolean {
82
+ return typeof url === 'string' && url.trim().toLowerCase().startsWith('https://');
83
+ }
84
+
71
85
  /**
72
86
  * Asserts that the cookies configuration is safe for production/staging environments.
73
87
  *
@@ -114,6 +128,7 @@ export function assertCookiesProductionSafe(
114
128
  * @param result - Auth result containing `token` and `refreshToken` (modified in place)
115
129
  * @param cookies - The `cookies` config value from IServerOptions
116
130
  * @param env - App-level env from `IServerOptions.env` (used for `secure` flag derivation)
131
+ * @param baseUrl - `IServerOptions.baseUrl`; an `https://` value sets `secure` too (since 11.42.12)
117
132
  * @returns The (possibly modified) result object
118
133
  *
119
134
  * @since 11.25.0
@@ -123,12 +138,13 @@ export function setLegacyAuthCookies<T extends { refreshToken?: string; token?:
123
138
  result: T,
124
139
  cookies: boolean | ICookiesConfig | undefined,
125
140
  env?: string,
141
+ baseUrl?: string,
126
142
  ): T {
127
143
  if (!isCookiesEnabled(cookies)) {
128
144
  return result;
129
145
  }
130
146
 
131
- const cookieOptions = getDefaultAuthCookieOptions(env);
147
+ const cookieOptions = getDefaultAuthCookieOptions(env, baseUrl);
132
148
 
133
149
  // If result is absent or not an object, clear any existing cookies (logout path)
134
150
  if (!result || typeof result !== 'object') {
@@ -261,12 +277,40 @@ export const LOCALHOST_URL_DEFAULTS = {
261
277
  } as const;
262
278
 
263
279
  /**
264
- * Environments that fall back to {@link LOCALHOST_URL_DEFAULTS} when no URLs are configured.
280
+ * The LOCAL environments: they run on a developer machine or in a test job, never as a deployment.
281
+ *
282
+ * They fall back to {@link LOCALHOST_URL_DEFAULTS} when no URLs are configured, and
283
+ * {@link isLocalEnv} reads this list for every other "local only" decision (the SSRF guard's
284
+ * private targets, the auth-link log). One list, so the decisions cannot drift apart.
285
+ *
286
+ * Deliberately NOT `development` or `test`: in projects built from nest-server-starter `test` is a
287
+ * DEPLOYED stage (often the customer's QA stage), and `develop`/`development` name a deployed dev
288
+ * stage as often as a laptop.
265
289
  *
266
290
  * @since 11.27.5
267
291
  */
268
292
  export const LOCALHOST_URL_ENVS: readonly string[] = ['ci', 'e2e', 'local'];
269
293
 
294
+ /**
295
+ * Checks whether the given environment is local ({@link LOCALHOST_URL_ENVS}: `local`, `ci`, `e2e`),
296
+ * matched trimmed and case-insensitively.
297
+ *
298
+ * Not the complement of {@link isProductionLikeEnv}. That one answers "must this be hardened?" and
299
+ * names only the environments that obviously hold real users; everything it does not name counts
300
+ * as non-production, including the deployed `develop` and `test` stages of a starter-based project.
301
+ * Use this one when the question is the opposite — "may this run without protection?" — so that an
302
+ * environment nobody listed stays protected. An unknown or missing name answers `false`.
303
+ *
304
+ * @since 11.42.12
305
+ */
306
+ export function isLocalEnv(env?: string): boolean {
307
+ return LOCALHOST_URL_ENVS.includes(
308
+ String(env ?? '')
309
+ .trim()
310
+ .toLowerCase(),
311
+ );
312
+ }
313
+
270
314
  /**
271
315
  * The hostname label stripped from `baseUrl` to derive `appUrl`.
272
316
  */
@@ -3,6 +3,7 @@ import { BlockList, isIP } from 'node:net';
3
3
  import { Agent, buildConnector, fetch as undiciFetch } from 'undici';
4
4
 
5
5
  import { ConfigService } from '../services/config.service';
6
+ import { isLocalEnv } from './cookies.helper';
6
7
 
7
8
  /**
8
9
  * Requests to a URL a USER entered — a webhook, an export target, an ERP address.
@@ -53,12 +54,6 @@ for (const [network, prefix] of [
53
54
  blocked.addSubnet(network, prefix, 'ipv6');
54
55
  }
55
56
 
56
- /**
57
- * Environments in which internal targets are allowed unless configured otherwise. Deliberately NOT
58
- * `test`: in projects built from nest-server-starter that is a DEPLOYED stage.
59
- */
60
- const LOCAL_ENVIRONMENTS = new Set(['ci', 'e2e', 'local']);
61
-
62
57
  /** Thrown for a target that is, or resolves to, an internal address. */
63
58
  export class OutboundUrlBlockedError extends Error {
64
59
  constructor(
@@ -93,10 +88,9 @@ export function privateOutboundTargetsAllowed(): boolean {
93
88
  if (flag === false || flag === 'false') {
94
89
  return false;
95
90
  }
96
- const env = String(config?.env ?? process.env.NODE_ENV ?? '')
97
- .trim()
98
- .toLowerCase();
99
- return LOCAL_ENVIRONMENTS.has(env);
91
+ // Internal targets are allowed only in the local environments (`isLocalEnv`), deliberately not
92
+ // in `test`: in projects built from nest-server-starter that is a DEPLOYED stage.
93
+ return isLocalEnv(config?.env ?? process.env.NODE_ENV);
100
94
  }
101
95
 
102
96
  /** Whether an IP address is internal. A hostname (not an IP) answers false — resolve it first. */
@@ -192,6 +192,7 @@ export class CoreAuthController {
192
192
  protected processCookies(res: ResponseType, result: any) {
193
193
  const cookiesConfig = this.configService.getFastButReadOnly<boolean | ICookiesConfig>('cookies');
194
194
  const env = this.configService.getFastButReadOnly<string>('env');
195
- return setLegacyAuthCookies(res, result, cookiesConfig, env);
195
+ const baseUrl = this.configService.getFastButReadOnly<string>('baseUrl');
196
+ return setLegacyAuthCookies(res, result, cookiesConfig, env, baseUrl);
196
197
  }
197
198
  }
@@ -174,6 +174,7 @@ export class CoreAuthResolver {
174
174
  protected processCookies(ctx: { res: ResponseType }, result: any) {
175
175
  const cookiesConfig = this.configService.getFastButReadOnly<boolean | ICookiesConfig>('cookies');
176
176
  const env = this.configService.getFastButReadOnly<string>('env');
177
- return setLegacyAuthCookies(ctx.res, result, cookiesConfig, env);
177
+ const baseUrl = this.configService.getFastButReadOnly<string>('baseUrl');
178
+ return setLegacyAuthCookies(ctx.res, result, cookiesConfig, env, baseUrl);
178
179
  }
179
180
  }
@@ -1505,6 +1505,7 @@ export class MyService {
1505
1505
  | `getBasePath()` | Get the base path for endpoints |
1506
1506
  | `getBaseUrl()` | Get the base URL |
1507
1507
  | `getCookieDomain()` | Get resolved cross-subdomain cookie domain |
1508
+ | `usesSecureCookies()` | Whether Better-Auth's cookies carry Secure |
1508
1509
  | `getSession(req)` | Get current session from request |
1509
1510
  | `revokeSession(token)` | Revoke a session (logout) |
1510
1511
  | `isSessionExpiringSoon(session, t?)` | Check if session is expiring soon |
@@ -172,6 +172,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
172
172
  env,
173
173
  legacyCookieEnabled: false, // Middleware doesn't need legacy cookie
174
174
  secret: config?.secret, // Required for cookie signing
175
+ secureTransport: this.betterAuthService.usesSecureCookies?.() === true, // Same `Secure` rule as Better-Auth
175
176
  },
176
177
  this.logger,
177
178
  );
@@ -81,6 +81,16 @@ export interface BetterAuthCookieHelperConfig {
81
81
  * CRITICAL: Required for Passkey/2FA to work correctly.
82
82
  */
83
83
  secret?: string;
84
+ /**
85
+ * Whether Better-Auth's own handlers set `Secure` on the cookies they write
86
+ * (`CoreBetterAuthService.usesSecureCookies()`). `true` makes this helper set it too, whatever the
87
+ * environment, so one session cookie never carries two different transport rules.
88
+ *
89
+ * @since 11.42.12 Before, `secure` followed {@link isProductionLikeEnv} alone, so on the deployed
90
+ * `develop` / `test` stages of a starter-based project the cookie this helper wrote
91
+ * lacked `Secure` while Better-Auth's handlers set it on the same https deployment.
92
+ */
93
+ secureTransport?: boolean;
84
94
  }
85
95
 
86
96
  /**
@@ -146,9 +156,11 @@ export class BetterAuthCookieHelper {
146
156
  /**
147
157
  * Gets the default cookie options for authentication cookies.
148
158
  *
149
- * The `secure` flag is `true` when either `config.env` is production-like
150
- * (`production` / `staging`) or `NODE_ENV === 'production'`. This covers
151
- * staging deployments where only one of the two signals is set.
159
+ * The `secure` flag is `true` when Better-Auth's own cookies are secure (`config.secureTransport`,
160
+ * i.e. an `https://` base URL unless the project opted out), when `config.env` is production-like
161
+ * (`production` / `staging`), or when `NODE_ENV === 'production'`. The first covers every https
162
+ * deployment whatever its environment name; the other two keep `Secure` where real users are
163
+ * certain even if a project switched it off in Better-Auth.
152
164
  *
153
165
  * @returns Cookie options with httpOnly, sameSite, and secure settings
154
166
  */
@@ -156,7 +168,7 @@ export class BetterAuthCookieHelper {
156
168
  const options: AuthCookieOptions = {
157
169
  httpOnly: true,
158
170
  sameSite: 'lax',
159
- secure: isProductionLikeEnv(this.config.env),
171
+ secure: this.config.secureTransport === true || isProductionLikeEnv(this.config.env),
160
172
  };
161
173
 
162
174
  if (this.config.domain) {
@@ -403,7 +415,13 @@ export class BetterAuthCookieHelper {
403
415
  */
404
416
  export function createCookieHelper(
405
417
  basePath: string,
406
- options?: { domain?: string; env?: string; legacyCookieEnabled?: boolean; secret?: string },
418
+ options?: {
419
+ domain?: string;
420
+ env?: string;
421
+ legacyCookieEnabled?: boolean;
422
+ secret?: string;
423
+ secureTransport?: boolean;
424
+ },
407
425
  logger?: Logger,
408
426
  ): BetterAuthCookieHelper {
409
427
  return new BetterAuthCookieHelper({
@@ -413,5 +431,6 @@ export function createCookieHelper(
413
431
  legacyCookieEnabled: options?.legacyCookieEnabled ?? false,
414
432
  logger,
415
433
  secret: options?.secret,
434
+ secureTransport: options?.secureTransport,
416
435
  });
417
436
  }
@@ -4,7 +4,7 @@ import ejs = require('ejs');
4
4
  import * as fs from 'fs';
5
5
  import * as path from 'path';
6
6
 
7
- import { isProductionLikeEnv, resolveAppUrlFromConfig } from '../../common/helpers/cookies.helper';
7
+ import { isLocalEnv, isProductionLikeEnv, resolveAppUrlFromConfig } from '../../common/helpers/cookies.helper';
8
8
  import { maskEmail } from '../../common/helpers/logging.helper';
9
9
  import { IBetterAuthEmailVerificationConfig } from '../../common/interfaces/server-options.interface';
10
10
  import { BrevoService } from '../../common/services/brevo.service';
@@ -838,25 +838,35 @@ export class CoreBetterAuthEmailVerificationService {
838
838
  * Print an auth link (verification / password reset) to stdout for local development.
839
839
  *
840
840
  * The URL embeds a bearer token: the verification link confirms an address, the reset link
841
- * changes a password outright. Neither may reach a deployment holding real accounts, so the gate
842
- * is `isProductionLikeEnv()` — the same two-layer check `EmailService` and the cookie helpers
843
- * already use. `NODE_ENV !== 'production'` alone is NOT enough: a staging deployment sets
844
- * `NODE_ENV=staging` so `getEnvironmentConfig()` loads its config block, which passes that test
845
- * while holding real users.
841
+ * changes a password outright. Neither may reach a deployment's logs, so the link is printed only
842
+ * in a LOCAL environment (`isLocalEnv()`: `local`, `ci`, `e2e`) — an allowlist, not "anything
843
+ * that is not production". Until 11.42.12 the gate was `!isProductionLikeEnv()`, which names only
844
+ * `production` and `staging`; the deployed `develop` and `test` stages of a starter-based project
845
+ * passed it and wrote live reset links into their log pipeline, where log access alone was
846
+ * enough to take over an account.
847
+ *
848
+ * `LT_LOG_AUTH_URLS=1` opts in for another environment that runs on a developer machine (this
849
+ * repository's own `development`, for one); `LT_LOG_AUTH_URLS=0` suppresses it everywhere. A
850
+ * production-like environment never prints, whatever the variable says: the opt-in exists for
851
+ * laptops, and a hard floor keeps it from being the thing that reopens a deployment.
846
852
  *
847
853
  * The address is masked (PII, and the rest of this file already masks it); the URL is printed in
848
- * full because following it without a mail server is the whole point locally. Set
849
- * `LT_LOG_AUTH_URLS=0` to suppress it even outside production.
854
+ * full because following it without a mail server is the whole point locally.
850
855
  *
851
856
  * `console.log` rather than the NestJS logger, deliberately and for two reasons: the logger
852
857
  * buffers, which makes interception unreliable under Vitest, and a logger call would route the
853
858
  * token into `HubLogBufferService`'s ring buffer, which is readable over HTTP by any ADMIN.
854
859
  */
855
860
  protected logAuthUrlForDevelopment(label: string, email: string, url: string): void {
856
- if (process.env.LT_LOG_AUTH_URLS === '0') {
861
+ const optIn = process.env.LT_LOG_AUTH_URLS;
862
+ if (optIn === '0') {
863
+ return;
864
+ }
865
+ const env = this.configService?.getFastButReadOnly<string>('env') ?? process.env.NODE_ENV;
866
+ if (isProductionLikeEnv(env)) {
857
867
  return;
858
868
  }
859
- if (isProductionLikeEnv(this.configService?.getFastButReadOnly<string>('env'))) {
869
+ if (!isLocalEnv(env) && optIn !== '1') {
860
870
  return;
861
871
  }
862
872
  // oxlint-disable-next-line no-console
@@ -268,6 +268,10 @@ export class CoreBetterAuthController {
268
268
  env: this.configService.getFastButReadOnly<string>('env'),
269
269
  legacyCookieEnabled: legacyAuthEnabled,
270
270
  secret: betterAuthConfig?.secret,
271
+ // Mirror Better-Auth's own `Secure` decision, so the cookie this controller writes and the
272
+ // one Better-Auth's handlers write follow the same transport rule on every https deployment.
273
+ // Optional call: a project's test stub of the service may predate the method.
274
+ secureTransport: this.betterAuthService.usesSecureCookies?.() === true,
271
275
  },
272
276
  this.logger,
273
277
  );
@@ -703,6 +703,30 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleIn
703
703
  return this.config.baseUrl || 'http://localhost:3000';
704
704
  }
705
705
 
706
+ /**
707
+ * Whether Better-Auth's own handlers set `Secure` on the cookies they write, read off the live
708
+ * instance.
709
+ *
710
+ * `createBetterAuthInstance()` pins `useSecureCookies: false` (for the cookie NAME) and restores
711
+ * the transport flag through `advanced.defaultCookieAttributes.secure` on an `https://` base URL;
712
+ * a project may override either. Reading the instance rather than re-deriving from a URL gives
713
+ * exactly the answer Better-Auth applies — including the base URL it actually uses, which
714
+ * {@link getBaseUrl} does not know when only the server's `baseUrl` is set.
715
+ *
716
+ * The framework's own cookie helper mirrors this, so a session cookie carries `Secure` no matter
717
+ * which path wrote it.
718
+ *
719
+ * @since 11.42.12
720
+ */
721
+ usesSecureCookies(): boolean {
722
+ const advanced = (
723
+ this.getInstance() as unknown as {
724
+ options?: { advanced?: { defaultCookieAttributes?: { secure?: unknown }; useSecureCookies?: unknown } };
725
+ } | null
726
+ )?.options?.advanced;
727
+ return advanced?.useSecureCookies === true || advanced?.defaultCookieAttributes?.secure === true;
728
+ }
729
+
706
730
  /**
707
731
  * Gets the resolved cookie domain for cross-subdomain cookie sharing.
708
732
  *