Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion FRAMEWORK-API.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# @lenne.tech/nest-server — Framework API Reference

> Auto-generated from source code on 2026-05-31 (v11.26.1)
> Auto-generated from source code on 2026-06-03 (v11.26.2)
> File: `FRAMEWORK-API.md` — compact, machine-readable API surface for Claude Code

## CoreModule.forRoot()
Expand Down
234 changes: 234 additions & 0 deletions migration-guides/11.26.1-to-11.26.2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
# Migration Guide: 11.26.1 → 11.26.2

## Overview

| Category | Details |
|----------|---------|
| **Breaking Changes** | None |
| **Bugfixes** | Latent BetterAuth session-cookie drift fixed — six call sites that independently derived the cookie name from `basePath` now share a single resolver, so a `cookiePrefix` override no longer breaks sign-in / authenticated requests / sign-out |
| **New Features** | New `COOKIE_PREFIX` env variable — isolates the BetterAuth session cookie name on shared hosts (e.g. several lenne.tech apps on `*.localhost`). New helper module `better-auth-cookie-prefix.helper.ts` exporting `resolveBetterAuthCookiePrefix()`, `resolveBetterAuthSessionCookieName()`, `detectCookiePrefixDrift()`. New `CoreBetterAuthService.getCookiePrefix()`. Drift warning when `options.advanced.cookiePrefix` is used programmatically |
| **Migration Effort** | 0 minutes (automatic) — opt-in `COOKIE_PREFIX` for multi-app shared-host deployments only |

---

## Quick Migration

No code changes required. The fix and the new resolver activate automatically; `COOKIE_PREFIX` is opt-in.

```bash
# Update package
pnpm add @lenne.tech/nest-server@11.26.2

# Verify build
pnpm run build

# Run tests
pnpm test
```

---

## What's New in 11.26.2

### 1. `COOKIE_PREFIX` env variable — isolate auth cookies per app

**Use case:** Several lenne.tech apps deployed on the same host (e.g. via `lt dev` — `nest-server.localhost`, `offers.localhost`, `showroom.localhost` all served by Caddy on the same machine). Browser cookies are scoped by host, not port — without isolation a session cookie from one app collides with another and authentication breaks. The BetterAuth REST surface in 11.26.1 derives the cookie name from `basePath` (default: `iam.session_token`), which is identical across apps.

**Fix:** Set `COOKIE_PREFIX` per app — the BetterAuth session cookie becomes `<prefix>.session_token`:

```bash
# App A
COOKIE_PREFIX=offers # → cookie name: offers.session_token

# App B
COOKIE_PREFIX=showroom # → cookie name: showroom.session_token
```

**Precedence (resolved by `resolveBetterAuthCookiePrefix`):**

1. **`COOKIE_PREFIX` env** (dedicated, always wins) — sanitised to the safe cookie-name subset `[A-Za-z0-9._-]`; if it sanitises to empty it is ignored
2. otherwise the **basePath-derived** prefix (`/iam` → `iam`, `/api/iam` → `api.iam`) — the previous default, fully backward compatible when `COOKIE_PREFIX` is unset

**Frontend pairing (required when set):** The frontend `@lenne.tech/nuxt-extensions` exposes `NUXT_PUBLIC_COOKIE_PREFIX` (same precedence, same sanitisation). The two sides MUST agree, otherwise the browser sends one name and the server reads another. The backend logs a `COOKIE_PREFIX override active → …` line on bootstrap to make the override visible in operator logs.

### 2. Single source of truth helper module

New file: `src/core/modules/better-auth/better-auth-cookie-prefix.helper.ts`. Dependency-free on purpose so it can be imported from the config builder, the service, controllers and helpers without any import cycle.

```typescript
// All public API:
import {
resolveBetterAuthCookiePrefix, // → 'iam' (default) or 'acme' (under COOKIE_PREFIX=acme)
resolveBetterAuthSessionCookieName, // → 'iam.session_token' or 'acme.session_token'
detectCookiePrefixDrift, // → null | warning string
} from '@lenne.tech/nest-server';
```

