Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat: add tenant-scoped Workers Analytics Engine reports
Timothy Yinee599d736c74
diff --git a/.github/workflows/deploy-saas.yml b/.github/workflows/deploy-saas.ymlindex e156a6a9..fac3712e 100644--- a/.github/workflows/deploy-saas.yml+++ b/.github/workflows/deploy-saas.yml@@ -125,6 +125,9 @@ jobs:PLATFORM_DOMAIN_SITE_WORKER: ${{ vars.PLATFORM_DOMAIN_SITE_WORKER }}PLATFORM_DOMAIN_RESOURCE_LIMIT: ${{ vars.PLATFORM_DOMAIN_RESOURCE_LIMIT }}PLATFORM_DOMAIN_PROVIDER_TOKEN: ${{ secrets.PLATFORM_DOMAIN_PROVIDER_TOKEN }}+ ANALYTICS_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}+ ANALYTICS_API_TOKEN: ${{ secrets.ANALYTICS_API_TOKEN }}+ ANALYTICS_VISITOR_SECRET: ${{ secrets.ANALYTICS_VISITOR_SECRET }}steps:- name: Checkout approved immutable sourceuses: actions/checkout@v7@@ -224,6 +227,8 @@ jobs:}const { configureDomainDeployment } = await import('./scripts/domain-deployment.mjs')configureDomainDeployment(config,process.env.ENTRY,process.env.DEPLOY_ENVIRONMENT,process.env)+ const { configureAnalyticsDeployment } = await import('./scripts/analytics-deployment.mjs')+ configureAnalyticsDeployment(config, process.env.DEPLOY_ENVIRONMENT, process.env)delete config.envfs.writeFileSync(path, JSON.stringify(config, null, 2) + '\n')NODE@@ -307,6 +312,10 @@ jobs:const values = secret ? { NUXT_PLATFORM_SECRET: secret } : {}if (process.env.PLATFORM_STORAGE_SECRET) values.NUXT_PLATFORM_STORAGE_SECRET = process.env.PLATFORM_STORAGE_SECRETif (process.env.ENTRY === 'cloud' && process.env.PLATFORM_DOMAIN_PROVIDER_TOKEN) values.NUXT_PLATFORM_DOMAIN_PROVIDER_TOKEN = process.env.PLATFORM_DOMAIN_PROVIDER_TOKEN+ if (process.env.ANALYTICS_API_TOKEN && process.env.ANALYTICS_VISITOR_SECRET) {+ values.ANALYTICS_VISITOR_SECRET = process.env.ANALYTICS_VISITOR_SECRET+ if (process.env.ENTRY === 'cloud') values.ANALYTICS_API_TOKEN = process.env.ANALYTICS_API_TOKEN+ }fs.writeFileSync(process.env.WORKER_SECRET_FILE, JSON.stringify(values), { mode: 0o600 })NODEif [[ -n "$PLATFORM_S3_ENDPOINT_HOSTS" ]]; thendiff --git a/apps/cloud/app/components/CloudPortalShell.vue b/apps/cloud/app/components/CloudPortalShell.vueindex 3a4c6fb6..d11814d0 100644--- a/apps/cloud/app/components/CloudPortalShell.vue+++ b/apps/cloud/app/components/CloudPortalShell.vue@@ -20,6 +20,7 @@ const section = computed(() => {domains: 'cloud.messages.domains',storage: 'cloud.messages.storage',sites: 'cloud.messages.sites',+ analytics: 'cloud.billing.analytics',plan: 'cloud.dashboard.planUsage',redeem: 'cloud.billing.redeem',account: 'cloud.messages.accountSecurity',diff --git a/apps/cloud/app/components/CloudPricing.vue b/apps/cloud/app/components/CloudPricing.vueindex ad75f69e..3ccfc27c 100644--- a/apps/cloud/app/components/CloudPricing.vue+++ b/apps/cloud/app/components/CloudPricing.vue@@ -735,6 +735,22 @@ async function submitCheckout(plan: any, mode?: string) {></CfButton><ul class="cf-plan-features">+ <li>+ <span>{{ $t('cloud.billing.analytics') }}</span+ ><strong+ ><UIcon+ :name="+ plan.policy.analytics ? 'i-lucide-check' : 'i-lucide-minus'+ "+ :aria-label="+ $t(+ plan.policy.analytics+ ? 'cloud.billing.yes'+ : 'cloud.billing.no',+ )+ "+ /></strong>+ </li><liv-for="key in BILLING_LIMITS":key="key"@@ -833,11 +849,13 @@ async function submitCheckout(plan: any, mode?: string) {</section></template><footer class="cf-pricing-footer">- <div class="cf-pricing-footer-actions"><CloudSupportLink /><NuxtLink- :to="links.redeem"- :external="!portal"- >{{ $t('cloud.billing.redeem') }}</NuxtLink- ></div>+ <div class="cf-pricing-footer-actions">+ <CloudSupportLink /><NuxtLink+ :to="links.redeem"+ :external="!portal"+ >{{ $t('cloud.billing.redeem') }}</NuxtLink+ >+ </div><CloudLegalLinks /></footer><UModaldiff --git a/apps/cloud/app/components/CloudSidebarNavigation.vue b/apps/cloud/app/components/CloudSidebarNavigation.vueindex 1e23d6f7..e72161a7 100644--- a/apps/cloud/app/components/CloudSidebarNavigation.vue+++ b/apps/cloud/app/components/CloudSidebarNavigation.vue@@ -1,6 +1,7 @@<script setup lang="ts">import {ArrowLeft,+ ChartNoAxesCombined,Images,LibraryBig,PanelsTopLeft,@@ -9,6 +10,7 @@ import {Globe,HardDrive,} from 'lucide-vue-next'+const billing = useWorkspaceBilling()const route = useRoute(),context = useEntryContext()const site = computed(() =>@@ -132,6 +134,15 @@ watch(mode, (next) => {$t('cloud.messages.sites')}}</NuxtLink>+ <NuxtLink+ v-if="billing.data.value?.plan?.analytics"+ to="/analytics"+ :class="{ active: route.path === '/analytics' }"+ :aria-current="route.path === '/analytics' ? 'page' : undefined"+ ><ChartNoAxesCombined :size="17" />{{+ $t('cloud.billing.analytics')+ }}</NuxtLink+ ></nav></template></div></Transitiondiff --git a/apps/cloud/app/middleware/platform.global.ts b/apps/cloud/app/middleware/platform.global.tsindex 062b6d3f..a8f12c6e 100644--- a/apps/cloud/app/middleware/platform.global.ts+++ b/apps/cloud/app/middleware/platform.global.ts@@ -27,6 +27,7 @@ export default defineNuxtRouteMiddleware(async (to) => {(path === '/pricing' &&(useCloudRequestURL().hostname === 'app.chronoframe.art' ||to.query.portal === '1')) ||+ path === '/analytics' ||path === '/workspace' ||path === '/account' ||path.startsWith('/account/') ||diff --git a/apps/cloud/app/pages/analytics.vue b/apps/cloud/app/pages/analytics.vuenew file mode 100644index 00000000..f2b78ae0--- /dev/null+++ b/apps/cloud/app/pages/analytics.vue@@ -0,0 +1,148 @@+<script setup lang="ts">+definePageMeta({ layout: 'portal' })+const { locale } = useI18n()+const zh = computed(() => locale.value.startsWith('zh'))+const tr = (en: string, cn: string) => (zh.value ? cn : en)+useSeoMeta({+ title: () => tr('Analytics — ChronoFrame Cloud', '分析 — ChronoFrame Cloud'),+ robots: 'noindex',+})+const billing = useWorkspaceBilling()+await billing.ready+if (!billing.data.value?.plan?.analytics)+ throw createError({+ statusCode: 403,+ statusMessage: 'Analytics is not included in this plan',+ })+const fetcher = useRequestFetch()+const { data: siteList } = await useAsyncData('analytics-site-options', () =>+ fetcher<any>('/api/sites'),+)+const sites = computed(() =>+ (siteList.value?.sites ?? []).filter(+ (s: any) => s.workspaceId === billing.selected.value,+ ),+)+const siteId = ref(''),+ to = ref(new Date().toISOString().slice(0, 10)),+ from = ref(new Date(Date.now() - 6 * 86400000).toISOString().slice(0, 10))+const report = ref<any>(),+ loading = ref(false),+ error = ref('')+let generation = 0+async function load() {+ const request = ++generation+ loading.value = true+ error.value = ''+ report.value = null+ try {+ const result = await fetcher('/api/analytics/report', {+ query: {+ workspaceId: billing.selected.value,+ siteId: siteId.value || undefined,+ from: from.value,+ to: to.value,+ },+ timeout: 20000,+ })+ if (request === generation) report.value = result+ } catch (e: any) {+ if (request === generation)+ error.value =+ e.statusCode === 403+ ? tr(+ 'Your plan does not include analytics.',+ '当前套餐不包含分析权益。',+ )+ : tr(+ 'Unable to load analytics. Check the date range or try again later.',+ '无法加载分析数据,请检查日期范围或稍后重试。',+ )+ } finally {+ if (request === generation) loading.value = false+ }+}+await load()+</script>+<template>+ <div class="cf-dashboard">+ <header>+ <h1 class="cf-page-title">{{ tr('Analytics', '分析') }}</h1>+ <p class="cf-page-description">+ {{+ tr(+ 'Traffic to the public galleries in your workspace.',+ '查看工作区内公开站点的访问情况。',+ )+ }}+ </p>+ </header>+ <CfCard class="p-5"+ ><form+ class="flex flex-wrap items-end gap-4"+ @submit.prevent="load"+ >+ <label class="grid gap-2"+ >{{ tr('Site', '站点')+ }}<select+ v-model="siteId"+ class="cf-input"+ >+ <option value="">{{ tr('All sites', '全部站点') }}</option>+ <option+ v-for="site in sites"+ :key="site.siteId"+ :value="String(site.siteId)"+ >+ {{ site.name }}+ </option>+ </select></label+ >+ <label class="grid gap-2"+ >{{ tr('From (UTC)', '开始日期(UTC)')+ }}<input+ v-model="from"+ type="date"+ required+ class="cf-input"+ /></label>+ <label class="grid gap-2"+ >{{ tr('To (UTC)', '结束日期(UTC)')+ }}<input+ v-model="to"+ type="date"+ required+ class="cf-input"+ /></label>+ <CfButton+ type="submit"+ :disabled="loading"+ >{{ tr('Apply', '应用') }}</CfButton+ >+ <p class="cf-field-hint">+ {{+ tr(+ 'Select up to 31 days within the last 90 days.',+ '可查询最近 90 天内、最长 31 天的数据。',+ )+ }}+ </p>+ </form></CfCard+ >+ <p+ v-if="error"+ role="alert"+ >+ {{ error }}+ </p>+ <CfSkeleton+ v-if="loading"+ class="h-64 w-full"+ />+ <CfAnalyticsReport+ v-else-if="report"+ :report="report"+ :zh="zh"+ />+ </div>+</template>diff --git a/apps/cloud/app/plugins/visit-analytics.client.ts b/apps/cloud/app/plugins/visit-analytics.client.tsnew file mode 100644index 00000000..0900dc44--- /dev/null+++ b/apps/cloud/app/plugins/visit-analytics.client.ts@@ -0,0 +1,5 @@+import { installVisitTracking } from '../../../shared/analytics/tracker'+export default defineNuxtPlugin((app) => {+ const router = useRouter()+ installVisitTracking(app, () => router.currentRoute.value.path)+})diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.jsonindex 8b3a94d7..c13bb48d 100644--- a/apps/cloud/i18n/locales/en.json+++ b/apps/cloud/i18n/locales/en.json@@ -664,6 +664,7 @@"fileBytes": "Maximum file size","sites": "Sites","photos": "Photographs",+ "analytics": "Site analytics","photosQuotaHelp": "Photo usage includes uploaded photographs and reserved slots for uploads that have been requested but are not yet complete. Reservations prevent concurrent uploads from exceeding your plan limit; they do not mean those uploads have completed.","customDomains": "Custom domains","byos": "Custom S3 storage",diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.jsonindex 1b69f8e0..1f5eb8ee 100644--- a/apps/cloud/i18n/locales/zh-Hans.json+++ b/apps/cloud/i18n/locales/zh-Hans.json@@ -664,6 +664,7 @@"fileBytes": "单文件上限","sites": "站点数量","photos": "照片数量",+ "analytics": "站点分析","photosQuotaHelp": "照片配额按已上传的照片与已申请上传但尚未完成的预留名额合计。预留名额用于防止并发上传超出套餐上限,不代表这些照片已上传完成。","customDomains": "自定义域名","byos": "自定义 S3 存储",diff --git a/apps/cloud/server/api/analytics/report.get.ts b/apps/cloud/server/api/analytics/report.get.tsnew file mode 100644index 00000000..60951c31--- /dev/null+++ b/apps/cloud/server/api/analytics/report.get.ts@@ -0,0 +1,47 @@+import { getQuery, createError, setResponseHeader } from 'h3'+import {+ definePlatformHandler,+ platformDatabase,+} from '../../../../shared/platform/runtime'+import { requirePlatformSession } from '../../../../shared/platform/context'+import { workspaceEntitlements } from '../../../../../packages/platform/src/entitlements'+import { analyticsFilter } from '../../../../../packages/platform/src/analytics'+import { analyticsReport } from '../../../../shared/analytics/query'+export default definePlatformHandler(async (event) => {+ setResponseHeader(event, 'Cache-Control', 'no-store')+ const session = await requirePlatformSession(+ event,+ useRuntimeConfig(event).platform,+ )+ const query = getQuery(event)+ let filter+ try {+ filter = analyticsFilter(query)+ } catch {+ throw createError({ statusCode: 400 })+ }+ if (!filter.workspaceId) throw createError({ statusCode: 400 })+ const db = platformDatabase(event)+ const member = await db+ .prepare(+ "SELECT workspace_id FROM platform_memberships WHERE user_id=? AND workspace_id=? AND role IN('admin','member')",+ )+ .bind(session.userId, filter.workspaceId)+ .first()+ if (!member) throw createError({ statusCode: 404 })+ if (!(await workspaceEntitlements(db, filter.workspaceId)).analytics)+ throw createError({+ statusCode: 403,+ statusMessage: 'Analytics is not included in this plan',+ })+ if (+ filter.siteId &&+ !(await db+ .prepare('SELECT id FROM platform_sites WHERE id=? AND workspace_id=?')+ .bind(filter.siteId, filter.workspaceId)+ .first())+ )+ throw createError({ statusCode: 404 })+ // Client kind/scope can never broaden this query to portal traffic or another tenant.+ return analyticsReport(event, { ...filter, kind: 'site' })+})diff --git a/apps/cloud/server/api/analytics/visit.post.ts b/apps/cloud/server/api/analytics/visit.post.tsnew file mode 100644index 00000000..503979cb--- /dev/null+++ b/apps/cloud/server/api/analytics/visit.post.ts@@ -0,0 +1,8 @@+import { collectVisit } from '../../../../shared/analytics/collect'+export default defineEventHandler((event) =>+ collectVisit(+ event,+ 'cloud',+ String(event.context.cloudflare?.env?.ANALYTICS_VISITOR_SECRET ?? ''),+ ),+)diff --git a/apps/cloud/server/middleware/platform-boundary.ts b/apps/cloud/server/middleware/platform-boundary.tsindex cfeab095..0cb2a400 100644--- a/apps/cloud/server/middleware/platform-boundary.ts+++ b/apps/cloud/server/middleware/platform-boundary.ts@@ -14,6 +14,8 @@ export default defineEventHandler((event) => {}const platformRoute =[+ '/api/analytics/visit',+ '/api/analytics/report','/api/auth/status','/api/auth/session','/api/auth/marketing-session',diff --git a/apps/shared/analytics/collect.ts b/apps/shared/analytics/collect.tsnew file mode 100644index 00000000..1dc5fe0b--- /dev/null+++ b/apps/shared/analytics/collect.ts@@ -0,0 +1,120 @@+import {+ createError,+ getHeader,+ getRequestWebStream,+ setResponseStatus,+ setResponseHeader,+} from 'h3'+import type { H3Event } from 'h3'+import { readSiteBody } from '../platform/json'+import { platformRequestURL } from '../platform/runtime'+import { publicSiteContext } from '../platform/context'+import {+ visitAgent,+ visitPath,+ visitReferrer,+ visitorHash,+} from '../../../packages/platform/src/analytics'+import type { VisitScope } from '../../../packages/platform/src/analytics'+export async function collectVisit(+ event: H3Event,+ entry: 'cloud' | 'site',+ secret: string,+) {+ setResponseHeader(event, 'Cache-Control', 'no-store')+ const url = platformRequestURL(event)+ if (+ event.method !== 'POST' ||+ getHeader(event, 'origin') !== url.origin ||+ !getHeader(event, 'content-type')?.startsWith('application/json')+ )+ throw createError({ statusCode: 403 })+ const body = await readSiteBody(getRequestWebStream(event), 4096)+ const binding = event.context.cloudflare?.env?.VISIT_ANALYTICS as+ | {+ writeDataPoint(point: {+ indexes: string[]+ blobs: string[]+ doubles: number[]+ }): void+ }+ | undefined+ setResponseStatus(event, 204)+ const ua = getHeader(event, 'user-agent') ?? ''+ if (+ !binding ||+ secret.length < 32 ||+ getHeader(event, 'dnt') === '1' ||+ getHeader(event, 'sec-gpc') === '1' ||+ /bot|crawler|spider|headless|preview|curl|wget/i.test(ua)+ )+ return+ let scope: VisitScope+ if (entry === 'site') {+ const context = await publicSiteContext(event)+ scope = {+ kind: 'site',+ workspaceId: context.site.workspaceId,+ siteId: context.site.id,+ }+ } else {+ scope = {+ kind: /^\/(?:sites|workspace|analytics|account|auth|signin|signup|login|register|onboarding)(?:\/|$)/.test(+ String(body.path),+ )+ ? 'portal'+ : 'website',+ workspaceId: 0,+ siteId: 0,+ }+ }+ let path: string+ try {+ path = visitPath(body.path, scope.kind)+ } catch {+ throw createError({ statusCode: 400 })+ }+ const request = event.context.cloudflare?.request as+ | (Request & { cf?: { country?: string } })+ | undefined+ // Only Cloudflare's trusted client-IP header is used transiently; never persist it.+ const ip = getHeader(event, 'cf-connecting-ip') ?? ''+ if (!ip) return // Fail closed in local/proxy environments without a trustworthy visitor identity.+ const visitor = await visitorHash(+ secret,+ new Date().toISOString().slice(0, 10),+ scope,+ ip,+ ua,+ )+ const { browser, device, os } = visitAgent(ua)+ const campaign = (value: unknown) =>+ typeof value === 'string' && /^[\p{L}\p{N} _.-]{1,64}$/u.test(value)+ ? value+ : ''+ try {+ binding.writeDataPoint({+ indexes: [`${scope.kind}:${scope.workspaceId}:${scope.siteId}`],+ blobs: [+ 'v1',+ scope.kind,+ String(scope.workspaceId),+ String(scope.siteId),+ url.hostname,+ path,+ visitor,+ visitReferrer(body.referrer, url.hostname),+ String(request?.cf?.country ?? 'Unknown'),+ browser,+ device,+ os,+ [campaign(body.source), campaign(body.medium), campaign(body.campaign)]+ .filter(Boolean)+ .join(' / ') || 'None',+ ],+ doubles: [1],+ })+ } catch {+ /* Analytics must not break browsing; no credentials or request data in logs. */+ }+}diff --git a/apps/shared/analytics/query.ts b/apps/shared/analytics/query.tsnew file mode 100644index 00000000..a213a48a--- /dev/null+++ b/apps/shared/analytics/query.ts@@ -0,0 +1,25 @@+import type { H3Event } from 'h3'+import { createError } from 'h3'+import { queryAnalytics } from '../../../packages/platform/src/analytics'+import type { AnalyticsFilter } from '../../../packages/platform/src/analytics'+export async function analyticsReport(event: H3Event, filter: AnalyticsFilter) {+ const env = event.context.cloudflare?.env ?? {}+ try {+ return await queryAnalytics(+ {+ accountId: String(env.ANALYTICS_ACCOUNT_ID ?? ''),+ token: String(env.ANALYTICS_API_TOKEN ?? ''),+ dataset: String(env.ANALYTICS_DATASET ?? ''),+ },+ filter,+ )+ } catch (error) {+ throw createError({+ statusCode: 503,+ statusMessage:+ error instanceof Error && error.message === 'analytics_not_configured'+ ? 'Analytics is not configured'+ : 'Analytics is temporarily unavailable',+ })+ }+}diff --git a/apps/shared/analytics/tracker.ts b/apps/shared/analytics/tracker.tsnew file mode 100644index 00000000..7dcbfb10--- /dev/null+++ b/apps/shared/analytics/tracker.ts@@ -0,0 +1,38 @@+/** Explicit page views cover SSR entry and SPA navigation; assets and prefetches are excluded. */+export function installVisitTracking(+ app: { hook: (name: any, callback: () => void) => void },+ path: () => string,+) {+ let previous = ''+ let first = true+ function track() {+ if (+ navigator.doNotTrack === '1' ||+ (navigator as Navigator & { globalPrivacyControl?: boolean })+ .globalPrivacyControl+ )+ return+ const current = path()+ if (current === previous) return+ const parameters = new URLSearchParams(location.search)+ const data = {+ path: current,+ referrer: first ? document.referrer : location.origin + previous,+ source: parameters.get('utm_source'),+ medium: parameters.get('utm_medium'),+ campaign: parameters.get('utm_campaign'),+ }+ previous = current+ first = false+ // Cookies are unnecessary: this endpoint authorizes Site identity from the request Host.+ void fetch('/api/analytics/visit', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'omit',+ keepalive: true,+ body: JSON.stringify(data),+ }).catch(() => {})+ }+ app.hook('app:mounted', track)+ app.hook('page:finish', track)+}diff --git a/apps/site/app/plugins/visit-analytics.client.ts b/apps/site/app/plugins/visit-analytics.client.tsnew file mode 100644index 00000000..0900dc44--- /dev/null+++ b/apps/site/app/plugins/visit-analytics.client.ts@@ -0,0 +1,5 @@+import { installVisitTracking } from '../../../shared/analytics/tracker'+export default defineNuxtPlugin((app) => {+ const router = useRouter()+ installVisitTracking(app, () => router.currentRoute.value.path)+})diff --git a/apps/site/server/api/analytics/visit.post.ts b/apps/site/server/api/analytics/visit.post.tsnew file mode 100644index 00000000..9550b807--- /dev/null+++ b/apps/site/server/api/analytics/visit.post.ts@@ -0,0 +1,8 @@+import { collectVisit } from '../../../../shared/analytics/collect'+export default defineEventHandler((event) =>+ collectVisit(+ event,+ 'site',+ String(event.context.cloudflare?.env?.ANALYTICS_VISITOR_SECRET ?? ''),+ ),+)diff --git a/apps/site/server/middleware/platform-boundary.ts b/apps/site/server/middleware/platform-boundary.tsindex 27af0a03..afb7167e 100644--- a/apps/site/server/middleware/platform-boundary.ts+++ b/apps/site/server/middleware/platform-boundary.ts@@ -12,6 +12,7 @@ export default defineEventHandler((event) => {}if ([+ '/api/analytics/visit','/api/public/context','/api/public/system/settings/all','/api/public/photos',diff --git a/docs/development/visit-analytics.md b/docs/development/visit-analytics.mdnew file mode 100644index 00000000..67244805--- /dev/null+++ b/docs/development/visit-analytics.md@@ -0,0 +1,52 @@+# SaaS visit analytics++Cloud and Site write to Workers Analytics Engine. Production uses `chronoframe_visits`; named staging Previews use `chronoframe_visits_preview`. Bindings create the dataset on the first write. Do not create a dataset per tenant. Local builds without bindings do not collect visits.++## Configuration++Enable Analytics Engine in the Cloudflare account. In each main-repository deployment GitHub Environment, configure:++| Type | Name | Value |+| --- | --- | --- |+| Existing Secret | `CLOUDFLARE_ACCOUNT_ID` | Reused automatically; no additional account-ID variable is required |+| Secret | `ANALYTICS_API_TOKEN` | API token with **Account / Account Analytics / Read**, restricted to this account |+| Secret | `ANALYTICS_VISITOR_SECRET` | At least 32 characters of cryptographically random key material; generate with `openssl rand -hex 32` |++Use different visitor secrets in production and staging. The deploy workflow creates `VISIT_ANALYTICS`, sets the dataset and account ID on each Worker, and supplies the visitor secret to both Cloud and Site. Only Cloud receives the query token. Credentials are never bundled into browser JavaScript or committed Wrangler files. With neither new secret configured, analytics remains disabled. Configuring only one of the two new secrets fails deployment validation.++In the private Admin repository's **platform-production** Environment, reuse the existing `CLOUDFLARE_ACCOUNT_ID` Secret and configure the query-token Secret. Admin does not require the visitor secret or a write binding. Its runtime-secrets step sets `ANALYTICS_ACCOUNT_ID`, `ANALYTICS_API_TOKEN`, and `ANALYTICS_DATASET=chronoframe_visits` on the Admin Worker.++Merge and deploy Cloud and Site from the main repository, then deploy Admin. The Admin source pin must include this feature. Admin's private migration grants `analytics.read` to existing operator/admin roles; root always has access. Custom roles remain unchanged and can be configured by root.++## Entitlements and access++All existing plans default to analytics disabled. Enable **Allow workspace site analytics** in the Admin plan editor to grant access. The workspace navigation displays Analytics only with the effective current plan's entitlement. API access independently requires an active authenticated workspace membership, the current entitlement, and, when selected, a site belonging to that workspace. A missing entitlement returns 403 even for a manually entered URL. All-site queries still force the workspace and site traffic scope; they cannot include website, portal or another tenant.++Admin's Analytics page supports all traffic or website/portal/customer-site filters and optional workspace/site IDs. Portal's Analytics page supports all sites in the workspace or one site. Reports include PV, daily UV total, daily trends and the top 20 pages, referrer hosts, countries, hosts, browsers, devices, operating systems and campaign labels. Queries allow up to 31 days within the last 90 days, UTC. Responses are private and query results are cached internally for 60 seconds after authorization. Retention is Analytics Engine's three-month window; this is not a permanent archive.++## Counting and privacy++A browser page entry or SPA path navigation sends one same-origin event. Assets, API requests and prefetches do not count. Same-path query/hash changes do not count as new views. Reloading a page does count. Blocked scripts, privacy preferences, network failures and known-bot filtering affect coverage; this is an operational reference rather than billing evidence. Configure Cloudflare rate limiting on `/api/analytics/visit` for your traffic profile; like ordinary client analytics, events are not proof that a human visited.++The collector derives workspace/site identity from the verified request Host, never client-supplied IDs. It honors DNT and GPC, excludes known bot user agents, uses Cloudflare's trusted visitor IP transiently and does not set cookies. The HMAC visitor identifier rotates daily (UTC), is scoped by traffic kind and workspace, and cannot be linked across workspaces or days. Shared-network users with identical browser information may be grouped. Changing the key during a day may split that day's UV.++No raw IP, full user agent, URL query string or full referrer URL is written. Only referrer host and coarse browser/device categories are stored. Private portal routes are recorded as templates, not account identifiers. Published privacy-policy defaults disclose the collection; if you have customized published policy records, update those records through the Admin legal editor before enabling collection.++PV uses `SUM(_sample_interval)`. UV uses distinct daily HMAC values; over multiple days it is the daily UV sum, not cross-day distinct users. When Analytics Engine sampling occurs, observed UV can undercount and the UI explicitly identifies sampled results. Per-dimension UV is not additive across rows. Queries return only aggregates, never visitor hashes. Empty data, an uninitialized dataset and query/configuration errors are separate states.++## Dataset schema v1++| Field | Content |+| --- | --- |+| index1 | `kind:workspaceId:siteId` |+| blob1 | `v1` |+| blob2 | `website`, `portal`, or `site` |+| blob3–4 | Server-resolved workspace and site IDs; `0` for platform traffic |+| blob5–6 | Request hostname and path / private route template |+| blob7 | Daily HMAC visitor identifier |+| blob8–9 | Referrer hostname and Cloudflare country |+| blob10–12 | Browser, device, operating-system categories |+| blob13 | Validated campaign source / medium / name |+| double1 | `1` |++Official references: [Bindings and dataset creation](https://developers.cloudflare.com/analytics/analytics-engine/get-started/), [SQL API token](https://developers.cloudflare.com/analytics/analytics-engine/sql-api/), [sampling](https://developers.cloudflare.com/analytics/analytics-engine/sampling/).diff --git a/packages/platform/src/analytics.ts b/packages/platform/src/analytics.tsnew file mode 100644index 00000000..d11469d2--- /dev/null+++ b/packages/platform/src/analytics.ts@@ -0,0 +1,319 @@+/** Workers Analytics Engine visit schema v1. No raw IP, query strings or full user agent. */+export type VisitScope = {+ kind: 'website' | 'portal' | 'site'+ workspaceId: number+ siteId: number+}+export type AnalyticsConfig = {+ accountId: string+ token: string+ dataset: string+}+export type AnalyticsFilter = {+ from: string+ to: string+ kind?: VisitScope['kind']+ workspaceId?: number+ siteId?: number+}+export function analyticsFilter(+ input: Record<string, unknown>,+ now = Date.now(),+): AnalyticsFilter {+ const today = new Date(now).toISOString().slice(0, 10)+ const from = String(+ input.from ?? new Date(now - 6 * 86400000).toISOString().slice(0, 10),+ )+ const to = String(input.to ?? today)+ const date = (s: string) =>+ /^\d{4}-\d{2}-\d{2}$/.test(s) &&+ new Date(s).toISOString().slice(0, 10) === s+ if (+ !date(from) ||+ !date(to) ||+ from > to ||+ to > today ||+ Date.parse(to) - Date.parse(from) > 30 * 86400000 ||+ Date.parse(from) < Date.parse(today) - 89 * 86400000+ )+ throw new Error('invalid_analytics_range')+ const filter: AnalyticsFilter = { from, to }+ if (input.kind !== undefined && input.kind !== '') {+ if (!['website', 'portal', 'site'].includes(String(input.kind)))+ throw new Error('invalid_analytics_kind')+ filter.kind = input.kind as VisitScope['kind']+ }+ for (const key of ['workspaceId', 'siteId'] as const) {+ if (input[key] === undefined || input[key] === '') continue+ const value = Number(input[key])+ if (!Number.isSafeInteger(value) || value < 1)+ throw new Error('invalid_analytics_scope')+ filter[key] = value+ }+ return filter+}+export function visitPath(raw: unknown, kind: VisitScope['kind']): string {+ if (+ typeof raw !== 'string' ||+ !raw.startsWith('/') ||+ raw.startsWith('//') ||+ raw.length > 2048+ )+ throw new Error('invalid_visit_path')+ const path = new URL(raw, 'https://local.invalid').pathname+ if (+ path.startsWith('/api/') ||+ path.startsWith('/_nuxt/') ||+ path === '/__nuxt_error'+ )+ throw new Error('invalid_visit_path')+ // Portal paths can contain account identifiers. Only record route templates.+ if (kind === 'portal') {+ const routes = new Set([+ 'workspace',+ 'analytics',+ 'sites',+ 'account',+ 'auth',+ 'signin',+ 'signup',+ 'login',+ 'register',+ 'onboarding',+ 'overview',+ 'photos',+ 'albums',+ 'information',+ 'domains',+ 'storage',+ 'settings',+ 'plan',+ 'security',+ 'verify-email',+ 'reset-password',+ 'forgot-password',+ ])+ return (+ '/' ++ path+ .split('/')+ .filter(Boolean)+ .map((segment) => (routes.has(segment) ? segment : ':id'))+ .join('/')+ .slice(0, 200)+ )+ }+ return path.slice(0, 200)+}+export function visitAgent(ua: string) {+ const browser = /Edg\//.test(ua)+ ? 'Edge'+ : /Firefox\//.test(ua)+ ? 'Firefox'+ : /(?:Chrome|CriOS)\//.test(ua)+ ? 'Chrome'+ : /Safari\//.test(ua)+ ? 'Safari'+ : 'Other'+ const os = /Android/i.test(ua)+ ? 'Android'+ : /iPhone|iPad/i.test(ua)+ ? 'iOS'+ : /Windows/i.test(ua)+ ? 'Windows'+ : /Macintosh/i.test(ua)+ ? 'macOS'+ : /Linux/i.test(ua)+ ? 'Linux'+ : 'Other'+ return {+ browser,+ os,+ device: /iPad|Tablet/i.test(ua)+ ? 'Tablet'+ : /Mobile|iPhone|Android/i.test(ua)+ ? 'Mobile'+ : 'Desktop',+ }+}+export function visitReferrer(value: unknown, host: string) {+ try {+ const u = new URL(String(value))+ return ['https:', 'http:'].includes(u.protocol) && u.hostname !== host+ ? u.hostname.slice(0, 253)+ : 'Direct / internal'+ } catch {+ return 'Direct / internal'+ }+}+export async function visitorHash(+ secret: string,+ day: string,+ scope: VisitScope,+ ip: string,+ ua: string,+) {+ if (secret.length < 32) throw new Error('analytics_secret_required')+ const key = await crypto.subtle.importKey(+ 'raw',+ new TextEncoder().encode(secret),+ { name: 'HMAC', hash: 'SHA-256' },+ false,+ ['sign'],+ )+ const value = JSON.stringify([+ day,+ scope.kind,+ scope.workspaceId,+ ip,+ ua.slice(0, 512),+ ])+ const bytes = new Uint8Array(+ await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(value)),+ )+ return Array.from(bytes.slice(0, 16), (b) =>+ b.toString(16).padStart(2, '0'),+ ).join('')+}+export function analyticsQueries(dataset: string, filter: AnalyticsFilter) {+ if (!/^[a-z][a-z0-9_]{0,63}$/.test(dataset))+ throw new Error('invalid_analytics_dataset')+ if (+ !/^\d{4}-\d{2}-\d{2}$/.test(filter.from) ||+ !/^\d{4}-\d{2}-\d{2}$/.test(filter.to) ||+ (filter.kind && !['website', 'portal', 'site'].includes(filter.kind))+ )+ throw new Error('invalid_analytics_filter')+ const terms = [+ `timestamp >= toDateTime('${filter.from} 00:00:00')`,+ `timestamp < toDateTime('${new Date(Date.parse(filter.to) + 86400000).toISOString().slice(0, 10)} 00:00:00')`,+ `blob1 = 'v1'`,+ ]+ if (filter.kind) terms.push(`blob2 = '${filter.kind}'`)+ for (const [key, column] of [+ ['workspaceId', 'blob3'],+ ['siteId', 'blob4'],+ ] as const) {+ const n = filter[key]+ if (n !== undefined) {+ if (!Number.isSafeInteger(n) || n < 1)+ throw new Error('invalid_analytics_scope')+ terms.push(`${column} = '${n}'`)+ }+ }+ const where = `${dataset} WHERE ${terms.join(' AND ')}`+ const metrics =+ 'SUM(_sample_interval) AS pv, COUNT(DISTINCT blob7) AS uv, MAX(_sample_interval) AS sampleInterval'+ const group = (column: string) =>+ `SELECT ${column} AS label, ${metrics} FROM ${where} GROUP BY label ORDER BY pv DESC LIMIT 20 FORMAT JSON`+ return {+ summary: `SELECT ${metrics} FROM ${where} FORMAT JSON`,+ daily: `SELECT toDate(timestamp) AS label, ${metrics} FROM ${where} GROUP BY label ORDER BY label FORMAT JSON`,+ pages: group('blob6'),+ sources: group('blob8'),+ countries: group('blob9'),+ browsers: group('blob10'),+ devices: group('blob11'),+ systems: group('blob12'),+ campaigns: group('blob13'),+ sites: group('blob5'),+ }+}+export type AnalyticsRow = {+ label: string+ pv: number+ uv: number+ sampleInterval: number+}+export type AnalyticsReport = {+ from: string+ to: string+ summary: AnalyticsRow+ daily: AnalyticsRow[]+ pages: AnalyticsRow[]+ sources: AnalyticsRow[]+ countries: AnalyticsRow[]+ browsers: AnalyticsRow[]+ devices: AnalyticsRow[]+ systems: AnalyticsRow[]+ campaigns: AnalyticsRow[]+ sites: AnalyticsRow[]+ notInitialized: boolean+}+const cache = new Map<string, { until: number; value: AnalyticsReport }>()+export async function queryAnalytics(+ config: AnalyticsConfig,+ filter: AnalyticsFilter,+ fetcher: typeof fetch = fetch,+): Promise<AnalyticsReport> {+ if (!/^[a-f0-9]{32}$/.test(config.accountId) || !config.token)+ throw new Error('analytics_not_configured')+ const queries = analyticsQueries(config.dataset, filter)+ const cacheKey = JSON.stringify([config.accountId, config.dataset, filter])+ const cached = cache.get(cacheKey)+ if (cached && cached.until > Date.now()) return cached.value+ let notInitialized = false+ const result = await Promise.all(+ Object.entries(queries).map(async ([key, sql]) => {+ const response = await fetcher(+ `https://api.cloudflare.com/client/v4/accounts/${config.accountId}/analytics_engine/sql`,+ {+ method: 'POST',+ headers: { Authorization: `Bearer ${config.token}` },+ body: sql,+ signal: AbortSignal.timeout(10000),+ },+ )+ if (!response.ok) {+ // Before the first event the dataset does not exist. Do not mask authentication or SQL errors.+ const text = await response.text()+ if (+ response.status === 400 &&+ /(?:unknown table|table[^\n]*(?:does not exist|not found))/i.test(+ text,+ )+ ) {+ notInitialized = true+ return [key, []] as const+ }+ throw new Error('analytics_query_failed')+ }+ const json = (await response.json()) as {+ data?: Record<string, unknown>[]+ }+ if (!Array.isArray(json.data)) throw new Error('analytics_query_failed')+ const rows = json.data.map((row) => ({+ label: String(row.label ?? ''),+ pv: Number(row.pv ?? 0),+ uv: Number(row.uv ?? 0),+ sampleInterval: Number(row.sampleInterval ?? 1),+ }))+ if (+ rows.some(+ (row) =>+ !Number.isFinite(row.pv) ||+ !Number.isFinite(row.uv) ||+ !Number.isFinite(row.sampleInterval),+ )+ )+ throw new Error('analytics_query_failed')+ return [key, rows] as const+ }),+ )+ const data = Object.fromEntries(result)+ const report = {+ ...data,+ from: filter.from,+ to: filter.to,+ summary: data.summary?.[0] ?? {+ label: '',+ pv: 0,+ uv: 0,+ sampleInterval: 1,+ },+ notInitialized,+ } as AnalyticsReport+ if (cache.size >= 200) cache.delete(cache.keys().next().value!)+ cache.set(cacheKey, { until: Date.now() + 60000, value: report })+ return report+}diff --git a/packages/platform/src/billing.ts b/packages/platform/src/billing.tsindex 3c0d1e50..92ae467f 100644--- a/packages/platform/src/billing.ts+++ b/packages/platform/src/billing.ts@@ -202,6 +202,7 @@ export async function workspaceBilling(id: plan.id,name: plan.name,limits: plan.limits,+ analytics: plan.analytics,byosLimits: byos.limits,},subscription: current.subscription,diff --git a/packages/platform/src/entitlements.ts b/packages/platform/src/entitlements.tsindex 26aaa9e7..e2efb92f 100644--- a/packages/platform/src/entitlements.ts+++ b/packages/platform/src/entitlements.ts@@ -40,6 +40,7 @@ export type PlanFeature = {value?: string | number}export interface PlanPolicy {+ analytics?: booleanfeatures?: PlanFeature[]limits: Limitsrules: { when: Condition; limits: Partial<Limits> }[]@@ -52,9 +53,13 @@ export function validatePolicy(value: unknown): PlanPolicy {!plain(value.limits) ||!Array.isArray(value.rules) ||value.rules.length > 32 ||- Object.keys(value).some((k) => !['limits', 'rules', 'features'].includes(k))+ Object.keys(value).some(+ (k) => !['limits', 'rules', 'features', 'analytics'].includes(k),+ ))throw new Error('Invalid policy')+ if (value.analytics !== undefined && typeof value.analytics !== 'boolean')+ throw new Error('Invalid analytics entitlement')if (value.features !== undefined) {if (!Array.isArray(value.features) || value.features.length > 32)throw new Error('Invalid plan features')@@ -185,6 +190,7 @@ export async function workspaceEntitlements(now = Date.now(),) {const row = await resolveSubscription(db, workspaceId, now)+ const policy = validatePolicy(JSON.parse(row.policy_json))const context: PolicyContext = {storageMode,workspaceAgeDays: Math.max(@@ -199,10 +205,8 @@ export async function workspaceEntitlements(revision: row.revision,subscription: row.subscription,quotaPeriod: row.quotaPeriod,- limits: evaluatePolicy(- validatePolicy(JSON.parse(row.policy_json)),- context,- ),+ analytics: policy.analytics === true,+ limits: evaluatePolicy(policy, context),}}diff --git a/packages/platform/src/legal-defaults.ts b/packages/platform/src/legal-defaults.tsindex 615ed5aa..28959d6d 100644--- a/packages/platform/src/legal-defaults.ts+++ b/packages/platform/src/legal-defaults.ts@@ -86,6 +86,9 @@ Published gallery content is disclosed according to its visibility settings. Inf## 5. Cookies and local preferencesWe use authentication cookies and local preferences necessary for sign-in, account security, language and appearance. We do not describe all cookies as advertising cookies. If optional analytics or marketing technologies are introduced, we will provide the disclosures and choices required by applicable law.+### Visitor analytics+We use Cloudflare Workers Analytics Engine to measure page views, daily unique visitors, referring hostnames, country/region, device and browser categories, and campaign labels across our website, portal and hosted galleries. We do not store raw IP addresses, full user agents, URL query strings or analytics cookies in this dataset. IP addresses and browser information are used transiently to derive a daily rotating keyed anonymous identifier. We honor Do Not Track and Global Privacy Control signals. Authorized gallery owners may view aggregate statistics for their workspace where their plan includes analytics; platform staff access is permission-controlled. Cross-day UV is the sum of daily unique visitors. Cloudflare may sample results. Analytics records are retained by Analytics Engine for up to three months.+## 6. Retention and deletionWe retain information as needed to provide the service, protect accounts, resolve disputes and satisfy legal obligations. Content remains until you remove it or applicable account lifecycle rules require cleanup. Unverified or inactive accounts may receive deletion notices with specific deadlines. After an account is marked for deletion, sign-in is disabled and a retention period allows a support restoration request; permanent cleanup follows when that period ends. Quotas, exemptions and lifecycle settings can affect the applicable process. Billing, security or legally required records may have different retention requirements. Copies in backups, caches or third-party systems may take additional time to expire. Your independently operated bucket and provider contract remain under your control.@@ -119,6 +122,9 @@ The effective date and latest revision appear on this page. We will provide appr## 五、Cookie 与本地偏好平台使用登录、安全、语言及外观等必要的 Cookie 和本地偏好设置。这些功能不等同于广告追踪。未来如引入可选分析或营销技术,我们会提供适用法律要求的说明与选择。+### 访问统计+我们使用 Cloudflare Workers Analytics Engine 统计官网、门户及托管站点的页面浏览量、每日独立访客、来源域名、国家/地区、设备与浏览器类别及推广活动标签。该数据集不保存原始 IP、完整浏览器信息、URL 查询参数,也不设置分析 Cookie。IP 和浏览器信息仅用于即时生成每日轮换的匿名密钥标识;我们遵循 Do Not Track 与 Global Privacy Control 信号。具有套餐权益的图库用户可查看所属工作区的汇总数据,平台人员访问受权限控制。跨天 UV 表示每日独立访客合计,Cloudflare 可能对结果采样。Analytics Engine 中的统计记录最长保留三个月。+## 六、保存与删除我们按提供服务、保护账号、解决争议及履行法律义务所需的期限保存信息。内容可因您的删除操作或适用的账号生命周期规则被清理。未验证或不活跃账号可能收到包含具体日期的删除通知。账号被标记删除后将无法登录,保留期内可联系客服申请恢复,保留期结束后进行永久清理;配额、豁免和生命周期设置可能影响具体流程。计费、安全或依法必须留存的记录可能适用不同期限。备份、缓存及第三方系统中的副本可能需要额外时间到期。您自行运营的存储桶和相关服务合同仍由您控制。diff --git a/packages/saas-ui/app/components/CfAnalyticsReport.vue b/packages/saas-ui/app/components/CfAnalyticsReport.vuenew file mode 100644index 00000000..38162f50--- /dev/null+++ b/packages/saas-ui/app/components/CfAnalyticsReport.vue@@ -0,0 +1,229 @@+<script setup lang="ts">+const props = defineProps<{ report: any; zh?: boolean }>()+const tr = (en: string, zh: string) => (props.zh ? zh : en)+const format = (value: number) =>+ new Intl.NumberFormat(props.zh ? 'zh-CN' : 'en-US', {+ maximumFractionDigits: 0,+ }).format(value)+const groups = computed(() => [+ ['pages', tr('Pages', '页面')],+ ['sources', tr('Referrer hosts', '来源域名')],+ ['countries', tr('Countries / regions', '国家/地区')],+ ['sites', tr('Site hosts', '站点域名')],+ ['browsers', tr('Browsers', '浏览器')],+ ['devices', tr('Devices', '设备')],+ ['systems', tr('Operating systems', '操作系统')],+ [+ 'campaigns',+ tr('Campaigns (source / medium / campaign)', '推广来源/媒介/活动'),+ ],+])+const peak = computed(() =>+ Math.max(1, ...props.report.daily.map((r: any) => r.pv)),+)+</script>+<template>+ <div class="cf-analytics-report">+ <p class="cf-field-hint">+ {{+ tr(+ 'UTC dates. UV is deduplicated daily without cookies; visitors returning on another day count again. Reports may lag and refresh at most once per minute. Known bots and privacy opt-outs are excluded.',+ '日期以 UTC 计算。UV 使用无 Cookie 的每日去重标识,跨天回访会再次计数。数据可能延迟,最多每分钟更新一次;排除已识别机器人及选择不被统计的访问。',+ )+ }}+ </p>+ <p+ v-if="report.notInitialized"+ role="status"+ >+ {{+ tr(+ 'The dataset has not received its first visit yet.',+ '数据集尚未收到首次访问记录。',+ )+ }}+ </p>+ <p+ v-if="report.summary.sampleInterval > 1"+ role="status"+ >+ {{+ tr(+ 'Cloudflare sampled these results. PV is weighted; UV is the observed daily visitor count and may be lower than the actual value.',+ 'Cloudflare 对本次结果进行了采样。PV 已加权折算;UV 为采样中观测到的每日访客数,可能低于实际值。',+ )+ }}+ </p>+ <div class="cf-analytics-metrics">+ <CfStatCard+ label="PV"+ :value="format(report.summary.pv)"+ :detail="tr('Page views', '页面浏览量')"+ />+ <CfStatCard+ :label="tr('Daily UV total', '每日 UV 合计')"+ :value="format(report.summary.uv)"+ :detail="+ tr(+ 'Daily unique visitors summed across the selected dates',+ '所选日期范围内每日独立访客的合计',+ )+ "+ />+ </div>+ <CfCard class="cf-analytics-card">+ <h2>{{ tr('Daily traffic', '每日访问趋势') }}</h2>+ <div+ v-if="report.daily.length"+ class="cf-analytics-trend"+ role="img"+ :aria-label="+ tr(+ 'Daily page views; exact figures are in the table below.',+ '每日浏览量,具体数值见下表。',+ )+ "+ >+ <div+ v-for="row in report.daily"+ :key="row.label"+ :title="`${row.label}: ${format(row.pv)} PV · ${format(row.uv)} UV`"+ class="cf-analytics-bar"+ :style="{ height: `${Math.max(1, (row.pv / peak) * 100)}%` }"+ ></div>+ </div>+ <div class="cf-analytics-table-wrap">+ <table class="cf-analytics-table">+ <thead>+ <tr>+ <th>{{ tr('Date (UTC)', '日期(UTC)') }}</th>+ <th>PV</th>+ <th>{{ tr('Daily UV', '每日 UV') }}</th>+ </tr>+ </thead>+ <tbody>+ <tr+ v-for="row in report.daily"+ :key="row.label"+ >+ <td>{{ row.label }}</td>+ <td>{{ format(row.pv) }}</td>+ <td>{{ format(row.uv) }}</td>+ </tr>+ <tr v-if="!report.daily.length">+ <td colspan="3">+ {{+ tr(+ 'No visits in this date range.',+ '此日期范围内暂无访问记录。',+ )+ }}+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </CfCard>+ <div class="cf-analytics-breakdowns">+ <CfCard+ v-for="[key, title] in groups"+ :key="key"+ class="cf-analytics-card"+ >+ <h2>+ {{ title }}+ <small class="cf-field-hint">{{ tr('Top 20', '前 20 项') }}</small>+ </h2>+ <div class="cf-analytics-table-wrap">+ <table class="cf-analytics-table">+ <thead>+ <tr>+ <th>{{ tr('Dimension', '维度') }}</th>+ <th>PV</th>+ <th>{{ tr('Daily UV total', '每日 UV 合计') }}</th>+ </tr>+ </thead>+ <tbody>+ <tr+ v-for="row in report[key]"+ :key="row.label"+ >+ <td>{{ row.label }}</td>+ <td>{{ format(row.pv) }}</td>+ <td>{{ format(row.uv) }}</td>+ </tr>+ <tr v-if="!report[key].length">+ <td colspan="3">{{ tr('No data', '暂无数据') }}</td>+ </tr>+ </tbody>+ </table>+ </div>+ </CfCard>+ </div>+ </div>+</template>+<style scoped>+.cf-analytics-report {+ display: grid;+ gap: 20px;+ min-width: 0;+}+.cf-analytics-metrics,+.cf-analytics-breakdowns {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 16px;+}+.cf-analytics-card {+ padding: 20px;+ min-width: 0;+}+.cf-analytics-card h2 {+ font-size: 15px;+ font-weight: 600;+ margin-bottom: 16px;+}+.cf-analytics-table-wrap {+ overflow-x: auto;+ max-height: 360px;+}+.cf-analytics-table {+ width: 100%;+ border-collapse: collapse;+ font-size: 13px;+}+.cf-analytics-table th,+.cf-analytics-table td {+ text-align: left;+ padding: 10px 8px;+ border-bottom: 1px solid var(--ui-border);+}+.cf-analytics-table td:first-child {+ overflow-wrap: anywhere;+}+.cf-analytics-table th:not(:first-child),+.cf-analytics-table td:not(:first-child) {+ text-align: right;+ white-space: nowrap;+}+.cf-analytics-trend {+ display: flex;+ align-items: flex-end;+ gap: 4px;+ height: 140px;+ padding: 8px 0;+ margin-bottom: 16px;+}+.cf-analytics-bar {+ flex: 1;+ background: var(--ui-primary);+ border-radius: 3px 3px 0 0;+ min-width: 2px;+}+@media (max-width: 700px) {+ .cf-analytics-metrics,+ .cf-analytics-breakdowns {+ grid-template-columns: 1fr;+ }+}+</style>diff --git a/scripts/analytics-deployment.mjs b/scripts/analytics-deployment.mjsnew file mode 100644index 00000000..b31a7b2e--- /dev/null+++ b/scripts/analytics-deployment.mjs@@ -0,0 +1,30 @@+/** Production and named Previews never share a dataset. No credential goes into Wrangler JSON. */+export function configureAnalyticsDeployment(config, environment, env) {+ delete config.analytics_engine_datasets+ if (config.previews) delete config.previews.analytics_engine_datasets+ if (!env.ANALYTICS_API_TOKEN && !env.ANALYTICS_VISITOR_SECRET) return+ if (!/^[a-f0-9]{32}$/.test(env.ANALYTICS_ACCOUNT_ID))+ throw new Error('Invalid ANALYTICS_ACCOUNT_ID')+ if (+ !env.ANALYTICS_API_TOKEN ||+ (env.ANALYTICS_VISITOR_SECRET ?? '').length < 32+ )+ throw new Error(+ 'Configure ANALYTICS_API_TOKEN and ANALYTICS_VISITOR_SECRET before enabling analytics',+ )+ const preview = environment === 'staging'+ const target = preview ? (config.previews ??= {}) : config+ target.analytics_engine_datasets = [+ {+ binding: 'VISIT_ANALYTICS',+ dataset: preview ? 'chronoframe_visits_preview' : 'chronoframe_visits',+ },+ ]+ target.vars = {+ ...target.vars,+ ANALYTICS_ACCOUNT_ID: env.ANALYTICS_ACCOUNT_ID,+ ANALYTICS_DATASET: preview+ ? 'chronoframe_visits_preview'+ : 'chronoframe_visits',+ }+}diff --git a/tests/visit-analytics.test.ts b/tests/visit-analytics.test.tsnew file mode 100644index 00000000..0079f005--- /dev/null+++ b/tests/visit-analytics.test.ts@@ -0,0 +1,378 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { readFile } from 'node:fs/promises'+import { createRequire } from 'node:module'+import {+ analyticsFilter,+ analyticsQueries,+ visitPath,+ visitReferrer,+ visitAgent,+ visitorHash,+ queryAnalytics,+} from '../packages/platform/src/analytics.ts'+import {+ FREE_LIMITS,+ validatePolicy,+} from '../packages/platform/src/entitlements.ts'+import { configureAnalyticsDeployment } from '../scripts/analytics-deployment.mjs'+const require = createRequire(import.meta.url),+ ts = require('typescript')+async function module(file: string, deps: Record<string, unknown>) {+ const source = (+ await readFile(new URL(file, import.meta.url), 'utf8')+ ).replace(/^import[\s\S]*?from ['"][^'"]+['"]\s*\n/gm, '')+ const code = ts.transpileModule(source, {+ compilerOptions: {+ module: ts.ModuleKind.CommonJS,+ target: ts.ScriptTarget.ES2022,+ },+ }).outputText+ return new Function(+ 'exports',+ ...Object.keys(deps),+ code + ';return exports',+ )({}, ...Object.values(deps))+}+test('daily identities are deterministic, isolated by workspace/day, and do not retain request secrets', async () => {+ const scope = { kind: 'site' as const, workspaceId: 1, siteId: 2 }+ const hash = await visitorHash(+ 'a'.repeat(64),+ '2026-11-01',+ scope,+ '203.0.113.1',+ 'browser',+ )+ assert.equal(hash.length, 32)+ assert.equal(+ hash,+ await visitorHash(+ 'a'.repeat(64),+ '2026-11-01',+ { ...scope, siteId: 3 },+ '203.0.113.1',+ 'browser',+ ),+ )+ assert.notEqual(+ hash,+ await visitorHash(+ 'a'.repeat(64),+ '2026-11-02',+ scope,+ '203.0.113.1',+ 'browser',+ ),+ )+ assert.notEqual(+ hash,+ await visitorHash(+ 'a'.repeat(64),+ '2026-11-01',+ { ...scope, workspaceId: 2 },+ '203.0.113.1',+ 'browser',+ ),+ )+ await assert.rejects(visitorHash('short', '2026-11-01', scope, '', ''))+ assert.equal(+ visitPath(+ '/account/reset-password/[email protected]',+ 'portal',+ ),+ '/account/reset-password/:id',+ )+ assert.equal(visitPath('/sites/21/photos', 'portal'), '/sites/:id/photos')+ assert.equal(+ visitPath('/photos/[email protected]', 'site'),+ '/photos/a',+ )+ assert.throws(() => visitPath('/api/public/photos', 'site'))+ assert.equal(+ visitReferrer('https://search.example/path?private=1', 'gallery.example'),+ 'search.example',+ )+ assert.equal(+ visitReferrer('javascript:alert(1)', 'gallery.example'),+ 'Direct / internal',+ )+ assert.equal(visitAgent('Mozilla iPhone Mobile Safari/600').device, 'Mobile')+})+test('analytics filters reject SQL injection and unbounded queries; every query carries tenant constraints', () => {+ const now = Date.parse('2026-11-01T12:00:00Z')+ const filter = analyticsFilter(+ { workspaceId: '7', siteId: '4', kind: 'site' },+ now,+ )+ const queries = analyticsQueries('chronoframe_visits', filter)+ for (const sql of Object.values(queries)) {+ assert.match(sql, /blob3 = '7'/)+ assert.match(sql, /blob4 = '4'/)+ assert.match(sql, /blob2 = 'site'/)+ assert.match(sql, /SUM\(_sample_interval\)/)+ }+ for (const input of [+ { from: "2026-11-01' OR 1=1" },+ { from: '2026-01-01' },+ { from: '2026-09-01' },+ { to: '2026-11-02' },+ { workspaceId: '1 OR 1=1' },+ { siteId: '-1' },+ { kind: 'other' },+ ])+ assert.throws(() => analyticsFilter(input, now))+ assert.throws(() => analyticsQueries('table; DROP TABLE users', filter))+ assert.throws(() =>+ analyticsQueries('chronoframe_visits', {+ ...filter,+ from: "' UNION SELECT",+ }),+ )+ assert.equal(+ validatePolicy({ limits: FREE_LIMITS, rules: [] }).analytics,+ undefined,+ )+ assert.equal(+ validatePolicy({ limits: FREE_LIMITS, rules: [], analytics: true })+ .analytics,+ true,+ )+ assert.throws(() =>+ validatePolicy({ limits: FREE_LIMITS, rules: [], analytics: 1 }),+ )+})+test('collector binds tenant identity to the verified host, respects opt-outs and excludes sensitive request fields', async () => {+ const points: any[] = []+ let headers: Record<string, string> = {+ origin: 'https://gallery.example',+ 'content-type': 'application/json',+ 'cf-connecting-ip': '203.0.113.2',+ 'user-agent': 'Mozilla Chrome/100',+ }+ let body: any = {+ path: '/[email protected]',+ workspaceId: 999,+ siteId: 999,+ referrer: 'https://search.example/?private=yes',+ campaign: 'Launch',+ }+ const { collectVisit } = await module('../apps/shared/analytics/collect.ts', {+ createError: (value: any) => Object.assign(new Error(), value),+ getHeader: (_: any, key: string) => headers[key],+ getRequestWebStream: () => null,+ setResponseStatus: () => {},+ setResponseHeader: () => {},+ readSiteBody: async () => body,+ platformRequestURL: () =>+ new URL('https://gallery.example/api/analytics/visit'),+ publicSiteContext: async () => ({ site: { id: 5, workspaceId: 3 } }),+ visitAgent,+ visitPath,+ visitReferrer,+ visitorHash,+ })+ const event = {+ method: 'POST',+ context: {+ cloudflare: {+ env: {+ VISIT_ANALYTICS: { writeDataPoint: (p: any) => points.push(p) },+ },+ request: { cf: { country: 'HK' } },+ },+ },+ }+ await collectVisit(event, 'site', 'a'.repeat(64))+ assert.equal(points.length, 1)+ assert.equal(points[0].indexes[0], 'site:3:5')+ const serialized = JSON.stringify(points)+ assert.ok(!serialized.includes('203.0.113.2'))+ assert.ok(!serialized.includes('private=yes'))+ assert.ok(!serialized.includes('[email protected]'))+ assert.ok(!serialized.includes('Mozilla'))+ for (const header of ['dnt', 'sec-gpc']) {+ headers[header] = '1'+ await collectVisit(event, 'site', 'a'.repeat(64))+ delete headers[header]+ }+ assert.equal(points.length, 1)+ headers.origin = 'https://evil.example'+ await assert.rejects(collectVisit(event, 'site', 'a'.repeat(64)), {+ statusCode: 403,+ })+})+test('portal report checks membership, live entitlement and selected-site ownership before executing any SQL API query', async () => {+ let membership = true,+ entitled = false,+ siteOwned = true,+ reports = 0+ let query: any = { workspaceId: '7', siteId: '3', kind: 'website' }+ const db = {+ prepare: (sql: string) => ({+ bind: (..._args: any[]) => ({+ first: async () =>+ sql.includes('memberships')+ ? membership+ ? { workspace_id: 7 }+ : null+ : siteOwned+ ? { id: 3 }+ : null,+ }),+ }),+ }+ const deps = {+ definePlatformHandler: (f: any) => f,+ getQuery: () => query,+ createError: (value: any) => Object.assign(new Error(), value),+ setResponseHeader: () => {},+ requirePlatformSession: async () => ({ userId: 1 }),+ useRuntimeConfig: () => ({ platform: {} }),+ platformDatabase: () => db,+ workspaceEntitlements: async () => ({ analytics: entitled }),+ analyticsFilter,+ analyticsReport: async (_: any, f: any) => {+ reports+++ return f+ },+ }+ const { default: report } = await module(+ '../apps/cloud/server/api/analytics/report.get.ts',+ deps,+ )+ await assert.rejects(report({}), { statusCode: 403 })+ assert.equal(reports, 0)+ entitled = true+ membership = false+ await assert.rejects(report({}), { statusCode: 404 })+ assert.equal(reports, 0)+ membership = true+ siteOwned = false+ await assert.rejects(report({}), { statusCode: 404 })+ assert.equal(reports, 0)+ siteOwned = true+ const filter = await report({})+ assert.equal(filter.kind, 'site')+ assert.equal(filter.workspaceId, 7)+ assert.equal(filter.siteId, 3)+ entitled = false+ await assert.rejects(report({}), { statusCode: 403 })+ assert.equal(reports, 1)+})+test('SQL API failures are not empty reports; sampled results preserve weighted PV and observed UV', async () => {+ const accountId = 'a'.repeat(32),+ filter = analyticsFilter({ workspaceId: 91, kind: 'site' })+ let calls = 0+ const report = await queryAnalytics(+ { accountId, dataset: 'fixture_visits', token: 'fixture-secret' },+ filter,+ async (_url, options) => {+ calls+++ assert.match(String(options?.body), /blob3 = '91'/)+ return new Response(+ JSON.stringify({+ data: [{ pv: 120, uv: 12, sampleInterval: 10, label: 'test' }],+ }),+ { status: 200 },+ )+ },+ )+ assert.equal(report.summary.pv, 120)+ assert.equal(report.summary.uv, 12)+ assert.equal(report.summary.sampleInterval, 10)+ assert.equal(calls, 10)+ await assert.rejects(+ queryAnalytics(+ { accountId, dataset: 'fixture_error', token: 'fixture-secret' },+ filter,+ async () => new Response('Unauthorized', { status: 403 }),+ ),+ )+ const empty = await queryAnalytics(+ { accountId, dataset: 'fixture_missing', token: 'fixture-secret' },+ filter,+ async () => new Response('Unknown table fixture_missing', { status: 400 }),+ )+ assert.equal(empty.notInitialized, true)+ assert.equal(empty.summary.pv, 0)+})+test('production and preview bindings are isolated and only enable with both secrets', () => {+ const env = {+ ANALYTICS_ACCOUNT_ID: 'a'.repeat(32),+ ANALYTICS_API_TOKEN: 'test',+ ANALYTICS_VISITOR_SECRET: 'b'.repeat(64),+ }+ const config: any = { previews: {} }+ configureAnalyticsDeployment(config, 'production', env)+ assert.equal(+ config.analytics_engine_datasets[0].dataset,+ 'chronoframe_visits',+ )+ assert.ok(!JSON.stringify(config).includes('bbbbbbbb'))+ configureAnalyticsDeployment(config, 'staging', env)+ assert.equal(config.analytics_engine_datasets, undefined)+ assert.equal(+ config.previews.analytics_engine_datasets[0].dataset,+ 'chronoframe_visits_preview',+ )+ assert.throws(() =>+ configureAnalyticsDeployment({}, 'production', {+ ...env,+ ANALYTICS_API_TOKEN: '',+ }),+ )+ configureAnalyticsDeployment(config, 'production', {+ ANALYTICS_ACCOUNT_ID: env.ANALYTICS_ACCOUNT_ID,+ })+ assert.equal(config.analytics_engine_datasets, undefined)+})+test('browser tracker counts initial entry and path navigation once, skips query-only duplication and respects privacy', async () => {+ const hooks: Record<string, () => void> = {},+ events: any[] = []+ let path = '/',+ navigator: any = {}+ const { installVisitTracking } = await module(+ '../apps/shared/analytics/tracker.ts',+ {+ navigator,+ location: {+ origin: 'https://gallery.example',+ search: '?utm_source=campaign',+ },+ document: { referrer: 'https://search.example/' },+ fetch: async (url: string, options: any) => {+ events.push({ url, options, body: JSON.parse(options.body) })+ return new Response()+ },+ },+ )+ installVisitTracking(+ {+ hook: (name: string, f: () => void) => {+ hooks[name] = f+ },+ },+ () => path,+ )+ hooks['app:mounted']!()+ hooks['page:finish']!()+ hooks['page:finish']!()+ assert.equal(events.length, 1)+ assert.equal(events[0].options.credentials, 'omit')+ assert.equal(events[0].body.source, 'campaign')+ path = '/albums/3'+ hooks['page:finish']!()+ assert.equal(events.length, 2)+ assert.equal(events[1].body.referrer, 'https://gallery.example/')+ path = '/'+ hooks['page:finish']!()+ assert.equal(events.length, 3)+ navigator.doNotTrack = '1'+ path = '/globe'+ hooks['page:finish']!()+ assert.equal(events.length, 3)+ navigator.doNotTrack = '0'+ navigator.globalPrivacyControl = true+ hooks['page:finish']!()+ assert.equal(events.length, 3)+})