# Migration Guide: 11.6.x → 11.7.x

## TL;DR

```bash
npm install @lenne.tech/nest-server@11.7.x
npm run build && npm test  # Done! No breaking changes.
```

**New in 11.7.x:** Simplified `CoreModule.forRoot(envConfig)` for IAM-only projects.

---

## Overview

| Category | Details |
|----------|---------|
| **Breaking Changes** | None |
| **New Features** | Simplified CoreModule signature, Legacy endpoint control, IAuthProvider interface, Migration status query, Bidirectional password sync |
| **Bugfixes** | Improved module inheritance pattern for BetterAuth |
| **Migration Effort** | ~5 minutes (package update only) |

---

## Choose Your Scenario

| Scenario | Use When | CoreModule Signature | Path |
|----------|----------|---------------------|------|
| **Legacy Only** | Existing project, no BetterAuth needed | `CoreModule.forRoot(AuthService, AuthModule, envConfig)` | [Path A](#path-a-keep-legacy-auth-no-changes-required) |
| **Legacy + IAM** | Existing project, migrating to BetterAuth | `CoreModule.forRoot(AuthService, AuthModule, envConfig)` | [Path B](#path-b-add-betterauth-migration-scenario) |
| **IAM Only** | New project, BetterAuth from start | `CoreModule.forRoot(envConfig)` *(New!)* | [Path C](#path-c-new-project-with-iam-only) |

---

## Quick Migration (No Breaking Changes)

Since there are no breaking changes, the migration is straightforward:

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

# Verify build
npm run build

# Run tests
npm test
```

**Done!** All existing code continues to work without modifications.

---

## What's New in 11.7.x

### 1. Simplified CoreModule Signature (IAM-Only)

New single-parameter signature for projects that only use BetterAuth:

```typescript
// server.module.ts - NEW: IAM-only (recommended for new projects)
@Module({
  imports: [
    CoreModule.forRoot(envConfig),  // Simple! No AuthService/AuthModule needed
    BetterAuthModule.forRoot({
      config: envConfig.betterAuth,
      fallbackSecrets: [envConfig.jwt?.secret],
    }),
    // ... other modules
  ],
})
export class ServerModule {}
```

**Benefits:**
- No need to create AuthService or AuthModule for new projects
- GraphQL subscriptions authenticate via BetterAuth sessions
- Cleaner setup for modern projects

**The 3-parameter signature is now `@deprecated` for new projects** but remains fully functional for existing projects during migration.

### 2. Legacy Endpoint Control (`auth.legacyEndpoints`)

New configuration option to disable legacy auth endpoints after BetterAuth migration:

```typescript
// config.env.ts
{
  auth: {
    legacyEndpoints: {
      enabled: true,    // Default: true
      graphql: true,    // Control GraphQL endpoints separately
      rest: true,       // Control REST endpoints separately
    }
  }
}
```

When disabled, legacy endpoints return HTTP 410 Gone with `LegacyAuthDisabledException`.

**Affected Endpoints:**
- GraphQL: `signIn`, `signUp`, `logout`, `refreshToken`
- REST: `POST /auth/signin`, `POST /auth/signup`, `GET /auth/logout`, `GET /auth/refresh-token`

### 3. Bidirectional Password Synchronization

Passwords are now synchronized between Legacy Auth and BetterAuth:

| Direction | Flow | Password Storage |
|-----------|------|------------------|
| Legacy → IAM | User signs up via Legacy | `bcrypt(sha256(pw))` + `scrypt(sha256(pw))` |
| IAM → Legacy | User signs up via BetterAuth | `scrypt(sha256(pw))` + `bcrypt(sha256(pw))` |

**Requirement:** Inject `BetterAuthUserMapper` in your `UserService`:

```typescript
// user.service.ts
constructor(
  // ... other params ...
  @Optional() private readonly betterAuthUserMapper?: BetterAuthUserMapper,
) {
  super(configService, emailService, mainDbModel, mainModelConstructor, { betterAuthUserMapper });
}
```

### 4. IAuthProvider Interface

New abstraction layer for authentication providers (preparation for future version):

```typescript
interface IAuthProvider {
  decodeJwt(token: string): JwtPayload;
  validateUser(payload: JwtPayload): Promise<any>;
  signToken(user: any, expiresIn?: string): string;
}
```

### 5. Migration Status Query

GraphQL query for monitoring BetterAuth migration progress (admin only):

```graphql
query {
  betterAuthMigrationStatus {
    totalUsers
    fullyMigratedUsers
    pendingMigrationUsers
    migrationPercentage
    canDisableLegacyAuth
    pendingUserEmails
  }
}
```

### 6. Deprecation Warnings

JSDoc `@deprecated` comments added to legacy auth endpoints and the 3-parameter CoreModule signature.

---

## Detailed Migration Paths

### Path A: Keep Legacy Auth (No Changes Required)

If you're not using BetterAuth:

```bash
npm install @lenne.tech/nest-server@11.7.x
npm run build && npm test
```

Your existing code continues to work unchanged.

### Path B: Add BetterAuth (Migration Scenario)

For existing projects adding BetterAuth alongside Legacy Auth:

1. **Update Package**
   ```bash
   npm install @lenne.tech/nest-server@11.7.x
   ```

2. **Keep Existing CoreModule Signature**
   ```typescript
   // server.module.ts - Keep your existing setup
   CoreModule.forRoot(AuthService, AuthModule.forRoot(envConfig.jwt), envConfig)
   ```

3. **Add BetterAuth Module**
   Follow the [BetterAuth Integration Checklist](../src/core/modules/better-auth/INTEGRATION-CHECKLIST.md)

4. **Configure Legacy Endpoints**
   ```typescript
   // config.env.ts
   auth: {
     legacyEndpoints: { enabled: true }  // Keep during migration
   }
   ```

5. **Monitor Migration Progress**
   ```graphql
   query { betterAuthMigrationStatus { migrationPercentage, canDisableLegacyAuth } }
   ```

6. **Disable Legacy When Ready**
   ```typescript
   auth: {
     legacyEndpoints: { enabled: false }  // After all users migrated
   }
   ```

### Path C: New Project with IAM Only

For new projects starting fresh with BetterAuth:

1. **Install Package**
   ```bash
   npm install @lenne.tech/nest-server@11.7.x
   ```

2. **Configure ServerModule**
   ```typescript
   // server.module.ts
   @Module({
     imports: [
       CoreModule.forRoot(envConfig),  // Simplified! No AuthService/AuthModule needed
       BetterAuthModule.forRoot({
         config: envConfig.betterAuth,
         fallbackSecrets: [envConfig.jwt?.secret],
       }),
       // ... other modules
     ],
   })
   export class ServerModule {}
   ```

3. **Configure config.env.ts**
   ```typescript
   // config.env.ts
   auth: {
     legacyEndpoints: { enabled: false }  // Disable Legacy endpoints
   },
   betterAuth: {
     jwt: {},       // Enable JWT tokens
     twoFactor: {}, // Enable 2FA (optional)
     passkey: {},   // Enable Passkeys (optional)
   }
   ```

4. **Follow Integration Checklist**
   See [BetterAuth Integration Checklist](../src/core/modules/better-auth/INTEGRATION-CHECKLIST.md) for required files.

---

## Compatibility Notes

### Module Inheritance Pattern

Projects extending `CoreAuthResolver` and `CoreAuthController` continue to work seamlessly. Common patterns observed:

**Pattern 1: Override with authService call (common) - MUST call check method**
```typescript
@Resolver()
export class AuthResolver extends CoreAuthResolver {
  override async signIn(input: SignInInput, ...): Promise<Auth> {
    this.checkLegacyGraphQLEnabled('signIn');  // Required!
    return this.authService.signIn(input, ...);
  }
}
```
⚠️ **Important:** When overriding `signIn`, `signUp`, `logout`, or `refreshToken`, you MUST call the protected `checkLegacyGraphQLEnabled()` method. Otherwise, the `auth.legacyEndpoints.enabled: false` configuration will be ignored and legacy endpoints remain accessible.

**Pattern 2: Simple extension (no overrides)**
```typescript
@Resolver()
export class AuthResolver extends CoreAuthResolver {}
```
This pattern benefits from the new deprecation warnings in IDE.

### Custom Role Enums

Projects using custom role enums (e.g., `CompanyRoles`) instead of `RoleEnum` continue to work without changes.

### Additional Auth Methods

Custom methods like `loginAsCompany`, `getCurrentUser`, or `sendVerificationMail` are unaffected.

---

## Client Configuration

New clients should hash passwords with SHA256 before sending:

```typescript
// auth-client.ts (Nuxt/Vue example)
import { createAuthClient } from 'better-auth/vue';

const baseClient = createAuthClient({
  baseURL: import.meta.env.VITE_API_URL,
  basePath: '/iam',  // Must match server config
  plugins: [/* ... */],
});

// Wrap signIn/signUp to hash passwords
export const authClient = {
  ...baseClient,
  signIn: {
    ...baseClient.signIn,
    email: async (params) => {
      const hashedPassword = await sha256(params.password);
      return baseClient.signIn.email({ ...params, password: hashedPassword });
    },
  },
  // ... same for signUp, resetPassword, etc.
};
```

The server accepts both plain and SHA256-hashed passwords but **new clients should always hash**.

---

## Troubleshooting

### Build Errors

If type errors occur related to `auth` configuration:

```bash
rm -rf node_modules package-lock.json
npm install
npm run build
```

### Legacy Endpoints Return 410

If legacy endpoints unexpectedly return 410 Gone:
1. Check `config.auth.legacyEndpoints.enabled` is not `false`
2. Remove the `auth` configuration block to use defaults

### Tests Fail

1. Ensure MongoDB is running
2. Run with debug: `npm run test:e2e-doh`
3. Check configuration matches test environment expectations

### GraphQL Subscriptions in IAM-Only Mode

GraphQL Subscriptions are fully supported in IAM-only mode. If authentication fails, check:
1. Client sends `Authorization: Bearer <session-token>` in WebSocket connection params
2. BetterAuth is configured: `betterAuth: { jwt: {} }` (JWT plugin enables token validation)
3. Session is valid and not expired

---

## Version Comparison

| Version | Feature | Status |
|---------|---------|--------|
| 11.6.x | BetterAuth module | Introduced |
| 11.7.x | Simplified CoreModule signature | New |
| 11.7.x | IAM-only GraphQL Subscriptions | New |
| 11.7.x | Legacy endpoint control | New |
| 11.7.x | Bidirectional password sync | New |
| 11.7.x | IAuthProvider interface | New |
| 11.7.x | Migration status query | New |
| Future | BetterAuth default | Planned |

---

## Module Documentation

For detailed information about affected modules, see:

### Auth Module (Legacy Auth)

- **Location:** `src/core/modules/auth/`
- **Key Files:**
  - `core-auth.resolver.ts` - GraphQL endpoints with deprecation warnings
  - `core-auth.controller.ts` - REST endpoints with deprecation warnings
  - `interfaces/auth-provider.interface.ts` - New IAuthProvider interface

### BetterAuth Module (IAM)

- **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/better-auth/`

---

## References

- [Module Deprecation Roadmap](../.claude/rules/module-deprecation.md)
- [nest-server-starter](https://github.com/lenneTech/nest-server-starter) (reference implementation)
- [BetterAuth README](../src/core/modules/better-auth/README.md)
