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!

added noscript tracking

Blue Mousea1a8914a3299
diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.ts
index e7f42e750..9357bf537 100644
--- a/src/analytics/analytics.controller.ts
+++ b/src/analytics/analytics.controller.ts
@@ -11,7 +11,7 @@ import { v4 as uuidv4 } from 'uuid'
import { hash } from 'blake3'
import {
Controller, Body, Query, UseGuards, Get, Post, Headers, BadRequestException, InternalServerErrorException,
- NotImplementedException, UnprocessableEntityException, PreconditionFailedException, Ip, ForbiddenException,
+ NotImplementedException, UnprocessableEntityException, PreconditionFailedException, Ip, ForbiddenException, Response,
} from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import * as UAParser from 'ua-parser-js'
@@ -71,6 +71,9 @@ const getPIDsArray = (pids, pid) => {
return pids
}
+// needed for serving 1x1 px GIF
+const TRANSPARENT_GIF_BUFFER = Buffer.from('R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=', 'base64')
+
@ApiTags('Analytics')
@UseGuards(RolesGuard)
@Controller('log')
@@ -274,4 +277,54 @@ export class AnalyticsController {
throw new InternalServerErrorException('Error occured while saving the log data')
}
}
+
+ // Fallback for logging pageviews for users with JavaScript disabled
+ // Returns 1x1 transparent gif
+ @Get('/noscript')
+ async noscript(@Query() data, @Headers() headers, @Ip() reqIP, @Response() res): Promise<any> {
+ const { 'user-agent': userAgent, origin } = headers
+ const { pid } = data
+
+ // todo: create a decorator for bot traffic detection
+ if (isbot(userAgent)) {
+ res.writeHead(200, { 'Content-Type': 'image/gif' })
+ return res.end(TRANSPARENT_GIF_BUFFER, 'binary')
+ }
+
+ const logDTO: PageviewsDTO = {
+ pid,
+ }
+
+ await this.analyticsService.validate(logDTO, origin)
+
+ const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''
+
+ // const salt = await redis.get(REDIS_SESSION_SALT_KEY)
+ const sessionHash = getSessionKey(ip, userAgent, logDTO.pid/*, salt */)
+ const unique = await this.analyticsService.isUnique(sessionHash)
+ let dto: Array<string | number>
+
+ if (unique) {
+ const ua = UAParser(userAgent)
+ const dv = ua.device.type || 'desktop'
+ const br = ua.browser.name
+ const os = ua.os.name
+ // using CloudFlare's IP based country code
+ const cc = headers['cf-ipcountry'] === 'XX' ? 'NULL' : headers['cf-ipcountry']
+ dto = analyticsDTO(logDTO.pid, 'NULL', dv, br, os, 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', cc, 1)
+ } else {
+ dto = analyticsDTO(logDTO.pid, 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 0)
+ }
+
+ // todo: fix: may be vulnerable to sql injection attack
+ const values = `(${dto.map(getElValue).join(',')})`
+ try {
+ await redis.rpush(REDIS_LOG_DATA_CACHE_KEY, values)
+ } catch (e) {
+ this.logger.error(e)
+ }
+
+ res.writeHead(200, { 'Content-Type': 'image/gif' })
+ return res.end(TRANSPARENT_GIF_BUFFER, 'binary')
+ }
}
diff --git a/src/analytics/dto/pageviews.dto.ts b/src/analytics/dto/pageviews.dto.ts
index 33e36bc52..5bcd69831 100644
--- a/src/analytics/dto/pageviews.dto.ts
+++ b/src/analytics/dto/pageviews.dto.ts
@@ -15,54 +15,54 @@ export class PageviewsDTO {
example: 'Europe/Kiev',
description: 'User\'s timezone'
})
- tz: string
+ tz?: string
@ApiProperty({
example: '/articles/my-awesome-article-1',
description: 'A page that user sent data from'
})
- pg: string
+ pg?: string
@ApiProperty({
example: 'en-GB',
description: 'User\'s locale'
})
- lc: string
+ lc?: string
@ApiProperty({
example: 'https://example.com',
description: 'The referrer'
})
- ref: string
+ ref?: string
@ApiProperty({
example: 'duckduckgo',
description: 'utm_source URL parameter'
})
- so: string
+ so?: string
@ApiProperty({
example: 'cpc',
description: 'utm_medium URL parameter'
})
- me: string
+ me?: string
@ApiProperty({
example: 'spring_sale',
description: 'utm_campaign URL parameter'
})
- ca: string
+ ca?: string
@ApiProperty({
example: false,
description: 'If true, only unique events will be saved'
})
- unique: boolean
+ unique?: boolean
// Performance metrics
@ApiProperty({
example: 261,
description: 'Page load time (in milliseconds)'
})
- lt: number
+ lt?: number
}
\ No newline at end of file