# Migration Guide: 11.11.x → 11.12.x

## Overview

| Category | Details |
|----------|---------|
| **Breaking Changes** | Cookie structure simplified, `better-auth.session_token` removed |
| **New Features** | Auto AppName detection, Token analysis helpers, Cookie-Mode/JWT-Mode dual support |
| **Bugfixes** | Passkey/2FA now works correctly in both Cookie and JWT modes |
| **Migration Effort** | Low (~10 minutes) - Cookie access changes |

---

## Quick Migration

```bash
# Update package
npm install @lenne.tech/nest-server@11.12.x

# Verify build
npm run build

# Run tests
npm test
```

**Note:** If you directly access `better-auth.session_token` or `session` cookies in your code, see the Breaking Changes section below.

---

## What's New in 11.12.x

### 1. Simplified Cookie Strategy

The number of authentication cookies has been significantly reduced:

| Before (11.11.x) | After (11.12.x) |
|------------------|-----------------|
| `token` | `{basePath}.session_token` (e.g., `iam.session_token`) |
| `iam.session_token` | `token` (only if Legacy Auth active) |
| `better-auth.session_token` | *(removed)* |
| `session` | *(removed)* |
| Custom configured cookie | *(removed)* |

**Benefits:**
- Smaller request headers
- Fewer cookies to manage
- Closer alignment with Better-Auth's native behavior

### 2. Auto AppName Detection

The `rpName` (for Passkey) and `issuer` (for 2FA/TOTP) are now automatically derived from your project's `package.json`:

```typescript
// package.json: { "name": "my-awesome-app" }

// Automatically becomes:
// - rpName: "My Awesome App"
// - issuer: "My Awesome App"

// In development environments (local, test, development):
// - rpName: "My Awesome App (Local)"
// - issuer: "My Awesome App (Local)"
```

This helps users distinguish between Passkeys from different projects running on the same localhost.

**To override:**
```typescript
// config.env.ts
betterAuth: {
  passkey: {
    rpName: 'Custom Name',  // Override auto-detection
  },
  twoFactor: {
    appName: 'Custom Name', // Override auto-detection
  },
}
```

### 3. Improved Token Analysis

New helper functions for robust token type detection:

```typescript
import {
  analyzeToken,
  isLegacyJwt,
  isBetterAuthJwt,
  isSessionToken,
  TokenType,
} from '@lenne.tech/nest-server';

// Analyze a token's type by examining its payload
const result = analyzeToken(token);
// result.type: TokenType.LEGACY_JWT | TokenType.BETTER_AUTH_JWT | TokenType.SESSION_TOKEN

// Quick checks
if (isLegacyJwt(token)) {
  // Has 'id' claim, no 'sub' - handled by Passport
}
if (isBetterAuthJwt(token)) {
  // Has 'sub' claim - Better-Auth JWT
}
if (isSessionToken(token)) {
  // Opaque token, not a JWT - use session lookup
}
```

### 4. Cookie-Mode / JWT-Mode Dual Support

Passkey and 2FA now work correctly in both authentication modes:

| Mode | Cookie Behavior |
|------|-----------------|
| Cookie-Mode | Session token in `iam.session_token` cookie |
| JWT-Mode | Session token passed via Authorization header, challenges stored in database |

No configuration needed - the mode is auto-detected based on how the client authenticates.

---

## Breaking Changes

### 1. Cookie Names Changed

**If you directly access authentication cookies in your code, update the cookie names:**

**Before:**
```typescript
// Accessing cookies directly
const token = req.cookies['better-auth.session_token'];
const sessionId = req.cookies['session'];
```

**After:**
```typescript
// Use the basePath-based cookie name
const token = req.cookies['iam.session_token']; // Default basePath is 'iam'

// Or use the extractSessionToken helper
import { extractSessionToken } from '@lenne.tech/nest-server';
const token = extractSessionToken(req, '/iam');
```

### 2. Legacy Auth Cookies Now Default-Enabled

**Before (11.11.x):**
```typescript
// Cookies only set if `cookies: true` in config
if (this.configService.getFastButReadOnly('cookies')) {
  // Set cookies
}
```

**After (11.12.x):**
```typescript
// Cookies enabled by default, unless explicitly disabled
if (this.configService.getFastButReadOnly('cookies') !== false) {
  // Set cookies
}
```

