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!

Make tracking salt adjustable (to support MAU metric)

Blue Mouse940fbc41fb10
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index 91ee92c61..b8647c13e 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -1060,13 +1060,12 @@ export class AnalyticsController {
)
await this.analyticsService.checkBillingAccess(pid)
- const keys = await redis.keys(`sd:*:${pid}`)
- if (_isEmpty(keys)) {
- return []
- }
-
- const psids = _map(keys, key => key.split(':')[1])
+ const thirtyMinutesAgo = dayjs
+ .utc()
+ .subtract(30, 'minute')
+ .format('YYYY-MM-DD HH:mm:ss')
+ // Query ClickHouse for active sessions in the last 30 minutes
const query = `
SELECT DISTINCT ON (psid)
any(dv) AS dv,
@@ -1084,8 +1083,9 @@ export class AnalyticsController {
cc
FROM analytics
WHERE
- psid IN ({ psids: Array(String) })
- AND pid = ({ pid: FixedString(12) })
+ pid = {pid:FixedString(12)}
+ AND created >= {since:DateTime}
+ AND psid IS NOT NULL
UNION ALL
SELECT
psid,
@@ -1095,8 +1095,9 @@ export class AnalyticsController {
cc
FROM customEV
WHERE
- psid IN ({ psids: Array(String) })
- AND pid = ({ pid: FixedString(12) })
+ pid = {pid:FixedString(12)}
+ AND created >= {since:DateTime}
+ AND psid IS NOT NULL
)
GROUP BY psid
`
@@ -1105,8 +1106,8 @@ export class AnalyticsController {
.query({
query,
query_params: {
- psids,
pid,
+ since: thirtyMinutesAgo,
},
})
.then(resultSet => resultSet.json())
diff --git a/backend/apps/cloud/src/analytics/analytics.module.ts b/backend/apps/cloud/src/analytics/analytics.module.ts
index 603932cc4..bb91359b0 100644
--- a/backend/apps/cloud/src/analytics/analytics.module.ts
+++ b/backend/apps/cloud/src/analytics/analytics.module.ts
@@ -2,14 +2,15 @@ import { Module, forwardRef } from '@nestjs/common'
import { AnalyticsService } from './analytics.service'
import { AnalyticsController } from './analytics.controller'
+import { SaltService } from './salt.service'
import { UserModule } from '../user/user.module'
import { AppLoggerModule } from '../logger/logger.module'
import { ProjectModule } from '../project/project.module'
@Module({
imports: [forwardRef(() => UserModule), AppLoggerModule, ProjectModule],
- providers: [AnalyticsService],
- exports: [AnalyticsService],
+ providers: [AnalyticsService, SaltService],
+ exports: [AnalyticsService, SaltService],
controllers: [AnalyticsController],
})
export class AnalyticsModule {}
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index f4bd8e440..59ab99d4c 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -43,7 +43,6 @@ import { DEFAULT_TIMEZONE, PlanCode } from '../user/entities/user.entity'
import {
redis,
UNIQUE_SESSION_LIFE_TIME,
- REDIS_SESSION_SALT_KEY,
TRAFFIC_COLUMNS,
ALL_COLUMNS,
CAPTCHA_COLUMNS,
@@ -57,6 +56,7 @@ import {
TRAFFIC_METAKEY_COLUMNS,
REDIS_TRIALS_COUNT_KEY,
} from '../common/constants'
+import { SaltService } from './salt.service'
import { clickhouse } from '../common/integrations/clickhouse'
import { getDomainsForRefName } from './utils/referrers.map'
import {
@@ -348,6 +348,7 @@ export class AnalyticsService {
constructor(
private readonly projectService: ProjectService,
private readonly userService: UserService,
+ private readonly saltService: SaltService,
) {}
async checkProjectAccess(
@@ -732,9 +733,9 @@ export class AnalyticsService {
userAgent: string,
ip: string,
): Promise<string> {
- const salt = await redis.get(REDIS_SESSION_SALT_KEY)
+ const salt = await this.saltService.getSaltForProject(pid)
- return `ses_${hash(`${userAgent}${ip}${pid}${salt || ''}`)}`
+ return `ses_${hash(`${userAgent}${ip}${pid}${salt}`)}`
}
async isSessionDurationOpen(sdKey: string): Promise<[string, boolean]> {
@@ -3679,8 +3680,42 @@ export class AnalyticsService {
}
async getOnlineUserCount(pid: string): Promise<number> {
- // @ts-expect-error
- return redis.countKeysByPattern(`sd:*:${pid}`)
+ const thirtyMinutesAgo = dayjs
+ .utc()
+ .subtract(30, 'minute')
+ .format('YYYY-MM-DD HH:mm:ss')
+
+ const query = `
+ SELECT uniqExact(psid) as count
+ FROM (
+ SELECT psid FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created >= {since:DateTime}
+ AND psid IS NOT NULL
+ UNION ALL
+ SELECT psid FROM customEV
+ WHERE pid = {pid:FixedString(12)}
+ AND created >= {since:DateTime}
+ AND psid IS NOT NULL
+ )
+ `
+
+ try {
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: {
+ pid,
+ since: thirtyMinutesAgo,
+ },
+ })
+ .then(resultSet => resultSet.json<{ count: string }>())
+
+ return Number(data[0]?.count || 0)
+ } catch (error) {
+ console.error(`[ERROR](getOnlineUserCount): ${error}`)
+ return 0
+ }
}
async groupCustomEVByTimeBucket(
diff --git a/backend/apps/cloud/src/analytics/salt.service.ts b/backend/apps/cloud/src/analytics/salt.service.ts
new file mode 100644
index 000000000..14f8d74d6
--- /dev/null
+++ b/backend/apps/cloud/src/analytics/salt.service.ts
@@ -0,0 +1,131 @@
+import { Injectable, Logger } from '@nestjs/common'
+import * as bcrypt from 'bcrypt'
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+
+import { SaltRotation } from '../project/entity/project.entity'
+import { redis } from '../common/constants'
+import { ProjectService } from '../project/project.service'
+
+dayjs.extend(utc)
+
+// Redis keys for global salts (one per rotation period)
+const REDIS_SALT_DAILY = 'salt:daily'
+const REDIS_SALT_WEEKLY = 'salt:weekly'
+const REDIS_SALT_MONTHLY = 'salt:monthly'
+
+// Calculate TTL until end of period
+const getTTLUntilEndOfPeriod = (rotation: SaltRotation): number => {
+ const now = dayjs.utc()
+ let endOfPeriod: dayjs.Dayjs
+
+ switch (rotation) {
+ case SaltRotation.DAILY:
+ endOfPeriod = now.endOf('day')
+ break
+ case SaltRotation.WEEKLY:
+ endOfPeriod = now.endOf('week')
+ break
+ case SaltRotation.MONTHLY:
+ endOfPeriod = now.endOf('month')
+ break
+ default:
+ endOfPeriod = now.endOf('day')
+ }
+
+ return Math.max(1, endOfPeriod.diff(now, 'second'))
+}
+
+// Get Redis key for rotation type
+const getRedisKeyForRotation = (rotation: SaltRotation): string => {
+ switch (rotation) {
+ case SaltRotation.WEEKLY:
+ return REDIS_SALT_WEEKLY
+ case SaltRotation.MONTHLY:
+ return REDIS_SALT_MONTHLY
+ default:
+ return REDIS_SALT_DAILY
+ }
+}
+
+@Injectable()
+export class SaltService {
+ private readonly logger = new Logger(SaltService.name)
+
+ constructor(private readonly projectService: ProjectService) {}
+
+ /**
+ * Generate a new salt value
+ */
+ private async generateSalt(): Promise<string> {
+ return bcrypt.genSalt(10)
+ }
+
+ /**
+ * Get the appropriate global salt based on the project's rotation setting.
+ * Since the hash includes project ID, the same global salt produces unique hashes per project.
+ */
+ async getSaltForProject(pid: string): Promise<string> {
+ // Get the project's salt rotation setting
+ let rotation = SaltRotation.DAILY
+
+ try {
+ const project = await this.projectService.getRedisProject(pid)
+ if (project?.saltRotation) {
+ rotation = project.saltRotation
+ }
+ } catch {
+ // Default to daily if project not found
+ }
+
+ return this.getGlobalSalt(rotation)
+ }
+
+ /**
+ * Get or create a global salt for the specified rotation period
+ */
+ async getGlobalSalt(
+ rotation: SaltRotation = SaltRotation.DAILY,
+ ): Promise<string> {
+ const redisKey = getRedisKeyForRotation(rotation)
+
+ // Check if salt exists
+ const existingSalt = await redis.get(redisKey)
+ if (existingSalt) {
+ return existingSalt
+ }
+
+ // Generate new salt and store with TTL
+ const salt = await this.generateSalt()
+ const ttl = getTTLUntilEndOfPeriod(rotation)
+ await redis.set(redisKey, salt, 'EX', ttl)
+
+ this.logger.log(`Generated new ${rotation} salt with TTL ${ttl}s`)
+
+ return salt
+ }
+
+ /**
+ * Regenerate all global salts (called by cron at midnight UTC)
+ * This ensures salts exist even if no requests come in at period boundaries
+ */
+ async regenerateExpiredSalts(): Promise<void> {
+ const rotations = [
+ SaltRotation.DAILY,
+ SaltRotation.WEEKLY,
+ SaltRotation.MONTHLY,
+ ]
+
+ for (const rotation of rotations) {
+ const redisKey = getRedisKeyForRotation(rotation)
+ const exists = await redis.exists(redisKey)
+
+ if (!exists) {
+ const salt = await this.generateSalt()
+ const ttl = getTTLUntilEndOfPeriod(rotation)
+ await redis.set(redisKey, salt, 'EX', ttl)
+ this.logger.log(`Regenerated ${rotation} salt with TTL ${ttl}s`)
+ }
+ }
+ }
+}
diff --git a/backend/apps/cloud/src/common/constants.ts b/backend/apps/cloud/src/common/constants.ts
index 0fd0b1270..8a16bfe5a 100644
--- a/backend/apps/cloud/src/common/constants.ts
+++ b/backend/apps/cloud/src/common/constants.ts
@@ -50,7 +50,7 @@ const getRedisUserCountKey = (uid: string) => `user_c_${uid}`
const getRedisUserUsageInfoKey = (uid: string) => `user_ui_${uid}`
const getRedisCaptchaKey = (token: string) => `captcha_${hash(token)}`
-const REDIS_SESSION_SALT_KEY = 'log_salt' // is updated every 24 hours
+const REDIS_SESSION_SALT_KEY = 'log_salt' // legacy key, kept for backward compatibility
const REDIS_USERS_COUNT_KEY = 'stats:users_count'
const REDIS_TRIALS_COUNT_KEY = 'stats:trials_count'
const REDIS_PROJECTS_COUNT_KEY = 'stats:projects_count'
diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.ts
index fd9cbe807..6b651ad37 100644
--- a/backend/apps/cloud/src/project/entity/project.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project.entity.ts
@@ -24,6 +24,12 @@ export enum BotsProtectionLevel {
BASIC = 'basic',
}
+export enum SaltRotation {
+ DAILY = 'daily', // Default - current behavior, for DAU tracking
+ WEEKLY = 'weekly', // For WAU (Weekly Active Users) tracking
+ MONTHLY = 'monthly', // For MAU (Monthly Active Users) tracking
+}
+
// In case of modifying some properties here add them to the GDPR data export email template
@Entity()
export class Project {
@@ -86,6 +92,14 @@ export class Project {
})
botsProtectionLevel: BotsProtectionLevel
+ @ApiProperty()
+ @Column({
+ type: 'enum',
+ enum: SaltRotation,
+ default: SaltRotation.DAILY,
+ })
+ saltRotation: SaltRotation
+
@ApiProperty({ type: () => User })
@ManyToOne(() => User, user => user.projects)
admin: User
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index c513b34f5..108b3ee4c 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -30,6 +30,7 @@ import { ActionTokensService } from '../action-tokens/action-tokens.service'
import { ActionTokenType } from '../action-tokens/action-token.entity'
import { LetterTemplate } from '../mailer/letter'
import { AnalyticsService } from '../analytics/analytics.service'
+import { SaltService } from '../analytics/salt.service'
import { PayoutsService } from '../payouts/payouts.service'
import { PayoutStatus } from '../payouts/entities/payouts.entity'
import {
@@ -296,6 +297,7 @@ export class TaskManagerService {
private readonly configService: ConfigService,
private readonly discordService: DiscordService,
private readonly slackService: SlackService,
+ private readonly saltService: SaltService,
) {}
generateUnsubscribeUrl(
@@ -688,12 +690,20 @@ export class TaskManagerService {
)
}
+ // Legacy global salt rotation (kept for backward compatibility with older clients)
@Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
async generateSessionSalt() {
const salt = await bcrypt.genSalt(10)
await redis.set(REDIS_SESSION_SALT_KEY, salt, 'EX', 87000)
}
+ // Ensure global salts exist for all rotation periods (daily/weekly/monthly)
+ // Salts auto-expire via Redis TTL, this just ensures they're regenerated if missing
+ @Cron(CronExpression.EVERY_HOUR)
+ async regenerateGlobalSalts() {
+ await this.saltService.regenerateExpiredSalts()
+ }
+
// EVERY SUNDAY AT 2:30 AM
@Cron('30 02 * * 0')
async weeklyReportsHandler() {
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index 1beb8f056..126278aac 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -810,13 +810,12 @@ export class AnalyticsController {
headers['x-password'],
)
- const keys = await redis.keys(`sd:*:${pid}`)
- if (_isEmpty(keys)) {
- return []
- }
-
- const psids = _map(keys, key => key.split(':')[1])
+ const thirtyMinutesAgo = dayjs
+ .utc()
+ .subtract(30, 'minute')
+ .format('YYYY-MM-DD HH:mm:ss')
+ // Query ClickHouse for active sessions in the last 30 minutes
const query = `
SELECT DISTINCT ON (psid)
any(dv) AS dv,
@@ -834,8 +833,9 @@ export class AnalyticsController {
cc
FROM analytics
WHERE
- psid IN ({ psids: Array(String) })
- AND pid = ({ pid: FixedString(12) })
+ pid = {pid:FixedString(12)}
+ AND created >= {since:DateTime}
+ AND psid IS NOT NULL
UNION ALL
SELECT
psid,
@@ -845,8 +845,9 @@ export class AnalyticsController {
cc
FROM customEV
WHERE
- psid IN ({ psids: Array(String) })
- AND pid = ({ pid: FixedString(12) })
+ pid = {pid:FixedString(12)}
+ AND created >= {since:DateTime}
+ AND psid IS NOT NULL
)
GROUP BY psid
`
@@ -855,8 +856,8 @@ export class AnalyticsController {
.query({
query,
query_params: {
- psids,
pid,
+ since: thirtyMinutesAgo,
},
})
.then(resultSet => resultSet.json())
diff --git a/backend/apps/community/src/analytics/analytics.module.ts b/backend/apps/community/src/analytics/analytics.module.ts
index 9d2e0d8e3..aa35b8dd4 100644
--- a/backend/apps/community/src/analytics/analytics.module.ts
+++ b/backend/apps/community/src/analytics/analytics.module.ts
@@ -2,13 +2,14 @@ import { Module } from '@nestjs/common'
import { AnalyticsService } from './analytics.service'
import { AnalyticsController } from './analytics.controller'
+import { SaltService } from './salt.service'
import { AppLoggerModule } from '../logger/logger.module'
import { ProjectModule } from '../project/project.module'
@Module({
imports: [AppLoggerModule, ProjectModule],
- providers: [AnalyticsService],
- exports: [AnalyticsService],
+ providers: [AnalyticsService, SaltService],
+ exports: [AnalyticsService, SaltService],
controllers: [AnalyticsController],
})
export class AnalyticsModule {}
diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.ts
index 16bd55009..a99f2d0bf 100644
--- a/backend/apps/community/src/analytics/analytics.service.ts
+++ b/backend/apps/community/src/analytics/analytics.service.ts
@@ -41,7 +41,6 @@ import { DEFAULT_TIMEZONE } from '../user/entities/user.entity'
import {
redis,
UNIQUE_SESSION_LIFE_TIME,
- REDIS_SESSION_SALT_KEY,
TRAFFIC_COLUMNS,
PERFORMANCE_COLUMNS,
ERROR_COLUMNS,
@@ -50,6 +49,7 @@ import {
ALL_COLUMNS,
TRAFFIC_METAKEY_COLUMNS,
} from '../common/constants'
+import { SaltService } from './salt.service'
import { clickhouse } from '../common/integrations/clickhouse'
import { getDomainsForRefName } from './utils/referrers.map'
import {
@@ -330,7 +330,10 @@ const isValidOrigin = (origins: string[], origin: string) => {
@Injectable()
export class AnalyticsService {
- constructor(private readonly projectService: ProjectService) {}
+ constructor(
+ private readonly projectService: ProjectService,
+ private readonly saltService: SaltService,
+ ) {}
async checkProjectAccess(
pid: string,
@@ -709,9 +712,9 @@ export class AnalyticsService {
userAgent: string,
ip: string,
): Promise<string> {
- const salt = await redis.get(REDIS_SESSION_SALT_KEY)
+ const salt = await this.saltService.getSaltForProject(pid)
- return `ses_${hash(`${userAgent}${ip}${pid}${salt || ''}`)}`
+ return `ses_${hash(`${userAgent}${ip}${pid}${salt}`)}`
}
async isSessionDurationOpen(sdKey: string): Promise<[string, boolean]> {
@@ -3364,8 +3367,42 @@ export class AnalyticsService {
}
async getOnlineUserCount(pid: string): Promise<number> {
- // @ts-expect-error
- return redis.countKeysByPattern(`sd:*:${pid}`)
+ const thirtyMinutesAgo = dayjs
+ .utc()
+ .subtract(30, 'minute')
+ .format('YYYY-MM-DD HH:mm:ss')
+
+ const query = `
+ SELECT uniqExact(psid) as count
+ FROM (
+ SELECT psid FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created >= {since:DateTime}
+ AND psid IS NOT NULL
+ UNION ALL
+ SELECT psid FROM customEV
+ WHERE pid = {pid:FixedString(12)}
+ AND created >= {since:DateTime}
+ AND psid IS NOT NULL
+ )
+ `
+
+ try {
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: {
+ pid,
+ since: thirtyMinutesAgo,
+ },
+ })
+ .then(resultSet => resultSet.json<{ count: string }>())
+
+ return Number(data[0]?.count || 0)
+ } catch (error) {
+ console.error(`[ERROR](getOnlineUserCount): ${error}`)
+ return 0
+ }
}
async groupCustomEVByTimeBucket(
diff --git a/backend/apps/community/src/analytics/salt.service.ts b/backend/apps/community/src/analytics/salt.service.ts
new file mode 100644
index 000000000..14f8d74d6
--- /dev/null
+++ b/backend/apps/community/src/analytics/salt.service.ts
@@ -0,0 +1,131 @@
+import { Injectable, Logger } from '@nestjs/common'
+import * as bcrypt from 'bcrypt'
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+
+import { SaltRotation } from '../project/entity/project.entity'
+import { redis } from '../common/constants'
+import { ProjectService } from '../project/project.service'
+
+dayjs.extend(utc)
+
+// Redis keys for global salts (one per rotation period)
+const REDIS_SALT_DAILY = 'salt:daily'
+const REDIS_SALT_WEEKLY = 'salt:weekly'
+const REDIS_SALT_MONTHLY = 'salt:monthly'
+
+// Calculate TTL until end of period
+const getTTLUntilEndOfPeriod = (rotation: SaltRotation): number => {
+ const now = dayjs.utc()
+ let endOfPeriod: dayjs.Dayjs
+
+ switch (rotation) {
+ case SaltRotation.DAILY:
+ endOfPeriod = now.endOf('day')
+ break
+ case SaltRotation.WEEKLY:
+ endOfPeriod = now.endOf('week')
+ break
+ case SaltRotation.MONTHLY:
+ endOfPeriod = now.endOf('month')
+ break
+ default:
+ endOfPeriod = now.endOf('day')
+ }
+
+ return Math.max(1, endOfPeriod.diff(now, 'second'))
+}
+
+// Get Redis key for rotation type
+const getRedisKeyForRotation = (rotation: SaltRotation): string => {
+ switch (rotation) {
+ case SaltRotation.WEEKLY:
+ return REDIS_SALT_WEEKLY
+ case SaltRotation.MONTHLY:
+ return REDIS_SALT_MONTHLY
+ default:
+ return REDIS_SALT_DAILY
+ }
+}
+
+@Injectable()
+export class SaltService {
+ private readonly logger = new Logger(SaltService.name)
+
+ constructor(private readonly projectService: ProjectService) {}
+
+ /**
+ * Generate a new salt value
+ */
+ private async generateSalt(): Promise<string> {
+ return bcrypt.genSalt(10)
+ }
+
+ /**
+ * Get the appropriate global salt based on the project's rotation setting.
+ * Since the hash includes project ID, the same global salt produces unique hashes per project.
+ */
+ async getSaltForProject(pid: string): Promise<string> {
+ // Get the project's salt rotation setting
+ let rotation = SaltRotation.DAILY
+
+ try {
+ const project = await this.projectService.getRedisProject(pid)
+ if (project?.saltRotation) {
+ rotation = project.saltRotation
+ }
+ } catch {
+ // Default to daily if project not found
+ }
+
+ return this.getGlobalSalt(rotation)
+ }
+
+ /**
+ * Get or create a global salt for the specified rotation period
+ */
+ async getGlobalSalt(
+ rotation: SaltRotation = SaltRotation.DAILY,
+ ): Promise<string> {
+ const redisKey = getRedisKeyForRotation(rotation)
+
+ // Check if salt exists
+ const existingSalt = await redis.get(redisKey)
+ if (existingSalt) {
+ return existingSalt
+ }
+
+ // Generate new salt and store with TTL
+ const salt = await this.generateSalt()
+ const ttl = getTTLUntilEndOfPeriod(rotation)
+ await redis.set(redisKey, salt, 'EX', ttl)
+
+ this.logger.log(`Generated new ${rotation} salt with TTL ${ttl}s`)
+
+ return salt
+ }
+
+ /**
+ * Regenerate all global salts (called by cron at midnight UTC)
+ * This ensures salts exist even if no requests come in at period boundaries
+ */
+ async regenerateExpiredSalts(): Promise<void> {
+ const rotations = [
+ SaltRotation.DAILY,
+ SaltRotation.WEEKLY,
+ SaltRotation.MONTHLY,
+ ]
+
+ for (const rotation of rotations) {
+ const redisKey = getRedisKeyForRotation(rotation)
+ const exists = await redis.exists(redisKey)
+
+ if (!exists) {
+ const salt = await this.generateSalt()
+ const ttl = getTTLUntilEndOfPeriod(rotation)
+ await redis.set(redisKey, salt, 'EX', ttl)
+ this.logger.log(`Regenerated ${rotation} salt with TTL ${ttl}s`)
+ }
+ }
+ }
+}
diff --git a/backend/apps/community/src/common/constants.ts b/backend/apps/community/src/common/constants.ts
index c81dcfe43..8e8b9c782 100644
--- a/backend/apps/community/src/common/constants.ts
+++ b/backend/apps/community/src/common/constants.ts
@@ -51,7 +51,7 @@ const isValidPID = (pid: string) => PID_REGEX.test(pid)
// redis keys
const getRedisProjectKey = (pid: string) => `pid_${pid}`
-const REDIS_SESSION_SALT_KEY = 'log_salt' // is updated every 24 hours
+const REDIS_SESSION_SALT_KEY = 'log_salt' // legacy key, kept for backward compatibility
const REDIS_OIDC_SESSION_KEY = 'oidc:session'
// 3600 sec -> 1 hour
diff --git a/backend/apps/community/src/common/utils.ts b/backend/apps/community/src/common/utils.ts
index e8cadce9b..2def65b77 100644
--- a/backend/apps/community/src/common/utils.ts
+++ b/backend/apps/community/src/common/utils.ts
@@ -120,6 +120,7 @@ const ALLOWED_KEYS = [
'isPasswordProtected',
'passwordHash',
'botsProtectionLevel',
+ 'saltRotation',
]
const CLICKHOUSE_PROJECT_UPDATABLE_KEYS = [...ALLOWED_KEYS, 'adminId']
diff --git a/backend/apps/community/src/project/entity/project.entity.ts b/backend/apps/community/src/project/entity/project.entity.ts
index f30d19789..09b51f542 100644
--- a/backend/apps/community/src/project/entity/project.entity.ts
+++ b/backend/apps/community/src/project/entity/project.entity.ts
@@ -3,6 +3,12 @@ export enum BotsProtectionLevel {
BASIC = 'basic',
}
+export enum SaltRotation {
+ DAILY = 'daily', // Default - current behavior, for DAU tracking
+ WEEKLY = 'weekly', // For WAU (Weekly Active Users) tracking
+ MONTHLY = 'monthly', // For MAU (Monthly Active Users) tracking
+}
+
export class Project {
id: string
name: string
@@ -12,6 +18,7 @@ export class Project {
public: boolean
isPasswordProtected: boolean
botsProtectionLevel: BotsProtectionLevel
+ saltRotation: SaltRotation
passwordHash?: string
created: Date
adminId: string | null
diff --git a/backend/apps/community/src/task-manager/task-manager.module.ts b/backend/apps/community/src/task-manager/task-manager.module.ts
index 74f9eaa3e..6833e02a4 100644
--- a/backend/apps/community/src/task-manager/task-manager.module.ts
+++ b/backend/apps/community/src/task-manager/task-manager.module.ts
@@ -1,9 +1,10 @@
-import { Module } from '@nestjs/common'
+import { Module, forwardRef } from '@nestjs/common'
import { TaskManagerService } from './task-manager.service'
import { AppLoggerModule } from '../logger/logger.module'
+import { AnalyticsModule } from '../analytics/analytics.module'
@Module({
- imports: [AppLoggerModule],
+ imports: [AppLoggerModule, forwardRef(() => AnalyticsModule)],
providers: [TaskManagerService],
exports: [TaskManagerService],
})
diff --git a/backend/apps/community/src/task-manager/task-manager.service.ts b/backend/apps/community/src/task-manager/task-manager.service.ts
index 6aeabec15..92bc31d84 100644
--- a/backend/apps/community/src/task-manager/task-manager.service.ts
+++ b/backend/apps/community/src/task-manager/task-manager.service.ts
@@ -10,19 +10,31 @@ import _now from 'lodash/now'
import { redis, REDIS_SESSION_SALT_KEY } from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
import { AppLoggerService } from '../logger/logger.service'
+import { SaltService } from '../analytics/salt.service'
dayjs.extend(utc)
@Injectable()
export class TaskManagerService {
- constructor(private readonly logger: AppLoggerService) {}
+ constructor(
+ private readonly logger: AppLoggerService,
+ private readonly saltService: SaltService,
+ ) {}
+ // Legacy global salt rotation (kept for backward compatibility with older clients)
@Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
async generateSessionSalt() {
const salt = await bcrypt.genSalt(10)
await redis.set(REDIS_SESSION_SALT_KEY, salt, 'EX', 87000)
}
+ // Ensure global salts exist for all rotation periods (daily/weekly/monthly)
+ // Salts auto-expire via Redis TTL, this just ensures they're regenerated if missing
+ @Cron(CronExpression.EVERY_HOUR)
+ async regenerateGlobalSalts() {
+ await this.saltService.regenerateExpiredSalts()
+ }
+
@Cron(CronExpression.EVERY_MINUTE)
async processSessionDuration() {
const keys = await redis.keys('sd:*')
diff --git a/backend/migrations/clickhouse/initialise_selfhosted.js b/backend/migrations/clickhouse/initialise_selfhosted.js
index 62aa7c8fa..769c89f5d 100644
--- a/backend/migrations/clickhouse/initialise_selfhosted.js
+++ b/backend/migrations/clickhouse/initialise_selfhosted.js
@@ -28,6 +28,7 @@ const CLICKHOUSE_INIT_QUERIES = [
public Int8,
isPasswordProtected Int8,
botsProtectionLevel String DEFAULT 'basic',
+ saltRotation String DEFAULT 'daily',
passwordHash Nullable(String),
adminId Nullable(String),
created DateTime
diff --git a/backend/migrations/clickhouse/selfhosted_2025_11_30_salt_rotation.js b/backend/migrations/clickhouse/selfhosted_2025_11_30_salt_rotation.js
new file mode 100644
index 000000000..27e55bad1
--- /dev/null
+++ b/backend/migrations/clickhouse/selfhosted_2025_11_30_salt_rotation.js
@@ -0,0 +1,8 @@
+// This migration adds the saltRotation column to the project table for self-hosted instances
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ `ALTER TABLE ${dbName}.project ADD COLUMN IF NOT EXISTS saltRotation String DEFAULT 'daily';`,
+]
+
+queriesRunner(queries)
diff --git a/backend/migrations/mysql/2025_11_30_salt_rotation.sql b/backend/migrations/mysql/2025_11_30_salt_rotation.sql
new file mode 100644
index 000000000..0f583bec6
--- /dev/null
+++ b/backend/migrations/mysql/2025_11_30_salt_rotation.sql
@@ -0,0 +1,3 @@
+-- Add saltRotation column to project table
+-- This determines which global salt (daily/weekly/monthly) to use for visitor hashing
+ALTER TABLE `project` ADD COLUMN `saltRotation` ENUM('daily', 'weekly', 'monthly') NOT NULL DEFAULT 'daily' AFTER `botsProtectionLevel`;
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index 70838763a..38e096a65 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -155,6 +155,7 @@ export interface Project {
isDataExists: boolean
isErrorDataExists: boolean
botsProtectionLevel: 'off' | 'basic'
+ saltRotation: 'daily' | 'weekly' | 'monthly'
role?: Role
gscPropertyUri?: string | null
}
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index e278c6ef7..8ffebdc98 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -290,6 +290,7 @@ const ProjectSettings = () => {
origins: null,
ipBlacklist: null,
botsProtectionLevel: 'basic',
+ saltRotation: 'daily',
gscPropertyUri: null,
})
const [validated, setValidated] = useState(false)
@@ -376,6 +377,23 @@ const ProjectSettings = () => {
] as const
}, [t])
+ const saltRotationOptions = useMemo(() => {
+ return [
+ {
+ name: 'daily',
+ title: t('project.settings.saltRotation.options.daily'),
+ },
+ {
+ name: 'weekly',
+ title: t('project.settings.saltRotation.options.weekly'),
+ },
+ {
+ name: 'monthly',
+ title: t('project.settings.saltRotation.options.monthly'),
+ },
+ ] as const
+ }, [t])
+
const organisations = useMemo(
() => [
{
@@ -776,6 +794,13 @@ const ProjectSettings = () => {
beenSubmitted={beenSubmitted}
handleInput={handleInput}
sharableLink={sharableLink}
+ saltRotationOptions={saltRotationOptions}
+ setSaltRotation={(name) =>
+ setForm((prevForm) => ({
+ ...prevForm,
+ saltRotation: name as any,
+ }))
+ }
/>
) : null}
diff --git a/web/app/pages/Project/Settings/tabs/General.tsx b/web/app/pages/Project/Settings/tabs/General.tsx
index 915f2d426..d7ba25100 100644
--- a/web/app/pages/Project/Settings/tabs/General.tsx
+++ b/web/app/pages/Project/Settings/tabs/General.tsx
@@ -2,11 +2,13 @@ import React from 'react'
import { useTranslation } from 'react-i18next'
import Input from '~/ui/Input'
+import Select from '~/ui/Select'
interface GeneralProps {
form: {
name?: string
id?: string
+ saltRotation?: string
}
errors: {
name?: string
@@ -14,9 +16,19 @@ interface GeneralProps {
beenSubmitted: boolean
handleInput: (e: React.ChangeEvent<HTMLInputElement>) => void
sharableLink: string
+ saltRotationOptions: readonly { name: string; title: string }[]
+ setSaltRotation: (name: string) => void
}
-const General = ({ form, errors, beenSubmitted, handleInput, sharableLink }: GeneralProps) => {
+const General = ({
+ form,
+ errors,
+ beenSubmitted,
+ handleInput,
+ sharableLink,
+ saltRotationOptions,
+ setSaltRotation,
+}: GeneralProps) => {
const { t } = useTranslation('common')
return (
@@ -50,6 +62,20 @@ const General = ({ form, errors, beenSubmitted, handleInput, sharableLink }: Gen
error={null}
disabled
/>
+ <div className='mt-4'>
+ <Select
+ id='saltRotation'
+ label={t('project.settings.saltRotation.title')}
+ hint={t('project.settings.saltRotation.hint')}
+ // @ts-expect-error
+ items={saltRotationOptions}
+ title={saltRotationOptions.find((predicate) => predicate.name === form.saltRotation)?.title || ''}
+ labelExtractor={(item: any) => item.title}
+ onSelect={(item) => setSaltRotation(item.name)}
+ capitalise
+ selectedItem={saltRotationOptions.find((predicate) => predicate.name === form.saltRotation)}
+ />
+ </div>
</>
)
}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 42862c28f..60c0f2540 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1182,6 +1182,15 @@
"basic": "Basic: we detect bots based on their user agent (Googlebot, Bingbot, curl, etc.)"
}
},
+ "saltRotation": {
+ "title": "Unique visitor tracking period",
+ "hint": "Controls how long a visitor is recognized as the same unique visitor. Daily is best for DAU (Daily Active Users), weekly for WAU, and monthly for MAU (Monthly Active Users) tracking.",
+ "options": {
+ "daily": "Daily (default): visitors reset at midnight UTC",
+ "weekly": "Weekly: visitors reset on Monday at midnight UTC",
+ "monthly": "Monthly: visitors reset on the 1st of each month"
+ }
+ },
"verify": "Please, verify your email address first",
"updated": "The project's settings were updated",
"created": "The project has been created",