📈 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
linting improvements
Blue Mouse0453c2a7ecb6
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.tsindex d10833acf..b8a02e7a4 100644--- a/src/analytics/analytics.service.ts+++ b/src/analytics/analytics.service.ts@@ -419,7 +419,11 @@ export class AnalyticsService {return Boolean(session)}- async getSummary(pids: string[], period: 'w' | 'M' = 'w', amountToSubtract = 1): Promise<Object> {+ async getSummary(+ pids: string[],+ period: 'w' | 'M' = 'w',+ amountToSubtract = 1,+ ): Promise<Object> {const result = {}for (let i = 0; i < _size(pids); ++i) {@@ -432,7 +436,9 @@ export class AnalyticsService {const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')const oneWRaw = dayjs.utc().subtract(amountToSubtract, period)const oneWeek = oneWRaw.format('YYYY-MM-DD HH:mm:ss')- const twoWeeks = oneWRaw.subtract(amountToSubtract, period).format('YYYY-MM-DD HH:mm:ss')+ const twoWeeks = oneWRaw+ .subtract(amountToSubtract, period)+ .format('YYYY-MM-DD HH:mm:ss')const query1 = `SELECT unique, count() FROM analytics WHERE pid = {pid:FixedString(12)} AND created BETWEEN {oneWeek:String} AND {now:String} GROUP BY unique`const query2 = `SELECT unique, count() FROM analytics WHERE pid = {pid:FixedString(12)} AND created BETWEEN {twoWeeks:String} AND {oneWeek:String} GROUP BY unique`@@ -998,6 +1004,6 @@ export class AnalyticsService {async getOnlineUserCount(pid: string): Promise<number> {// @ts-ignore- return await redis.countKeysByPattern(`hb:${pid}:*`)+ return redis.countKeysByPattern(`hb:${pid}:*`)}}diff --git a/src/analytics/dto/getData.dto.ts b/src/analytics/dto/getData.dto.tsindex 1c2f82c8f..5ec022d45 100644--- a/src/analytics/dto/getData.dto.ts+++ b/src/analytics/dto/getData.dto.ts@@ -9,6 +9,7 @@ export enum TimeBucketType {MONTH = 'month',}+// eslint-disable-next-line @typescript-eslint/naming-conventionexport class AnalyticsGET_DTO {@ApiProperty()@IsNotEmpty()diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex 656f50a24..fe957f2e3 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -43,12 +43,12 @@ export class AuthService {})}- private getFirstFiveChars(hash: string): string {- return hash.slice(0, 5)+ private getFirstFiveChars(passwordHash: string): string {+ return passwordHash.slice(0, 5)}- private async sendRequestToApi(hash: string) {- const url = `https://api.pwnedpasswords.com/range/${hash}`+ private async sendRequestToApi(passwordHash: string) {+ const url = `https://api.pwnedpasswords.com/range/${passwordHash}`const response = await axios.get(url)if (response.status !== 200) {diff --git a/src/auth/guards/jwt-refresh-token.guard.ts b/src/auth/guards/jwt-refresh-token.guard.tsindex 062deaec0..7a9074a2d 100644--- a/src/auth/guards/jwt-refresh-token.guard.ts+++ b/src/auth/guards/jwt-refresh-token.guard.ts@@ -1,7 +1,7 @@import { AuthGuard } from '@nestjs/passport'export class JwtRefreshTokenGuard extends AuthGuard('jwt-refresh-token') {- constructor() {- super()- }+ // constructor() {+ // super()+ // }}diff --git a/src/auth/strategies/api-key.strategy.ts b/src/auth/strategies/api-key.strategy.tsindex 8d05f0a0a..e87cae9a9 100644--- a/src/auth/strategies/api-key.strategy.ts+++ b/src/auth/strategies/api-key.strategy.ts@@ -12,6 +12,7 @@ export class ApiKeyStrategy extends PassportStrategy(super({ header: 'X-Api-Key', prefix: '' },true,+ // eslint-disable-next-line consistent-returnasync (apiKey: string, done: any) => {const user = await this.authService.validateApiKey(apiKey)if (!user) return done(new UnauthorizedException(), false)diff --git a/src/captcha/captcha.controller.ts b/src/captcha/captcha.controller.tsindex c98d03ff4..c4a17475c 100644--- a/src/captcha/captcha.controller.ts+++ b/src/captcha/captcha.controller.ts@@ -177,8 +177,8 @@ export class CaptchaController {// Set a new cookietry {newTokenCookie = this.captchaService.getTokenCaptcha()- } catch (e) {- console.error(e)+ } catch (reason) {+ console.error(reason)throw new InternalServerErrorException('Could not generate a captcha cookie',)diff --git a/src/captcha/captcha.service.ts b/src/captcha/captcha.service.tsindex 7bd639f5c..1bac52a59 100644--- a/src/captcha/captcha.service.ts+++ b/src/captcha/captcha.service.ts@@ -166,7 +166,7 @@ export class CaptchaService {async generateToken(pid: string,- hash: string,+ captchaHash: string,timestamp: number,autoVerified: boolean,): Promise<string> {@@ -188,7 +188,7 @@ export class CaptchaService {}const token = {- hash,+ hash: captchaHash,timestamp,autoVerified,pid,@@ -256,16 +256,16 @@ export class CaptchaService {noise: 2,...themeParams,})- const hash = this.hashCaptcha(_toLower(captcha.text))+ const captchaHash = this.hashCaptcha(_toLower(captcha.text))return {data: captcha.data,- hash,+ hash: captchaHash,}}- verifyCaptcha(text: string, hash: string): boolean {- return hash === this.hashCaptcha(text)+ verifyCaptcha(text: string, captchaHash: string): boolean {+ return captchaHash === this.hashCaptcha(text)}incrementManuallyVerified(tokenCaptcha: TokenCaptcha): TokenCaptcha {diff --git a/src/common/constants.ts b/src/common/constants.tsindex 5098802ca..b14a1be06 100644--- a/src/common/constants.ts+++ b/src/common/constants.ts@@ -2,9 +2,11 @@ import { ClickHouse } from 'clickhouse'import Redis from 'ioredis'import { hash } from 'blake3'import * as _toNumber from 'lodash/toNumber'+import * as _map from 'lodash/map'import { getSelfhostedUUID } from './utils'+// eslint-disable-next-line @typescript-eslint/no-var-requiresrequire('dotenv').config()const redis = new Redis(@@ -134,11 +136,18 @@ const CLICKHOUSE_INIT_QUERIES = [const initialiseClickhouse = async () => {console.log('Initialising Clickhouse')- for (const query of CLICKHOUSE_INIT_QUERIES) {+ const promises = _map(CLICKHOUSE_INIT_QUERIES, async query => {if (query) {- await clickhouse.query(query).toPromise()+ return clickhouse.query(query).toPromise()}- }++ return 1+ })++ await Promise.all(promises).catch(reason => {+ console.error('Initialising Clickhouse: FAILED')+ console.error(reason)+ })console.log('Initialising Clickhouse: DONE')console.log(`Swetrix API version is: ${process.env.npm_package_version}`)@@ -159,7 +168,7 @@ const JWT_LIFE_TIME = 7 * 24 * 60 * 60const HISTORY_LIFE_TIME_DAYS = 30const ORIGINS_REGEX =- /^(?=.{1,255}$)[0-9A-Za-z\:](?:(?:[0-9A-Za-z\:]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z\:](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/+ /^(?=.{1,255}$)[0-9A-Za-z:](?:(?:[0-9A-Za-z:]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z:](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/const IP_REGEX =/^(([12]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])(\.|\/)){4}([1-2]?[0-9]|3[0-2])$/const PID_REGEX = /^(?!.*--)[a-zA-Z0-9-]{12}$/diff --git a/src/common/interceptors/newrelic.interceptor.ts b/src/common/interceptors/newrelic.interceptor.tsindex 1c237f037..9691788c9 100644--- a/src/common/interceptors/newrelic.interceptor.ts+++ b/src/common/interceptors/newrelic.interceptor.ts@@ -11,7 +11,7 @@ const newrelic = require('newrelic')@Injectable()export class NewrelicInterceptor implements NestInterceptor {intercept(context: ExecutionContext, next: CallHandler): Observable<any> {- return newrelic.startWebTransaction(context.getHandler().name, function () {+ return newrelic.startWebTransaction(context.getHandler().name, () => {const transaction = newrelic.getTransaction()return next.handle().pipe(() => transaction.end())})diff --git a/src/common/utils.ts b/src/common/utils.tsindex ad8761fb3..23f9a0531 100644--- a/src/common/utils.ts+++ b/src/common/utils.ts@@ -54,7 +54,7 @@ const RATE_LIMIT_TIMEOUT = 86400 // 24 hoursconst allowedToUpdateKeys = ['name', 'origins', 'active', 'public']-const _getRateLimitHash = (ipOrApiKey: string, salt = '') =>+const getRateLimitHash = (ipOrApiKey: string, salt = '') =>`rl:${hash(`${ipOrApiKey}${salt}`).toString('hex')}`const splitAt = (x, index): Array<Array<any> | string> => [@@ -73,7 +73,7 @@ const checkRateLimit = async (reqAmount: number = RATE_LIMIT_REQUESTS_AMOUNT,reqTimeout: number = RATE_LIMIT_TIMEOUT,): Promise<void> => {- const rlHash = _getRateLimitHash(ip, action)+ const rlHash = getRateLimitHash(ip, action)const rlCount: number = _toNumber(await redis.get(rlHash)) || 0if (rlCount >= reqAmount) {@@ -87,7 +87,7 @@ export const checkRateLimitForApiKey = async (apiKey: string,reqAmount: number,): Promise<boolean> => {- const rlHash = _getRateLimitHash(apiKey)+ const rlHash = getRateLimitHash(apiKey)const rlCount: number = _toNumber(await redis.get(rlHash)) || 0if (rlCount >= reqAmount) {diff --git a/src/logger/logger.service.spec.ts b/src/logger/logger.service.spec.tsindex f577ca12f..39eee7782 100644--- a/src/logger/logger.service.spec.ts+++ b/src/logger/logger.service.spec.ts@@ -15,9 +15,10 @@ describe('AppLoggerService', () => {describe('root', () => {it('should be defined service', () => {expect(service).toBeDefined()- }),- it('should be defined log()', () => {- expect(service.log).toBeDefined()- })+ })++ it('should be defined log()', () => {+ expect(service.log).toBeDefined()+ })})})diff --git a/src/mailer/mailer.service.spec.ts b/src/mailer/mailer.service.spec.tsindex d51e58818..8cb27a6cc 100644--- a/src/mailer/mailer.service.spec.ts+++ b/src/mailer/mailer.service.spec.ts@@ -1,7 +1,6 @@import { Test, TestingModule } from '@nestjs/testing'import { AppLoggerService } from 'src/logger/logger.service'import { Util } from 'src/Util/Util'-import { LetterTemplate } from './letter'import { MailerService } from './mailer.service'describe('MailerService', () => {diff --git a/src/mailer/mailer.service.ts b/src/mailer/mailer.service.tsindex d60fa21b7..45c03de6f 100644--- a/src/mailer/mailer.service.ts+++ b/src/mailer/mailer.service.ts@@ -92,11 +92,12 @@ interface Params {[name: string]: any}-handlebars.registerHelper('ifEquals', function (arg1, arg2, options) {+handlebars.registerHelper('ifEquals', function ifEquals(arg1, arg2, options) {+ // eslint-disable-next-line eqeqeqreturn arg1 == arg2 ? options.fn(this) : options.inverse(this)})-handlebars.registerHelper('greater', function (v1, v2, options) {+handlebars.registerHelper('greater', function greater(v1, v2, options) {if (v1 > v2) {return options.fn(this)}diff --git a/src/main.ts b/src/main.tsindex 01bec6a42..8395c3b00 100644--- a/src/main.ts+++ b/src/main.ts@@ -31,6 +31,7 @@ async function bootstrap() {app.useGlobalInterceptors(new NewrelicInterceptor())}+ // eslint-disable-next-line consistent-returnapp.use(async (req, res, next) => {res.header('Cross-Origin-Embedder-Policy',@@ -48,6 +49,8 @@ async function bootstrap() {res.header('Access-Control-Allow-Headers', '*')if (req.method === 'OPTIONS') {+ // TODO: INVESTIGATE+ // eslint-disable-next-line @typescript-eslint/return-awaitreturn await res.sendStatus(204)}