A `@deprecated` re-export from `./better-auth.config` keeps old imports working — new code should import from the helper directly.

### 3. `CoreBetterAuthService.getCookiePrefix()` (new public method)

```typescript
class CoreBetterAuthService {
/** Cached on first read so it cannot drift away from the Better-Auth instance,
* which captures the prefix once at bootstrap. */
getCookiePrefix(): string;
getSessionCookieName(): string; // unchanged signature, now backed by getCookiePrefix()
}
```

### 4. Drift warning when `options.advanced.cookiePrefix` is set programmatically

```typescript
betterAuth: {
options: {
advanced: { cookiePrefix: 'custom' }, // ← BetterAuth would honour this, NestJS layer would not
},
}
```

This pattern silently broke sign-in / read / sign-out in 11.26.1 and earlier. 11.26.2 detects the drift via `detectCookiePrefixDrift()` and emits a loud `logger.warn` at bootstrap:

```
options.advanced.cookiePrefix="custom" overrides Better-Auth but the NestJS layer
still uses "iam". This will break sign-in / read / sign-out — use the COOKIE_PREFIX
env variable instead (honoured by every call site).
```

---

## What's Fixed in 11.26.2

### Cross-layer cookie-prefix drift in the BetterAuth pipeline

**Affects:** Any project that set a non-default `cookiePrefix` via `options.advanced.cookiePrefix` or via the proposed `COOKIE_PREFIX` env (introduced here). Default deployments (no override) are not affected.

**Symptom (before 11.26.2):**
With a non-default cookie prefix, Better-Auth set `Set-Cookie: <prefix>.session_token=…` but the NestJS layer kept reading `iam.session_token`:

| Stage | Cookie name in 11.26.1 | Result |
|---|---|---|
| Sign-up / Sign-in | `<prefix>.session_token` (Better-Auth) | Cookie correctly set by Better-Auth |
| Authenticated request | `iam.session_token` ([core-better-auth.controller.ts:778-781](../src/core/modules/better-auth/core-better-auth.controller.ts)) | User reads as anonymous (`success: false`) |
| `getSession()` cookie-signing | `iam.session_token` ([core-better-auth.service.ts:437-438](../src/core/modules/better-auth/core-better-auth.service.ts)) | Session never resolved |
| `extractSessionToken` (middleware) | `iam.session_token` ([core-better-auth-web.helper.ts:98-103](../src/core/modules/better-auth/core-better-auth-web.helper.ts)) | 401 on protected routes |
| `BetterAuthCookieHelper` (set + clear) | `iam.session_token` ([core-better-auth-cookie.helper.ts:127-128](../src/core/modules/better-auth/core-better-auth-cookie.helper.ts)) | Sign-out leaves real cookie behind |

**Fix (in 11.26.2):**
All six call sites now resolve the cookie name through `resolveBetterAuthSessionCookieName(basePath)` — a single function that honours `COOKIE_PREFIX` and falls back to the basePath default. Cached on the service so a late `process.env` mutation (typical in tests) cannot drift the value away from the Better-Auth instance, which captures the prefix at bootstrap.

---

## Compatibility Notes

- **Default deployments (no `COOKIE_PREFIX`, no programmatic override):** Cookie name remains `iam.session_token`, behaviour is bit-for-bit identical to 11.26.1. No change is observable.
- **Projects that read `iam.session_token` directly in tests (hardcoded strings):** Continue to work as long as `COOKIE_PREFIX` is unset. Under override the hardcoded name is wrong — prefer `resolveBetterAuthSessionCookieName('/iam')` or the `TestHelper.extractSessionToken()` default (which now resolves through the same helper).
- **`TestHelper.extractSessionToken(response, cookieName?)`:** The second parameter is now optional; when omitted it derives the cookie name through the shared resolver (so tests under `COOKIE_PREFIX=acme` automatically look at `acme.session_token`). Existing call sites that pass an explicit name are unaffected.
- **`TestHelper.buildBetterAuthCookies(token, basePath = 'iam')`:** Already honoured `COOKIE_PREFIX` since the prior release via the same resolver — no caller change required.
- **Programmatic `options.advanced.cookiePrefix`:** Still applied to the Better-Auth instance (no behaviour change in Better-Auth), but now emits a `logger.warn` drift notice on bootstrap. Switch to `COOKIE_PREFIX` (env) to remove the warning and the latent breakage.
- **`BetterAuthCookieHelper.getNormalizedBasePath()`:** Unchanged — still returns the basePath-derived string (e.g. `'iam'`). It is **NOT** a cookie prefix; the JSDoc now carries a loud warning so future code never reconstructs the cookie name as `` `${getNormalizedBasePath()}.session_token` `` (which would re-introduce the drift).
- **Vendor-mode consumers:** Same as npm consumers; the new file ships under `src/core/modules/better-auth/`.

