Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

16.5 KB
Raw Blame
import { createHash, randomBytes, randomUUID } from 'crypto'
import {
  BadRequestException,
  ConflictException,
  Injectable,
  InternalServerErrorException,
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
import { genSalt, hash, compare } from 'bcrypt'

import _isEmpty from 'lodash/isEmpty'
import { createRemoteJWKSet, jwtVerify, JWTPayload } from 'jose'

import {
  saveRefreshTokenClickhouse,
  findRefreshTokenClickhouse,
  deleteRefreshTokenClickhouse,
  assignUnassignedProjectsToUserClickhouse,
  deleteAllRefreshTokensClickhouse,
} from '../common/utils'
import {
  JWT_ACCESS_TOKEN_SECRET,
  JWT_ACCESS_TOKEN_LIFETIME,
  JWT_REFRESH_TOKEN_LIFETIME,
  REDIS_OIDC_SESSION_KEY,
  redis,
  IS_REGISTRATION_DISABLED,
  JWT_REFRESH_TOKEN_SECRET,
} from '../common/constants'
import { UserService } from '../user/user.service'
import { User } from '../common/types'
import { MailerService } from '../mailer/mailer.service'
import { LetterTemplate } from '../mailer/letter'

const REDIS_OIDC_SESSION_TIMEOUT = 60 * 5 // 5 minutes
const getOIDCRedisKey = (uuid: string) => `${REDIS_OIDC_SESSION_KEY}:${uuid}`
const generateOIDCState = () => `openid-connect:${randomUUID()}`

@Injectable()
export class AuthService {
  constructor(
    private readonly configService: ConfigService,
    private readonly jwtService: JwtService,
    private readonly userService: UserService,
    private readonly mailerService: MailerService,
  ) {}

  private async createSha1Hash(text: string): Promise<string> {
    return new Promise((resolve) => {
      const sha1sum = createHash('sha1')
        .update(text)
        .digest('hex')
        .toUpperCase()
      resolve(sha1sum)
    })
  }

  public async checkIfLeaked(potentialPassword: string): Promise<boolean> {
    const sha1Hash = await this.createSha1Hash(potentialPassword)
    const firstFiveChars = sha1Hash.slice(0, 5)
    const lastChars = sha1Hash.slice(5)

    const response = await fetch(
      `https://api.pwnedpasswords.com/range/${firstFiveChars}`,
    )

    if (!response.ok) {
      console.error(
        `[ERROR][AuthService -> checkIfLeaked]: Failed to get pwned passwords for ${firstFiveChars}: ${response.status}`,
      )
      return false
    }

    const body = await response.text()
    return body.includes(lastChars)
  }

  public async hashPassword(password: string): Promise<string> {
    const salt = await genSalt(10)
    return hash(password, salt)
  }

  public async generateJwtAccessToken(
    userId: string,
    isSecondFactorAuthenticated = false,
  ) {
    return this.jwtService.signAsync(
      {
        sub: userId,
        isSecondFactorAuthenticated,
      },
      {
        algorithm: 'HS256',
        expiresIn: JWT_ACCESS_TOKEN_LIFETIME,
        secret: JWT_ACCESS_TOKEN_SECRET,
      },
    )
  }

  public async createUser(email: string, password: string) {
    const hashedPassword = await this.hashPassword(password)

    return this.userService.create({
      email,
      password: hashedPassword, // Using the password field is incorrect.
    })
  }

  private generateRandomPassword(length = 48): string {
    return randomBytes(64).toString('hex').slice(0, length)
  }

  private async getOrCreateUserByEmail(email: string) {
    const existingUser = await this.userService.findOne({ email })

    if (existingUser && existingUser.id) {
      return existingUser
    }

    // Treat as registration attempt; respect registration-disabled setting
    const isRegistrationDisabled = await this.isRegistrationDisabled()

    if (isRegistrationDisabled) {
      throw new BadRequestException('Registration is disabled')
    }

    const randomPassword = this.generateRandomPassword(48)
    const hashedPassword = await this.hashPassword(randomPassword)

    const createdUser = await this.userService.create({
      email,
      password: hashedPassword,
    })

    // Assign any pre-v4 unassigned projects to the newly registered user
    await this.assignUnassignedProjectsToUser(createdUser.id)

    return createdUser
  }

  async isRegistrationDisabled() {
    const usersCount = await this.userService.count()

    if (usersCount === 0) {
      return false
    }

    return IS_REGISTRATION_DISABLED
  }

  private async deleteAllProjectCacheKeys() {
    const matchPattern = 'pid_*'
    const scanCount = 1000

    try {
      let cursor = '0'

      do {
        const [nextCursor, keys] = await redis.scan(
          cursor,
          'MATCH',
          matchPattern,
          'COUNT',
          scanCount,
        )

        if (keys && keys.length > 0) {
          const pipeline = redis.pipeline()
          for (const key of keys) {
            pipeline.del(key)
          }
          await pipeline.exec()
        }

        cursor = nextCursor
      } while (cursor !== '0')
    } catch (reason) {
      console.error(
        `[ERROR][AuthService -> deleteAllProjectCacheKeys]: ${reason}`,
      )
    }
  }

  // Before Swetrix CE v4 there could only be a single user, with login / password set in .env file
  // Because of that, projects were stored without an adminId as it was not needed
  // Unassigned projects are only possible when migrating from Swetrix CE v3 to v4, so people who migrated are
  // going to create an account anyway, so it's safe to assign them to the user
  async assignUnassignedProjectsToUser(userId: string) {
    await assignUnassignedProjectsToUserClickhouse(userId)
    await this.deleteAllProjectCacheKeys()
  }

  public async sendResetPasswordEmail(
    userId: string,
    email: string,
    headers: Record<string, string>,
  ) {
    const urlBase = headers.origin || ''

    const token = randomUUID()
    const url = `${urlBase}/password-reset/${token}`

    await redis.set(`password_reset:${token}`, userId, 'EX', 60 * 60 * 12)

    await this.mailerService.sendEmail(
      email,
      LetterTemplate.ConfirmPasswordChange,
      {
        url,
      },
    )
  }

  public async invalidatePasswordResetTokens(userId: string): Promise<void> {
    try {
      let cursor = '0'
      const scanCount = 100

      do {
        const [nextCursor, keys] = await redis.scan(
          cursor,
          'MATCH',
          'password_reset:*',
          'COUNT',
          scanCount,
        )

        if (keys && keys.length > 0) {
          const values = await redis.mget(...keys)
          const pipeline = redis.pipeline()

          for (let i = 0; i < keys.length; i++) {
            if (values[i] === userId) {
              pipeline.del(keys[i])
            }
          }

          await pipeline.exec()
        }

        cursor = nextCursor
      } while (cursor !== '0')
    } catch (reason) {
      console.error(
        `[ERROR][AuthService -> invalidatePasswordResetTokens]: ${reason}`,
      )
    }
  }

  public async resetPassword(userId: string, password: string): Promise<void> {
    const hashedPassword = await this.hashPassword(password)

    await this.userService.update(userId, {
      password: hashedPassword,
    })

    await this.logoutAll(userId)
  }

  async getBasicUser(email: string, password: string): Promise<User | null> {
    const user = await this.userService.findOne({ email })

    if (user && (await this.comparePassword(password, user.password))) {
      return user
    }

    return null
  }

  public async comparePassword(
    password: string,
    hashedPassword: string,
  ): Promise<boolean> {
    return compare(password, hashedPassword)
  }

  private async generateJwtRefreshToken(
    userId: string,
    isSecondFactorAuthenticated = false,
  ) {
    const refreshToken = await this.jwtService.signAsync(
      {
        sub: userId,
        isSecondFactorAuthenticated,
      },
      {
        algorithm: 'HS256',
        expiresIn: JWT_REFRESH_TOKEN_LIFETIME,
        secret: JWT_REFRESH_TOKEN_SECRET,
      },
    )

    await saveRefreshTokenClickhouse(userId, refreshToken)

    return refreshToken
  }

  public async checkRefreshToken(
    userId: string,
    refreshToken: string,
  ): Promise<boolean> {
    const tokens = await findRefreshTokenClickhouse(userId, refreshToken)
    return !_isEmpty(tokens)
  }

  public async generateJwtTokens(
    userId: string,
    isSecondFactorAuthenticated = false,
  ) {
    const accessToken = await this.generateJwtAccessToken(
      userId,
      isSecondFactorAuthenticated,
    )

    let refreshToken = 'NOT_AVAILABLE'

    if (isSecondFactorAuthenticated) {
      refreshToken = await this.generateJwtRefreshToken(
        userId,
        isSecondFactorAuthenticated,
      )
    }

    return { accessToken, refreshToken }
  }

  async logout(userId: string, refreshToken: string) {
    await deleteRefreshTokenClickhouse(userId, refreshToken)
  }

  async logoutAll(userId: string) {
    await deleteAllRefreshTokensClickhouse(userId)
  }

  getOidcConfig() {
    return {
      discoveryURL: this.configService.get('OIDC_DISCOVERY_URL'),
      clientID: this.configService.get('OIDC_CLIENT_ID'),
      clientSecret: this.configService.get('OIDC_CLIENT_SECRET'),
      prompt: this.configService.get('OIDC_PROMPT') || 'select_account',
      scope: 'openid email profile',
    }
  }

  async getOidcDiscovery() {
    const config = this.getOidcConfig()
    const discoveryURL = config.discoveryURL
    const response = await fetch(discoveryURL)

    if (!response.ok) {
      throw new BadRequestException('Failed to fetch OIDC discovery document')
    }

    return response.json()
  }

  async generateOidcAuthUrl(redirectUrl: string) {
    try {
      const uuid = generateOIDCState()

      const discovery = await this.getOidcDiscovery()
      const config = this.getOidcConfig()
      const codeVerifier = discovery.code_challenge_methods_supported?.includes(
        'S256',
      )
        ? randomBytes(32).toString('base64url')
        : undefined
      const authUrl = new URL(discovery.authorization_endpoint)
      const params = new URLSearchParams({
        client_id: config.clientID,
        response_type: 'code',
        scope: config.scope,
        redirect_uri: redirectUrl,
        state: uuid,
        prompt: config.prompt,
      })

      if (codeVerifier) {
        params.set('code_challenge_method', 'S256')
        params.set(
          'code_challenge',
          createHash('sha256').update(codeVerifier).digest('base64url'),
        )
      }

      params.forEach((value, key) => authUrl.searchParams.set(key, value))

      await redis.set(
        getOIDCRedisKey(uuid),
        JSON.stringify({ codeVerifier, redirectUrl }),
        'EX',
        REDIS_OIDC_SESSION_TIMEOUT,
      )

      return {
        auth_url: authUrl.toString(),
        uuid,
        expires_in: REDIS_OIDC_SESSION_TIMEOUT * 1000, // milliseconds
      }
    } catch (reason) {
      console.error(`[ERROR][AuthService -> generateOidcAuthUrl]: ${reason}`)
      throw new InternalServerErrorException(
        'Something went wrong, please try again',
      )
    }
  }

  async getIdToken(tokenData: any, discovery: any): Promise<JWTPayload> {
    if (!tokenData?.id_token) {
      throw new BadRequestException('ID token missing in token response')
    }

    const config = this.getOidcConfig()
    let idToken: JWTPayload

    try {
      const { payload } = await jwtVerify(
        tokenData.id_token,
        createRemoteJWKSet(new URL(discovery.jwks_uri)),
        {
          issuer: discovery.issuer,
          audience: config.clientID,
          algorithms: [
            'RS256',
            'RS384',
            'RS512',
            'PS256',
            'PS384',
            'PS512',
            'ES256',
            'ES384',
            'ES512',
            'EdDSA',
          ],
          requiredClaims: ['iss', 'sub', 'aud', 'exp', 'iat'],
        },
      )
      idToken = payload
    } catch (reason) {
      console.error(`[ERROR][AuthService -> getIdToken]: ${reason}`)
      throw new BadRequestException('Invalid ID token')
    }

    const now = Math.floor(Date.now() / 1000)
    const maxClockSkew = 300

    if (idToken.iat > now + maxClockSkew) {
      throw new BadRequestException(
        'ID token issued in the future or invalid iat (check clock skew)',
      )
    }

    return idToken
  }

  async processOidcToken(code: string, state: string, redirectUrl: string) {
    const config = this.getOidcConfig()

    const oidcRedisKey = getOIDCRedisKey(state)
    const sessionData = await redis.get(oidcRedisKey)

    if (sessionData === null) {
      throw new BadRequestException(
        'No authentication session opened for the provided state',
      )
    }

    const session = sessionData ? JSON.parse(sessionData) : {}

    if (session.id) {
      return
    }

    if (session.redirectUrl && session.redirectUrl !== redirectUrl) {
      throw new BadRequestException(
        'Invalid redirect URL for authentication session',
      )
    }

    const discovery = await this.getOidcDiscovery()
    const tokenParams = new URLSearchParams({
      grant_type: 'authorization_code',
      client_id: config.clientID,
      code,
      redirect_uri: session.redirectUrl || redirectUrl,
    })

    if (config.clientSecret) {
      tokenParams.set('client_secret', config.clientSecret)
    }

    if (session.codeVerifier) {
      tokenParams.set('code_verifier', session.codeVerifier)
    }

    const tokenResponse = await fetch(discovery.token_endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Accept: 'application/json',
      },
      body: tokenParams.toString(),
    })

    const tokenData = await tokenResponse.json()

    if (!tokenResponse.ok || tokenData.error) {
      throw new BadRequestException(
        tokenData.error_description || 'Unknown error',
      )
    }

    // Extract and validate ID token claims
    const idToken = await this.getIdToken(tokenData, discovery)

    const emailClaimRaw = idToken.email

    if (!emailClaimRaw || typeof emailClaimRaw !== 'string') {
      throw new BadRequestException('Email claim missing in ID token')
    }

    const email = emailClaimRaw.trim().toLowerCase()

    // Find or create user by email
    const user = await this.getOrCreateUserByEmail(email)

    // Store resolved user id in the existing OIDC session
    const dataToStore = JSON.stringify({ id: user.id })

    await redis.set(oidcRedisKey, dataToStore, 'EX', REDIS_OIDC_SESSION_TIMEOUT)
  }

  /**
   * Checks whether the OIDC session identified by the provided state already contains
   * resolved user data. This is used to gracefully handle duplicate callback deliveries
   * or double-invocation scenarios in the client where the same code might be posted twice.
   */
  async isOidcSessionReady(state: string): Promise<boolean> {
    const oidcRedisKey = getOIDCRedisKey(state)
    const data = await redis.get(oidcRedisKey)

    return Boolean(data && JSON.parse(data).id)
  }

  async doesOidcSessionExist(state: string): Promise<boolean> {
    const oidcRedisKey = getOIDCRedisKey(state)
    const exists = await redis.exists(oidcRedisKey)
    return Boolean(exists)
  }

  async processHash(state: string) {
    if (!state) {
      throw new BadRequestException('Missing state parameter')
    }

    const oidcRedisKey = getOIDCRedisKey(state)
    const exists = await redis.exists(oidcRedisKey)

    if (!exists) {
      throw new BadRequestException(
        'No authentication session opened for the provided state',
      )
    }

    const data = await redis.get(oidcRedisKey)

    if (!data) {
      throw new ConflictException(
        'Authentication session is opened but no data found',
      )
    }

    let payload

    try {
      payload = JSON.parse(data)
    } catch (reason) {
      console.error(
        `[ERROR][AuthService -> authenticateGoogle -> JSON.parse]: ${reason} - ${data}`,
      )
      throw new InternalServerErrorException(
        'Session related data is corrupted',
      )
    }

    if (!payload.id) {
      throw new ConflictException(
        'Authentication session is opened but no data found',
      )
    }

    await redis.del(oidcRedisKey)

    return payload
  }

  async authenticateOidc(state: string) {
    const { id } = await this.processHash(state)

    try {
      const user = await this.userService.findOne({ id })

      if (!user) {
        throw new BadRequestException('Invalid user ID')
      }

      const is2FAAuthenticated = !user.isTwoFactorAuthenticationEnabled
      const tokens = await this.generateJwtTokens(id, is2FAAuthenticated)

      return {
        ...tokens,
        user: this.userService.omitSensitiveData(user),
      }
    } catch (error) {
      console.error(`[ERROR][AuthService -> authenticateOidc]: ${error}`)
      throw new InternalServerErrorException(error)
    }
  }
}