📈 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
feat: CNAME adblocker bypass (#515)
Andrii Romasiun153070727632
diff --git a/backend/.env.example b/backend/.env.exampleindex 8a12d2ddb..bc3b63c8d 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -100,3 +100,11 @@ SWETRIX_LICENSE_KEY=OPENROUTER_API_KEY=SWETRIX_PID=STEzHcB1rALV++# Managed reverse proxy ("Bypass adblockers") edge auth+# Shared secret the proxy.swetrix.org edge box sends in `X-Edge-Api-Key` to+# call the /v1/proxy-domain/allow and /v1/proxy-domain/active endpoints.+# Generate with: openssl rand -hex 32+# Leave blank if you don't run the managed reverse proxy edge — the endpoints+# fail closed (404) when this is unset.+MANAGED_PROXY_EDGE_API_KEY=diff --git a/backend/apps/cloud/src/project/dto/index.ts b/backend/apps/cloud/src/project/dto/index.tsindex 1c2a8ba0b..547318497 100644--- a/backend/apps/cloud/src/project/dto/index.ts+++ b/backend/apps/cloud/src/project/dto/index.ts@@ -16,3 +16,4 @@ export * from './funnel-create.dto'export * from './funnel-update.dto'export * from './annotation-create.dto'export * from './annotation-update.dto'+export * from './proxy-domain-create.dto'diff --git a/backend/apps/cloud/src/project/dto/proxy-domain-create.dto.ts b/backend/apps/cloud/src/project/dto/proxy-domain-create.dto.tsnew file mode 100644index 000000000..c36019b71--- /dev/null+++ b/backend/apps/cloud/src/project/dto/proxy-domain-create.dto.ts@@ -0,0 +1,14 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty, Length } from 'class-validator'++export class ProxyDomainCreateDTO {+ @ApiProperty({+ example: 't.example.com',+ required: true,+ description:+ 'Subdomain you control that will reverse-proxy Swetrix. Avoid words ad blockers target (analytics, tracking, ...).',+ })+ @IsNotEmpty()+ @Length(3, 253)+ hostname: string+}diff --git a/backend/apps/cloud/src/project/entity/index.ts b/backend/apps/cloud/src/project/entity/index.tsindex ddcfb3992..d1e4ea053 100644--- a/backend/apps/cloud/src/project/entity/index.ts+++ b/backend/apps/cloud/src/project/entity/index.ts@@ -4,3 +4,4 @@ export * from './project.entity'export * from './project-share.entity'export * from './annotation.entity'export * from './pinned-project.entity'+export * from './proxy-domain.entity'diff --git a/backend/apps/cloud/src/project/entity/proxy-domain.entity.ts b/backend/apps/cloud/src/project/entity/proxy-domain.entity.tsnew file mode 100644index 000000000..3312e4195--- /dev/null+++ b/backend/apps/cloud/src/project/entity/proxy-domain.entity.ts@@ -0,0 +1,77 @@+import {+ Column,+ CreateDateColumn,+ Entity,+ Index,+ JoinColumn,+ ManyToOne,+ PrimaryGeneratedColumn,+} from 'typeorm'+import { ApiProperty } from '@nestjs/swagger'++import { Project } from './project.entity'++export enum ProxyDomainStatus {+ WAITING = 'waiting',+ ISSUING = 'issuing',+ LIVE = 'live',+ ERROR = 'error',+}++@Entity('proxy_domain')+export class ProxyDomain {+ @ApiProperty()+ @PrimaryGeneratedColumn('uuid')+ id: string++ @ApiProperty()+ @Index()+ @Column('varchar', { length: 12 })+ projectId: string++ @ManyToOne(() => Project, { onDelete: 'CASCADE' })+ @JoinColumn({ name: 'projectId' })+ project: Project++ // Customer-controlled hostname (e.g. "t.example.com")+ @ApiProperty()+ @Index({ unique: true })+ @Column('varchar', { length: 253 })+ hostname: string++ // 32-char hex; CNAME target = "<proxyTargetId>.proxy.swetrix.org"+ @ApiProperty()+ @Index({ unique: true })+ @Column('varchar', { length: 32 })+ proxyTargetId: string++ @ApiProperty({ enum: ProxyDomainStatus })+ @Column({+ type: 'enum',+ enum: ProxyDomainStatus,+ default: ProxyDomainStatus.WAITING,+ })+ status: ProxyDomainStatus++ @ApiProperty({ nullable: true })+ @Column('varchar', { length: 500, nullable: true, default: null })+ errorMessage: string | null++ @ApiProperty({ nullable: true })+ @Column('datetime', { nullable: true, default: null })+ lastCheckedAt: Date | null++ @ApiProperty({ nullable: true })+ @Column('datetime', { nullable: true, default: null })+ liveSince: Date | null++ // Updated whenever `status` transitions. Used by the verifier to escalate+ // domains stuck in `issuing` to `error` after a timeout.+ @ApiProperty({ nullable: true })+ @Column('datetime', { nullable: true, default: null })+ statusChangedAt: Date | null++ @ApiProperty()+ @CreateDateColumn()+ created: Date+}diff --git a/backend/apps/cloud/src/project/project.module.ts b/backend/apps/cloud/src/project/project.module.tsindex b4fb53d18..988558fab 100644--- a/backend/apps/cloud/src/project/project.module.ts+++ b/backend/apps/cloud/src/project/project.module.ts@@ -16,7 +16,13 @@ import {ProjectShare,Annotation,PinnedProject,+ ProxyDomain,} from './entity'+import { ProxyDomainService } from './proxy-domain.service'+import {+ ProxyDomainController,+ ProxyDomainEdgeController,+} from './proxy-domain.controller'import { ProjectsViewsRepository } from './repositories/projects-views.repository'import { ProjectViewEntity } from './entity/project-view.entity'import { ProjectViewCustomEventEntity } from './entity/project-view-custom-event.entity'@@ -34,6 +40,7 @@ import { PendingInvitationModule } from '../pending-invitation/pending-invitatioProjectViewEntity,ProjectViewCustomEventEntity,PinnedProject,+ ProxyDomain,]),forwardRef(() => UserModule),forwardRef(() => OrganisationModule),@@ -42,8 +49,23 @@ import { PendingInvitationModule } from '../pending-invitation/pending-invitatioMailerModule,PendingInvitationModule,],- providers: [ProjectService, ProjectsViewsRepository, GSCService],- exports: [ProjectService, ProjectsViewsRepository, GSCService],- controllers: [ProjectController, GSCController],+ providers: [+ ProjectService,+ ProjectsViewsRepository,+ GSCService,+ ProxyDomainService,+ ],+ exports: [+ ProjectService,+ ProjectsViewsRepository,+ GSCService,+ ProxyDomainService,+ ],+ controllers: [+ ProjectController,+ GSCController,+ ProxyDomainController,+ ProxyDomainEdgeController,+ ],})export class ProjectModule {}diff --git a/backend/apps/cloud/src/project/proxy-domain-edge.guard.ts b/backend/apps/cloud/src/project/proxy-domain-edge.guard.tsnew file mode 100644index 000000000..24a76b276--- /dev/null+++ b/backend/apps/cloud/src/project/proxy-domain-edge.guard.ts@@ -0,0 +1,51 @@+import * as crypto from 'crypto'+import {+ CanActivate,+ ExecutionContext,+ Injectable,+ Logger,+ NotFoundException,+} from '@nestjs/common'++// Shared-secret guard for the public-facing edge endpoints in+// ProxyDomainEdgeController. The proxy.swetrix.org edge box passes the secret+// in `X-Edge-Api-Key`; everything else gets a generic 404 so an attacker+// can't even tell that the endpoint exists, let alone enumerate hostnames.+//+// Fails closed: if MANAGED_PROXY_EDGE_API_KEY is unset, every request is+// rejected. Self-hosted deployments that don't run the managed proxy never+// hit these routes anyway.+@Injectable()+export class ProxyDomainEdgeGuard implements CanActivate {+ private readonly logger = new Logger(ProxyDomainEdgeGuard.name)++ canActivate(context: ExecutionContext): boolean {+ const expected = process.env.MANAGED_PROXY_EDGE_API_KEY++ if (!expected) {+ this.logger.warn(+ 'MANAGED_PROXY_EDGE_API_KEY is not configured; rejecting edge request',+ )+ throw new NotFoundException()+ }++ const request = context.switchToHttp().getRequest()+ const provided = request.headers['x-edge-api-key']++ if (typeof provided !== 'string' || provided.length === 0) {+ throw new NotFoundException()+ }++ const expectedBuf = Buffer.from(expected)+ const providedBuf = Buffer.from(provided)++ if (+ expectedBuf.length !== providedBuf.length ||+ !crypto.timingSafeEqual(expectedBuf, providedBuf)+ ) {+ throw new NotFoundException()+ }++ return true+ }+}diff --git a/backend/apps/cloud/src/project/proxy-domain.controller.ts b/backend/apps/cloud/src/project/proxy-domain.controller.tsnew file mode 100644index 000000000..ac9614e26--- /dev/null+++ b/backend/apps/cloud/src/project/proxy-domain.controller.ts@@ -0,0 +1,186 @@+import {+ Controller,+ Body,+ Param,+ Get,+ Post,+ Delete,+ HttpCode,+ BadRequestException,+ NotFoundException,+ Query,+ Header,+ UseGuards,+} from '@nestjs/common'+import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'++import { Auth, Public } from '../auth/decorators'+import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'+import { isValidPID } from '../common/constants'+import { ProjectService } from './project.service'+import { ProxyDomainService, PROXY_BASE_DOMAIN } from './proxy-domain.service'+import { ProxyDomainCreateDTO } from './dto'+import { ProxyDomainEdgeGuard } from './proxy-domain-edge.guard'++@ApiTags('Project - Managed Reverse Proxy')+@Controller(['project', 'v1/project'])+export class ProxyDomainController {+ constructor(+ private readonly proxyDomainService: ProxyDomainService,+ private readonly projectService: ProjectService,+ ) {}++ @ApiBearerAuth()+ @Get(':pid/proxy-domains')+ @Auth()+ @ApiOperation({ summary: 'List managed reverse proxy domains for a project' })+ async list(@Param('pid') pid: string, @CurrentUserId() uid: string) {+ if (!isValidPID(pid)) {+ throw new BadRequestException('The provided project ID is incorrect')+ }++ const project = await this.projectService.getFullProject(pid)+ if (!project) {+ throw new NotFoundException('Project not found')+ }+ this.projectService.allowedToManage(project, uid)++ const domains = await this.proxyDomainService.listForProject(pid)+ return { domains, proxyBaseDomain: PROXY_BASE_DOMAIN }+ }++ @ApiBearerAuth()+ @Post(':pid/proxy-domains')+ @Auth()+ @HttpCode(201)+ @ApiOperation({ summary: 'Register a new managed reverse proxy domain' })+ async create(+ @Param('pid') pid: string,+ @Body() body: ProxyDomainCreateDTO,+ @CurrentUserId() uid: string,+ ) {+ if (!isValidPID(pid)) {+ throw new BadRequestException('The provided project ID is incorrect')+ }++ const project = await this.projectService.getFullProject(pid)+ if (!project) {+ throw new NotFoundException('Project not found')+ }+ this.projectService.allowedToManage(project, uid)++ const { domain, blockedKeywordWarning } =+ await this.proxyDomainService.create(pid, body.hostname)++ return { domain, blockedKeywordWarning }+ }++ @ApiBearerAuth()+ @Delete(':pid/proxy-domains/:id')+ @Auth()+ @HttpCode(204)+ @ApiOperation({ summary: 'Delete a managed reverse proxy domain' })+ async remove(+ @Param('pid') pid: string,+ @Param('id') id: string,+ @CurrentUserId() uid: string,+ ): Promise<void> {+ if (!isValidPID(pid)) {+ throw new BadRequestException('The provided project ID is incorrect')+ }++ const project = await this.projectService.getFullProject(pid)+ if (!project) {+ throw new NotFoundException('Project not found')+ }+ this.projectService.allowedToManage(project, uid)++ await this.proxyDomainService.delete(pid, id)+ }++ @ApiBearerAuth()+ @Post(':pid/proxy-domains/:id/verify')+ @Auth()+ @HttpCode(200)+ @ApiOperation({+ summary: 'Force a DNS / TLS re-check of a managed reverse proxy domain',+ })+ async verify(+ @Param('pid') pid: string,+ @Param('id') id: string,+ @CurrentUserId() uid: string,+ ) {+ if (!isValidPID(pid)) {+ throw new BadRequestException('The provided project ID is incorrect')+ }++ const project = await this.projectService.getFullProject(pid)+ if (!project) {+ throw new NotFoundException('Project not found')+ }+ this.projectService.allowedToManage(project, uid)++ const domain = await this.proxyDomainService.findById(pid, id)+ const updated = await this.proxyDomainService.verifyDomain(domain)+ return { domain: this.proxyDomainService.serialise(updated) }+ }+}++// Edge endpoints consumed by the proxy.swetrix.org edge server.+//+// These are gated by ProxyDomainEdgeGuard (shared-secret in `X-Edge-Api-Key`,+// validated against the MANAGED_PROXY_EDGE_API_KEY env var with a constant-time+// compare). Without the secret every request gets a generic 404 — same shape+// as a real "not registered" response — so an unauthenticated probe can't+// distinguish missing endpoint, missing secret, missing hostname, wrong+// status, or suspended project.+//+// The endpoints themselves are not throttled at the Nest layer: the edge+// caches positive answers for 30s and negative answers for 15s in+// `proxy_domain_active` (lua_shared_dict, see proxy.swetrix.org.conf), and+// auto-ssl only invokes `/allow` during ACME issuance. Combined with the+// shared secret gate that's the throttle.+@ApiTags('Project - Managed Reverse Proxy (edge)')+@Controller(['v1/proxy-domain'])+@UseGuards(ProxyDomainEdgeGuard)+export class ProxyDomainEdgeController {+ constructor(private readonly proxyDomainService: ProxyDomainService) {}++ @Public()+ @Get('allow')+ @Header('Cache-Control', 'no-store')+ @ApiOperation({+ summary:+ 'Used by the edge proxy to decide whether to issue a Let\u2019s Encrypt certificate for a hostname',+ })+ async allow(@Query('domain') domain: string) {+ const allowed = await this.proxyDomainService.isHostnameAllowedForIssuance(+ domain || '',+ )++ if (!allowed) {+ throw new NotFoundException()+ }++ return { allowed: true }+ }++ // Per-request runtime gate consumed by the proxy.swetrix.org edge server.+ // Returns 200 only when the hostname is currently `live`.+ @Public()+ @Get('active')+ @Header('Cache-Control', 'no-store')+ @ApiOperation({+ summary:+ 'Used by the edge proxy to decide whether to serve runtime traffic for a hostname',+ })+ async active(@Query('domain') domain: string) {+ const live = await this.proxyDomainService.isHostnameLive(domain || '')++ if (!live) {+ throw new NotFoundException()+ }++ return { active: true }+ }+}diff --git a/backend/apps/cloud/src/project/proxy-domain.service.ts b/backend/apps/cloud/src/project/proxy-domain.service.tsnew file mode 100644index 000000000..92b1445a9--- /dev/null+++ b/backend/apps/cloud/src/project/proxy-domain.service.ts@@ -0,0 +1,576 @@+import { promises as dns } from 'dns'+import * as crypto from 'crypto'+import * as tls from 'tls'+import {+ Injectable,+ Logger,+ BadRequestException,+ ConflictException,+ NotFoundException,+} from '@nestjs/common'+import { InjectRepository } from '@nestjs/typeorm'+import { DataSource, QueryFailedError, Repository, In } from 'typeorm'+import dayjs from 'dayjs'+import { parse as parseDomain } from 'tldts'++import { ProxyDomain, ProxyDomainStatus } from './entity/proxy-domain.entity'+import { Project } from './entity/project.entity'+import { redis } from '../common/constants'++const DEFAULT_PROXY_BASE_DOMAIN = 'proxy.swetrix.org'++export const PROXY_BASE_DOMAIN =+ process.env.MANAGED_PROXY_BASE_DOMAIN || DEFAULT_PROXY_BASE_DOMAIN++const MAX_PROXY_DOMAINS_PER_PROJECT = 5++// Domains stuck in `issuing` (DNS resolves but TLS keeps failing) are+// escalated to `error` after this timeout so the user gets an actionable+// message instead of a perpetual spinner.+const MAX_ISSUING_MINUTES = 30++// WAITING/ERROR rows older than this are considered abandoned and can be+// reclaimed by another owner when they try to register the same hostname+// (or by the same project when they bump up against the per-project limit).+// This prevents a user from indefinitely squatting on a hostname they never+// finished verifying. 7 days matches the existing CNAME-not-found timeout+// in `verifyDomain` so a row first hits ERROR and then becomes reclaimable.+const RESERVATION_EXPIRY_DAYS = 7++// Match the `prefix` used by lua-resty-auto-ssl in the edge nginx config+// (see internal-docs/configs/nginx/sites/proxy.swetrix.org.conf). All cert+// data for a hostname lives under `<prefix>:<hostname>:*`.+const AUTOSSL_REDIS_PREFIX = 'swetrix-managed-proxy'++// Domains belonging to Swetrix that customers cannot register as proxies for.+const RESERVED_HOSTNAME_SUFFIXES = [+ 'swetrix.com',+ 'swetrix.org',+ 'swetrixcaptcha.com',+ 'europehog.com',+]++// Words commonly blocked by adblockers when present in a hostname. We still+// allow the domain to be created but warn the user in the API response.+const BLOCKED_KEYWORDS_REGEX =+ /\b(analytics|tracking|telemetry|posthog|track|metrics?|stats?|count|pixel|tag(s|ger)?|ads?)\b/i++// Strict label check so we still reject things like leading/trailing hyphens+// or labels longer than 63 chars after tldts has done its normalisation.+const HOSTNAME_LABEL_REGEX = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/++interface ValidatedHostname {+ hostname: string+ blockedKeywordWarning: boolean+}++const validateHostname = (raw: string): ValidatedHostname => {+ if (typeof raw !== 'string') {+ throw new BadRequestException('Hostname must be a string')+ }++ const trimmed = raw.trim().toLowerCase()++ if (!trimmed) {+ throw new BadRequestException('Hostname is required')+ }++ // Bound input size up front so we never run the parser over absurd input.+ // 253 + a small slack for a trailing dot / leading whitespace already+ // handled above.+ if (trimmed.length > 254) {+ throw new BadRequestException('Hostname is too long')+ }++ if (trimmed.includes('*')) {+ throw new BadRequestException('Wildcard hostnames are not supported')+ }++ // Defer all normalisation to tldts: it strips trailing dots, validates the+ // hostname against the public suffix list, and tells us about IPs and+ // apex/subdomain split in one pass. This also avoids running our own+ // regex over user-controlled input (CodeQL flag).+ const parsed = parseDomain(trimmed)++ if (parsed.isIp) {+ throw new BadRequestException('IP addresses are not supported')+ }++ if (!parsed.hostname || !parsed.domain || !parsed.publicSuffix) {+ throw new BadRequestException(+ 'Hostname does not look like a real internet domain',+ )+ }++ const hostname = parsed.hostname++ if (hostname.length > 253) {+ throw new BadRequestException('Hostname is too long')+ }++ // Validate each label individually rather than the whole string with one+ // big regex (avoids any catastrophic-backtracking concerns and keeps the+ // failure mode predictable).+ for (const label of hostname.split('.')) {+ if (!HOSTNAME_LABEL_REGEX.test(label)) {+ throw new BadRequestException('Hostname is not a valid subdomain')+ }+ }++ // Apex domains (`example.com`, `example.co.uk`) can't host a CNAME, so+ // reject them up front instead of leaving the user stuck in `waiting`.+ if (!parsed.subdomain) {+ throw new BadRequestException(+ 'Please use a subdomain (e.g. t.example.com) — a CNAME record cannot be set on the root domain',+ )+ }++ for (const reserved of RESERVED_HOSTNAME_SUFFIXES) {+ if (hostname === reserved || hostname.endsWith(`.${reserved}`)) {+ throw new BadRequestException(+ 'This hostname belongs to Swetrix and cannot be used',+ )+ }+ }++ const blockedKeywordWarning = BLOCKED_KEYWORDS_REGEX.test(hostname)++ return { hostname, blockedKeywordWarning }+}++@Injectable()+export class ProxyDomainService {+ private readonly logger = new Logger(ProxyDomainService.name)++ constructor(+ @InjectRepository(ProxyDomain)+ private readonly proxyDomainRepository: Repository<ProxyDomain>,+ private readonly dataSource: DataSource,+ ) {}++ getProxyTarget(domain: ProxyDomain): string {+ return `${domain.proxyTargetId}.${PROXY_BASE_DOMAIN}`+ }++ // Public projection that the frontend consumes.+ serialise(domain: ProxyDomain) {+ return {+ id: domain.id,+ hostname: domain.hostname,+ proxyTargetId: domain.proxyTargetId,+ proxyTarget: this.getProxyTarget(domain),+ status: domain.status,+ errorMessage: domain.errorMessage,+ lastCheckedAt: domain.lastCheckedAt,+ liveSince: domain.liveSince,+ statusChangedAt: domain.statusChangedAt,+ created: domain.created,+ }+ }++ async listForProject(projectId: string) {+ const domains = await this.proxyDomainRepository.find({+ where: { projectId },+ order: { created: 'ASC' },+ })++ return domains.map((d) => this.serialise(d))+ }++ async create(projectId: string, rawHostname: string) {+ const { hostname, blockedKeywordWarning } = validateHostname(rawHostname)+ const proxyTargetId = this.generateProxyTargetId()++ let saved: ProxyDomain+ try {+ saved = await this.dataSource.transaction(async (manager) => {+ // Lock the parent project row for the duration of the transaction so+ // two concurrent creates on the same project can't both pass the+ // per-project limit check. Mirrors the pattern used in+ // DataImportService.create.+ await manager.getRepository(Project).findOneOrFail({+ where: { id: projectId },+ lock: { mode: 'pessimistic_write' },+ })++ const repo = manager.getRepository(ProxyDomain)++ // Reclaim abandoned reservations before counting/checking duplicates:+ // 1. expired WAITING/ERROR rows in this project (free up the limit)+ // 2. an expired WAITING/ERROR row globally for the requested+ // hostname (free up the global unique index for the new owner)+ // Both happen inside the same transaction as the insert below so the+ // window between cleanup and re-insert is atomic.+ const expiredBefore = dayjs()+ .subtract(RESERVATION_EXPIRY_DAYS, 'day')+ .toDate()+ const reclaimableStatuses = [+ ProxyDomainStatus.WAITING,+ ProxyDomainStatus.ERROR,+ ]++ await repo+ .createQueryBuilder()+ .delete()+ .where('projectId = :projectId', { projectId })+ .andWhere('status IN (:...statuses)', {+ statuses: reclaimableStatuses,+ })+ .andWhere('COALESCE(statusChangedAt, created) < :expiredBefore', {+ expiredBefore,+ })+ .execute()++ await repo+ .createQueryBuilder()+ .delete()+ .where('hostname = :hostname', { hostname })+ .andWhere('status IN (:...statuses)', {+ statuses: reclaimableStatuses,+ })+ .andWhere('COALESCE(statusChangedAt, created) < :expiredBefore', {+ expiredBefore,+ })+ .execute()++ const projectDomains = await repo.find({+ where: { projectId },+ select: ['id', 'hostname'],+ })++ if (projectDomains.length >= MAX_PROXY_DOMAINS_PER_PROJECT) {+ throw new ConflictException(+ `You can register up to ${MAX_PROXY_DOMAINS_PER_PROJECT} managed proxy domains per project`,+ )+ }++ if (projectDomains.some((d) => d.hostname === hostname)) {+ throw new ConflictException(+ 'This hostname is already registered as a managed proxy',+ )+ }++ const entity = repo.create({+ projectId,+ hostname,+ proxyTargetId,+ status: ProxyDomainStatus.WAITING,+ statusChangedAt: new Date(),+ })++ return repo.save(entity)+ })+ } catch (err) {+ // The hostname is globally unique (UQ_proxy_domain_hostname); a race+ // between two projects trying to register the same hostname loses at+ // commit time. Translate the resulting duplicate-key error so the+ // caller sees the same ConflictException as the in-tx check above.+ if (this.isUniqueConstraintError(err)) {+ throw new ConflictException(+ 'This hostname is already registered as a managed proxy',+ )+ }+ throw err+ }++ return {+ domain: this.serialise(saved),+ blockedKeywordWarning,+ }+ }++ private isUniqueConstraintError(err: unknown): boolean {+ if (!(err instanceof QueryFailedError)) return false+ const driverErr = (err as QueryFailedError & { driverError?: unknown })+ .driverError as { code?: string; errno?: number } | undefined+ return driverErr?.code === 'ER_DUP_ENTRY' || driverErr?.errno === 1062+ }++ async delete(projectId: string, id: string) {+ const domain = await this.proxyDomainRepository.findOne({+ where: { id, projectId },+ })++ if (!domain) {+ throw new NotFoundException('Proxy domain not found')+ }++ await this.proxyDomainRepository.delete({ id, projectId })++ // Drop the cached cert at the edge. The edge also revalidates each+ // request via `isHostnameLive`, so this is best-effort: if it fails the+ // hostname stops serving traffic almost immediately anyway, but we still+ // want to free the Redis storage and avoid serving a now-orphaned cert.+ this.purgeAutoSslCertCache(domain.hostname).catch((err) => {+ this.logger.warn(+ `purgeAutoSslCertCache(${domain.hostname}) failed: ${err}`,+ )+ })+ }++ async findById(projectId: string, id: string) {+ const domain = await this.proxyDomainRepository.findOne({+ where: { id, projectId },+ })++ if (!domain) {+ throw new NotFoundException('Proxy domain not found')+ }++ return domain+ }++ async findByHostname(hostname: string) {+ return this.proxyDomainRepository.findOne({+ where: { hostname: hostname.trim().toLowerCase() },+ })+ }++ // Used by lua-resty-auto-ssl: allow Let's Encrypt issuance only for hostnames+ // that are actively registered.+ async isHostnameAllowedForIssuance(hostname: string): Promise<boolean> {+ const domain = await this.findActiveDomainByHostname(hostname)+ if (!domain) return false++ // Allow cert issuance for any status that hasn't been administratively+ // disabled. ERROR rows are intentionally excluded — if we've already+ // determined this hostname can't be served (e.g. CNAME timeout, ISSUING+ // timeout) we shouldn't keep handing out certs for it.+ return (+ domain.status === ProxyDomainStatus.WAITING ||+ domain.status === ProxyDomainStatus.ISSUING ||+ domain.status === ProxyDomainStatus.LIVE+ )+ }++ // Used by the OpenResty edge `access_by_lua_block`: per-request gate that+ // decides whether to actually serve traffic for a hostname. This is what+ // makes a freshly-deleted hostname stop proxying within seconds, even if+ // its TLS cert is still cached in Redis.+ async isHostnameLive(hostname: string): Promise<boolean> {+ const domain = await this.findActiveDomainByHostname(hostname)+ if (!domain) return false+ return domain.status === ProxyDomainStatus.LIVE+ }++ private async findActiveDomainByHostname(+ hostname: string,+ ): Promise<ProxyDomain | null> {+ if (!hostname) return null++ let normalised: string+ try {+ normalised = validateHostname(hostname).hostname+ } catch {+ return null+ }++ const domain = await this.proxyDomainRepository.findOne({+ where: { hostname: normalised },+ relations: { project: true },+ })+ if (!domain) return null++ // Reject hostnames whose project has been deactivated (e.g. account+ // suspended) so they can't keep proxying traffic.+ if (domain.project && domain.project.active === false) return null++ return domain+ }++ // Verifier — runs DNS + TLS checks and updates the row's status.+ async verifyDomain(domain: ProxyDomain): Promise<ProxyDomain> {+ const expectedTarget = this.getProxyTarget(domain).replace(/\.$/, '')+ const update: Partial<ProxyDomain> = {+ lastCheckedAt: new Date(),+ }++ let resolvedTarget: string | null = null+ try {+ const records = await this.resolveCnameWithTimeout(domain.hostname)+ const found = (records || []).find(+ (r) => r.replace(/\.$/, '').toLowerCase() === expectedTarget,+ )+ if (found) {+ resolvedTarget = found+ }+ } catch {+ // NXDOMAIN/NODATA/timeout — treated as still waiting+ }++ if (!resolvedTarget) {+ // CNAME not configured yet — keep "waiting" unless we've been stuck for too long.+ const stuckMinutes = dayjs().diff(domain.created, 'minute')+ if (stuckMinutes > 60 * 24 * 7) {+ this.applyStatusTransition(domain, update, ProxyDomainStatus.ERROR)+ update.errorMessage =+ 'CNAME record not found after 7 days. Please verify your DNS configuration.'+ } else {+ this.applyStatusTransition(domain, update, ProxyDomainStatus.WAITING)+ update.errorMessage = null+ }++ await this.proxyDomainRepository.update({ id: domain.id }, update)+ return { ...domain, ...update } as ProxyDomain+ }++ // DNS is good; probe TLS to see if Let's Encrypt has issued the cert.+ const tlsOk = await this.probeTLS(domain.hostname)++ if (tlsOk) {+ this.applyStatusTransition(domain, update, ProxyDomainStatus.LIVE)+ update.errorMessage = null+ if (!domain.liveSince) {+ update.liveSince = new Date()+ }+ } else if (+ domain.status === ProxyDomainStatus.ISSUING &&+ domain.statusChangedAt &&+ dayjs().diff(domain.statusChangedAt, 'minute') > MAX_ISSUING_MINUTES+ ) {+ // DNS resolves but TLS keeps failing for too long — escalate to ERROR+ // so the user gets an actionable message instead of a permanent+ // spinner. The verifier will keep re-checking and can demote back to+ // ISSUING / LIVE on the next successful probe.+ this.applyStatusTransition(domain, update, ProxyDomainStatus.ERROR)+ update.errorMessage =+ `SSL certificate could not be issued after ${MAX_ISSUING_MINUTES} minutes. ` ++ 'Confirm your CNAME points to the value shown above, that DNS proxying ' ++ '(e.g. Cloudflare orange-cloud) is disabled, and that ports 80/443 ' ++ 'are reachable. Use "Re-check" once fixed.'+ } else {+ this.applyStatusTransition(domain, update, ProxyDomainStatus.ISSUING)+ update.errorMessage = null+ }++ await this.proxyDomainRepository.update({ id: domain.id }, update)+ return { ...domain, ...update } as ProxyDomain+ }++ private applyStatusTransition(+ current: ProxyDomain,+ update: Partial<ProxyDomain>,+ next: ProxyDomainStatus,+ ): void {+ update.status = next+ if (current.status !== next || !current.statusChangedAt) {+ update.statusChangedAt = new Date()+ }+ }++ // Best-effort wipe of the cached TLS cert in Redis so a deleted hostname+ // can't be served by the edge anymore. Mirrors the storage layout used by+ // lua-resty-auto-ssl: every key for a hostname lives under+ // `<prefix>:<hostname>:*` (latest cert, historical versions, etc).+ private async purgeAutoSslCertCache(hostname: string): Promise<void> {+ const pattern = `${AUTOSSL_REDIS_PREFIX}:${hostname.toLowerCase()}:*`+ const keys: string[] = []++ await new Promise<void>((resolve, reject) => {+ const stream = redis.scanStream({ match: pattern, count: 100 })+ stream.on('data', (batch: string[]) => {+ if (batch && batch.length) keys.push(...batch)+ })+ stream.on('end', () => resolve())+ stream.on('error', reject)+ })++ if (keys.length) {+ await redis.del(...keys)+ }+ }++ async findPendingForVerification(limit = 200): Promise<ProxyDomain[]> {+ // Order by oldest check first so an oversized backlog drains evenly+ // (rather than starving rows that happen to sort late in the table).+ // `id` is the deterministic tie-breaker. NULL `lastCheckedAt` rows+ // (i.e. never-checked) sort first on MySQL where NULLs are less than+ // any value with ASC ordering.+ return this.proxyDomainRepository+ .createQueryBuilder('pd')+ .where({+ status: In([+ ProxyDomainStatus.WAITING,+ ProxyDomainStatus.ISSUING,+ ProxyDomainStatus.ERROR,+ ]),+ })+ .orderBy('pd.lastCheckedAt', 'ASC')+ .addOrderBy('pd.id', 'ASC')+ .take(limit)+ .getMany()+ }++ async findLiveForRecheck(+ olderThan: Date,+ limit = 200,+ ): Promise<ProxyDomain[]> {+ return this.proxyDomainRepository+ .createQueryBuilder('pd')+ .where('pd.status = :status', { status: ProxyDomainStatus.LIVE })+ .andWhere('(pd.lastCheckedAt IS NULL OR pd.lastCheckedAt < :ts)', {+ ts: olderThan,+ })+ .orderBy('pd.lastCheckedAt', 'ASC')+ .addOrderBy('pd.id', 'ASC')+ .take(limit)+ .getMany()+ }++ // Node's `dns.resolveCname` honours OS timeouts but in practice can hang+ // for tens of seconds on misbehaving authoritatives. Bound it ourselves so+ // a single bad domain can't stall the verifier batch.+ private async resolveCnameWithTimeout(+ hostname: string,+ timeoutMs = 10_000,+ ): Promise<string[]> {+ let timer: NodeJS.Timeout | undefined+ const timeout = new Promise<string[]>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('dns.resolveCname timed out')),+ timeoutMs,+ )+ })+ try {+ return await Promise.race([dns.resolveCname(hostname), timeout])+ } finally {+ if (timer) clearTimeout(timer)+ }+ }++ private async probeTLS(hostname: string): Promise<boolean> {+ return new Promise((resolve) => {+ const socket = tls.connect(+ {+ host: hostname,+ servername: hostname,+ port: 443,+ rejectUnauthorized: true,+ // Self-signed fallback or invalid cert == not yet issued.+ ALPNProtocols: ['http/1.1'],+ },+ () => {+ const ok = socket.authorized === true+ socket.end()+ resolve(ok)+ },+ )++ const timer = setTimeout(() => {+ socket.destroy()+ resolve(false)+ }, 5000)++ socket.once('error', () => {+ clearTimeout(timer)+ resolve(false)+ })++ socket.once('close', () => clearTimeout(timer))+ })+ }++ private generateProxyTargetId(): string {+ return crypto.randomBytes(16).toString('hex')+ }+}diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.tsindex 47c8e0e88..ff7d25c97 100644--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts@@ -58,6 +58,7 @@ import { SlackService } from '../integrations/slack/slack.service'import { RevenueService } from '../revenue/revenue.service'import { PaddleAdapter } from '../revenue/adapters/paddle.adapter'import { StripeAdapter } from '../revenue/adapters/stripe.adapter'+import { ProxyDomainService } from '../project/proxy-domain.service'dayjs.extend(utc)@@ -298,6 +299,14 @@ const EMAIL_REPORTS_MAP = {@Injectable()export class TaskManagerService {+ // In-memory re-entrancy guards: the verifier batches up to 200 domains at+ // a time and a single slow DNS/TLS probe can stretch a tick past the+ // 60s cron interval. Without these flags the next tick would re-fire+ // duplicate probes for everything still in flight.+ private verifyingPendingProxyDomains = false++ private recheckingLiveProxyDomains = false+constructor(private readonly mailerService: MailerService,private readonly userService: UserService,@@ -315,6 +324,7 @@ export class TaskManagerService {private readonly revenueService: RevenueService,private readonly paddleAdapter: PaddleAdapter,private readonly stripeAdapter: StripeAdapter,+ private readonly proxyDomainService: ProxyDomainService,) {}/**@@ -2150,4 +2160,83 @@ export class TaskManagerService {await this.userService.deleteRefreshTokensWhere(where)}++ // Verify managed reverse proxy domains: resolve CNAME -> probe TLS to advance+ // the row's status (waiting -> issuing -> live).+ @Cron(CronExpression.EVERY_MINUTE)+ async verifyPendingProxyDomains() {+ if (!isPrimaryNode()) {+ return+ }++ if (this.verifyingPendingProxyDomains) {+ return+ }+ this.verifyingPendingProxyDomains = true++ try {+ const pending =+ await this.proxyDomainService.findPendingForVerification(200)++ if (_isEmpty(pending)) {+ return+ }++ await mapLimit(pending, 8, async (domain) => {+ try {+ await this.proxyDomainService.verifyDomain(domain)+ } catch (err) {+ this.logger.error(+ `[CRON WORKER](verifyPendingProxyDomains) ${domain.hostname}: ${err}`,+ )+ }+ })+ } catch (err) {+ this.logger.error(+ `[CRON WORKER](verifyPendingProxyDomains) Error: ${err}`,+ )+ } finally {+ this.verifyingPendingProxyDomains = false+ }+ }++ // Periodically re-check live domains so we notice when DNS / cert breaks+ // (e.g. user removed the CNAME or revoked the cert).+ @Cron(CronExpression.EVERY_6_HOURS)+ async recheckLiveProxyDomains() {+ if (!isPrimaryNode()) {+ return+ }++ if (this.recheckingLiveProxyDomains) {+ return+ }+ this.recheckingLiveProxyDomains = true++ try {+ const cutoff = dayjs.utc().subtract(6, 'hour').toDate()+ const domains = await this.proxyDomainService.findLiveForRecheck(+ cutoff,+ 500,+ )++ if (_isEmpty(domains)) {+ return+ }++ await mapLimit(domains, 8, async (domain) => {+ try {+ await this.proxyDomainService.verifyDomain(domain)+ } catch (err) {+ this.logger.error(+ `[CRON WORKER](recheckLiveProxyDomains) ${domain.hostname}: ${err}`,+ )+ }+ })+ } catch (err) {+ this.logger.error(`[CRON WORKER](recheckLiveProxyDomains) Error: ${err}`)+ } finally {+ this.recheckingLiveProxyDomains = false+ }+ }}diff --git a/backend/migrations/mysql/2026_04_17_managed_proxy_domains.sql b/backend/migrations/mysql/2026_04_17_managed_proxy_domains.sqlnew file mode 100644index 000000000..41dd85f8d--- /dev/null+++ b/backend/migrations/mysql/2026_04_17_managed_proxy_domains.sql@@ -0,0 +1,19 @@+-- Managed reverse proxy domains for the "Bypass adblockers" feature+CREATE TABLE IF NOT EXISTS `proxy_domain` (+ `id` varchar(36) NOT NULL,+ `projectId` varchar(12) NOT NULL,+ `hostname` varchar(253) NOT NULL,+ `proxyTargetId` varchar(32) NOT NULL,+ `status` enum('waiting', 'issuing', 'live', 'error') NOT NULL DEFAULT 'waiting',+ `errorMessage` varchar(500) DEFAULT NULL,+ `lastCheckedAt` datetime DEFAULT NULL,+ `liveSince` datetime DEFAULT NULL,+ `statusChangedAt` datetime DEFAULT NULL,+ `created` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),+ PRIMARY KEY (`id`),+ UNIQUE KEY `UQ_proxy_domain_hostname` (`hostname`),+ UNIQUE KEY `UQ_proxy_domain_target` (`proxyTargetId`),+ KEY `IDX_proxy_domain_project` (`projectId`),+ KEY `IDX_proxy_domain_status` (`status`),+ CONSTRAINT `FK_proxy_domain_project` FOREIGN KEY (`projectId`) REFERENCES `project` (`id`) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;diff --git a/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdx b/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdxindex 6880d05b6..81a58adb2 100644--- a/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdx+++ b/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdx@@ -11,20 +11,42 @@ On average, [32% of users](https://backlinko.com/ad-blockers-users?ref=swetrix)## How to proxy Swetrix-The most effective way to bypass ad blockers is to proxy the Swetrix script and calls to the Swetrix servers through this script.+The most effective way to bypass ad blockers is to proxy the Swetrix script and calls to the Swetrix servers through your own infrastructure.A proxy is basically the mapping of our servers' URLs through your domain. So analytics requests will not be sent to `https://api.swetrix.com/log`, but instead to `https://<your domain>/path`.The advantage of this approach is that your site will only make first-party requests, preventing them from being blocked by adblockers.-### How to proxy tracking script?+You have two options, summarised below. Pick the one that matches how much DevOps work you're willing to do:-If you've installed [Swetrix using npm](/install-script#install-swetrix-via-npm), you don't need to proxy it as it's already bundled into your web application's code (but you still need to proxy our API, see one of the proxy guides below).+| | Managed reverse proxy | Self-hosted proxy |+| -------------------------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- |+| **Setup effort** | A few minutes — add a CNAME record in your DNS, paste a snippet | Configure your own web server (Nginx, Netlify, Next.js, etc.) |+| **Technical knowledge required** | Minimal | Moderate to high |+| **SSL certificate** | Provisioned automatically by Swetrix | You provide it (or your platform does) |+| **How it looks to ad blockers** | A request to a subdomain of your site to a Swetrix-controlled edge | A request to your own server, fully indistinguishable from any other request to your site |+| **Detectability** | Low | **Lowest** — the most effective option |-If you have installed Swetrix using our CDN (`swetrix.org/swetrix.js`), you will need to proxy it to bypass adblockers. Please refer to one of the guides below on how to do this.+### Best: Self-hosted proxy (least detectable)-### Managed proxy guides+Routing analytics through a server you already operate is the **gold standard** for adblocker bypass. Because the request is served entirely by your own infrastructure, with the same IP and TLS certificate as the rest of your site, ad blockers have nothing to fingerprint — there's no third-party CNAME chain or shared edge IP they can list.+The trade-off is that you have to set it up yourself. If you already run Nginx, deploy on Netlify, or use Next.js, this is straightforward — pick one of the guides below.++- [Nginx](/adblockers/guides/nginx)- [Netlify](/adblockers/guides/netlify)- [Next.js](/adblockers/guides/nextjs)-- [Nginx](/adblockers/guides/nginx)++### Easiest: Managed reverse proxy (zero-config)++If you don't want to maintain proxy configuration yourself, Swetrix Cloud can run a reverse proxy on your behalf. You add a CNAME record on a subdomain you control, and we handle the SSL certificate and proxying automatically.++This is **highly effective for the majority of users**, but slightly more detectable than a self-hosted proxy because the requests still ultimately resolve to a Swetrix-controlled edge IP. Aggressive blocklists may eventually pick up on the shared edge.++See **[Managed reverse proxy](/adblockers/managed-proxy)** for the full walkthrough.++### A note on the tracking script++If you've installed [Swetrix using npm](/install-script#install-swetrix-via-npm), you don't need to proxy the script as it's already bundled into your web application's code — but you still need to proxy our API (use either of the options above).++If you've installed Swetrix using our CDN (`swetrix.org/swetrix.js`), you'll want to proxy that too — both options above cover the script as well as the API.diff --git a/docs/content/docs/adblockers/managed-proxy.mdx b/docs/content/docs/adblockers/managed-proxy.mdxnew file mode 100644index 000000000..86d5c32e4--- /dev/null+++ b/docs/content/docs/adblockers/managed-proxy.mdx@@ -0,0 +1,126 @@+---+title: Bypass adblockers with a managed reverse proxy+slug: /adblockers/managed-proxy+---++Swetrix Cloud can run a reverse proxy for you on a subdomain you control, so the tracker script and analytics events are served from your own domain. Browsers (and ad blockers) see only first-party requests to your site, which means dramatically less data loss.++This page walks you through setting one up. The whole process takes about 5 minutes plus DNS propagation time.++> **Looking for the most effective option?** A [self-hosted proxy](/adblockers/how-to#best-self-hosted-proxy-least-detectable) running on your own infrastructure is the gold standard for adblocker bypass — it's fully indistinguishable from any other request to your site. It requires more technical knowledge to set up. The managed reverse proxy described here is highly effective for most users and far easier to configure, but the request ultimately resolves to a Swetrix-controlled edge, which makes it slightly more detectable to aggressive blocklists.++## How it works++```+Visitor's browser ──► t.example.com ─(CNAME)─► <random-id>.proxy.swetrix.org+ │+ ▼+ Swetrix edge proxy+ (Let's Encrypt cert+ issued automatically)+ │+ ┌────────────┴────────────┐+ ▼ ▼+ swetrix.com/swetrix.js api.swetrix.com/log+```++- You add a CNAME record on a subdomain you own — for example `t.example.com` — pointing at a target hostname Swetrix gives you (`<random-id>.proxy.swetrix.org`).+- Our edge servers terminate TLS for your hostname, automatically issuing a Let's Encrypt certificate the first time a request hits the edge.+- Two routes are exposed on your subdomain:+ - `GET https://t.example.com/script.js` — the tracker script (cached at the edge).+ - `POST https://t.example.com/log/*` — the analytics API (event ingestion, session/profile calls, etc.).++The visitor's real IP address is preserved via `X-Forwarded-For`, and we strip cookies / authorisation headers before forwarding requests upstream.++## Step 1 — Pick a subdomain++Pick a subdomain on a domain you control. The subdomain should be something **generic** — try to avoid words ad blockers commonly target.++| ✅ Good | ❌ Avoid |+| --------------- | ----------------------- |+| `t.example.com` | `analytics.example.com` |+| `m.example.com` | `tracking.example.com` |+| `s.example.com` | `stats.example.com` |+| `i.example.com` | `telemetry.example.com` |++You can register up to 5 managed proxy domains per project.++## Step 2 — Add the domain in Swetrix++1. Open your project in the Swetrix dashboard.+2. Go to **Settings → Managed proxy**.+3. Click **Add managed reverse proxy**, enter your subdomain, and submit.++You'll see the domain appear in the list with a `Waiting` status and a **CNAME target** that looks like `<random-id>.proxy.swetrix.org`.++## Step 3 — Add the CNAME record++In your DNS provider, create a `CNAME` record:++| Name | Type | Value | TTL |+| -------------------------------------- | ------- | -------------------------------- | ---------------- |+| `t` (or whatever subdomain you picked) | `CNAME` | `<random-id>.proxy.swetrix.org.` | 3600 (or "Auto") |++A few common gotchas:++- **Cloudflare users:** make sure the record is **DNS-only** (gray cloud, not orange). Cloudflare's proxy will interfere with our cert provisioning.+- **Apex domains** (e.g. `example.com`) cannot be used directly because CNAME records aren't allowed on the root. Use a subdomain.+- DNS propagation can take a few minutes.++## Step 4 — Wait for the status to flip++After the CNAME resolves, the status moves from `Waiting` → `Issuing` → `Live` automatically (we re-check every minute). You can also click the refresh icon to force a re-check.++- `Waiting` — we haven't seen the CNAME resolve yet.+- `Issuing` — DNS is good; Let's Encrypt is provisioning the cert (usually under a minute).+- `Live` — your subdomain is fully operational.+- `Error` — something went wrong. The reason is shown next to the domain.++## Step 5 — Update your tracker code++Once your domain is `Live`, replace your existing tracker tag:++```html+<script src="https://t.example.com/script.js" defer></script>+<script>+ document.addEventListener("DOMContentLoaded", () => {+ swetrix.init("YOUR_PROJECT_ID", {+ apiURL: "https://t.example.com/log",+ });+ swetrix.trackViews();+ });+</script>+```++If you're using the [npm package](/install-script#install-swetrix-via-npm), only set the `apiURL` — the script itself is bundled with your app:++```ts+import * as swetrix from "swetrix";++swetrix.init("YOUR_PROJECT_ID", {+ apiURL: "https://t.example.com/log",+});+swetrix.trackViews();+```++The `apiURL` option overrides the default API host for _all_ requests the tracker makes (events, session pings, profile identification, etc.) — there's nothing else to configure.++## Limits++- Up to **5 proxy domains per project**.+- One CNAME target per registered domain.+- We rate-limit certificate issuance per hostname (Let's Encrypt has its own limits — be careful when renaming hostnames repeatedly).++## Troubleshooting++**The status is stuck on `Waiting`.**+The CNAME hasn't propagated yet. You can check from your machine with `dig CNAME t.example.com` — the answer should match the target Swetrix gave you. If you've waited more than an hour, double-check that the record is a CNAME (not an A) and that any DNS proxy (e.g. Cloudflare) is disabled for this record.++**The status flipped to `Error`.**+The error message in the UI explains what's wrong. The most common causes are CNAME records pointing to the wrong target, DNS-level proxies (Cloudflare orange cloud) breaking the certificate validation, or the CNAME being removed.++**Adblockers are still blocking my events.**+Most likely the subdomain you picked contains a flagged keyword (`analytics`, `track`, `stats`, etc.). Add a different subdomain with a generic name and switch your tracker code to it.++**I removed the CNAME / I deleted the domain in Swetrix.**+That immediately stops accepting traffic on that hostname. Tracker calls will start failing — make sure your tracker code points at a domain that's still live.diff --git a/docs/content/docs/adblockers/meta.json b/docs/content/docs/adblockers/meta.jsonindex ce07efd53..40aff7b3d 100644--- a/docs/content/docs/adblockers/meta.json+++ b/docs/content/docs/adblockers/meta.json@@ -1,4 +1,4 @@{"title": "Adblockers",- "pages": ["how-to-deal-with-adblockers", "guides"]+ "pages": ["how-to-deal-with-adblockers", "managed-proxy", "guides"]}diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.tsindex 43dd33a87..40290ee96 100644--- a/web/app/lib/models/Project.ts+++ b/web/app/lib/models/Project.ts@@ -188,6 +188,21 @@ export const IMPORT_PROVIDERS: Provider[] = ['umami',].filter((x): x is Provider => !!x)+export type ProxyDomainStatus = 'waiting' | 'issuing' | 'live' | 'error'++export interface ProxyDomain {+ id: string+ hostname: string+ proxyTargetId: string+ proxyTarget: string+ status: ProxyDomainStatus+ errorMessage: string | null+ lastCheckedAt: string | null+ liveSince: string | null+ statusChangedAt: string | null+ created: string+}+export interface DataImport {id: numberimportId: numberdiff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsxindex 385cae096..3bb201352 100644--- a/web/app/pages/Project/Settings/ProjectSettings.tsx+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx@@ -23,6 +23,7 @@ import {CurrencyDollarIcon,DownloadIcon,BellRingingIcon,+ GlobeIcon,} from '@phosphor-icons/react'import React, { useState, useEffect, useMemo, useRef } from 'react'import { Trans, useTranslation } from 'react-i18next'@@ -68,6 +69,7 @@ import Revenue from './tabs/Revenue'import Shields from './tabs/Shields'import ProjectAlerts from './Alerts/ProjectAlertsView'import DataImportTab from './components/DataImportTab'+import ProxyDomainsTab from './components/ProxyDomainsTab'const MAX_NAME_LENGTH = 50const MAX_ORIGINS_LENGTH = 300@@ -365,6 +367,7 @@ const ProjectSettings = () => {| 'people'| 'annotations'| 'import'+ | 'proxy'| 'danger'const tabs = useMemo(@@ -450,6 +453,14 @@ const ProjectSettings = () => {iconColor: 'text-cyan-500',visible: true,},+ {+ id: 'proxy',+ label: t('project.settings.tabs.proxy'),+ description: t('project.settings.tabs.proxyDesc'),+ icon: GlobeIcon,+ iconColor: 'text-fuchsia-500',+ visible: !isSelfhosted,+ },{id: 'annotations',label: t('project.settings.tabs.annotations'),@@ -1084,6 +1095,17 @@ const ProjectSettings = () => {<DataImportTab projectId={id} /></>) : null}+ {activeTab === 'proxy' && activeTabConfig ? (+ <>+ <TabHeader+ icon={activeTabConfig.icon}+ label={activeTabConfig.label}+ description={activeTabConfig.description}+ iconColorClass={activeTabConfig.iconColor}+ />+ <ProxyDomainsTab projectId={id} />+ </>+ ) : null}{activeTab === 'integrations' && activeTabConfig ? (<div>diff --git a/web/app/pages/Project/Settings/components/ProxyDomainsTab.tsx b/web/app/pages/Project/Settings/components/ProxyDomainsTab.tsxnew file mode 100644index 000000000..a5ca5ccde--- /dev/null+++ b/web/app/pages/Project/Settings/components/ProxyDomainsTab.tsx@@ -0,0 +1,813 @@+import { useCallback, useEffect, useRef, useState } from 'react'+import {+ CopyIcon,+ CheckIcon,+ TrashIcon,+ ArrowClockwiseIcon,+ CheckCircleIcon,+ XCircleIcon,+ ClockIcon,+ SpinnerIcon,+ PlusIcon,+ CaretDownIcon,+} from '@phosphor-icons/react'+import cx from 'clsx'+import dayjs from 'dayjs'+import { Trans, useTranslation } from 'react-i18next'+import { useFetcher } from 'react-router'+import { toast } from 'sonner'++import type { ProxyDomain, ProxyDomainStatus } from '~/lib/models/Project'+import type { ProjectSettingsActionData } from '~/routes/projects.settings.$id'+import Alert from '~/ui/Alert'+import Button from '~/ui/Button'+import {+ CloudflareDnsOnlyIcon,+ CloudflareProxiedIcon,+} from '~/ui/icons/Cloudflare'+import Input from '~/ui/Input'+import Loader from '~/ui/Loader'+import Modal from '~/ui/Modal'+import { Text } from '~/ui/Text'++const DOCS_URL = 'https://swetrix.com/docs/adblockers/managed-proxy'++const STATUS_CLASSES: Record<ProxyDomainStatus, string> = {+ waiting:+ 'bg-amber-50 text-amber-700 ring-amber-600/20 dark:bg-amber-500/10 dark:text-amber-400 dark:ring-amber-500/20',+ issuing:+ 'bg-blue-50 text-blue-700 ring-blue-600/20 dark:bg-blue-500/10 dark:text-blue-400 dark:ring-blue-500/20',+ live: 'bg-emerald-50 text-emerald-700 ring-emerald-600/20 dark:bg-emerald-500/10 dark:text-emerald-400 dark:ring-emerald-500/20',+ error:+ 'bg-red-50 text-red-700 ring-red-600/20 dark:bg-red-500/10 dark:text-red-400 dark:ring-red-500/20',+}++const STATUS_ICONS: Record<+ ProxyDomainStatus,+ React.ComponentType<{ className?: string }>+> = {+ waiting: ClockIcon,+ issuing: SpinnerIcon,+ live: CheckCircleIcon,+ error: XCircleIcon,+}++// Same shape as the backend HOSTNAME_REGEX. Keep these in sync.+const HOSTNAME_REGEX =+ /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/++const BLOCKED_KEYWORDS_REGEX =+ /\b(analytics|tracking|telemetry|swetrix|track|metrics?|stats?|count|pixel|tag(s|ger)?|ads?)\b/i++const validateHostnameClient = (raw: string): string | null => {+ const value = raw.trim().toLowerCase()+ if (!value) return null+ if (value.length > 253) return null+ if (!HOSTNAME_REGEX.test(value)) return null+ if (value.split('.').length < 3) return null+ return value+}++function StatusBadge({+ status,+ label,+}: {+ status: ProxyDomainStatus+ label: string+}) {+ const Icon = STATUS_ICONS[status]+ return (+ <Text+ as='span'+ size='xs'+ weight='medium'+ colour='inherit'+ className={cx(+ 'inline-flex items-center gap-1 rounded-md px-2 py-0.5 ring-1 ring-inset',+ STATUS_CLASSES[status],+ )}+ >+ <Icon+ className={cx('size-3', { 'animate-spin': status === 'issuing' })}+ />+ {label}+ </Text>+ )+}++function CopyButton({+ value,+ className,+ title,+}: {+ value: string+ className?: string+ title?: string+}) {+ const { t } = useTranslation('common')+ const [copied, setCopied] = useState(false)++ const onCopy = async (e: React.MouseEvent) => {+ e.stopPropagation()+ e.preventDefault()+ try {+ await navigator.clipboard.writeText(value)+ setCopied(true)+ setTimeout(() => setCopied(false), 1500)+ toast.success(t('project.settings.proxy.copied'))+ } catch {+ toast.error(t('common.failedToCopy'))+ }+ }++ return (+ <button+ type='button'+ onClick={onCopy}+ title={title ?? t('project.settings.proxy.copy')}+ className={cx(+ 'inline-flex items-center justify-center rounded-md text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-slate-800 dark:hover:text-gray-200',+ className,+ )}+ >+ {copied ? (+ <CheckIcon className='size-4 text-emerald-500' />+ ) : (+ <CopyIcon className='size-4' />+ )}+ </button>+ )+}++function CopyableCode({ value }: { value: string }) {+ const { t } = useTranslation('common')++ return (+ <div className='flex items-stretch gap-2'>+ <Text+ as='div'+ size='sm'+ colour='primary'+ className='grow overflow-x-auto rounded-md border border-gray-200 bg-gray-50 px-3 py-2 font-mono whitespace-pre dark:border-slate-700/80 dark:bg-slate-900'+ >+ {value}+ </Text>+ <CopyButton+ value={value}+ title={t('project.settings.proxy.copy')}+ className='border border-gray-200 px-2 dark:border-slate-700/80'+ />+ </div>+ )+}++function DnsRecordTable({ domain }: { domain: ProxyDomain }) {+ const { t } = useTranslation('common')++ const headerCell = (key: string) => (+ <th className='px-3 py-2'>+ <Text+ as='span'+ size='xs'+ weight='semibold'+ colour='muted'+ tracking='wide'+ className='uppercase'+ >+ {t(`project.settings.proxy.${key}`)}+ </Text>+ </th>+ )++ return (+ <div className='overflow-hidden rounded-lg border border-gray-200 dark:border-slate-700/80'>+ <table className='w-full text-left'>+ <thead className='bg-gray-50 dark:bg-slate-900'>+ <tr>+ {headerCell('dnsRecordType')}+ {headerCell('dnsRecordName')}+ {headerCell('dnsRecordValue')}+ {headerCell('dnsRecordTTL')}+ </tr>+ </thead>+ <tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-800 dark:bg-slate-950'>+ <tr>+ <td className='px-3 py-2.5'>+ <Text as='span' size='sm' colour='primary' className='font-mono'>+ CNAME+ </Text>+ </td>+ <td className='px-3 py-2.5'>+ <div className='flex items-center gap-1.5'>+ <Text+ as='span'+ size='sm'+ colour='primary'+ className='font-mono break-all'+ >+ {domain.hostname}+ </Text>+ <CopyButton+ value={domain.hostname}+ className='size-6 shrink-0'+ />+ </div>+ </td>+ <td className='px-3 py-2.5'>+ <div className='flex items-center gap-1.5'>+ <Text+ as='span'+ size='sm'+ colour='primary'+ className='font-mono break-all'+ >+ {domain.proxyTarget}+ </Text>+ <CopyButton+ value={domain.proxyTarget}+ className='size-6 shrink-0'+ />+ </div>+ </td>+ <td className='px-3 py-2.5'>+ <Text as='span' size='sm' colour='primary' className='font-mono'>+ {t('project.settings.proxy.ttlAuto')}+ </Text>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ )+}++function CloudflareTip() {+ const { t } = useTranslation('common')++ return (+ <Alert+ variant='warning'+ title={t('project.settings.proxy.cloudflareTipTitle')}+ >+ <Text as='p' size='sm' colour='inherit'>+ <Trans+ i18nKey='project.settings.proxy.cloudflareTipBody'+ t={t}+ components={{ 1: <strong />, 3: <strong /> }}+ />+ </Text>+ <div className='mt-3 flex flex-wrap gap-2'>+ <Text+ as='span'+ size='xs'+ weight='medium'+ colour='inherit'+ className='inline-flex items-center gap-2 rounded-md border border-amber-300/60 bg-white/70 px-2.5 py-1.5 dark:border-amber-500/30 dark:bg-amber-500/10'+ >+ <CloudflareDnsOnlyIcon className='h-5 w-auto' />+ {t('project.settings.proxy.cloudflareDnsOnly')}+ <CheckCircleIcon className='size-4 text-emerald-600 dark:text-emerald-400' />+ </Text>+ <Text+ as='span'+ size='xs'+ weight='medium'+ colour='inherit'+ className='inline-flex items-center gap-2 rounded-md border border-amber-300/60 bg-white/70 px-2.5 py-1.5 opacity-70 dark:border-amber-500/30 dark:bg-amber-500/10'+ >+ <CloudflareProxiedIcon className='h-5 w-auto' />+ {t('project.settings.proxy.cloudflareProxied')}+ <XCircleIcon className='size-4 text-red-600 dark:text-red-400' />+ </Text>+ </div>+ </Alert>+ )+}++interface ProxyDomainsTabProps {+ projectId: string+}++export default function ProxyDomainsTab({ projectId }: ProxyDomainsTabProps) {+ const { t, i18n } = useTranslation('common')++ const listFetcher = useFetcher<ProjectSettingsActionData>()+ const addFetcher = useFetcher<ProjectSettingsActionData>()+ const deleteFetcher = useFetcher<ProjectSettingsActionData>()+ const verifyFetcher = useFetcher<ProjectSettingsActionData>()++ const settingsAction = `/projects/settings/${projectId}`++ const [domains, setDomains] = useState<ProxyDomain[]>([])+ const [loading, setLoading] = useState(true)+ const [showAddModal, setShowAddModal] = useState(false)+ const [hostnameInput, setHostnameInput] = useState('')+ const [hostnameError, setHostnameError] = useState<string | null>(null)+ const [deleteTarget, setDeleteTarget] = useState<ProxyDomain | null>(null)+ const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set())+ const userToggledRef = useRef(false)+ const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)+ const fetchDomainsRef = useRef<() => void>(() => {})+ const verifyingIdRef = useRef<string | null>(null)+ const [verifyingId, setVerifyingId] = useState<string | null>(null)++ const statusLabels: Record<ProxyDomainStatus, string> = {+ waiting: t('project.settings.proxy.statusWaiting'),+ issuing: t('project.settings.proxy.statusIssuing'),+ live: t('project.settings.proxy.statusLive'),+ error: t('project.settings.proxy.statusError'),+ }++ const fetchDomains = useCallback(() => {+ listFetcher.submit(+ { intent: 'list-proxy-domains' },+ { method: 'POST', action: settingsAction },+ )+ }, [listFetcher, settingsAction])++ fetchDomainsRef.current = fetchDomains++ useEffect(() => {+ fetchDomains()+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])++ useEffect(() => {+ if (listFetcher.state !== 'idle' || !listFetcher.data) return+ if (listFetcher.data.intent !== 'list-proxy-domains') return++ if (listFetcher.data.error) {+ toast.error(listFetcher.data.error)+ } else if (listFetcher.data.proxyDomains) {+ setDomains(listFetcher.data.proxyDomains)+ }+ setLoading(false)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [listFetcher.state, listFetcher.data])++ // Auto-expand when there's only a single domain so the user sees the+ // setup steps (or the install snippet) immediately.+ useEffect(() => {+ if (userToggledRef.current) return+ if (domains.length === 1) {+ setExpandedIds(new Set([domains[0].id]))+ } else if (domains.length === 0) {+ setExpandedIds(new Set())+ }+ }, [domains])++ // Poll while any domain is still waiting/issuing so the UI advances quickly.+ const hasPending = domains.some(+ (d) => d.status === 'waiting' || d.status === 'issuing',+ )++ useEffect(() => {+ if (!hasPending) return++ pollRef.current = setInterval(() => {+ fetchDomainsRef.current()+ }, 8000)++ return () => {+ if (pollRef.current) {+ clearInterval(pollRef.current)+ pollRef.current = null+ }+ }+ }, [hasPending])++ useEffect(() => {+ if (addFetcher.state !== 'idle' || !addFetcher.data) return+ if (addFetcher.data.intent !== 'add-proxy-domain') return++ if (addFetcher.data.error) {+ toast.error(addFetcher.data.error)+ return+ }++ if (addFetcher.data.proxyDomain) {+ toast.success(t('project.settings.proxy.added'))+ if (addFetcher.data.proxyDomainKeywordWarning) {+ toast.warning(t('project.settings.proxy.domainKeywordWarning'))+ }+ const newId = addFetcher.data.proxyDomain.id+ setExpandedIds((prev) => {+ const next = new Set(prev)+ next.add(newId)+ return next+ })+ setShowAddModal(false)+ setHostnameInput('')+ setHostnameError(null)+ fetchDomains()+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [addFetcher.state, addFetcher.data])++ useEffect(() => {+ if (deleteFetcher.state !== 'idle' || !deleteFetcher.data) return+ if (deleteFetcher.data.intent !== 'delete-proxy-domain') return++ if (deleteFetcher.data.error) {+ toast.error(deleteFetcher.data.error)+ } else if (deleteFetcher.data.success) {+ toast.success(t('project.settings.proxy.deleted'))+ setDeleteTarget(null)+ fetchDomains()+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [deleteFetcher.state, deleteFetcher.data])++ useEffect(() => {+ if (verifyFetcher.state !== 'idle' || !verifyFetcher.data) return+ if (verifyFetcher.data.intent !== 'verify-proxy-domain') return++ if (verifyFetcher.data.error) {+ toast.error(verifyFetcher.data.error)+ } else if (verifyFetcher.data.proxyDomain) {+ const updated = verifyFetcher.data.proxyDomain+ setDomains((prev) => prev.map((d) => (d.id === updated.id ? updated : d)))+ }+ verifyingIdRef.current = null+ setVerifyingId(null)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [verifyFetcher.state, verifyFetcher.data])++ const submitAddDomain = () => {+ const validated = validateHostnameClient(hostnameInput)+ if (!validated) {+ setHostnameError(t('project.settings.proxy.invalidDomain'))+ return+ }++ addFetcher.submit(+ { intent: 'add-proxy-domain', hostname: validated },+ { method: 'POST', action: settingsAction },+ )+ }++ const submitDelete = () => {+ if (!deleteTarget) return+ deleteFetcher.submit(+ { intent: 'delete-proxy-domain', id: deleteTarget.id },+ { method: 'POST', action: settingsAction },+ )+ }++ const verifyDomain = (domain: ProxyDomain) => {+ verifyingIdRef.current = domain.id+ setVerifyingId(domain.id)+ verifyFetcher.submit(+ { intent: 'verify-proxy-domain', id: domain.id },+ { method: 'POST', action: settingsAction },+ )+ }++ const toggleExpanded = (id: string) => {+ userToggledRef.current = true+ setExpandedIds((prev) => {+ const next = new Set(prev)+ if (next.has(id)) next.delete(id)+ else next.add(id)+ return next+ })+ }++ const adding = addFetcher.state !== 'idle'+ const deleting = deleteFetcher.state !== 'idle'++ const renderInstallSnippet = (domain: ProxyDomain) => (+ <div className='space-y-4'>+ <Text as='h4' size='sm' weight='semibold' colour='primary'>+ {t('project.settings.proxy.installSnippetTitle')}+ </Text>+ <Text as='p' size='sm' colour='muted'>+ {t('project.settings.proxy.installSnippetDescription')}+ </Text>+ <div>+ <Text+ as='p'+ size='xs'+ weight='semibold'+ colour='primary'+ className='mb-1'+ >+ {t('project.settings.proxy.scriptTagLabel')}+ </Text>+ <CopyableCode+ value={`<script src="https://${domain.hostname}/script.js" defer></script>`}+ />+ </div>+ <div>+ <Text+ as='p'+ size='xs'+ weight='semibold'+ colour='primary'+ className='mb-1'+ >+ {t('project.settings.proxy.initLabel')}+ </Text>+ <CopyableCode+ value={`swetrix.init("${projectId}", {\n apiURL: "https://${domain.hostname}/log",\n})`}+ />+ </div>+ </div>+ )++ const renderDnsSetup = (domain: ProxyDomain) => (+ <div className='space-y-4'>+ <div>+ <Text as='h4' size='sm' weight='semibold' colour='primary'>+ {t('project.settings.proxy.almostThere')}+ </Text>+ <Text as='p' size='sm' colour='muted' className='mt-1'>+ <Trans+ i18nKey='project.settings.proxy.cnameInstructions'+ t={t}+ components={{ 1: <strong /> }}+ />+ </Text>+ </div>++ <DnsRecordTable domain={domain} />++ <CloudflareTip />++ {domain.status === 'error' && domain.errorMessage ? (+ <Alert variant='error'>+ <Text as='span' size='sm' colour='inherit'>+ {t('project.settings.proxy.errorPrefix')}+ {domain.errorMessage}+ </Text>+ </Alert>+ ) : null}+ </div>+ )++ const renderIssuing = () => (+ <div className='space-y-2'>+ <div className='flex items-center gap-2'>+ <SpinnerIcon className='size-4 animate-spin text-blue-600 dark:text-blue-400' />+ <Text as='h4' size='sm' weight='semibold' colour='primary'>+ {t('project.settings.proxy.issuingTitle')}+ </Text>+ </div>+ <Text as='p' size='sm' colour='muted'>+ {t('project.settings.proxy.issuingDescription')}+ </Text>+ </div>+ )++ return (+ <div className='space-y-6'>+ <div>+ <Text as='p' size='sm' colour='muted'>+ <Trans+ i18nKey='project.settings.proxy.descriptionWithDocs'+ t={t}+ components={{+ 1: (+ <a+ href={DOCS_URL}+ target='_blank'+ rel='noreferrer'+ className='font-medium text-indigo-600 underline decoration-dashed underline-offset-2 hover:decoration-solid dark:text-indigo-400'+ >+ {''}+ </a>+ ),+ }}+ />+ </Text>+ </div>++ <div>+ <div className='flex items-center justify-between'>+ <Text as='h3' size='base' weight='semibold' colour='primary'>+ {t('project.settings.proxy.domainsTitle')}+ </Text>+ <Button+ type='button'+ primary+ small+ onClick={() => {+ setHostnameInput('')+ setHostnameError(null)+ setShowAddModal(true)+ }}+ >+ <PlusIcon className='size-4' />+ {t('project.settings.proxy.addDomain')}+ </Button>+ </div>++ {loading ? (+ <div className='mt-4 flex justify-center py-8'>+ <Loader />+ </div>+ ) : domains.length === 0 ? (+ <div className='mt-4 rounded-lg border border-dashed border-gray-300 py-8 text-center dark:border-slate-700'>+ <Text as='p' size='sm' colour='muted'>+ {t('project.settings.proxy.noDomains')}+ </Text>+ </div>+ ) : (+ <div className='mt-4 divide-y divide-gray-200 overflow-hidden rounded-lg border border-gray-200 dark:divide-slate-800 dark:border-slate-800'>+ {domains.map((domain) => {+ const expanded = expandedIds.has(domain.id)+ return (+ <div key={domain.id}>+ <div className='flex items-center gap-2 px-2 py-2 transition-colors hover:bg-gray-50 dark:hover:bg-slate-900/40'>+ <button+ type='button'+ onClick={() => toggleExpanded(domain.id)}+ aria-expanded={expanded}+ aria-label={+ expanded ? t('common.collapse') : t('common.expand')+ }+ className='flex min-w-0 flex-1 items-center gap-3 rounded px-2 py-1.5 text-left'+ >+ <CaretDownIcon+ className={cx(+ 'size-4 shrink-0 text-gray-500 transition-transform dark:text-gray-400',+ expanded ? 'rotate-0' : '-rotate-90',+ )}+ />+ <div className='min-w-0 flex-1'>+ <Text+ as='p'+ size='sm'+ weight='semibold'+ colour='primary'+ className='truncate font-mono'+ >+ {domain.hostname}+ </Text>+ <Text+ as='p'+ size='xs'+ colour='muted'+ className='mt-0.5 truncate'+ >+ {domain.liveSince+ ? t('project.settings.proxy.liveSince', {+ date: dayjs(domain.liveSince)+ .locale(i18n.language)+ .format('MMM D, YYYY HH:mm'),+ })+ : t('project.settings.proxy.addedOn', {+ date: dayjs(domain.created)+ .locale(i18n.language)+ .format('MMM D, YYYY HH:mm'),+ })}+ </Text>+ </div>+ </button>+ <StatusBadge+ status={domain.status}+ label={statusLabels[domain.status]}+ />+ <div className='flex items-center gap-1'>+ <button+ type='button'+ onClick={() => verifyDomain(domain)}+ disabled={+ verifyFetcher.state !== 'idle' &&+ verifyingId === domain.id+ }+ className='rounded p-1.5 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:opacity-50 dark:text-gray-400 dark:hover:bg-slate-800 dark:hover:text-gray-200'+ title={t('project.settings.proxy.verifyNow')}+ >+ <ArrowClockwiseIcon+ className={cx('size-4', {+ 'animate-spin':+ verifyFetcher.state !== 'idle' &&+ verifyingId === domain.id,+ })}+ />+ </button>+ <button+ type='button'+ onClick={() => setDeleteTarget(domain)}+ className='rounded p-1.5 text-red-500 transition-colors hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-900/20 dark:hover:text-red-300'+ title={t('common.delete')}+ >+ <TrashIcon className='size-4' />+ </button>+ </div>+ </div>++ {expanded ? (+ <div className='border-t border-gray-200 bg-gray-50/60 px-4 py-4 dark:border-slate-800 dark:bg-slate-900/40'>+ {domain.status === 'live'+ ? renderInstallSnippet(domain)+ : domain.status === 'issuing'+ ? renderIssuing()+ : renderDnsSetup(domain)}+ </div>+ ) : null}+ </div>+ )+ })}+ </div>+ )}+ </div>++ <Modal+ isOpened={showAddModal}+ onClose={() => {+ if (!adding) setShowAddModal(false)+ }}+ title={t('project.settings.proxy.addDomainTitle')}+ size='medium'+ message={+ <div className='space-y-4'>+ <Input+ label={t('project.settings.proxy.domain')}+ placeholder={t('project.settings.proxy.domainPlaceholder')}+ value={hostnameInput}+ onChange={(e) => {+ setHostnameInput(e.target.value)+ setHostnameError(null)+ }}+ error={hostnameError}+ />++ {hostnameInput && BLOCKED_KEYWORDS_REGEX.test(hostnameInput) ? (+ <Text as='p' size='xs' colour='warning'>+ {t('project.settings.proxy.domainKeywordWarning')}+ </Text>+ ) : null}++ <Alert+ variant='warning'+ title={t('project.settings.proxy.warningTitle')}+ >+ <ul className='ml-5 list-disc space-y-1'>+ <li>+ <Trans+ i18nKey='project.settings.proxy.warningSubdomain'+ t={t}+ components={{+ 1: (+ <Text as='span' code size='sm' colour='inherit'>+ {''}+ </Text>+ ),+ 3: (+ <Text as='span' code size='sm' colour='inherit'>+ {''}+ </Text>+ ),+ 5: (+ <Text as='span' code size='sm' colour='inherit'>+ {''}+ </Text>+ ),+ }}+ />+ </li>+ <li>+ <Trans+ i18nKey='project.settings.proxy.warningGeneric'+ t={t}+ components={{+ 1: (+ <Text as='span' code size='sm' colour='inherit'>+ {''}+ </Text>+ ),+ }}+ />+ </li>+ </ul>+ </Alert>+ </div>+ }+ submitText={t('common.add')}+ closeText={t('common.cancel')}+ onSubmit={submitAddDomain}+ isLoading={adding}+ submitDisabled={!hostnameInput.trim()}+ />++ <Modal+ isOpened={!!deleteTarget}+ onClose={() => {+ if (!deleting) setDeleteTarget(null)+ }}+ type='warning'+ title={t('project.settings.proxy.deleteTitle')}+ message={+ <Text as='p'>{t('project.settings.proxy.deleteConfirm')}</Text>+ }+ submitText={t('common.delete')}+ closeText={t('common.cancel')}+ submitType='danger'+ onSubmit={submitDelete}+ isLoading={deleting}+ />+ </div>+ )+}diff --git a/web/app/routes/projects.settings.$id.tsx b/web/app/routes/projects.settings.$id.tsxindex 109de885a..63ccaec6a 100644--- a/web/app/routes/projects.settings.$id.tsx+++ b/web/app/routes/projects.settings.$id.tsx@@ -8,7 +8,7 @@ import { data, redirect } from 'react-router'import { serverFetch } from '~/api/api.server'import { getOgImageUrl } from '~/lib/constants'-import { Project, DataImport } from '~/lib/models/Project'+import { Project, DataImport, ProxyDomain } from '~/lib/models/Project'import { Subscriber } from '~/lib/models/Subscriber'import ProjectSettings from '~/pages/Project/Settings'import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'@@ -95,6 +95,9 @@ export interface ProjectSettingsActionData {dataImport?: unknownga4AuthUrl?: stringga4Properties?: { propertyId: string; displayName: string }[]+ proxyDomains?: ProxyDomain[]+ proxyDomain?: ProxyDomain+ proxyDomainKeywordWarning?: boolean}export async function action({ request, params }: ActionFunctionArgs) {@@ -938,6 +941,127 @@ export async function action({ request, params }: ActionFunctionArgs) {)}+ case 'list-proxy-domains': {+ const result = await serverFetch<{ domains: ProxyDomain[] }>(+ request,+ `project/${id}/proxy-domains`,+ )++ if (result.error) {+ return data<ProjectSettingsActionData>(+ { intent, error: result.error as string },+ { status: result.status || 400 },+ )+ }++ return data<ProjectSettingsActionData>(+ {+ intent,+ success: true,+ proxyDomains: (result.data?.domains as ProxyDomain[]) || [],+ },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }++ case 'add-proxy-domain': {+ const hostname = formData.get('hostname')?.toString()++ if (!hostname) {+ return data<ProjectSettingsActionData>(+ { intent, error: 'Hostname is required' },+ { status: 400 },+ )+ }++ const result = await serverFetch<{+ domain: ProxyDomain+ blockedKeywordWarning?: boolean+ }>(request, `project/${id}/proxy-domains`, {+ method: 'POST',+ body: { hostname },+ })++ if (result.error) {+ return data<ProjectSettingsActionData>(+ { intent, error: result.error as string },+ { status: result.status || 400 },+ )+ }++ return data<ProjectSettingsActionData>(+ {+ intent,+ success: true,+ proxyDomain: result.data?.domain,+ proxyDomainKeywordWarning: !!result.data?.blockedKeywordWarning,+ },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }++ case 'delete-proxy-domain': {+ const proxyDomainId = formData.get('id')?.toString()++ if (!proxyDomainId) {+ return data<ProjectSettingsActionData>(+ { intent, error: 'Proxy domain ID is required' },+ { status: 400 },+ )+ }++ const result = await serverFetch(+ request,+ `project/${id}/proxy-domains/${proxyDomainId}`,+ { method: 'DELETE' },+ )++ if (result.error) {+ return data<ProjectSettingsActionData>(+ { intent, error: result.error as string },+ { status: result.status || 400 },+ )+ }++ return data<ProjectSettingsActionData>(+ { intent, success: true },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }++ case 'verify-proxy-domain': {+ const proxyDomainId = formData.get('id')?.toString()++ if (!proxyDomainId) {+ return data<ProjectSettingsActionData>(+ { intent, error: 'Proxy domain ID is required' },+ { status: 400 },+ )+ }++ const result = await serverFetch<{ domain: ProxyDomain }>(+ request,+ `project/${id}/proxy-domains/${proxyDomainId}/verify`,+ { method: 'POST' },+ )++ if (result.error) {+ return data<ProjectSettingsActionData>(+ { intent, error: result.error as string },+ { status: result.status || 400 },+ )+ }++ return data<ProjectSettingsActionData>(+ {+ intent,+ success: true,+ proxyDomain: result.data?.domain,+ },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }+default:return data<ProjectSettingsActionData>({ error: 'Unknown action' },diff --git a/web/app/ui/icons/Cloudflare.tsx b/web/app/ui/icons/Cloudflare.tsxnew file mode 100644index 000000000..04626cd33--- /dev/null+++ b/web/app/ui/icons/Cloudflare.tsx@@ -0,0 +1,45 @@+import type { SVGProps } from 'react'++export function CloudflareProxiedIcon(props: SVGProps<SVGSVGElement>) {+ return (+ <svg+ xmlns='http://www.w3.org/2000/svg'+ viewBox='0 0 104 39.5'+ aria-hidden='true'+ {...props}+ >+ <polygon+ fill='#999'+ points='104 20.12 94 10.62 94 16.12 0 16.12 0 24.12 94 24.12 94 29.62 104 20.12'+ />+ <path+ fill='#f68a1d'+ d='M74.5,39c-2.08,0-15.43-.13-28.34-.25-12.62-.12-25.68-.25-27.66-.25a8,8,0,0,1-1-15.93c0-.19,0-.38,0-.57a9.49,9.49,0,0,1,14.9-7.81,19.48,19.48,0,0,1,38.05,4.63A10.5,10.5,0,1,1,74.5,39Z'+ />+ <path+ fill='#fff'+ d='M51,1A19,19,0,0,1,70,19.59,10,10,0,1,1,74.5,38.5c-4.11,0-52-.5-56-.5a7.5,7.5,0,0,1-.44-15A8.47,8.47,0,0,1,18,22a9,9,0,0,1,14.68-7A19,19,0,0,1,51,1m0-1A20,20,0,0,0,32.13,13.42,10,10,0,0,0,17,22v.14A8.5,8.5,0,0,0,18.5,39c2,0,15,.13,27.66.25,12.91.12,26.26.25,28.34.25a11,11,0,1,0-3.61-21.39A20.1,20.1,0,0,0,51,0Z'+ />+ </svg>+ )+}++export function CloudflareDnsOnlyIcon(props: SVGProps<SVGSVGElement>) {+ return (+ <svg+ xmlns='http://www.w3.org/2000/svg'+ viewBox='0 0 90.5 59'+ aria-hidden='true'+ {...props}+ >+ <path+ fill='#92979b'+ d='M49,13.5V19L59,9.5,49,0V5.5H40.78a12.43,12.43,0,0,0-9.5,4.42L17.65,27.16a8.83,8.83,0,0,1-6.91,3.34H5l-5,8H13.39a11.27,11.27,0,0,0,9-4.48L35.05,17.18a9.81,9.81,0,0,1,7.66-3.68Z'+ />+ <path+ fill='#92979b'+ d='M80.5,39A10,10,0,0,0,76,40.09a19,19,0,0,0-37.3-4.57A9,9,0,0,0,24,42.5a8.47,8.47,0,0,0,.06,1,7.5,7.5,0,0,0,.44,15c4,0,51.89.5,56,.5a10,10,0,0,0,0-20Z'+ />+ </svg>+ )+}diff --git a/web/public/locales/de.json b/web/public/locales/de.jsonindex 27e3115cb..d5e60f9bc 100644--- a/web/public/locales/de.json+++ b/web/public/locales/de.json@@ -125,6 +125,7 @@"copy": "Kopieren","copied": "Kopiert","failedToCopy": "Kopieren fehlgeschlagen",+ "add": "Hinzufügen","new": "Neu","all": "Alle","active": "Aktiv",@@ -1780,7 +1781,9 @@"revenue": "Umsatz","revenueDesc": "Verfolgen Sie Einnahmen und ordnen Sie Verkäufe Kampagnen zu.","import": "Daten importieren",- "importDesc": "Analysedaten von anderen Plattformen importieren"+ "importDesc": "Analysedaten von anderen Plattformen importieren",+ "proxy": "Verwalteter Proxy",+ "proxyDesc": "Leiten Sie das Tracker-Skript und die Analyse-Ereignisse über Ihre eigene Domain, um Werbeblocker zu umgehen."},"revenue": {"title": "Umsatz-Tracking",@@ -1863,6 +1866,56 @@"importNote": "Daten werden im Hintergrund importiert. Einige Details wie Gebietsschema oder Browser-/Betriebssystemversionen sind in aggregierten GA4-Exporten nicht verfügbar."}},+ "proxy": {+ "title": "Verwalteter Proxy",+ "description": "Leiten Sie das Swetrix-Tracker-Skript und Analyse-Ereignisse über eine von Ihnen kontrollierte Subdomain. Werbeblocker kennen den Hostnamen nicht, daher können sie die Anfragen nicht blockieren, und Sie verlieren keine Daten mehr.",+ "descriptionWithDocs": "Leiten Sie das Swetrix-Tracker-Skript und Analyse-Ereignisse über eine von Ihnen kontrollierte Subdomain. Werbeblocker kennen den Hostnamen nicht, daher können sie die Anfragen nicht blockieren. <1>Lesen Sie die vollständige Einrichtungsanleitung</1>.",+ "addDomain": "Proxy-Domain hinzufügen",+ "addDomainTitle": "Verwalteten Reverse-Proxy hinzufügen",+ "warningTitle": "Vermeiden Sie Domains, die Werbeblocker als analyse- oder werbebezogen markieren könnten.",+ "warningSubdomain": "Verwenden Sie keine Subdomains, die Wörter im Zusammenhang mit Tracking, Analyse, Werbung oder Ähnlichem enthalten (z. B. <1>analytics.meinedomain.com</1>, <3>tracking.meinedomain.com</3> oder <5>stats.meinedomain.com</5>). Diese werden häufig von Werbeblockern blockiert und führen zu Datenverlust.",+ "warningGeneric": "Verwenden Sie stattdessen eine generische Subdomain wie <1>t.meinedomain.com</1>.",+ "domain": "Domain",+ "domainPlaceholder": "Geben Sie eine Domain ein (z. B. t.meinedomain.com)",+ "invalidDomain": "Geben Sie eine gültige Subdomain wie t.meinedomain.com ein.",+ "domainKeywordWarning": "Achtung: Dieser Hostname enthält ein Wort, das von Werbeblockern häufig markiert wird (analytics, tracking usw.). Der Proxy wird eingerichtet, könnte aber trotzdem blockiert werden. Wir empfehlen eine generische Subdomain wie t.meinedomain.com.",+ "noDomains": "Noch keine Proxy-Domains. Fügen Sie eine hinzu, um zu beginnen.",+ "domainsTitle": "Verwaltete Reverse-Proxys",+ "liveSince": "Aktiv seit {{date}}",+ "addedOn": "Hinzugefügt am {{date}}",+ "domainColumn": "Domain",+ "statusColumn": "Status",+ "statusWaiting": "Warten auf DNS",+ "statusIssuing": "Zertifikat wird ausgestellt",+ "statusLive": "Aktiv",+ "statusError": "Fehler",+ "almostThere": "Fast fertig — richten Sie Ihr DNS ein",+ "cnameInstructions": "Fügen Sie den folgenden <1>CNAME</1>-Eintrag bei Ihrem DNS-Anbieter hinzu, um Ihre Subdomain auf unser Netzwerk zu verweisen.",+ "issuingTitle": "Ihr Zertifikat wird bereitgestellt",+ "issuingDescription": "DNS ist aufgelöst. Wir stellen ein Let's Encrypt-Zertifikat aus — dies dauert normalerweise weniger als eine Minute.",+ "dnsRecordType": "Typ",+ "dnsRecordName": "Name",+ "dnsRecordValue": "Wert",+ "dnsRecordTTL": "TTL",+ "ttlAuto": "Auto",+ "cloudflareTipTitle": "Nutzen Sie Cloudflare?",+ "cloudflareTipBody": "Stellen Sie sicher, dass der Eintrag auf <1>Nur DNS</1> (DNS only) und nicht auf <3>Proxied</3> gesetzt ist. Der Proxy von Cloudflare stört unsere Zertifikatsbereitstellung.",+ "cloudflareProxied": "Proxied",+ "cloudflareDnsOnly": "Nur DNS",+ "verifyNow": "Status prüfen",+ "deleteTitle": "Proxy-Domain entfernen?",+ "deleteConfirm": "Dies stoppt die Annahme von Analyse-Traffic auf diesem Hostnamen. Stellen Sie sicher, dass Ihr Tracker-Code nicht mehr darauf verweist.",+ "deleted": "Proxy-Domain gelöscht",+ "added": "Proxy-Domain hinzugefügt. Richten Sie unten den CNAME-Eintrag ein, um abzuschließen.",+ "installSnippetTitle": "Snippet installieren",+ "installSnippetDescription": "Ersetzen Sie Ihr bestehendes Tracker-Tag und den Init-Aufruf durch Folgendes:",+ "scriptTagLabel": "Tracker-Skript-Tag",+ "initLabel": "Tracker initialisieren",+ "copy": "Kopieren",+ "copied": "Kopiert",+ "learnMore": "Vollständige Einrichtungsanleitung lesen",+ "errorPrefix": "Fehler: "+ },"captcha": {"title": "CAPTCHA-Integration","description": "Aktivieren Sie CAPTCHA-Schutz für Ihre Formulare und Aktionen. Generieren Sie einen geheimen Schlüssel, um Swetrix CAPTCHA in Ihre Anwendung zu integrieren.",diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex c74862114..21a866373 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -125,6 +125,7 @@"copy": "Copy","copied": "Copied","failedToCopy": "Failed to copy",+ "add": "Add","new": "New","all": "All","active": "Active",@@ -1780,7 +1781,9 @@"revenue": "Revenue","revenueDesc": "Track revenue and attribute sales to campaigns.","import": "Import data",- "importDesc": "Import analytics data from other platforms"+ "importDesc": "Import analytics data from other platforms",+ "proxy": "Managed proxy",+ "proxyDesc": "Route the tracker script and analytics events through your own domain to bypass ad blockers."},"revenue": {"title": "Revenue Tracking",@@ -1863,6 +1866,56 @@"importNote": "Data will be imported in the background. Some details like locale or browser/OS versions are not available from GA4 aggregate exports."}},+ "proxy": {+ "title": "Managed proxy",+ "description": "Route the Swetrix tracker script and analytics events through a subdomain you control. Ad blockers don't know the hostname, so they can't block the requests, and you stop losing data.",+ "descriptionWithDocs": "Route the Swetrix tracker script and analytics events through a subdomain you control. Ad blockers don't know the hostname, so they can't block the requests. <1>Read the full setup guide</1>.",+ "addDomain": "Add proxy domain",+ "addDomainTitle": "Add managed reverse proxy",+ "warningTitle": "Avoid domains that ad-blockers may flag as analytics or advertising related.",+ "warningSubdomain": "Do not use subdomains containing words related to tracking, analytics, advertising, or anything similar (e.g. <1>analytics.mydomain.com</1>, <3>tracking.mydomain.com</3>, or <5>stats.mydomain.com</5>). These are commonly blocked by ad-blockers and will cause data loss.",+ "warningGeneric": "Use a generic subdomain such as <1>t.mydomain.com</1> instead.",+ "domain": "Domain",+ "domainPlaceholder": "Enter a domain (e.g. t.mydomain.com)",+ "invalidDomain": "Enter a valid subdomain like t.mydomain.com.",+ "domainKeywordWarning": "Heads up: this hostname contains a word that ad blockers commonly flag (analytics, tracking, etc.). The proxy will be set up, but it may still be blocked. We recommend a generic subdomain like t.mydomain.com.",+ "noDomains": "No proxy domains yet. Add one to get started.",+ "domainsTitle": "Managed reverse proxies",+ "liveSince": "Live since {{date}}",+ "addedOn": "Added {{date}}",+ "domainColumn": "Domain",+ "statusColumn": "Status",+ "statusWaiting": "Waiting for DNS",+ "statusIssuing": "Issuing certificate",+ "statusLive": "Live",+ "statusError": "Error",+ "almostThere": "Almost there — set up your DNS",+ "cnameInstructions": "Add the following <1>CNAME</1> record at your DNS provider to point your subdomain at our edge.",+ "issuingTitle": "Provisioning your certificate",+ "issuingDescription": "DNS is resolved. We're issuing a Let's Encrypt certificate — this usually takes under a minute.",+ "dnsRecordType": "Type",+ "dnsRecordName": "Name",+ "dnsRecordValue": "Value",+ "dnsRecordTTL": "TTL",+ "ttlAuto": "Auto",+ "cloudflareTipTitle": "Using Cloudflare?",+ "cloudflareTipBody": "Make sure the record is set to <1>DNS only</1>, not <3>Proxied</3>. Cloudflare's proxy interferes with our certificate provisioning.",+ "cloudflareProxied": "Proxied",+ "cloudflareDnsOnly": "DNS only",+ "verifyNow": "Check status",+ "deleteTitle": "Remove proxy domain?",+ "deleteConfirm": "This will stop accepting analytics traffic on this hostname. Make sure your tracker code is no longer pointing at it.",+ "deleted": "Proxy domain deleted",+ "added": "Proxy domain added. Set up the CNAME record below to finish.",+ "installSnippetTitle": "Install snippet",+ "installSnippetDescription": "Replace your existing tracker tag and init call with the following:",+ "scriptTagLabel": "Tracker script tag",+ "initLabel": "Initialise the tracker",+ "copy": "Copy",+ "copied": "Copied",+ "learnMore": "Read the full setup guide",+ "errorPrefix": "Error: "+ },"captcha": {"title": "CAPTCHA Integration","description": "Enable CAPTCHA protection for your forms and actions. Generate a secret key to integrate Swetrix CAPTCHA with your application.",diff --git a/web/public/locales/fr.json b/web/public/locales/fr.jsonindex 44b7930c3..0496bc2cb 100644--- a/web/public/locales/fr.json+++ b/web/public/locales/fr.json@@ -125,6 +125,7 @@"copy": "Copier","copied": "Copié","failedToCopy": "Échec de la copie",+ "add": "Ajouter","new": "Nouveau","all": "Tous","active": "Actif",@@ -1780,7 +1781,9 @@"revenue": "Revenus","revenueDesc": "Suivez les revenus et attribuez les ventes aux campagnes.","import": "Importer des données",- "importDesc": "Importer des données d'analyse depuis d'autres plateformes"+ "importDesc": "Importer des données d'analyse depuis d'autres plateformes",+ "proxy": "Proxy géré",+ "proxyDesc": "Acheminez le script de suivi et les événements d'analyse via votre propre domaine pour contourner les bloqueurs de publicités."},"revenue": {"title": "Suivi des revenus",@@ -1863,6 +1866,56 @@"importNote": "Les données seront importées en arrière-plan. Certains détails comme les paramètres régionaux ou les versions du navigateur/système d'exploitation ne sont pas disponibles dans les exportations agrégées de GA4."}},+ "proxy": {+ "title": "Proxy géré",+ "description": "Acheminez le script de suivi Swetrix et les événements d'analyse via un sous-domaine que vous contrôlez. Les bloqueurs de publicités ne connaissent pas le nom d'hôte, ils ne peuvent donc pas bloquer les requêtes, et vous arrêtez de perdre des données.",+ "descriptionWithDocs": "Acheminez le script de suivi Swetrix et les événements d'analyse via un sous-domaine que vous contrôlez. Les bloqueurs de publicités ne connaissent pas le nom d'hôte, ils ne peuvent donc pas bloquer les requêtes. <1>Lisez le guide de configuration complet</1>.",+ "addDomain": "Ajouter un domaine proxy",+ "addDomainTitle": "Ajouter un reverse proxy géré",+ "warningTitle": "Évitez les domaines que les bloqueurs de publicités pourraient signaler comme étant liés à l'analyse ou à la publicité.",+ "warningSubdomain": "N'utilisez pas de sous-domaines contenant des mots liés au suivi, à l'analyse, à la publicité ou quoi que ce soit de similaire (par ex. <1>analytics.mondomaine.com</1>, <3>tracking.mondomaine.com</3> ou <5>stats.mondomaine.com</5>). Ceux-ci sont couramment bloqués par les bloqueurs de publicités et entraîneront une perte de données.",+ "warningGeneric": "Utilisez plutôt un sous-domaine générique tel que <1>t.mondomaine.com</1>.",+ "domain": "Domaine",+ "domainPlaceholder": "Entrez un domaine (par ex. t.mondomaine.com)",+ "invalidDomain": "Entrez un sous-domaine valide comme t.mondomaine.com.",+ "domainKeywordWarning": "Attention : ce nom d'hôte contient un mot que les bloqueurs de publicités signalent couramment (analytics, tracking, etc.). Le proxy sera configuré, mais il pourrait toujours être bloqué. Nous recommandons un sous-domaine générique comme t.mondomaine.com.",+ "noDomains": "Aucun domaine proxy pour le moment. Ajoutez-en un pour commencer.",+ "domainsTitle": "Reverse proxies gérés",+ "liveSince": "En ligne depuis le {{date}}",+ "addedOn": "Ajouté le {{date}}",+ "domainColumn": "Domaine",+ "statusColumn": "Statut",+ "statusWaiting": "En attente du DNS",+ "statusIssuing": "Émission du certificat",+ "statusLive": "En ligne",+ "statusError": "Erreur",+ "almostThere": "Presque terminé — configurez votre DNS",+ "cnameInstructions": "Ajoutez l'enregistrement <1>CNAME</1> suivant chez votre fournisseur DNS pour faire pointer votre sous-domaine vers notre réseau.",+ "issuingTitle": "Génération de votre certificat",+ "issuingDescription": "Le DNS est résolu. Nous émettons un certificat Let's Encrypt — cela prend généralement moins d'une minute.",+ "dnsRecordType": "Type",+ "dnsRecordName": "Nom",+ "dnsRecordValue": "Valeur",+ "dnsRecordTTL": "TTL",+ "ttlAuto": "Auto",+ "cloudflareTipTitle": "Vous utilisez Cloudflare ?",+ "cloudflareTipBody": "Assurez-vous que l'enregistrement est défini sur <1>DNS uniquement</1> (DNS only), et non sur <3>Proxy activé</3> (Proxied). Le proxy de Cloudflare interfère avec la génération de notre certificat.",+ "cloudflareProxied": "Proxy activé",+ "cloudflareDnsOnly": "DNS uniquement",+ "verifyNow": "Vérifier le statut",+ "deleteTitle": "Supprimer le domaine proxy ?",+ "deleteConfirm": "Cela cessera d'accepter le trafic d'analyse sur ce nom d'hôte. Assurez-vous que votre code de suivi ne pointe plus vers celui-ci.",+ "deleted": "Domaine proxy supprimé",+ "added": "Domaine proxy ajouté. Configurez l'enregistrement CNAME ci-dessous pour terminer.",+ "installSnippetTitle": "Installer l'extrait de code",+ "installSnippetDescription": "Remplacez votre balise de suivi existante et l'appel d'initialisation par ce qui suit :",+ "scriptTagLabel": "Balise de script de suivi",+ "initLabel": "Initialiser le suivi",+ "copy": "Copier",+ "copied": "Copié",+ "learnMore": "Lire le guide de configuration complet",+ "errorPrefix": "Erreur : "+ },"captcha": {"title": "Intégration CAPTCHA","description": "Activez la protection CAPTCHA pour vos formulaires et actions. Générez une clé secrète pour intégrer le CAPTCHA Swetrix à votre application.",diff --git a/web/public/locales/pl.json b/web/public/locales/pl.jsonindex 51f4b6ef0..334df5d47 100644--- a/web/public/locales/pl.json+++ b/web/public/locales/pl.json@@ -125,6 +125,7 @@"copy": "Kopiuj","copied": "Skopiowano","failedToCopy": "Kopiowanie nie powiodło się",+ "add": "Dodaj","new": "Nowy","all": "Wszystkie","active": "Aktywne",@@ -1780,7 +1781,9 @@"revenue": "Przychody","revenueDesc": "Śledź przychody i przypisuj sprzedaż do kampanii.","import": "Importuj dane",- "importDesc": "Importuj dane analityczne z innych platform"+ "importDesc": "Importuj dane analityczne z innych platform",+ "proxy": "Zarządzane proxy",+ "proxyDesc": "Kieruj skrypt śledzący i zdarzenia analityczne przez własną domenę, aby ominąć programy blokujące reklamy."},"revenue": {"title": "Śledzenie przychodów",@@ -1863,6 +1866,56 @@"importNote": "Dane będą importowane w tle. Niektóre szczegóły, takie jak ustawienia regionalne lub wersje przeglądarki/systemu operacyjnego, nie są dostępne w zagregowanych eksportach GA4."}},+ "proxy": {+ "title": "Zarządzane proxy",+ "description": "Kieruj skrypt śledzący Swetrix i zdarzenia analityczne przez kontrolowaną przez siebie subdomenę. Programy blokujące reklamy nie znają nazwy hosta, więc nie mogą zablokować żądań, a Ty przestajesz tracić dane.",+ "descriptionWithDocs": "Kieruj skrypt śledzący Swetrix i zdarzenia analityczne przez kontrolowaną przez siebie subdomenę. Programy blokujące reklamy nie znają nazwy hosta, więc nie mogą zablokować żądań. <1>Przeczytaj pełny poradnik konfiguracji</1>.",+ "addDomain": "Dodaj domenę proxy",+ "addDomainTitle": "Dodaj zarządzane reverse proxy",+ "warningTitle": "Unikaj domen, które programy blokujące reklamy mogą oflagować jako związane z analityką lub reklamą.",+ "warningSubdomain": "Nie używaj subdomen zawierających słowa związane ze śledzeniem, analityką, reklamami lub czymkolwiek podobnym (np. <1>analytics.mojadomena.pl</1>, <3>tracking.mojadomena.pl</3> lub <5>stats.mojadomena.pl</5>). Są one powszechnie blokowane przez programy blokujące reklamy i powodują utratę danych.",+ "warningGeneric": "Zamiast tego użyj ogólnej subdomeny, takiej jak <1>t.mojadomena.pl</1>.",+ "domain": "Domena",+ "domainPlaceholder": "Wprowadź domenę (np. t.mojadomena.pl)",+ "invalidDomain": "Wprowadź prawidłową subdomenę, np. t.mojadomena.pl.",+ "domainKeywordWarning": "Uwaga: ta nazwa hosta zawiera słowo często blokowane przez programy blokujące reklamy (analytics, tracking itp.). Proxy zostanie skonfigurowane, ale nadal może być blokowane. Zalecamy użycie ogólnej subdomeny, np. t.mojadomena.pl.",+ "noDomains": "Brak jeszcze domen proxy. Dodaj jedną, aby rozpocząć.",+ "domainsTitle": "Zarządzane reverse proxy",+ "liveSince": "Aktywne od {{date}}",+ "addedOn": "Dodano {{date}}",+ "domainColumn": "Domena",+ "statusColumn": "Status",+ "statusWaiting": "Oczekiwanie na DNS",+ "statusIssuing": "Wystawianie certyfikatu",+ "statusLive": "Aktywne",+ "statusError": "Błąd",+ "almostThere": "Prawie gotowe — skonfiguruj swój DNS",+ "cnameInstructions": "Dodaj poniższy rekord <1>CNAME</1> u swojego dostawcy DNS, aby skierować subdomenę na naszą sieć.",+ "issuingTitle": "Przygotowywanie certyfikatu",+ "issuingDescription": "DNS został rozwiązany. Wystawiamy certyfikat Let's Encrypt — zajmuje to zazwyczaj niecałą minutę.",+ "dnsRecordType": "Typ",+ "dnsRecordName": "Nazwa",+ "dnsRecordValue": "Wartość",+ "dnsRecordTTL": "TTL",+ "ttlAuto": "Auto",+ "cloudflareTipTitle": "Używasz Cloudflare?",+ "cloudflareTipBody": "Upewnij się, że rekord jest ustawiony na <1>Tylko DNS</1> (DNS only), a nie <3>Obsługiwane przez proxy</3> (Proxied). Proxy Cloudflare zakłóca proces wydawania naszego certyfikatu.",+ "cloudflareProxied": "Obsługiwane przez proxy",+ "cloudflareDnsOnly": "Tylko DNS",+ "verifyNow": "Sprawdź status",+ "deleteTitle": "Usunąć domenę proxy?",+ "deleteConfirm": "Spowoduje to zatrzymanie akceptowania ruchu analitycznego na tej nazwie hosta. Upewnij się, że kod śledzący już na nią nie wskazuje.",+ "deleted": "Domena proxy usunięta",+ "added": "Domena proxy dodana. Skonfiguruj poniższy rekord CNAME, aby zakończyć.",+ "installSnippetTitle": "Zainstaluj fragment kodu",+ "installSnippetDescription": "Zastąp istniejący tag śledzący i wywołanie init następującym kodem:",+ "scriptTagLabel": "Tag skryptu śledzącego",+ "initLabel": "Zainicjuj tracker",+ "copy": "Kopiuj",+ "copied": "Skopiowano",+ "learnMore": "Przeczytaj pełny poradnik konfiguracji",+ "errorPrefix": "Błąd: "+ },"captcha": {"title": "Integracja CAPTCHA","description": "Włącz ochronę CAPTCHA dla swoich formularzy i działań. Wygeneruj tajny klucz, aby zintegrować Swetrix CAPTCHA z Twoją aplikacją.",diff --git a/web/public/locales/uk.json b/web/public/locales/uk.jsonindex 32d725895..9cb34c771 100644--- a/web/public/locales/uk.json+++ b/web/public/locales/uk.json@@ -125,6 +125,7 @@"copy": "Копіювати","copied": "Скопійовано","failedToCopy": "Не вдалося скопіювати",+ "add": "Додати","new": "Нове","all": "Усі","active": "Активна",@@ -1780,7 +1781,9 @@"revenue": "Дохід","revenueDesc": "Відстежуйте дохід і прив’язуйте продажі до кампаній.","import": "Імпорт даних",- "importDesc": "Імпорт аналітичних даних з інших платформ"+ "importDesc": "Імпорт аналітичних даних з інших платформ",+ "proxy": "Керований проксі",+ "proxyDesc": "Маршрутизуйте скрипт трекера та події аналітики через власний домен, щоб обійти блокувальники реклами."},"revenue": {"title": "Відстеження доходу",@@ -1863,6 +1866,56 @@"importNote": "Дані імпортуватимуться у фоновому режимі. Деякі деталі, такі як мова/регіон або версії браузера/ОС, недоступні в агрегованих експортах GA4."}},+ "proxy": {+ "title": "Керований проксі",+ "description": "Маршрутизуйте скрипт трекера Swetrix та події аналітики через піддомен, який ви контролюєте. Блокувальники реклами не знають імені хоста, тому не можуть блокувати запити, і ви припиняєте втрачати дані.",+ "descriptionWithDocs": "Маршрутизуйте скрипт трекера Swetrix та події аналітики через піддомен, який ви контролюєте. Блокувальники реклами не знають імені хоста, тому не можуть блокувати запити. <1>Прочитайте повний посібник із налаштування</1>.",+ "addDomain": "Додати проксі-домен",+ "addDomainTitle": "Додати керований зворотний проксі",+ "warningTitle": "Уникайте доменів, які блокувальники реклами можуть позначити як пов’язані з аналітикою або рекламою.",+ "warningSubdomain": "Не використовуйте піддомени, що містять слова, пов’язані з відстеженням, аналітикою, рекламою або чимось подібним (наприклад, <1>analytics.miydomen.com</1>, <3>tracking.miydomen.com</3> або <5>stats.miydomen.com</5>). Вони зазвичай блокуються адблокерами і призводять до втрати даних.",+ "warningGeneric": "Замість цього використовуйте загальний піддомен, наприклад <1>t.miydomen.com</1>.",+ "domain": "Домен",+ "domainPlaceholder": "Введіть домен (наприклад, t.miydomen.com)",+ "invalidDomain": "Введіть дійсний піддомен, наприклад t.miydomen.com.",+ "domainKeywordWarning": "Увага: це ім'я хоста містить слово, яке зазвичай блокується адблокерами (analytics, tracking тощо). Проксі буде налаштовано, але його все одно можуть заблокувати. Ми рекомендуємо використовувати загальний піддомен, як-от t.miydomen.com.",+ "noDomains": "Ще немає проксі-доменів. Додайте один, щоб почати.",+ "domainsTitle": "Керовані зворотні проксі",+ "liveSince": "Активно з {{date}}",+ "addedOn": "Додано {{date}}",+ "domainColumn": "Домен",+ "statusColumn": "Статус",+ "statusWaiting": "Очікування DNS",+ "statusIssuing": "Випуск сертифіката",+ "statusLive": "Активно",+ "statusError": "Помилка",+ "almostThere": "Майже готово — налаштуйте свій DNS",+ "cnameInstructions": "Додайте наступний <1>CNAME</1> запис у вашого DNS-провайдера, щоб спрямувати піддомен на нашу мережу.",+ "issuingTitle": "Створення вашого сертифіката",+ "issuingDescription": "DNS розпізнано. Ми випускаємо сертифікат Let's Encrypt — зазвичай це займає менше хвилини.",+ "dnsRecordType": "Тип",+ "dnsRecordName": "Назва",+ "dnsRecordValue": "Значення",+ "dnsRecordTTL": "TTL",+ "ttlAuto": "Авто",+ "cloudflareTipTitle": "Використовуєте Cloudflare?",+ "cloudflareTipBody": "Переконайтеся, що запис встановлено на <1>Тільки DNS</1> (DNS only), а не <3>Через проксі</3> (Proxied). Проксі Cloudflare заважає випуску нашого сертифіката.",+ "cloudflareProxied": "Через проксі",+ "cloudflareDnsOnly": "Тільки DNS",+ "verifyNow": "Перевірити статус",+ "deleteTitle": "Видалити проксі-домен?",+ "deleteConfirm": "Це зупинить прийом аналітичного трафіку на цьому імені хоста. Переконайтеся, що ваш код трекера більше на нього не вказує.",+ "deleted": "Проксі-домен видалено",+ "added": "Проксі-домен додано. Налаштуйте запис CNAME нижче, щоб завершити.",+ "installSnippetTitle": "Встановити фрагмент коду",+ "installSnippetDescription": "Замініть існуючий тег трекера та виклик ініціалізації на наступні:",+ "scriptTagLabel": "Тег скрипта трекера",+ "initLabel": "Ініціалізувати трекер",+ "copy": "Копіювати",+ "copied": "Скопійовано",+ "learnMore": "Прочитати повний посібник із налаштування",+ "errorPrefix": "Помилка: "+ },"captcha": {"title": "Інтеграція CAPTCHA","description": "Увімкніть захист CAPTCHA для ваших форм і дій. Згенеруйте секретний ключ, щоб інтегрувати Swetrix CAPTCHA з вашим застосунком.",