All files / src/modules/auth auth.service.ts

64.39% Statements 208/323
49.71% Branches 86/173
68.57% Functions 24/35
66% Lines 198/300

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 70315x 15x 15x 15x 15x 15x 15x 15x 15x     15x 15x 15x 15x   15x 15x 15x           130x       15x   35x 35x 35x 35x 35x 35x         104x 104x 3x 3x   101x 1x 1x   100x 100x 9x 9x   91x 1x     90x               90x 90x 90x       5x       4x 4x 4x       5x 5x 3x 3x     2x         2x 2x 2x 2x             2x         3x 3x 3x 2x 2x   1x 1x 1x 1x 1x 1x         4x 4x 4x 4x 4x 4x 4x       4x 4x 3x 3x 2x 2x       1x 1x         4x 4x 2x 2x   2x               3x 3x       3x 3x 1x 1x         1x       1x                     4x 4x 3x 3x 1x 1x                                                                                                 15x                                                                                                                                               2x       2x 2x 2x 2x     2x   2x             8x 8x 8x 6x 6x   2x   2x 2x 2x 2x 2x   2x   2x                 2x         2x         2x 2x 2x               1x       1x 1x 1x 1x     1x   1x             2x 2x 2x 1x 1x   1x   1x 1x 1x 1x   1x                 1x           1x       1x 1x               95x     95x 95x 95x 95x 2x 2x   93x                     93x         1x 1x         1x 1x     1x               5x 5x 1x 1x   4x               17x 17x 1x 1x     16x 16x     16x 12x     4x 4x 4x 3x       3x               3x 3x 3x                                                                                                                                                                                                                                                                           2x 2x 2x                                   3x 3x 3x 3x 3x 1x 1x 1x 1x 1x               1x 1x    
import { Injectable, BadRequestException, NotFoundException, UnauthorizedException, InternalServerErrorException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '@app/modules/prisma/prisma.service';
import { LoggerService } from '@app/common/services/logger.service';
import * as bcrypt from 'bcrypt';
import { randomBytes, createHash } from 'crypto';
import { Cron, CronExpression } from '@nestjs/schedule';
import { AuditService } from '@app/modules/audit/audit.service';
import { NotificationService } from '@app/common/services/notification.service';
// import { Response } from 'express';
// import { LoginDto } from '@app/modules/auth/dto/login.dto';
import { JwksService } from '@app/modules/jwks/jwks.service';
import { authenticator } from 'otplib';
import QRCode from 'qrcode';
import { OAuth2Client, TokenPayload } from 'google-auth-library';
 
const PASSWORD_RESET_TOKEN_EXPIRY_MINUTES = 7;
const TOKEN_EXPIRY_MINUTES = 10;
const REFRESH_TOKEN_EXPIRY_DAYS = 14;
 
// Note: hashToken uses SHA-256 for deterministic lookups via unique index
// Used for password reset, email change, phone change, and refresh tokens
// High-entropy tokens don't need bcrypt's slow hashing - SHA-256 is sufficient for security
function hashToken(token: string): string {
  return createHash('sha256').update(token).digest('hex');
}
 
@Injectable()
export class AuthService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly jwt: JwtService,
    private readonly jwks: JwksService,
    private readonly logger: LoggerService,
    private readonly audit: AuditService,
    private readonly notification: NotificationService,
  ) {}
 
  /** Secure login: validate email and password */
  async login(email: string, password: string, meta: { ip?: string; userAgent?: string } = {}) {
    const user = await this.prisma.client.user.findUnique({ where: { email } });
    if (!user) {
      this.logger.info('Login failed', { email, result: 'user_not_found', ...meta });
      return null;
    }
    if (!user.password) {
      this.logger.info('Login failed', { email, result: 'no_local_password', ...meta });
      return null;
    }
    const passwordValid = await bcrypt.compare(password, user.password);
    if (!passwordValid) {
      this.logger.info('Login failed', { email, result: 'invalid_password', ...meta });
      return null;
    }
    if (!this.jwks.isInitialized || !this.jwks.signingKey) {
      throw new Error('JWT keys are not configured. Cannot generate access token.');
    }
 
    const accessToken = this.jwt.sign(
      { sub: user.id, email: user.email, tokenVersion: user.tokenVersion },
      {
        algorithm: this.jwks.signingKey.alg as any,
        expiresIn: '15m',
        header: { kid: this.jwks.signingKey.kid, alg: this.jwks.signingKey.alg },
      },
    );
    const refreshToken = await this.generateRefreshToken(user.id, meta);
    this.logger.info('Login success', { email, userId: user.id, ...meta });
    return { accessToken, refreshToken };
  }
 
  async findUserByEmail(email: string) {
    return this.prisma.client.user.findUnique({ where: { email } });
  }
 
  async createUser(data: { email: string; password: string; name: string }, meta: { ip?: string } = {}) {
    const user = await this.prisma.client.user.create({ data });
    this.logger.info('User registered', { email: user.email, userId: user.id, ...meta });
    return user;
  }
 
  async requestPasswordReset(email: string, meta: { ip?: string } = {}) {
    const user = await this.prisma.client.user.findUnique({ where: { email } });
    if (!user) {
      this.logger.info('Password reset requested for non-existent email', { email, ...meta });
      return;
    }
    // Invalidate old tokens
    await this.prisma.client.passwordResetToken.updateMany({
      where: { userId: user.id, used: false, expiresAt: { gt: new Date() } },
      data: { used: true },
    });
    // Generate secure token
    const token = randomBytes(32).toString('hex');
    const tokenHash = hashToken(token);
    const expiresAt = new Date(Date.now() + PASSWORD_RESET_TOKEN_EXPIRY_MINUTES * 60 * 1000);
    await this.prisma.client.passwordResetToken.create({
      data: {
        userId: user.id,
        tokenHash,
        expiresAt,
      },
    });
    this.logger.info('Password reset token created', { email, userId: user.id, ...meta });
    // TODO: Send email with token (integration point)
  }
 
  async resetPassword(token: string, newPassword: string, meta: { ip?: string } = {}) {
    const tokenHash = hashToken(token);
    const resetToken = await this.prisma.client.passwordResetToken.findFirst({ where: { tokenHash } });
    if (!resetToken || resetToken.used || Date.now() > resetToken.expiresAt.getTime()) {
      this.logger.info('Invalid or expired password reset token', { tokenHash, ...meta });
      throw new BadRequestException('Invalid or expired token');
    }
    const user = await this.prisma.client.user.findUnique({ where: { id: resetToken.userId } });
    Iif (!user) throw new NotFoundException('User not found');
    const hashed = await bcrypt.hash(newPassword, 12);
    await this.prisma.client.user.update({ where: { id: user.id }, data: { password: hashed } });
    await this.prisma.client.passwordResetToken.update({ where: { id: resetToken.id }, data: { used: true } });
    this.logger.info('Password reset successful', { userId: user.id, ...meta });
  }
 
  // ===== MFA TOTP =====
  async setupTotp(userId: number) {
    const secret = authenticator.generateSecret();
    const user = await this.prisma.client.user.update({ where: { id: userId }, data: { totpSecret: secret } });
    const label = encodeURIComponent(user.email || `user-${userId}`);
    const issuer = encodeURIComponent('1uy.uz');
    const otpauth = `otpauth://totp/${issuer}:${label}?secret=${secret}&issuer=${issuer}`;
    const qrDataUrl = await QRCode.toDataURL(otpauth);
    return { secret, otpauth, qrDataUrl };
  }
 
  async verifyTotp(userId: number, token: string) {
    const user = await this.prisma.client.user.findUnique({ where: { id: userId } });
    if (!user || !user.totpSecret) throw new BadRequestException('No TOTP setup');
    const valid = authenticator.verify({ token, secret: user.totpSecret });
    if (!valid) throw new BadRequestException('Invalid code');
    await this.prisma.client.user.update({ where: { id: userId }, data: { totpEnabled: true } });
    return { enabled: true };
  }
 
  async disableTotp(userId: number) {
    await this.prisma.client.user.update({ where: { id: userId }, data: { totpEnabled: false, totpSecret: null as any } });
    return { enabled: false };
  }
 
  // ===== Sessions (Refresh tokens) =====
  listSessions(userId: number) {
    const rt = (this.prisma.client as any).refreshToken || (this.prisma as any).refreshToken;
    if (!rt) {
      this.logger.error('RefreshToken delegate missing on Prisma client');
      throw new InternalServerErrorException('refresh_store_missing');
    }
    return rt.findMany({
      where: { userId, revoked: false },
      select: { id: true, createdAt: true, expiresAt: true, ip: true, userAgent: true, deviceId: true },
      orderBy: { createdAt: 'desc' },
    });
  }
 
  async revokeSession(userId: number, sessionId: number) {
    const delegate = (this.prisma.client as any).refreshToken || (this.prisma as any).refreshToken;
    Iif (!delegate) {
      this.logger.error('RefreshToken delegate missing on Prisma client');
      throw new InternalServerErrorException('refresh_store_missing');
    }
    const rt = await delegate.findUnique({ where: { id: sessionId } });
    if (!rt || rt.userId !== userId) throw new NotFoundException('Session not found');
    await delegate.update({ where: { id: sessionId }, data: { revoked: true } });
    return { revoked: true };
  }
 
  // ===== Token issuing helpers & impersonation =====
  issueAccessTokenForUser(user: { id: number; email: string; tokenVersion: number }) {
    Iif (!this.jwks.isInitialized || !this.jwks.signingKey) {
      throw new Error('JWT keys are not configured. Cannot generate access token.');
    }
 
    return this.jwt.sign(
      { sub: user.id, email: user.email, tokenVersion: user.tokenVersion },
      {
        algorithm: this.jwks.signingKey.alg as any,
        expiresIn: '15m',
        header: { kid: this.jwks.signingKey.kid, alg: this.jwks.signingKey.alg },
      },
    );
  }
 
  async impersonate(adminId: number, targetUserId: number) {
    const admin = await this.prisma.client.user.findUnique({ where: { id: adminId } });
    if (!admin || (admin.role !== 'ADMIN' && admin.role !== 'MODERATOR')) throw new BadRequestException('Not allowed');
    const user = await this.prisma.client.user.findUnique({ where: { id: targetUserId } });
    if (!user) throw new NotFoundException('User not found');
    const accessToken = this.issueAccessTokenForUser({ id: user.id, email: user.email, tokenVersion: user.tokenVersion });
    return { accessToken };
  }
 
  /**
   * Check if database connection is healthy
   */
  private async checkDatabaseHealth(): Promise<boolean> {
    try {
      // Simple query to verify connection
      await this.prisma.client.$queryRaw`SELECT 1`;
      return true;
    } catch (_error) {
      return false;
    }
  }
 
  /**
   * Determine if Prisma error is transient (retryable)
   */
  private isTransientPrismaError(error: any): boolean {
    Iif (!error) return false;
    
    const code = error.code || error.$metadata?.httpStatusCode || error.name;
    const transientCodes = ['P1001', 'P1008', 'P1017']; // Connection errors
    const transientNames = ['PrismaClientInitializationError', 'PrismaClientKnownRequestError'];
    
    // Check for connection-related errors
    const message = error.message || '';
    const isConnectionError = 
      message.includes("Can't reach database server") ||
      message.includes('Connection') ||
      message.includes('timeout') ||
      message.includes('ETIMEDOUT') ||
      message.includes('EHOSTUNREACH') ||
      message.includes('ECONNREFUSED');
    
    return transientCodes.includes(code) || transientNames.includes(error.name) || isConnectionError;
  }
 
  /**
   * Scheduled cleanup for expired tokens (password reset, email change, phone change)
   * Runs every 10 minutes for prompt cleanup
   * 
   * Features:
   * - Database health check before execution
   * - Retry logic for transient failures
   * - Graceful degradation when DB is unavailable
   */
  @Cron(CronExpression.EVERY_10_MINUTES)
  async deleteExpiredTokens() {
    // Check database health before attempting cleanup
    const isHealthy = await this.checkDatabaseHealth();
    Iif (!isHealthy) {
      this.logger.warn('Skipping expired token cleanup: database connection unavailable');
      return;
    }
 
    const maxRetries = 3;
    let lastError: any = null;
    
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        const [pwCount, emailCount, phoneCount] = await Promise.all([
          this.prisma.client.passwordResetToken.deleteMany({ where: { expiresAt: { lt: new Date() }, used: false } }),
          this.prisma.client.emailChangeToken.deleteMany({ where: { expiresAt: { lt: new Date() }, used: false } }),
          this.prisma.client.phoneChangeToken.deleteMany({ where: { expiresAt: { lt: new Date() }, used: false } }),
        ]);
        
        this.logger.info('Deleted expired tokens', {
          passwordReset: pwCount.count,
          emailChange: emailCount.count,
          phoneChange: phoneCount.count,
        });
        return; // Success - exit
      } catch (error: any) {
        lastError = error;
        const isTransient = this.isTransientPrismaError(error);
        
        Iif (!isTransient || attempt === maxRetries) {
          // Non-retryable error or max retries reached
          break;
        }
        
        // Exponential backoff with jitter
        const baseDelay = Math.min(1000 * Math.pow(2, attempt - 1), 5000);
        const jitter = Math.random() * 500;
        const delay = baseDelay + jitter;
        
        this.logger.warn(`Failed to delete expired tokens (attempt ${attempt}/${maxRetries}). Retrying in ${Math.round(delay)}ms...`, {
          error: {
            code: error?.code,
            name: error?.name,
            message: error?.message,
          },
        });
        
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
    
    // All retries failed - log error but don't crash scheduler
    this.logger.error('Failed to delete expired tokens after all retries', {
      error:
        lastError instanceof Error
          ? {
              name: lastError.name,
              message: lastError.message,
              code: (lastError as any).code,
              stack: lastError.stack,
            }
          : { value: lastError },
      attempts: maxRetries,
    });
    // Don't rethrow to prevent scheduler from crashing
  }
 
  /**
   * Create and store a secure email change token
   */
  async createEmailChangeToken(userId: number, newEmail: string, meta: { ip?: string } = {}) {
    // Invalidate old tokens
    await this.prisma.client.emailChangeToken.updateMany({
      where: { userId, used: false, expiresAt: { gt: new Date() } },
      data: { used: true },
    });
    const token = randomBytes(32).toString('hex');
    const tokenHash = hashToken(token);
    const expiresAt = new Date(Date.now() + TOKEN_EXPIRY_MINUTES * 60 * 1000);
    await this.prisma.client.emailChangeToken.create({
      data: { userId, newEmail, tokenHash, expiresAt },
    });
    this.logger.info('Email change token created', { userId, newEmail, ...meta });
    // TODO: Send email with token (integration point)
    return token;
  }
 
  /**
   * Validate and use an email change token
   */
  async useEmailChangeToken(token: string, meta: { ip?: string; userAgent?: string } = {}) {
    const tokenHash = hashToken(token);
    const record = await this.prisma.client.emailChangeToken.findFirst({ where: { tokenHash } });
    if (!record || record.used || Date.now() > record.expiresAt.getTime()) {
      this.logger.info('Invalid or expired email change token', { tokenHash, ...meta });
      throw new BadRequestException('Invalid or expired token');
    }
    await this.prisma.client.emailChangeToken.update({ where: { id: record.id }, data: { used: true } });
    // Update user email and increment tokenVersion
    const user = await this.prisma.client.user.findUnique({ where: { id: record.userId } });
    Iif (!user) throw new NotFoundException('User not found');
    const oldEmail = user.email;
    const newTokenVersion = user.tokenVersion + 1;
    await this.prisma.client.user.update({ where: { id: record.userId }, data: { email: record.newEmail, tokenVersion: newTokenVersion } });
    // Revoke all refresh tokens so old sessions are invalidated immediately
    await this.revokeAllRefreshTokensForUser(record.userId);
    // Audit log
    await this.audit.createAuditLog({
      entityType: 'User',
      entityId: record.userId,
      action: 'UPDATE',
      oldValue: { email: oldEmail, tokenVersion: user.tokenVersion },
      newValue: { email: record.newEmail, tokenVersion: newTokenVersion, ip: meta.ip, userAgent: meta.userAgent },
      userId: record.userId,
    });
    // Notify old and new email
    await this.notification.sendEmail(
      oldEmail,
      'Your email was changed',
      `Your account email was changed to ${record.newEmail}. If this wasn't you, contact support immediately.`
    );
    await this.notification.sendEmail(
      record.newEmail,
      'Email change confirmation',
      'Your email has been successfully updated.'
    );
    this.logger.info('Sessions invalidated for user after email change', { userId: record.userId });
    this.logger.info('Email change token used', { userId: record.userId, ...meta });
    return record;
  }
 
  /**
   * Create and store a secure phone change token
   */
  async createPhoneChangeToken(userId: number, newPhone: string, meta: { ip?: string } = {}) {
    // Invalidate old tokens
    await this.prisma.client.phoneChangeToken.updateMany({
      where: { userId, used: false, expiresAt: { gt: new Date() } },
      data: { used: true },
    });
    const token = randomBytes(32).toString('hex');
    const tokenHash = hashToken(token);
    const expiresAt = new Date(Date.now() + TOKEN_EXPIRY_MINUTES * 60 * 1000);
    await this.prisma.client.phoneChangeToken.create({
      data: { userId, newPhone, tokenHash, expiresAt },
    });
    this.logger.info('Phone change token created', { userId, newPhone, ...meta });
    // TODO: Send SMS with token (integration point)
    return token;
  }
 
  /**
   * Validate and use a phone change token
   */
  async usePhoneChangeToken(token: string, meta: { ip?: string; userAgent?: string } = {}) {
    const tokenHash = hashToken(token);
    const record = await this.prisma.client.phoneChangeToken.findFirst({ where: { tokenHash } });
    if (!record || record.used || Date.now() > record.expiresAt.getTime()) {
      this.logger.info('Invalid or expired phone change token', { tokenHash, ...meta });
      throw new BadRequestException('Invalid or expired token');
    }
    await this.prisma.client.phoneChangeToken.update({ where: { id: record.id }, data: { used: true } });
    // Update user phone
    const user = await this.prisma.client.user.findUnique({ where: { id: record.userId } });
    Iif (!user) throw new NotFoundException('User not found');
    const oldPhone = user.phone || null;
    await this.prisma.client.user.update({ where: { id: record.userId }, data: { phone: record.newPhone } });
    // Audit log
    await this.audit.createAuditLog({
      entityType: 'User',
      entityId: record.userId,
      action: 'UPDATE',
      oldValue: { phone: oldPhone },
      newValue: { phone: record.newPhone, ip: meta.ip, userAgent: meta.userAgent },
      userId: record.userId,
    });
    // Notify old and new phone (SMS)
    Iif (oldPhone) {
      await this.notification.sendSMS(
        oldPhone,
        `Your account phone was changed to ${record.newPhone}. If this wasn't you, contact support immediately.`
      );
    }
    await this.notification.sendSMS(
      record.newPhone,
      'Your phone has been successfully updated.'
    );
    this.logger.info('Phone change token used', { userId: record.userId, ...meta });
    return record;
  }
 
  /** Generate a new refresh token, store SHA-256 hash in DB, return plaintext */
  async generateRefreshToken(
    userId: number,
    meta: { ip?: string; userAgent?: string; createdById?: number | null; deviceId?: string } = {},
  ) {
    const token = randomBytes(64).toString('hex');
    // Use SHA-256 for refresh tokens (fast, deterministic lookup via unique index)
    // High-entropy tokens don't need bcrypt's slow hashing - SHA-256 is sufficient
    const tokenHash = hashToken(token);
    const expiresAt = new Date(Date.now() + REFRESH_TOKEN_EXPIRY_DAYS * 24 * 60 * 60 * 1000);
    const delegate = (this.prisma.client as any).refreshToken || (this.prisma as any).refreshToken;
    if (!delegate) {
      this.logger.error('RefreshToken delegate missing on Prisma client');
      throw new InternalServerErrorException('refresh_store_missing');
    }
    await delegate.create({
      data: {
        userId,
        tokenHash,
        expiresAt,
        ip: meta.ip,
        userAgent: meta.userAgent,
        createdById: meta.createdById ?? null,
        deviceId: meta.deviceId,
      } as any,
    });
    return token;
  }
 
  /** Remove (revoke) a refresh token by plaintext value */
  async revokeRefreshToken(token: string) {
    const delegate = (this.prisma.client as any).refreshToken || (this.prisma as any).refreshToken;
    Iif (!delegate) {
      this.logger.error('RefreshToken delegate missing on Prisma client');
      throw new InternalServerErrorException('refresh_store_missing');
    }
    // Use SHA-256 hash for O(1) lookup via unique index
    const tokenHash = hashToken(token);
    const candidate = await delegate.findUnique({
      where: { tokenHash },
    });
    Iif (candidate && !candidate.revoked && candidate.expiresAt > new Date()) {
      await delegate.update({ where: { tokenHash }, data: { revoked: true } });
    }
    // Token not found or already revoked - silently succeed (defense in depth)
  }
 
  /** Remove all refresh tokens for a user (logout all) */
  async revokeAllRefreshTokensForUser(userId: number) {
    const delegate = (this.prisma.client as any).refreshToken || (this.prisma as any).refreshToken;
    if (!delegate) {
      this.logger.error('RefreshToken delegate missing on Prisma client');
      throw new InternalServerErrorException('refresh_store_missing');
    }
    await delegate.updateMany({
      where: { userId, revoked: false },
      data: { revoked: true },
    });
  }
 
  /** Validate and rotate refresh token */
  async refreshTokens(refreshToken: string, meta: { ip?: string; userAgent?: string } = {}) {
    const delegate = (this.prisma.client as any).refreshToken || (this.prisma as any).refreshToken;
    if (!delegate) {
      this.logger.error('RefreshToken delegate missing on Prisma client');
      throw new InternalServerErrorException('refresh_store_missing');
    }
    // Use SHA-256 hash for O(1) lookup via unique index
    const tokenHash = hashToken(refreshToken);
    const record = await delegate.findUnique({
      where: { tokenHash },
    });
    if (!record || record.revoked || record.expiresAt <= new Date()) {
      throw new BadRequestException('Invalid or expired refresh token');
    }
    // Rotate: revoke old, issue new
    await delegate.update({ where: { tokenHash }, data: { revoked: true } });
    const user = await this.prisma.client.user.findUnique({ where: { id: record.userId } });
    if (!user) throw new NotFoundException('User not found');
    Iif (!this.jwks.isInitialized || !this.jwks.signingKey) {
      throw new Error('JWT keys are not configured. Cannot generate access token.');
    }
 
    const accessToken = this.jwt.sign(
      { sub: user.id, email: user.email, tokenVersion: user.tokenVersion },
      {
        algorithm: this.jwks.signingKey.alg as any,
        expiresIn: '15m',
        header: { kid: this.jwks.signingKey.kid, alg: this.jwks.signingKey.alg },
      },
    );
    const newRefreshToken = await this.generateRefreshToken(user.id, { ip: meta.ip, userAgent: meta.userAgent });
    this.logger.info('Refresh token rotated', { userId: user.id, ip: meta.ip });
    return { accessToken, refreshToken: newRefreshToken };
  }
 
  // ===== OAuth (Google) =====
  private getGoogleClientIds(): string[] {
    const val = process.env.GOOGLE_CLIENT_ID || '';
    return val
      .split(',')
      .map((s) => s.trim())
      .filter((s) => s.length > 0);
  }
 
  private async verifyGoogleIdToken(idToken: string): Promise<TokenPayload | null> {
    const ids = this.getGoogleClientIds();
    this.logger.info('Google audiences configured', { ids });
    try {
      const [, payloadB64] = idToken.split('.');
      const claims = JSON.parse(Buffer.from(payloadB64, 'base64url').toString('utf8'));
      this.logger.info('Google ID token claims', { aud: claims.aud, azp: claims.azp, iss: claims.iss, email: claims.email, ev: claims.email_verified });
    } catch {
      this.logger.error('Failed to decode idToken header/payload');
    }
    Iif (ids.length === 0) {
      this.logger.warn('GOOGLE_CLIENT_ID not configured');
      return null;
    }
    const client = new OAuth2Client();
    for (const aud of ids) {
      try {
        const ticket = await client.verifyIdToken({ idToken, audience: aud });
        const payload = ticket.getPayload();
        Iif (payload) return payload;
      } catch (e: any) {
        this.logger.error('Google verify failed', { aud, err: e?.message || String(e) });
      }
    }
    return null;
  }
 
  async loginWithGoogle(idToken: string, meta: { ip?: string; userAgent?: string; deviceId?: string } = {}) {
    const payload = await this.verifyGoogleIdToken(idToken);
    Iif (!payload) throw new UnauthorizedException('invalid_google_token');
    Iif (!payload.email || payload.email_verified !== true) {
      throw new BadRequestException('google_email_not_verified');
    }
    this.logger.info('Google verify OK', { sub: payload.sub, email: payload.email });
    const googleSub = payload.sub as string;
 
    const deriveName = (): string | null => {
      const fullName = (payload as any).name as string | undefined;
      const given = (payload as any).given_name as string | undefined;
      const family = (payload as any).family_name as string | undefined;
      Iif (fullName && fullName.trim().length > 0) return fullName.trim();
      const gf = [given, family].filter(Boolean).join(' ').trim();
      Iif (gf.length > 0) return gf;
      const local = payload.email?.split('@')[0] ?? '';
      return local || null;
    };
 
    try {
      this.logger.info('G: starting transactional upsert');
      const user = await this.prisma.client.$transaction(async (tx: any) => {
        const upsertedUser = await tx.user.upsert({
          where: { email: payload.email! },
          update: {
            // do not overwrite existing name here
          },
          create: {
            email: payload.email!,
            name: deriveName(),
            password: null as any,
          },
        });
 
        // Link or create external account by scalar foreign key
        await tx.externalAccount.upsert({
          where: { provider_providerUserId: { provider: 'GOOGLE', providerUserId: googleSub } },
          update: {
            userId: upsertedUser.id,
            email: payload.email!,
            profile: {
              picture: (payload as any).picture || null,
              locale: (payload as any).locale || null,
              given_name: (payload as any).given_name || null,
              family_name: (payload as any).family_name || null,
            } as any,
            lastLoginAt: new Date(),
          },
          create: {
            userId: upsertedUser.id,
            provider: 'GOOGLE',
            providerUserId: googleSub,
            email: payload.email!,
            profile: {
              picture: (payload as any).picture || null,
              locale: (payload as any).locale || null,
              given_name: (payload as any).given_name || null,
              family_name: (payload as any).family_name || null,
            } as any,
            lastLoginAt: new Date(),
          },
        });
 
        return upsertedUser;
      });
      this.logger.info('G: transactional upsert done', { userId: user.id });
      Iif (!this.jwks.isInitialized || !this.jwks.signingKey) {
        throw new Error('JWT keys are not configured. Cannot generate access token.');
      }
 
      const accessToken = this.jwt.sign(
        { sub: user.id, email: user.email, tokenVersion: user.tokenVersion },
        {
          algorithm: this.jwks.signingKey.alg as any,
          expiresIn: '15m',
          header: { kid: this.jwks.signingKey.kid, alg: this.jwks.signingKey.alg },
        },
      );
      this.logger.info('G: creating refresh token', { userId: user.id });
      const refreshToken = await this.generateRefreshToken(user.id, meta);
      this.logger.info('Google login success', { email: user.email, userId: user.id, ...meta });
      return { accessToken, refreshToken };
    } catch (e: any) {
      this.logger.error('Google upsert/link failed', { code: e?.code, meta: e?.meta, msg: e?.message });
      Iif (e?.code === 'P2002') {
        // Unique conflict on email or external account; return a safe message
        throw new BadRequestException('google_account_conflict');
      }
      throw new InternalServerErrorException('google_link_failed');
    }
  }
 
  // ===== Password management =====
  async setPasswordForUser(userId: number, newPassword: string) {
    const user = await this.prisma.client.user.findUnique({ where: { id: userId } });
    Iif (!user) throw new NotFoundException('User not found');
    if (user.password) throw new BadRequestException('Password already set');
    const hashed = await bcrypt.hash(newPassword, 12);
    const newTokenVersion = user.tokenVersion + 1;
    await this.prisma.client.user.update({ where: { id: userId }, data: { password: hashed, tokenVersion: newTokenVersion } });
    await this.revokeAllRefreshTokensForUser(userId);
    await this.audit.createAuditLog({
      entityType: 'User',
      entityId: userId,
      action: 'UPDATE',
      oldValue: { password: null, tokenVersion: user.tokenVersion },
      newValue: { password: 'SET', tokenVersion: newTokenVersion },
      userId: userId,
    });
    this.logger.info('User set password', { userId });
    return { ok: true };
  }
 
  async changePasswordForUser(userId: number, currentPassword: string, newPassword: string) {
    const user = await this.prisma.client.user.findUnique({ where: { id: userId } });
    Iif (!user) throw new NotFoundException('User not found');
    Iif (!user.password) throw new BadRequestException('Password not set');
    const valid = await bcrypt.compare(currentPassword, user.password);
    if (!valid) throw new BadRequestException('Current password is incorrect');
    const hashed = await bcrypt.hash(newPassword, 12);
    const newTokenVersion = user.tokenVersion + 1;
    await this.prisma.client.user.update({ where: { id: userId }, data: { password: hashed, tokenVersion: newTokenVersion } });
    await this.revokeAllRefreshTokensForUser(userId);
    await this.audit.createAuditLog({
      entityType: 'User',
      entityId: userId,
      action: 'UPDATE',
      oldValue: { password: 'SET', tokenVersion: user.tokenVersion },
      newValue: { password: 'SET', tokenVersion: newTokenVersion },
      userId: userId,
    });
    this.logger.info('User changed password', { userId });
    return { ok: true };
  }
}