---

## Adopting `COOKIE_PREFIX` (Optional)

### Step 1: Decide the prefix per app

Pick a short, unique slug per app — typically the project slug (`offers`, `showroom`) or a kebab/dot subset that matches your environment hygiene.

| Pick | Valid? | Result |
|---|---|---|
| `offers` | ✓ | `offers.session_token` |
| `kit-test_01` | ✓ | `kit-test_01.session_token` |
| `a;c=me x\r\n` | sanitised | `acmex.session_token` (semicolons, equals, whitespace, CR/LF stripped) |
| `;;==` | sanitises to empty → falls back to basePath | `iam.session_token` (the env is ignored) |

### Step 2: Set both sides in lockstep

```bash
# Backend (this package)
COOKIE_PREFIX=offers

# Frontend (@lenne.tech/nuxt-extensions)
NUXT_PUBLIC_COOKIE_PREFIX=offers
```

### Step 3: Verify

```bash
# Bootstrap should log:
# COOKIE_PREFIX override active → auth cookies use prefix "offers" (e.g. "offers.session_token").
# The frontend NUXT_PUBLIC_COOKIE_PREFIX MUST match.

# Sign in and inspect the Set-Cookie header — it must use the overridden name:
curl -i -X POST http://localhost:3000/iam/sign-in/email \
-H 'Content-Type: application/json' \
-d '{"email":"…","password":"…"}' \
| grep -i set-cookie
# Set-Cookie: offers.session_token=…; Path=/; HttpOnly; …
```

---

## Troubleshooting

### After setting `COOKIE_PREFIX`, sign-in succeeds but every follow-up request is unauthenticated

Verify the frontend `NUXT_PUBLIC_COOKIE_PREFIX` matches the backend value. The most common cause is one side set in `.env` and the other still inheriting the default. The backend log line `COOKIE_PREFIX override active → …` confirms the backend value; check the browser's DevTools → Application → Cookies for the actual cookie name the browser holds.

### Bootstrap log says `options.advanced.cookiePrefix="…" overrides Better-Auth but the NestJS layer still uses "…"`

You are setting the cookie prefix programmatically via `betterAuth.options.advanced.cookiePrefix`. Move the override to the `COOKIE_PREFIX` env variable — that is the only path that is honoured by every call site (sign-up, sign-in, get-session, sign-out, middleware). The programmatic override is left untouched but the NestJS layer cannot follow it, so sign-in writes one cookie and authenticated requests look for another.

### Existing browser cookies under the old name keep the user "logged in" after switching `COOKIE_PREFIX`

Expected. Browser cookies are persistent — changing the prefix does not retroactively rename them. Users will be silently signed out (the server no longer reads the old name) and sign in again, after which the new cookie is set. Old cookies fall out of the browser at their max-age. To force a clean state, instruct users to clear cookies for the affected host, or set a one-off `Clear-Site-Data: "cookies"` header during the rollout.

### Tests under `COOKIE_PREFIX=acme` return `{ success: false }` from `/iam/session` although sign-in succeeded

