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!

6.1 KB
Raw Blame
import Redis from 'ioredis'
import path from 'path'
import _toNumber from 'lodash/toNumber'
import 'dotenv/config'
import { deriveKey, hash } from './utils'

const { EMAIL_ACTION_ENCRYPTION_KEY } = process.env

const redis = new Redis(
  _toNumber(process.env.REDIS_PORT),
  process.env.REDIS_HOST,
  {
    password: process.env.REDIS_PASSWORD,
    username: process.env.REDIS_USER,
    family: 0,
  },
)

export const JWT_ACCESS_TOKEN_SECRET = deriveKey('access-token')
export const JWT_REFRESH_TOKEN_SECRET = deriveKey('refresh-token')

const {
  // 30 days
  JWT_REFRESH_TOKEN_LIFETIME = 60 * 60 * 24 * 30,
  // 30 minutes
  JWT_ACCESS_TOKEN_LIFETIME = 60 * 30,
} = process.env
const isDevelopment = process.env.NODE_ENV === 'development'
const PRODUCTION_ORIGIN = process.env.CLIENT_URL || 'https://swetrix.com'

const { TWO_FACTOR_AUTHENTICATION_APP_NAME } = process.env

const 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*:])?)*)?$/
const PID_REGEX = /^(?!.*--)[a-zA-Z0-9-]{12}$/
const isValidPID = (pid: string) => PID_REGEX.test(pid)

// redis keys
const getRedisProjectKey = (pid: string) => `pid_${pid}`
const getRedisUserCountKey = (uid: string) => `user_c_billable_${uid}`
const getRedisUserUsageInfoKey = (uid: string) => `user_ui_billable_${uid}`
const getRedisCaptchaKey = (token: string) => `captcha_${hash(token)}`

const REDIS_USERS_COUNT_KEY = 'stats:users_count'
const REDIS_TRIALS_COUNT_KEY = 'stats:trials_count'
const REDIS_PROJECTS_COUNT_KEY = 'stats:projects_count'
const REDIS_EVENTS_COUNT_KEY = 'stats:events'
const REDIS_SSO_UUID = 'sso:uuid'

// 3600 sec -> 1 hour
const redisProjectCacheTimeout = 3600

// 15 minutes
const redisProjectCountCacheTimeout = 900

// 5 minutes
const redisUserUsageinfoCacheTimeout = 300

// 30 minues -> the amount of time analytics requests within one session are counted as non-unique
const UNIQUE_SESSION_LIFE_TIME = 1800

const ONLINE_VISITORS_WINDOW_MINUTES = 5

// send email warning when 85% of events in tier are used
const SEND_WARNING_AT_PERC = 85

const PROJECT_INVITE_EXPIRE = 48

const CAPTCHA_TOKEN_LIFETIME = 300 * 1000 // milliseconds (5 minutes).
const CAPTCHA_SECRET_KEY_LENGTH = 50

// Funnels
const MIN_PAGES_IN_FUNNEL = 2
const MAX_PAGES_IN_FUNNEL = 10

const BLOG_POSTS_PATH = isDevelopment
  ? path.join(__dirname, '../../../..', 'blog-posts', 'posts')
  : path.join(__dirname, '../..', 'blog-posts', 'posts')

const TRAFFIC_COLUMNS = [
  'cc',
  'rg',
  'ct',
  'isp',
  'og',
  'ut',
  'ctp',
  'host',
  'pg',
  'title',
  'lc',
  'br',
  'brv',
  'os',
  'osv',
  'dv',
  'ref',
  'so',
  'me',
  'ca',
  'te',
  'co',
]

const TRAFFIC_METAKEY_COLUMNS = ['tag:key', 'tag:value']

const ALL_COLUMNS = [...TRAFFIC_COLUMNS, 'ev', 'entryPage', 'exitPage']

const V2_VIEW_FILTER_DIMENSIONS = [
  'country',
  'region',
  'city',
  'page',
  'title',
  'host',
  'locale',
  'browser',
  'browser_version',
  'os',
  'os_version',
  'device',
  'referrer',
  'referrer_name',
  'utm_source',
  'utm_medium',
  'utm_campaign',
  'utm_term',
  'utm_content',
  'isp',
  'organization',
  'user_type',
  'connection_type',
  'entry_page',
  'exit_page',
  'event',
  'error_name',
  'error_message',
  'error_filename',
  'event_metadata',
  'page_property',
]

