📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
implemented password leak check
Blue Mouse454baf97ad29
diff --git a/src/action-tokens/action-tokens.service.ts b/src/action-tokens/action-tokens.service.tsindex 527ad66c6..2bd815a75 100644--- a/src/action-tokens/action-tokens.service.ts+++ b/src/action-tokens/action-tokens.service.ts@@ -13,11 +13,11 @@ export class ActionTokensService {) {}async createForUser(user: User, action: ActionTokenType, newValue: string = null): Promise<ActionToken> {- return this.actionTokensRepository.save({user, action, newValue})+ return this.actionTokensRepository.save({ user, action, newValue })}async find(id: string): Promise<ActionToken> {- return this.actionTokensRepository.findOneOrFail(id, { relations: ['user']})+ return this.actionTokensRepository.findOneOrFail(id, { relations: ['user'] })}async delete(id: string): Promise<void> {diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsindex 3ae9824b0..8f8f7692b 100644--- a/src/auth/auth.controller.ts+++ b/src/auth/auth.controller.ts@@ -68,10 +68,10 @@ export class AuthController {if (userLoginDTO.email !== SELFHOSTED_EMAIL || userLoginDTO.password !== SELFHOSTED_PASSWORD) {throw new UnprocessableEntityException('Email or password is incorrect')}- return await this.authService.login(SELFHOSTED_EMAIL)+ return this.authService.login(SELFHOSTED_EMAIL)} else {const user = await this.authService.validateUser(userLoginDTO.email, userLoginDTO.password)- return await this.authService.login(user)+ return this.authService.login(user)}}@@ -80,10 +80,23 @@ export class AuthController {async register(@Body() userDTO: SignupUserDTO, /*@Body('recaptcha') recaptcha: string,*/ @Req() request: Request, @Headers() headers, @Ip() reqIP): Promise<any> {this.logger.log({ userDTO }, 'POST /auth/register')const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''- await checkRateLimit(ip, 'register')+ await checkRateLimit(ip, 'register', 4)// await this.authService.checkCaptcha(recaptcha)this.userService.validatePassword(userDTO.password)++ const doesEmailExist = await this.userService.findOneWhere({+ email: userDTO.email,+ })++ if (doesEmailExist) {+ throw new BadRequestException('emailRegistered')+ }++ if (userDTO.checkIfLeaked) {+ await this.authService.checkIfPasswordLeaked(userDTO.password)+ }+userDTO.password = await this.authService.hashPassword(userDTO.password)try {@@ -92,13 +105,9 @@ export class AuthController {const url = `${request.headers.origin}/verify/${actionToken.id}`await this.mailerService.sendEmail(userDTO.email, LetterTemplate.SignUp, { url })- return await this.authService.login(user)+ return this.authService.login(user)} catch(e) {- if (e.code === 'ER_DUP_ENTRY') {- if (e.sqlMessage.includes(userDTO.email)) {- throw new BadRequestException('A user with this email already exists')- }- }+ this.logger.log(`[ERROR WHILE CREATING ACCOUNT]: ${e}`, 'POST /auth/register', true)}}diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex c2ddd42e5..28756d70c 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -1,26 +1,87 @@-import { Injectable, UnprocessableEntityException } from '@nestjs/common'+import { Injectable, UnprocessableEntityException, BadRequestException } from '@nestjs/common'import { sign } from 'jsonwebtoken'import * as bcrypt from 'bcrypt'+import * as crypto from 'crypto'+import * as https from 'https'+import * as _toUpper from 'lodash/toUpper'+import * as _includes from 'lodash/includes'import { UserService } from '../user/user.service'+import { AppLoggerService } from '../logger/logger.service'import { User } from '../user/entities/user.entity'import {isSelfhosted, JWT_LIFE_TIME, SELFHOSTED_UUID,} from '../common/constants'+import { splitAt } from '../common/utils'+const HIBP_URL = 'https://api.pwnedpasswords.com/range'const BCRYPT_SALT_ROUNDS = 10+const httpsOptions = {+ headers: {+ 'User-Agent': 'Swetrix API ([email protected])',+ }+}+@Injectable()export class AuthService {constructor(private userService: UserService,- ) {}+ private readonly logger: AppLoggerService+ ) { }async hashPassword(pass: string): Promise<string> {const salt = await bcrypt.genSalt(BCRYPT_SALT_ROUNDS)return await bcrypt.hash(pass, salt)}+ async get(hash) {+ return new Promise((resolve, reject) => {+ https.get(`${HIBP_URL}/${hash}`, httpsOptions, (res) => {+ let data = ''++ if (res.statusCode !== 200) {+ return reject(`Failed to load ${HIBP_URL} API: ${res.statusCode}`)+ }++ res.on('data', (chunk) => {+ data += chunk+ })++ res.on('end', () => {+ resolve(data)+ })++ return true+ }).on('error', (err) => {+ reject(err)+ })+ })+ }++ async sha1hash(string): Promise<string> {+ return new Promise((resolve) => {+ const shasum = _toUpper(crypto.createHash('sha1').update(string).digest('hex'))+ resolve(shasum)+ })+ }++ async checkIfPasswordLeaked(pass: string): Promise<void> {+ const shasum = splitAt(await this.sha1hash(pass), 5)+ let isLeaked++ try {+ const result = await this.get(shasum[0])+ isLeaked = _includes(result, shasum[1])+ } catch (e) {+ this.logger.log(`[ERROR / HAVEIBEENPWNED]: ${e}`, 'AUTH SERVICE', true)+ }++ if (isLeaked) {+ throw new BadRequestException('leakedPassword')+ }+ }+async checkPassword(passToCheck: string, hashedPass: string): Promise<boolean> {return await bcrypt.compare(passToCheck, hashedPass)}@@ -35,7 +96,7 @@ export class AuthService {throw new UnprocessableEntityException('Email or password is incorrect')}- async login(user: User | string): Promise<any> {+ login(user: User | string): object {let userData = userif (isSelfhosted) {@@ -44,7 +105,7 @@ export class AuthService {id: SELFHOSTED_UUID,}}-+// @ts-ignoreconst token = sign({ user_id: user.id }, process.env.JWT_SECRET, {expiresIn: JWT_LIFE_TIME,diff --git a/src/auth/dto/user-signup.dto.ts b/src/auth/dto/user-signup.dto.tsindex 4d4a8d887..ebeede210 100644--- a/src/auth/dto/user-signup.dto.ts+++ b/src/auth/dto/user-signup.dto.ts@@ -16,5 +16,8 @@ export class SignupUserDTO {@ApiProperty()@IsNotEmpty()- tos: Date+ tos: boolean++ @ApiProperty()+ checkIfLeaked: boolean}diff --git a/src/common/utils.ts b/src/common/utils.tsindex 5af114ab2..2e0ce9835 100644--- a/src/common/utils.ts+++ b/src/common/utils.ts@@ -47,6 +47,8 @@ const allowedToUpdateKeys = ['name', 'origins', 'active', 'public']const _getRateLimitHash = (ip: string, salt: string = '') => `rl:${hash(`${ip}${salt}`).toString('hex')}`+const splitAt = (x, index): Array<Array<any> | string> => [x.slice(0, index), x.slice(index)]+const getRandomTip = (language: string = 'en'): string => {return _sample(marketingTips[language])}@@ -101,5 +103,5 @@ const createProjectClickhouse = async (project: Project) => {}export {- getRandomTip, checkRateLimit, createProjectClickhouse, getProjectsClickhouse, updateProjectClickhouse, deleteProjectClickhouse,+ getRandomTip, checkRateLimit, createProjectClickhouse, getProjectsClickhouse, updateProjectClickhouse, deleteProjectClickhouse, splitAt,}