📈 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
Migrate to Hetzner S3
Blue Mouse352426b42e3f
diff --git a/backend/.env.example b/backend/.env.exampleindex 6577ba87d..114c5f2ba 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -109,25 +109,22 @@ EMAIL_ACTION_ENCRYPTION_KEY=# Swetrix Enterprise (Cloud)SWETRIX_LICENSE_KEY=-# Cloudflare R2 storage defaults. Session Replay uses these when the-# SESSION_REPLAY_R2_* variables below are not set.-R2_ACCOUNT_ID=-R2_ENDPOINT=-R2_BUCKET=-R2_ACCESS_KEY_ID=-R2_SECRET_ACCESS_KEY=--# Cloudflare R2 storage for Session Replays.-# If SESSION_REPLAY_R2_ENDPOINT is empty and SESSION_REPLAY_R2_ACCOUNT_ID is set,-# the endpoint defaults to https://${SESSION_REPLAY_R2_ACCOUNT_ID}.r2.cloudflarestorage.com.-# For EU jurisdiction buckets, set SESSION_REPLAY_R2_ENDPOINT explicitly to-# https://${SESSION_REPLAY_R2_ACCOUNT_ID}.eu.r2.cloudflarestorage.com.-# Do not include the bucket path in SESSION_REPLAY_R2_ENDPOINT.-SESSION_REPLAY_R2_ACCOUNT_ID=-SESSION_REPLAY_R2_ENDPOINT=-SESSION_REPLAY_R2_BUCKET=-SESSION_REPLAY_R2_ACCESS_KEY_ID=-SESSION_REPLAY_R2_SECRET_ACCESS_KEY=+# Hetzner S3 storage defaults. Session Replay uses these when the+# SESSION_REPLAY_S3_* variables below are not set.+# HETZNER_S3_ENDPOINT is the location endpoint, for example https://fsn1.your-objectstorage.com.+# Do not include the bucket path in HETZNER_S3_ENDPOINT.+HETZNER_S3_ENDPOINT=+HETZNER_S3_BUCKET=+HETZNER_S3_ACCESS_KEY_ID=+HETZNER_S3_SECRET_ACCESS_KEY=++# Hetzner S3 storage for Session Replays.+# SESSION_REPLAY_S3_ENDPOINT is the location endpoint, for example https://fsn1.your-objectstorage.com.+# Do not include the bucket path in SESSION_REPLAY_S3_ENDPOINT.+SESSION_REPLAY_S3_ENDPOINT=+SESSION_REPLAY_S3_BUCKET=+SESSION_REPLAY_S3_ACCESS_KEY_ID=+SESSION_REPLAY_S3_SECRET_ACCESS_KEY=# OpenRouter API key for AI featuresOPENROUTER_API_KEY=diff --git a/backend/apps/cloud/src/analytics/analytics.module.ts b/backend/apps/cloud/src/analytics/analytics.module.tsindex 2f4219963..7adc7bcfa 100644--- a/backend/apps/cloud/src/analytics/analytics.module.ts+++ b/backend/apps/cloud/src/analytics/analytics.module.ts@@ -8,7 +8,7 @@ import { BotDetectionService } from './bot-detection.service'import { HeartbeatGateway } from './heartbeat.gateway'import { SaltService } from './salt.service'import { Salt } from './entities/salt.entity'-import { SessionReplayR2Service } from './session-replay-r2.service'+import { SessionReplayS3Service } from './session-replay-s3.service'import { UserModule } from '../user/user.module'import { AppLoggerModule } from '../logger/logger.module'import { ProjectModule } from '../project/project.module'@@ -34,7 +34,7 @@ import { SessionReplayExportProcessor } from './session-replay-export.processor'AnalyticsService,BotDetectionService,SaltService,- SessionReplayR2Service,+ SessionReplayS3Service,SessionReplayExportService,SessionReplayExportProcessor,HeartbeatGateway,diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.tsindex d597e014a..67d7eb4e9 100644--- a/backend/apps/cloud/src/analytics/analytics.service.ts+++ b/backend/apps/cloud/src/analytics/analytics.service.ts@@ -119,7 +119,7 @@ import { ProjectViewCustomEventDto } from '../project/dto/create-project-view.dtimport { UAParser } from '@ua-parser-js/pro-business'import { extensions } from './utils/ua-parser'import { In, Not } from 'typeorm'-import { SessionReplayR2Service } from './session-replay-r2.service'+import { SessionReplayS3Service } from './session-replay-s3.service'import { SessionReplayPrivacyMode } from './dto/session-replay.dto'dayjs.extend(utc)@@ -474,7 +474,7 @@ export class AnalyticsService {private readonly saltService: SaltService,private readonly botDetectionService: BotDetectionService,private readonly logger: AppLoggerService,- private readonly sessionReplayStorage: SessionReplayR2Service,+ private readonly sessionReplayStorage: SessionReplayS3Service,) {}async checkBot(diff --git a/backend/apps/cloud/src/analytics/session-replay-export.service.ts b/backend/apps/cloud/src/analytics/session-replay-export.service.tsindex f7836d5b4..970abc88f 100644--- a/backend/apps/cloud/src/analytics/session-replay-export.service.ts+++ b/backend/apps/cloud/src/analytics/session-replay-export.service.ts@@ -19,7 +19,7 @@ import type { Response } from 'express'import { redis } from '../common/constants'import { hash } from '../common/utils'import { AnalyticsService } from './analytics.service'-import { SessionReplayR2Service } from './session-replay-r2.service'+import { SessionReplayS3Service } from './session-replay-s3.service'export const SESSION_REPLAY_EXPORT_QUEUE = 'session-replay-export'@@ -126,7 +126,7 @@ export class SessionReplayExportService {constructor(private readonly analyticsService: AnalyticsService,- private readonly sessionReplayStorage: SessionReplayR2Service,+ private readonly sessionReplayStorage: SessionReplayS3Service,@InjectQueue(SESSION_REPLAY_EXPORT_QUEUE)private readonly exportQueue: Queue<SessionReplayExportJobData>,) {}diff --git a/backend/apps/cloud/src/analytics/session-replay-r2.service.ts b/backend/apps/cloud/src/analytics/session-replay-s3.service.tssimilarity index 65%rename from backend/apps/cloud/src/analytics/session-replay-r2.service.tsrename to backend/apps/cloud/src/analytics/session-replay-s3.service.tsindex 21949956a..556e32b9f 100644--- a/backend/apps/cloud/src/analytics/session-replay-r2.service.ts+++ b/backend/apps/cloud/src/analytics/session-replay-s3.service.ts@@ -2,9 +2,10 @@ import crypto from 'crypto'import { Readable } from 'stream'import { Injectable } from '@nestjs/common'-interface R2Config {+interface S3Config {endpoint: stringbucket: string+ region: stringaccessKeyId: stringsecretAccessKey: string}@@ -20,30 +21,47 @@ const hmac = (key: Buffer | string, value: string) =>const encodeKeyPath = (key: string) =>key.split('/').map(encodeURIComponent).join('/')+const normalizeEndpoint = (endpoint: string) => {+ const value = endpoint.trim().replace(/\/+$/, '')++ return /^https?:\/\//.test(value) ? value : `https://${value}`+}++const inferHetznerRegion = (endpoint: string) => {+ const suffix = '.your-objectstorage.com'+ const hostname = new URL(endpoint).hostname++ if (!hostname.endsWith(suffix)) {+ return ''+ }++ return hostname.slice(0, -suffix.length).split('.')[0] || ''+}+@Injectable()-export class SessionReplayR2Service {- private getConfig(): R2Config | null {- const accountId =- process.env.SESSION_REPLAY_R2_ACCOUNT_ID || process.env.R2_ACCOUNT_ID- const endpoint =- process.env.SESSION_REPLAY_R2_ENDPOINT ||- process.env.R2_ENDPOINT ||- (accountId ? `https://${accountId}.r2.cloudflarestorage.com` : '')- const bucket = process.env.SESSION_REPLAY_R2_BUCKET || process.env.R2_BUCKET+export class SessionReplayS3Service {+ private getConfig(): S3Config | null {+ const endpointValue =+ process.env.SESSION_REPLAY_S3_ENDPOINT || process.env.HETZNER_S3_ENDPOINT+ const endpoint = endpointValue ? normalizeEndpoint(endpointValue) : ''+ const region = endpoint ? inferHetznerRegion(endpoint) : ''+ const bucket =+ process.env.SESSION_REPLAY_S3_BUCKET || process.env.HETZNER_S3_BUCKETconst accessKeyId =- process.env.SESSION_REPLAY_R2_ACCESS_KEY_ID ||- process.env.R2_ACCESS_KEY_ID+ process.env.SESSION_REPLAY_S3_ACCESS_KEY_ID ||+ process.env.HETZNER_S3_ACCESS_KEY_IDconst secretAccessKey =- process.env.SESSION_REPLAY_R2_SECRET_ACCESS_KEY ||- process.env.R2_SECRET_ACCESS_KEY+ process.env.SESSION_REPLAY_S3_SECRET_ACCESS_KEY ||+ process.env.HETZNER_S3_SECRET_ACCESS_KEY- if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) {+ if (!endpoint || !bucket || !region || !accessKeyId || !secretAccessKey) {return null}return {- endpoint: endpoint.replace(/\/+$/, ''),+ endpoint,bucket,+ region,accessKeyId,secretAccessKey,}@@ -63,7 +81,7 @@ export class SessionReplayR2Service {})if (!response.ok) {- throw new Error(`R2 PUT failed with status ${response.status}`)+ throw new Error(`Hetzner S3 PUT failed with status ${response.status}`)}}@@ -75,7 +93,7 @@ export class SessionReplayR2Service {}if (!response.ok) {- throw new Error(`R2 GET failed with status ${response.status}`)+ throw new Error(`Hetzner S3 GET failed with status ${response.status}`)}return Buffer.from(await response.arrayBuffer())@@ -93,7 +111,7 @@ export class SessionReplayR2Service {}if (!response.ok) {- throw new Error(`R2 GET failed with status ${response.status}`)+ throw new Error(`Hetzner S3 GET failed with status ${response.status}`)}if (!response.body) {@@ -111,7 +129,7 @@ export class SessionReplayR2Service {const response = await this.signedFetch('DELETE', key)if (!response.ok && response.status !== 404) {- throw new Error(`R2 DELETE failed with status ${response.status}`)+ throw new Error(`Hetzner S3 DELETE failed with status ${response.status}`)}}@@ -123,19 +141,19 @@ export class SessionReplayR2Service {): Promise<Response> {const config = this.getConfig()if (!config) {- throw new Error('R2 session replay storage is not configured')+ throw new Error('Hetzner S3 session replay storage is not configured')}const payloadHash = sha256Hex(body || '')const now = new Date()const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, '')const dateStamp = amzDate.slice(0, 8)- const url = new URL(- `${config.endpoint}/${config.bucket}/${encodeKeyPath(key)}`,- )+ const endpoint = new URL(config.endpoint)+ endpoint.hostname = `${config.bucket}.${endpoint.hostname}`+ endpoint.pathname = `/${encodeKeyPath(key)}`const headers: HeaderMap = {- host: url.host,+ host: endpoint.host,'x-amz-content-sha256': payloadHash,'x-amz-date': amzDate,...extraHeaders,@@ -147,10 +165,10 @@ export class SessionReplayR2Service {.map((header) => `${header}:${headers[header].trim()}\n`).join('')const signedHeaders = signedHeaderKeys.join(';')- const credentialScope = `${dateStamp}/auto/s3/aws4_request`+ const credentialScope = `${dateStamp}/${config.region}/s3/aws4_request`const canonicalRequest = [method,- url.pathname,+ endpoint.pathname,'',canonicalHeaders,signedHeaders,@@ -163,7 +181,7 @@ export class SessionReplayR2Service {sha256Hex(canonicalRequest),].join('\n')const dateKey = hmac(`AWS4${config.secretAccessKey}`, dateStamp)- const regionKey = hmac(dateKey, 'auto')+ const regionKey = hmac(dateKey, config.region)const serviceKey = hmac(regionKey, 's3')const signingKey = hmac(serviceKey, 'aws4_request')const signature = crypto@@ -178,7 +196,7 @@ export class SessionReplayR2Service {].join(', ')const requestBody = body ? new Uint8Array(body) : undefined- return fetch(url, {+ return fetch(endpoint, {method,headers,body: requestBody,