const CAPTCHA_COLUMNS = [
  'cc',
  'br',
  'os',
  'dv',
  'captcha_event',
  'captcha_difficulty',
  'captcha_reason',
  'solve_time',
]
const PERFORMANCE_COLUMNS = [
  'cc',
  'rg',
  'ct',
  'isp',
  'og',
  'ut',
  'ctp',
  'host',
  'pg',
  'dv',
  'br',
  'brv',
]
const ERROR_COLUMNS = [
  'host',
  'pg',
  'dv',
  'br',
  'brv',
  'os',
  'osv',
  'lc',
  'cc',
  'rg',
  'ct',
  'isp',
  'og',
  'ut',
  'ctp',
]

const sentryIgnoreErrors: (string | RegExp)[] = [
  'BadRequestException',
  'UnauthorizedException',
  'PaymentRequiredException',
  'ForbiddenException',
  'NotFoundException',
  'MethodNotAllowedException',
  'NotAcceptableException',
  'ProxyAuthenticationRequiredException',
  'RequestTimeoutException',
  'ConflictException',
  'GoneException',
  'LengthRequiredException',
  'PreconditionFailedException',
  'PayloadTooLargeException',
  'URITooLongException',
  'UnsupportedMediaTypeException',
  'RangeNotSatisfiableException',
  'ExpectationFailedException',
  'ImATeapotException',
  'MisdirectedRequestException',
  'UnprocessableEntityException',
  'LockedException',
  'FailedDependencyException',
  'TooEarlyException',
  'UpgradeRequiredException',
  'PreconditionRequiredException',
  'TooManyRequestsException',
  'RequestHeaderFieldsTooLargeException',
  'UnavailableForLegalReasonsException',
  'ClientClosedRequestException',
  'HttpException', // at the moment, these are either rate-limiting or payment required errors, so no need to track them
]

const parseLifetimeSeconds = (value: unknown, fallback: number) => {
  const parsed = Number(value)
  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback
}

const NUMBER_JWT_REFRESH_TOKEN_LIFETIME = parseLifetimeSeconds(
  JWT_REFRESH_TOKEN_LIFETIME,
  60 * 60 * 24 * 30,
)
const NUMBER_JWT_ACCESS_TOKEN_LIFETIME = parseLifetimeSeconds(
  JWT_ACCESS_TOKEN_LIFETIME,
  60 * 30,
)

const MAX_FUNNELS = 100

export {
  redis,
  isValidPID,
  getRedisProjectKey,
  redisProjectCacheTimeout,
  UNIQUE_SESSION_LIFE_TIME,
  ONLINE_VISITORS_WINDOW_MINUTES,
  getRedisUserCountKey,
  redisProjectCountCacheTimeout,
  REDIS_USERS_COUNT_KEY,
  REDIS_TRIALS_COUNT_KEY,
  REDIS_PROJECTS_COUNT_KEY,
  REDIS_EVENTS_COUNT_KEY,
  SEND_WARNING_AT_PERC,
  PROJECT_INVITE_EXPIRE,
  TWO_FACTOR_AUTHENTICATION_APP_NAME,
  ORIGINS_REGEX,
  EMAIL_ACTION_ENCRYPTION_KEY,
  isDevelopment,
  getRedisCaptchaKey,
  CAPTCHA_TOKEN_LIFETIME,
  CAPTCHA_SECRET_KEY_LENGTH,
  PRODUCTION_ORIGIN,
  REDIS_SSO_UUID,
  NUMBER_JWT_REFRESH_TOKEN_LIFETIME as JWT_REFRESH_TOKEN_LIFETIME,
  NUMBER_JWT_ACCESS_TOKEN_LIFETIME as JWT_ACCESS_TOKEN_LIFETIME,
  getRedisUserUsageInfoKey,
  redisUserUsageinfoCacheTimeout,
  TRAFFIC_COLUMNS,
  TRAFFIC_METAKEY_COLUMNS,
  V2_VIEW_FILTER_DIMENSIONS,
  CAPTCHA_COLUMNS,
  ERROR_COLUMNS,
  PERFORMANCE_COLUMNS,
  sentryIgnoreErrors,
  BLOG_POSTS_PATH,
  MIN_PAGES_IN_FUNNEL,
  MAX_PAGES_IN_FUNNEL,
  MAX_FUNNELS,
  ALL_COLUMNS,
  PID_REGEX,
}