**Impact:** If you relied on cookies NOT being set by default, explicitly disable them:
```typescript
// config.env.ts
cookies: false,
```

### 3. Session Cookie No Longer Set

The `session` cookie (containing the session ID) is no longer set. If you used this cookie for debugging or reference, it's no longer available.

**Alternative:** Use the session token from `iam.session_token` to look up session details via the API.

---

## Detailed Migration Steps

### Step 1: Update Package

```bash
npm install @lenne.tech/nest-server@11.12.x
```

### Step 2: Search for Direct Cookie Access

Search your codebase for direct access to the old cookie names:

```bash
# Search for old cookie names
grep -r "better-auth.session_token" src/
grep -r "cookies\['session'\]" src/
grep -r "cookies\.session" src/
```

Replace with the new cookie name or use the helper function.

### Step 3: Verify Cookie Configuration

If you explicitly set `cookies: true` in your config, you can remove it (now the default):

```typescript
// config.env.ts
// cookies: true,  // Can be removed - now default
```

### Step 4: Test Authentication Flows

Test the following flows in your application:
- [ ] Email/Password Sign-In (Cookie mode)
- [ ] Email/Password Sign-In (JWT mode)
- [ ] Passkey Registration
- [ ] Passkey Login
- [ ] 2FA Enable/Verify
- [ ] Sign-Out

---

## Compatibility Notes

### Existing Projects Without Direct Cookie Access

If you don't directly access cookies in your application code (most common case), this update is **fully backward compatible**.

### Projects Using Legacy Auth + Better-Auth

When Legacy Auth (Passport/JWT) is active alongside Better-Auth:
- The `token` cookie is automatically set for backward compatibility
- Better-Auth's `iam.session_token` is also set
- Token analysis correctly routes JWTs to Passport and session tokens to Better-Auth

### Frontend Cookie Handling

If your frontend (e.g., Nuxt, Next.js) uses the Better-Auth client library, ensure it's configured with the correct cookie name:

```typescript
// nuxt.config.ts or frontend config
betterAuth: {
  basePath: '/iam',  // Cookies will be named 'iam.session_token'
}
```

---

## Troubleshooting

### Passkey Registration/Login Returns 401

**Cause:** Cookie signing mismatch.

**Solution:** Ensure `betterAuth.secret` is configured in your environment:

```typescript
// config.env.ts
betterAuth: {
  secret: process.env.BETTER_AUTH_SECRET,
}
```

### "No secret configured" Warning

**Symptom:** Warning in logs: "No secret configured - setting unsigned cookie"

**Solution:** Configure the Better-Auth secret. Without it, Passkey and 2FA may not work correctly.

### Session Not Found After Cookie Migration

**Cause:** Old cookies from previous version still in browser.

**Solution:** Clear browser cookies and re-authenticate, or sign out and sign in again.

---

## New Exports

The following are now exported from `@lenne.tech/nest-server`:

```typescript
// Token analysis helpers
export {
  analyzeToken,
  getUserIdFromToken,
  isBetterAuthJwt,
  isJwt,
  isLegacyJwt,
  isSessionToken,
  TokenAnalysisResult,
  TokenType,
} from './core/modules/better-auth/core-better-auth-token.helper';

// Cookie helper
export {
  AUTH_COOKIE_NAMES,
  AuthCookieOptions,
  BetterAuthCookieHelper,
  BetterAuthCookieHelperConfig,
  CookieProcessingResult,
  createCookieHelper,
} from './core/modules/better-auth/core-better-auth-cookie.helper';
```

---

## Module Documentation

### Better-Auth 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)
- **Reference Implementation:** `src/server/modules/iam/`
- **Key Files:**
  - `core-better-auth-cookie.helper.ts` - Centralized cookie handling
  - `core-better-auth-token.helper.ts` - Token type analysis
  - `core-better-auth-web.helper.ts` - Web/Express conversion helpers

---

## References

- [Better-Auth Module](../src/core/modules/better-auth/) - Core module implementation
- [nest-server-starter](https://github.com/lenneTech/nest-server-starter) - Reference implementation
- [Better-Auth Documentation](https://www.better-auth.com/) - Official Better-Auth docs