Most likely you are passing the JWT-converted token (sign-in response body's `token` field) instead of the raw session token. With `betterAuth.jwt` enabled the response token is a JWT (`eyJ…`), which goes in the `Authorization: Bearer` header — not in the session cookie. For cookie-based authenticated tests, read the raw token from the `session` collection:

```typescript
const sessionRow = await db.collection('session').findOne(
{ $or: [{ userId: iamUser._id }, { userId: iamUser._id.toString() }] },
{ sort: { createdAt: -1 } },
);
const rawSessionToken = sessionRow.token;
```

See `tests/stories/better-auth-cookie-prefix.story.test.ts` for a complete e2e reference.

### `TestHelper.extractSessionToken(response)` returns `null` although the cookie is in the Set-Cookie header

You are likely on a `COOKIE_PREFIX=acme` setup but pass an explicit `cookieName: 'iam.session_token'` as the second argument. Either omit the argument (the new default goes through the resolver) or pass the resolved name explicitly.

---

## Module Documentation

### BetterAuth Module

- **README:** [src/core/modules/better-auth/README.md](../src/core/modules/better-auth/README.md)
- **Integration Checklist:** [src/core/modules/better-auth/INTEGRATION-CHECKLIST.md](../src/core/modules/better-auth/INTEGRATION-CHECKLIST.md)
- **Customization Guide:** [src/core/modules/better-auth/CUSTOMIZATION.md](../src/core/modules/better-auth/CUSTOMIZATION.md)
- **Reference Implementation:** `src/server/modules/better-auth/`
- **Key Files:**
- `src/core/modules/better-auth/better-auth-cookie-prefix.helper.ts` — single source of truth for the prefix (`resolveBetterAuthCookiePrefix`, `resolveBetterAuthSessionCookieName`, `detectCookiePrefixDrift`)
- `src/core/modules/better-auth/better-auth.config.ts` — bootstrap-time resolution + drift warning + `@deprecated` re-export
- `src/core/modules/better-auth/core-better-auth.service.ts` — `getCookiePrefix()` (new, cached), `getSessionCookieName()` (now via cache)
- `src/core/modules/better-auth/core-better-auth.controller.ts`, `core-better-auth-cookie.helper.ts`, `core-better-auth-web.helper.ts` — all converted to the shared resolver
- **Reference tests:**
- `tests/unit/better-auth-cookie-prefix.spec.ts` — pure resolver + drift detector
- `tests/unit/better-auth-cookie-helper.spec.ts` — cross-layer set/read lockstep + service cache + `TestHelper` default
- `tests/stories/better-auth-cookie-prefix.story.test.ts` — e2e sign-up / authenticated request / sign-out against a real Mongo + Better-Auth boot under `COOKIE_PREFIX=acme`

---

## References

- [Migration Guide 11.26.0 → 11.26.1](./11.26.0-to-11.26.1.md) — Previous release (roles in REST auth response)
- [Configurable Features](../.claude/rules/configurable-features.md) — Pattern notes for env-driven overrides
- [BetterAuth module rules](../.claude/rules/better-auth.md) — Standard-compliance & security baselines
- [nest-server-starter](https://github.com/lenneTech/nest-server-starter) (reference implementation)
- [@lenne.tech/nuxt-extensions `resolveLtCookiePrefix`](https://github.com/lenneTech/nuxt-extensions) — frontend pendant (`NUXT_PUBLIC_COOKIE_PREFIX`)
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@lenne.tech/nest-server",
"version": "11.26.1",
"version": "11.26.2",
"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).",
"keywords": [
"node",
Expand Down
2 changes: 1 addition & 1 deletion spectaql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ servers:
info:
title: lT Nest Server
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).
version: 11.26.1
version: 11.26.2
contact:
name: lenne.Tech GmbH
url: https://lenne.tech
Expand Down
84 changes: 84 additions & 0 deletions src/core/modules/better-auth/better-auth-cookie-prefix.helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* Single source of truth for the Better-Auth session cookie prefix.
*
* The session cookie is named `<prefix>.session_token` (e.g. `iam.session_token`).
* The prefix is resolved here — and ONLY here — so every place that sets, reads,
* signs, extracts or clears the session cookie agrees on the exact name. (A
* previous bug derived the name from `basePath` independently in 6 places, so a
* `COOKIE_PREFIX` override broke the auth pipeline: Better-Auth set
* `acme.session_token` while the NestJS layer still looked for `iam.session_token`.)
*
* Dependency-free on purpose so it can be imported from the config builder, the
* service, controllers and helpers without any import cycle.
*/

/**
* Characters allowed in a cookie-name token. A safe subset of RFC 6265 that is
* IDENTICAL to the frontend resolver (`@lenne.tech/nuxt-extensions`
* `resolveLtCookiePrefix`), so a shared `COOKIE_PREFIX` produces the SAME prefix
* on both sides. Everything else (spaces, `;`, `=`, `\r`, `\n`, …) is stripped so
* a typo can never corrupt the `Set-Cookie` header.
*/
function sanitizeCookiePrefix(raw: string): string {
return raw.trim().replace(/[^A-Za-z0-9._-]/g, '');
}

/**
* Resolve the Better-Auth cookie prefix (the `iam` in `iam.session_token`).
*
* Precedence:
* 1. **`COOKIE_PREFIX` env** (dedicated, always wins) — for fully autonomous
* cookie isolation on a shared host (several lenne.tech apps on the same
* host, where cookies collide by host, not port). Sanitised to valid
* cookie-name characters; if it sanitises to empty it is ignored.
* 2. otherwise the **basePath-derived** prefix (`/iam` → `iam`,
* `/api/iam` → `api.iam`) — the previous behaviour, fully backward
* compatible when `COOKIE_PREFIX` is unset.
*
* IMPORTANT: when `COOKIE_PREFIX` is set it MUST match the frontend
* `NUXT_PUBLIC_COOKIE_PREFIX` (see `@lenne.tech/nuxt-extensions`
* `resolveLtCookiePrefix`) — otherwise the two sides use different cookie names
* and authentication breaks.
*
* @param basePath - Better-Auth base path (e.g. `/iam`)
* @param env - environment to read `COOKIE_PREFIX` from (defaults to `process.env`)
*/
export function resolveBetterAuthCookiePrefix(basePath: string, env: NodeJS.ProcessEnv = process.env): string {
const basePathPrefix = (basePath || '/iam').replace(/^\//, '').replace(/\//g, '.');
const explicit = sanitizeCookiePrefix(typeof env.COOKIE_PREFIX === 'string' ? env.COOKIE_PREFIX : '');
return explicit || basePathPrefix;
}

/**
* Convenience: the full session-cookie name (`<prefix>.session_token`) for the
* given basePath, honouring `COOKIE_PREFIX`. Use this wherever the session
* cookie name is needed so all call sites stay in lockstep.
*/
export function resolveBetterAuthSessionCookieName(basePath: string, env: NodeJS.ProcessEnv = process.env): string {
return `${resolveBetterAuthCookiePrefix(basePath, env)}.session_token`;
}

/**
* Detect a Better-Auth cookie-prefix drift between the value the NestJS layer
* resolves (via {@link resolveBetterAuthCookiePrefix}) and a programmatic
* `options.advanced.cookiePrefix` passed straight to Better-Auth. Such a
* mismatch silently breaks the auth pipeline because Better-Auth sets the
* cookie under the programmatic prefix while the NestJS read/clear path still
* uses the resolved prefix.
*
* Returns `null` when there is no drift (no programmatic prefix, or it
* matches), otherwise a human-readable warning sentence ready for `logger.warn`.
*
* Extracted so the drift-detection logic is testable without booting the full
* Better-Auth instance (which requires Mongo).
*/
export function detectCookiePrefixDrift(resolvedPrefix: string, programmaticOptionsAdvanced: unknown): null | string {
if (!programmaticOptionsAdvanced || typeof programmaticOptionsAdvanced !== 'object') return null;
const programmaticPrefix = (programmaticOptionsAdvanced as Record<string, unknown>).cookiePrefix;
if (typeof programmaticPrefix !== 'string' || programmaticPrefix === resolvedPrefix) return null;
return (
`options.advanced.cookiePrefix="${programmaticPrefix}" overrides Better-Auth but the ` +
`NestJS layer still uses "${resolvedPrefix}". This will break sign-in / read / sign-out — ` +
`use the COOKIE_PREFIX env variable instead (honoured by every call site).`
);
}
Loading
Loading