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!

Get rid of sid paremeter

Blue Mouse299671742c0b
diff --git a/backend/apps/production/src/analytics/analytics.controller.ts b/backend/apps/production/src/analytics/analytics.controller.ts
index f3de4d612..913e80f16 100644
--- a/backend/apps/production/src/analytics/analytics.controller.ts
+++ b/backend/apps/production/src/analytics/analytics.controller.ts
@@ -39,7 +39,6 @@ import { OptionalJwtAccessTokenGuard } from '../auth/guards'
import { Auth, Public } from '../auth/decorators'
import {
AnalyticsService,
- getSessionKey,
getHeartbeatKey,
DataType,
validPeriods,
@@ -63,14 +62,12 @@ import {
REDIS_USERS_COUNT_KEY,
REDIS_PROJECTS_COUNT_KEY,
REDIS_EVENTS_COUNT_KEY,
- REDIS_SESSION_SALT_KEY,
} from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
import {
checkRateLimit,
getGeoDetails,
getIPFromHeaders,
- hash,
} from '../common/utils'
import { BotDetection } from '../common/decorators/bot-detection.decorator'
import { BotDetectionGuard } from '../common/guards/bot-detection.guard'
@@ -107,14 +104,6 @@ dayjs.extend(dayjsTimezone)
export const DEFAULT_MEASURE = 'median'
-const getSessionKeyCustom = (
- ip: string,
- ua: string,
- pid: string,
- ev: string,
- salt = '',
-) => `cses_${hash(`${ua}${ip}${pid}${ev}${salt}`)}`
-
// Performance object validator: none of the values cannot be bigger than 1000 * 60 * 5 (5 minutes) and are >= 0
const MAX_PERFORMANCE_VALUE = 1000 * 60 * 5
const isPerformanceValid = (perf: any) => {
@@ -1102,14 +1091,11 @@ export class AnalyticsController {
return []
}
- const sids = _map(keys, key => key.split(':')[1])
-
- console.log('keys:', keys)
- console.log('sids:', sids)
+ const psids = _map(keys, key => key.split(':')[1])
const query = `
SELECT
- sid,
+ psid,
dv,
br,
os,
@@ -1117,14 +1103,14 @@ export class AnalyticsController {
FROM
analytics
WHERE
- sid IN ({ sids: Array(String) })
+ psid IN ({ psids: Array(String) })
AND created > ({ createdAfter: String })
`
const { data } = await clickhouse
.query({
query,
query_params: {
- sids,
+ psids,
createdAfter: dayjs
.utc()
.subtract(3, 'hours')
@@ -1132,7 +1118,8 @@ export class AnalyticsController {
},
})
.then(resultSet => resultSet.json())
- const processed = _map(_uniqBy(data, 'sid'), el =>
+
+ const processed = _map(_uniqBy(data, 'psid'), el =>
_pick(el, ['dv', 'br', 'os', 'cc']),
)
@@ -1241,17 +1228,12 @@ export class AnalyticsController {
this.analyticsService.validateCustomEVMeta(eventsDTO.meta)
await this.analyticsService.validate(eventsDTO, origin, 'custom', ip)
- const salt = await redis.get(REDIS_SESSION_SALT_KEY)
-
if (eventsDTO.unique) {
- const sessionHash = getSessionKeyCustom(
- ip,
+ const [unique] = await this.analyticsService.isUnique(
+ `${eventsDTO.pid}-${eventsDTO.ev}`,
userAgent,
- eventsDTO.pid,
- eventsDTO.ev,
- salt,
+ ip,
)
- const [unique] = await this.analyticsService.isUnique(sessionHash)
if (!unique) {
throw new ForbiddenException(
@@ -1267,8 +1249,11 @@ export class AnalyticsController {
const br = ua.browser.name
const os = ua.os.name
- const sessionHash = getSessionKey(ip, userAgent, eventsDTO.pid, salt)
- const [, psid] = await this.analyticsService.isUnique(sessionHash)
+ const [, psid] = await this.analyticsService.isUnique(
+ eventsDTO.pid,
+ userAgent,
+ ip,
+ )
const transformed = customEventTransformer(
psid,
@@ -1321,7 +1306,7 @@ export class AnalyticsController {
const { pid } = logDTO
const ip = getIPFromHeaders(headers, true) || reqIP || ''
- const sessionID = await this.analyticsService.getSessionHash(
+ const [, sessionID] = await this.analyticsService.isUnique(
pid,
userAgent,
ip,
@@ -1352,11 +1337,13 @@ export class AnalyticsController {
await this.analyticsService.validate(logDTO, origin, 'log', ip)
- const salt = await redis.get(REDIS_SESSION_SALT_KEY)
- const sessionHash = getSessionKey(ip, userAgent, logDTO.pid, salt)
- const [unique, psid] = await this.analyticsService.isUnique(sessionHash)
+ const [unique, psid] = await this.analyticsService.isUnique(
+ logDTO.pid,
+ userAgent,
+ ip,
+ )
- await this.analyticsService.processInteractionSD(sessionHash, logDTO.pid)
+ await this.analyticsService.processInteractionSD(psid, logDTO.pid)
if (!unique && logDTO.unique) {
throw new ForbiddenException(
@@ -1372,7 +1359,7 @@ export class AnalyticsController {
const transformed = trafficTransformer(
psid,
- sessionHash,
+ null,
logDTO.pid,
logDTO.pg,
logDTO.prev,
@@ -1482,11 +1469,13 @@ export class AnalyticsController {
await this.analyticsService.validate(logDTO, origin)
const ip = getIPFromHeaders(headers) || reqIP || ''
- const salt = await redis.get(REDIS_SESSION_SALT_KEY)
- const sessionHash = getSessionKey(ip, userAgent, logDTO.pid, salt)
- const [unique, psid] = await this.analyticsService.isUnique(sessionHash)
+ const [unique, psid] = await this.analyticsService.isUnique(
+ logDTO.pid,
+ userAgent,
+ ip,
+ )
- await this.analyticsService.processInteractionSD(sessionHash, logDTO.pid)
+ await this.analyticsService.processInteractionSD(psid, logDTO.pid)
const { city, region, country } = getGeoDetails(ip)
const ua = UAParser(userAgent)
@@ -1496,7 +1485,7 @@ export class AnalyticsController {
const transformed = trafficTransformer(
psid,
- sessionHash,
+ null,
logDTO.pid,
null,
null,
diff --git a/backend/apps/production/src/analytics/analytics.service.ts b/backend/apps/production/src/analytics/analytics.service.ts
index 0c906f340..08e72f723 100644
--- a/backend/apps/production/src/analytics/analytics.service.ts
+++ b/backend/apps/production/src/analytics/analytics.service.ts
@@ -109,14 +109,10 @@ dayjs.extend(utc)
dayjs.extend(dayjsTimezone)
dayjs.extend(isSameOrBefore)
-export const getSessionKey = (ip: string, ua: string, pid: string, salt = '') =>
- `ses_${hash(`${ua}${ip}${pid}${salt}`)}`
-
export const getHeartbeatKey = (pid: string, sessionID: string) =>
`hb:${pid}:${sessionID}`
-const getSessionDurationKey = (sessionHash: string, pid: string) =>
- `sd:${sessionHash}:${pid}`
+const getSessionDurationKey = (psid: string, pid: string) => `sd:${psid}:${pid}`
const GMT_0_TIMEZONES = [
'Atlantic/Azores',
@@ -749,11 +745,9 @@ export class AnalyticsService {
userAgent: string,
ip: string,
): Promise<string> {
- this.validatePID(pid)
-
const salt = await redis.get(REDIS_SESSION_SALT_KEY)
- return getSessionKey(ip, userAgent, pid, salt)
+ return `ses_${hash(`${userAgent}${ip}${pid}${salt || ''}`)}`
}
async isSessionDurationOpen(sdKey: string): Promise<[string, boolean]> {
@@ -762,8 +756,8 @@ export class AnalyticsService {
}
// Processes interaction for session duration
- async processInteractionSD(sessionHash: string, pid: string): Promise<void> {
- const sdKey = getSessionDurationKey(sessionHash, pid)
+ async processInteractionSD(psid: string, pid: string): Promise<void> {
+ const sdKey = getSessionDurationKey(psid, pid)
const [sd, isOpened] = await this.isSessionDurationOpen(sdKey)
const now = _now()
@@ -1106,7 +1100,13 @@ export class AnalyticsService {
* @param sessionHash
* @returns [isUnique, psid]
*/
- async isUnique(sessionHash: string): Promise<[boolean, string]> {
+ async isUnique(
+ pid: string,
+ userAgent: string,
+ ip: string,
+ ): Promise<[boolean, string]> {
+ const sessionHash = await this.getSessionHash(pid, userAgent, ip)
+
let psid = await redis.get(sessionHash)
const exists = Boolean(psid)
diff --git a/backend/apps/production/src/task-manager/task-manager.service.ts b/backend/apps/production/src/task-manager/task-manager.service.ts
index f6be2c327..181617e76 100644
--- a/backend/apps/production/src/task-manager/task-manager.service.ts
+++ b/backend/apps/production/src/task-manager/task-manager.service.ts
@@ -783,17 +783,23 @@ export class TaskManagerService {
if (_size(toSave) > 0) {
await redis.del(..._map(toSave, ([key]) => key))
- const setSdurQuery = `ALTER TABLE analytics UPDATE sdur = sdur + CASE ${_map(
- toSave,
- ([key, duration]) =>
- `WHEN sid = '${key.split(':')[1]}' THEN ${duration / 1000}`, // converting to seconds
- ).join(' ')} END WHERE sid IN (${_map(
- toSave,
- ([key]) => `'${key.split(':')[1]}'`,
- ).join(',')})`
+ const psids = _map(toSave, ([key]) => `'${key.split(':')[1]}'`)
+
+ const setSdurQuery = `
+ ALTER TABLE
+ analytics
+ UPDATE sdur = sdur + CASE ${_map(
+ toSave,
+ ([key, duration]) =>
+ `WHEN psid = ${key.split(':')[1]} THEN ${duration / 1000}`, // converting to seconds
+ ).join(' ')} END WHERE psid IN ({ psids: Array(String) })
+ `
await clickhouse.query({
query: setSdurQuery,
+ query_params: {
+ psids,
+ },
})
}
}
diff --git a/backend/migrations/clickhouse/initialise_database.js b/backend/migrations/clickhouse/initialise_database.js
index 172fc9b33..df5d1a2dd 100644
--- a/backend/migrations/clickhouse/initialise_database.js
+++ b/backend/migrations/clickhouse/initialise_database.js
@@ -8,7 +8,6 @@ const CLICKHOUSE_INIT_QUERIES = [
`CREATE TABLE IF NOT EXISTS ${dbName}.analytics
(
psid Nullable(UInt64),
- sid Nullable(String),
pid FixedString(12),
pg Nullable(String),
prev Nullable(String),