Skip to content

AI-native design editor. Open-source Figma alternative.

feat(feedback): serve the metrics dashboard's data behind Cloudflare Access (#1319)

Danila Poyarkov654d636404b2
diff --git a/bun.lock b/bun.lock
index 1d7311776..04b0f0029 100644
--- a/bun.lock
+++ b/bun.lock
@@ -422,6 +422,7 @@
"@vue-email/render": "^0.0.9",
"es-toolkit": "^1.52.0",
"hono": "^4.13.13",
+ "jose": "^6.2.8",
"kysely": "^0.29.6",
"kysely-d1": "0.4.0",
"valibot": "^1.5.0",
@@ -5111,6 +5112,7 @@
"@modelcontextprotocol/sdk/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
+
"@oxc-parser/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="],
"@oxc-resolver/binding-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q=="],
diff --git a/packages/feedback/AGENTS.md b/packages/feedback/AGENTS.md
index c9805b4fb..28f82c3ec 100644
--- a/packages/feedback/AGENTS.md
+++ b/packages/feedback/AGENTS.md
@@ -10,3 +10,4 @@ Cloudflare Worker for pings, opt-in usage stats, and the Cloud waitlist; overvie
- Bindings are declared in `src/env.ts` with importable Workers types, so the app can typecheck `FeedbackAPI`; never use the generated global `Env` in code the router reaches. Run `bun --filter @open-pencil/feedback types` after changing `wrangler.jsonc`; `src/index.ts` checks `Env` against `FeedbackBindings` and `bun run test:feedback` checks the generated file.
- Outside services (`fetch`, the clock) come through `FeedbackServices`, and bindings through `Env`, so tests run the real app against a local D1 under `bun test` (`tests/harness.ts`).
- The metrics snapshot (`src/snapshot/`) keys every table on the UTC day it describes and replaces whole days in one D1 batch (`replaceDays`), so a rerun corrects a day and a failed write keeps the old rows; it writes the table it resumes from (`site_visits`) last, runs each source on its own, and parses every answer with Valibot before writing (`tests/snapshot.test.ts`).
+- Everything under `/admin` passes `requireAccess` (`src/admin/access.ts`), which verifies Cloudflare Access's signed token against the team's keys and the application's audience even though Access already blocks others at the edge; admin answers are `private, no-store` and carry waitlist domains, never addresses (`tests/admin.test.ts`).
diff --git a/packages/feedback/README.md b/packages/feedback/README.md
index 21e2b9716..005105ac5 100644
--- a/packages/feedback/README.md
+++ b/packages/feedback/README.md
@@ -6,6 +6,7 @@ The Cloudflare Worker behind `feedback.openpencil.dev`. It is operated by the Op
| --- | --- | --- |
| `POST /ping` | The daily anonymous ping. | One counter per day and build (version, OS, architecture, desktop or web, browser family). Nothing per install, no addresses. |
| `POST /ingest` | Opt-in usage stats, forwarded to PostHog EU. Refuses any event or property not in `src/contract`. | Nothing. PostHog gets no client address, person profile, or GeoIP. |
+| `GET /admin/api/snapshot?start&end` | The metrics dashboard's data for a range of UTC days, behind Cloudflare Access. | Nothing; it reads pings, snapshots, and the waitlist from D1 (email domains only) and asks PostHog for usage. |
| `POST /waitlist` | OpenPencil Cloud waitlist sign-ups from the website and the web app's Settings, checked by Turnstile and confirmed by email. | The address and optional note; unconfirmed sign-ups are removed after seven days. |
Two daily cron jobs run besides the routes. Just after midnight UTC the metrics snapshot records the day that ended for the team's metrics dashboard: GitHub stars and forks, running download totals per release and kind of file (installers, macOS updates, and `latest.json` update checks), repository views, clones, and referrers, and Cloudflare's visits to `openpencil.dev` and `app.openpencil.dev` with the website's top pages and countries. GitHub keeps traffic for 14 days and Cloudflare's Free plan keeps visits for 31, so these tables are the only lasting history; each run also fetches again the last few days Cloudflare may still have been counting, and fills any missing days it still can. At 03:17 UTC, retention deletes unconfirmed waitlist sign-ups.
@@ -32,3 +33,5 @@ Done once on the Cloudflare account; `.github/workflows/feedback.yml` deploys ev
3. Create a Turnstile widget for `openpencil.dev` and `app.openpencil.dev`, the hostnames in `TURNSTILE_HOSTNAMES` (its public site key is `TURNSTILE_SITE_KEY` in the contract; the form gives it the `waitlist` action), then `bunx wrangler secret put TURNSTILE_SECRET`.
4. Create a PostHog EU project with "Discard client IP data" on and data retention at 12 months, as the privacy page promises, then `bunx wrangler secret put POSTHOG_KEY` with its project key.
5. For the metrics snapshot, `bunx wrangler secret put GITHUB_TOKEN` with a fine-grained token for the repository in `GITHUB_REPOSITORY` that has read-only **Administration** access, which the traffic API requires (every token can already read the public repository's releases), and `bunx wrangler secret put CLOUDFLARE_ANALYTICS_TOKEN` with an account API token that has **Zone → Analytics → Read** on the zone in `SITE_ZONE_ID`.
+6. For the dashboard's API, create a Cloudflare Access self-hosted application for `feedback.openpencil.dev/admin/*` that allows the team's addresses (add the One-time PIN login method for people without a Cloudflare account), then `bunx wrangler secret put ACCESS_TEAM_DOMAIN` with `https://<team>.cloudflareaccess.com` and `bunx wrangler secret put ACCESS_AUD` with the application's audience tag. Until both are set, `/admin` refuses every request.
+7. Create a PostHog personal API key scoped to the project in `POSTHOG_PROJECT_ID` with only **Query: Read**, then `bunx wrangler secret put POSTHOG_PERSONAL_KEY`.
diff --git a/packages/feedback/package.json b/packages/feedback/package.json
index 691846e9b..313619320 100644
--- a/packages/feedback/package.json
+++ b/packages/feedback/package.json
@@ -28,6 +28,7 @@
"@vue-email/render": "^0.0.9",
"es-toolkit": "^1.52.0",
"hono": "^4.13.13",
+ "jose": "^6.2.8",
"kysely": "^0.29.6",
"kysely-d1": "0.4.0",
"valibot": "^1.5.0",
diff --git a/packages/feedback/src/admin/access.ts b/packages/feedback/src/admin/access.ts
new file mode 100644
index 000000000..2a511d615
--- /dev/null
+++ b/packages/feedback/src/admin/access.ts
@@ -0,0 +1,57 @@
+import type { FeedbackEnv, FeedbackServices } from '#feedback/env'
+import { createMiddleware } from 'hono/factory'
+import { createLocalJWKSet, jwtVerify, type JSONWebKeySet } from 'jose'
+import * as v from 'valibot'
+
+const CERTS_TIMEOUT_MS = 10_000
+// Cloudflare rotates the signing key every six weeks and publishes the next one in advance, so
+// a short cache never misses a rotation for long.
+const CERTS_TTL_MS = 10 * 60 * 1000
+
+const CertsSchema = v.object({
+ keys: v.array(v.looseObject({ kty: v.string(), kid: v.optional(v.string()) }))
+})
+
+/**
+ * Lets a request through only with a valid Cloudflare Access token for the admin application.
+ * Access already blocks everyone else at Cloudflare's edge; checking the token here as well means
+ * a misconfigured route or a request that bypasses Access still gets nothing.
+ */
+export function requireAccess(services: FeedbackServices) {
+ let cached: { team: string; keys: JSONWebKeySet; fetchedAt: number } | undefined
+
+ async function keysFor(team: string): Promise<JSONWebKeySet> {
+ const now = services.now().getTime()
+ if (cached?.team === team && now - cached.fetchedAt < CERTS_TTL_MS) return cached.keys
+ const response = await services.fetch(`${team}/cdn-cgi/access/certs`, {
+ signal: AbortSignal.timeout(CERTS_TIMEOUT_MS)
+ })
+ if (!response.ok) throw new Error(`Access certificates answered ${response.status}`)
+ const parsed = v.safeParse(
+ v.pipe(v.string(), v.parseJson(), CertsSchema),
+ await response.text()
+ )
+ if (!parsed.success) throw new Error('Access certificates have an unexpected shape')
+ cached = { team, keys: parsed.output, fetchedAt: now }
+ return parsed.output
+ }
+
+ return createMiddleware<FeedbackEnv>(async (c, next) => {
+ const token = c.req.header('cf-access-jwt-assertion')
+ const team = c.env.ACCESS_TEAM_DOMAIN
+ if (!token || !team || !c.env.ACCESS_AUD) return c.body(null, 403)
+ try {
+ await jwtVerify(token, createLocalJWKSet(await keysFor(team)), {
+ issuer: team,
+ audience: c.env.ACCESS_AUD,
+ currentDate: services.now(),
+ // jose checks `exp` only when a token has one; Access always sets it, so one without is refused.
+ requiredClaims: ['exp']
+ })
+ } catch (error) {
+ console.warn('Admin request refused', { error: String(error) })
+ return c.body(null, 403)
+ }
+ return next()
+ })
+}
diff --git a/packages/feedback/src/admin/posthog.ts b/packages/feedback/src/admin/posthog.ts
new file mode 100644
index 000000000..effa3bc19
--- /dev/null
+++ b/packages/feedback/src/admin/posthog.ts
@@ -0,0 +1,106 @@
+import type { MetricsQuery, MetricsUsage, RankedCount } from '#feedback/contract'
+import type { FeedbackBindings, FeedbackServices } from '#feedback/env'
+import { groupBy, orderBy } from 'es-toolkit'
+import * as v from 'valibot'
+
+const QUERY_TIMEOUT_MS = 20_000
+
+const UsageRow = v.tuple([v.string(), v.string(), v.number()])
+const RetentionRow = v.tuple([v.string(), v.number(), v.number()])
+
+/**
+ * The range's days as SQL date literals. Both are validated `YYYY-MM-DD` strings by the time
+ * they get here (`MetricsQuerySchema`), so nothing else can reach the query text.
+ */
+const dayRange = ({ start, end }: MetricsQuery, column = 'toDate(timestamp)') =>
+ `${column} >= toDate('${start}') AND ${column} <= toDate('${end}')`
+
+/** Installs per day and in all, then documents, exports, and AI replies by kind. */
+function usageQuery(range: MetricsQuery) {
+ const inRange = dayRange(range)
+ const counted = (event: string, property: string) =>
+ `SELECT '${event}', toString(properties.${property}), count() FROM events WHERE event = '${event}' AND ${inRange} GROUP BY properties.${property}`
+ return [
+ `SELECT 'installs', toString(toDate(timestamp)) AS day, count(DISTINCT distinct_id) FROM events WHERE event = 'app_opened' AND ${inRange} GROUP BY day`,
+ `SELECT 'unique', '', count(DISTINCT distinct_id) FROM events WHERE event = 'app_opened' AND ${inRange}`,
+ counted('document_opened', 'format'),
+ counted('document_exported', 'format'),
+ counted('ai_reply_finished', 'provider')
+ ].join('\nUNION ALL ')
+}
+
+/** For installs first seen in the range, how many opened the app again each day after. */
+function retentionQuery(range: MetricsQuery) {
+ return `SELECT toString(f.first_day), dateDiff('day', f.first_day, toDate(e.timestamp)) AS n, count(DISTINCT e.distinct_id)
+FROM events e
+INNER JOIN (SELECT distinct_id, min(toDate(timestamp)) AS first_day FROM events WHERE event = 'app_opened' GROUP BY distinct_id) AS f ON e.distinct_id = f.distinct_id
+WHERE e.event = 'app_opened' AND ${dayRange(range, 'f.first_day')}
+GROUP BY f.first_day, n`
+}
+
+const ranked = (rows: [string, string, number][]): RankedCount[] =>
+ orderBy(
+ rows.map(([, name, value]) => ({ name: name || 'unknown', value })),
+ ['value'],
+ ['desc']
+ )
+
+/**
+ * Asks PostHog over its query API with a personal key that can only read queries. The project
+ * runs at most three queries at once, so the two run one after the other.
+ */
+export async function fetchUsage(
+ env: FeedbackBindings,
+ services: FeedbackServices,
+ range: MetricsQuery
+): Promise<MetricsUsage> {
+ async function query<T extends v.GenericSchema>(
+ sql: string,
+ row: T
+ ): Promise<v.InferOutput<T>[]> {
+ const response = await services.fetch(
+ `${env.POSTHOG_APP_HOST}/api/projects/${env.POSTHOG_PROJECT_ID}/query/`,
+ {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${env.POSTHOG_PERSONAL_KEY}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ query: { kind: 'HogQLQuery', query: sql } }),
+ signal: AbortSignal.timeout(QUERY_TIMEOUT_MS)
+ }
+ )
+ if (!response.ok) throw new Error(`PostHog answered ${response.status}`)
+ const schema = v.pipe(v.string(), v.parseJson(), v.object({ results: v.array(row) }))
+ const parsed = v.safeParse(schema, await response.text())
+ if (!parsed.success) throw new Error('PostHog sent an unexpected answer')
+ return parsed.output.results
+ }
+
+ const usage = await query(usageQuery(range), UsageRow)
+ const retention = await query(retentionQuery(range), RetentionRow)
+ // A kind with no events has no rows at all, so rows are picked by kind rather than looked up.
+ const rowsOf = (kind: string) => usage.filter(([rowKind]) => rowKind === kind)
+ const cohorts = Object.entries(groupBy(retention, ([cohort]) => cohort))
+ return {
+ installs: rowsOf('unique').at(0)?.[2] ?? 0,
+ daily: orderBy(
+ rowsOf('installs').map(([, day, installs]) => ({ day, installs })),
+ ['day'],
+ ['asc']
+ ),
+ retention: cohorts
+ .toSorted(([a], [b]) => a.localeCompare(b))
+ .map(([cohort, rows]) => {
+ const counts = new Map(rows.map(([, day, installs]) => [day, installs]))
+ const last = Math.max(...counts.keys())
+ return {
+ cohort,
+ values: Array.from({ length: last + 1 }, (_, day) => counts.get(day) ?? 0)
+ }
+ }),
+ documents: ranked(rowsOf('document_opened')),
+ exports: ranked(rowsOf('document_exported')),
+ aiProviders: ranked(rowsOf('ai_reply_finished'))
+ }
+}
diff --git a/packages/feedback/src/admin/route.ts b/packages/feedback/src/admin/route.ts
new file mode 100644
index 000000000..0125e589e
--- /dev/null
+++ b/packages/feedback/src/admin/route.ts
@@ -0,0 +1,20 @@
+import { MetricsQuerySchema } from '#feedback/contract'
+import type { FeedbackEnv, FeedbackServices } from '#feedback/env'
+import { validatedQuery } from '#feedback/http/request'
+import { Hono } from 'hono'
+
+import { requireAccess } from './access'
+import { buildSnapshot } from './snapshot'
+
+/**
+ * The metrics dashboard's API, behind Cloudflare Access. Answers are for one signed-in person,
+ * so nothing between here and the browser may keep a copy.
+ */
+export function adminRoutes(services: FeedbackServices) {
+ return new Hono<FeedbackEnv>()
+ .use('/admin/*', requireAccess(services))
+ .get('/admin/api/snapshot', validatedQuery(MetricsQuerySchema), async (c) => {
+ c.header('Cache-Control', 'private, no-store')
+ return c.json(await buildSnapshot(c.env, services, c.req.valid('query')), 200)
+ })
+}
diff --git a/packages/feedback/src/admin/snapshot.ts b/packages/feedback/src/admin/snapshot.ts
new file mode 100644
index 000000000..8f8ed88bd
--- /dev/null
+++ b/packages/feedback/src/admin/snapshot.ts
@@ -0,0 +1,314 @@
+import type { DailyGrowth, MetricsQuery, MetricsSnapshot, RankedCount } from '#feedback/contract'
+import { eachDay, utcDayOf } from '#feedback/days'
+import { createFeedbackDatabase, type FeedbackDatabase } from '#feedback/db'
+import type { FeedbackBindings, FeedbackServices } from '#feedback/env'
+import { minDate, parseDate, toZoned } from '@internationalized/date'
+import { groupBy, maxBy, sumBy } from 'es-toolkit'
+import type { Kysely } from 'kysely'
+
+import { fetchUsage } from './posthog'
+
+/** How many entries a ranking keeps. */
+const TOP = 10
+/** How many recent sign-ups the waitlist list shows. */
+const RECENT_SIGNUPS = 50
+/** The kinds of release file that are installers rather than updates or update checks. */
+const INSTALLER_KINDS = new Set(['macos-installer', 'windows-installer', 'linux-installer'])
+
+const STABLE_VERSION = /^(\d+)\.(\d+)\.(\d+)$/
+
+/** A released version's parts, or `undefined` for betas, development builds, and anything else. */
+function stableParts(version: string): [number, number, number] | undefined {
+ const match = STABLE_VERSION.exec(version)
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : undefined
+}
+
+function newestStable(versions: string[]): string | undefined {
+ return maxBy(
+ versions.filter((version) => stableParts(version)),
+ (version) => {
+ const [major = 0, minor = 0, patch = 0] = stableParts(version) ?? []
+ return major * 1e12 + minor * 1e6 + patch
+ }
+ )
+}
+
+/** Each day's increase in a running total, from the day before the range on. */
+function dailyGrowth(days: string[], totals: Map<string, number>): DailyGrowth[] {
+ return days.flatMap((day) => {
+ const total = totals.get(day)
+ const before = totals.get(parseDate(day).subtract({ days: 1 }).toString())
+ return total === undefined || before === undefined ? [] : [{ day, added: total - before }]
+ })
+}
+
+const ranking = (rows: { name: string; value: number | string | bigint | null }[]): RankedCount[] =>
+ rows.map((row) => ({ name: row.name, value: Number(row.value ?? 0) }))
+
+async function pings(db: Kysely<FeedbackDatabase>, range: MetricsQuery, days: string[]) {
+ const inRange = db
+ .selectFrom('usagePings')
+ .where('day', '>=', range.start)
+ .where('day', '<=', range.end)
+ const [byApp, byPlatform, byVersion, versions] = await Promise.all([
+ inRange
+ .select(['day', 'app', (eb) => eb.fn.sum<number>('count').as('pings')])
+ .groupBy(['day', 'app'])
+ .execute(),
+ inRange
+ .select(['platform', 'app', (eb) => eb.fn.sum<number>('count').as('pings')])
+ .groupBy(['platform', 'app'])
+ .execute(),
+ inRange
+ .select(['day', 'version', (eb) => eb.fn.sum<number>('count').as('pings')])
+ .groupBy(['day', 'version'])
+ .execute(),
+ db
+ .selectFrom('usagePings')
+ .select(['version', (eb) => eb.fn.min<string>('day').as('firstDay')])
+ .groupBy('version')
+ .execute()
+ ])
+ const latest = newestStable(versions.map((row) => row.version)) ?? null
+ const pingsOn = (rows: typeof byApp, day: string, app: string) =>
+ Number(rows.find((row) => row.day === day && row.app === app)?.pings ?? 0)
+ const platforms = Object.entries(groupBy(byPlatform, (row) => row.platform)).map(
+ ([os, rows]) => ({
+ os,
+ desktop: Number(rows.find((row) => row.app === 'desktop')?.pings ?? 0),
+ web: Number(rows.find((row) => row.app === 'web')?.pings ?? 0)
+ })
+ )
+ return {
+ dailyActive: days.map((day) => ({
+ day,
+ desktop: pingsOn(byApp, day, 'desktop'),
+ web: pingsOn(byApp, day, 'web')
+ })),
+ platforms: platforms.toSorted((a, b) => b.desktop + b.web - (a.desktop + a.web)),
+ versions: {
+ latest,
+ daily: days.map((day) => {
+ const onDay = byVersion.filter((row) => row.day === day)
+ const latestPings = Number(onDay.find((row) => row.version === latest)?.pings ?? 0)
+ return {
+ day,
+ latest: latestPings,
+ other: sumBy(onDay, (row) => Number(row.pings)) - latestPings
+ }
+ })
+ },
+ releases: versions
+ .filter(
+ (row) =>
+ stableParts(row.version) && row.firstDay >= range.start && row.firstDay <= range.end
+ )
+ .map((row) => ({ day: row.firstDay, version: row.version }))
+ .toSorted((a, b) => a.day.localeCompare(b.day))
+ }
+}
+
+async function site(
+ db: Kysely<FeedbackDatabase>,
+ env: FeedbackBindings,
+ range: MetricsQuery,
+ days: string[]
+) {
+ const [website, app] = env.SITE_HOSTS.split(',').map((host) => host.trim())
+ const [visits, pages, countries] = await Promise.all([
+ db
+ .selectFrom('siteVisits')
+ .selectAll()
+ .where('day', '>=', range.start)
+ .where('day', '<=', range.end)
+ .execute(),
+ db
+ .selectFrom('sitePages')
+ .select(['path as name', (eb) => eb.fn.sum<number>('visits').as('value')])
+ .where('day', '>=', range.start)
+ .where('day', '<=', range.end)
+ .groupBy('path')
+ .orderBy('value', 'desc')
+ .limit(TOP)
+ .execute(),
+ db
+ .selectFrom('siteCountries')
+ .select(['country as name', (eb) => eb.fn.sum<number>('visits').as('value')])
+ .where('day', '>=', range.start)
+ .where('day', '<=', range.end)
+ .groupBy('country')
+ .orderBy('value', 'desc')
+ .limit(TOP)
+ .execute()
+ ])
+ const visitsOn = (day: string, host: string | undefined) =>
+ visits.find((row) => row.day === day && row.host === host)?.visits ?? 0
+ return {
+ visits: days.map((day) => ({ day, site: visitsOn(day, website), app: visitsOn(day, app) })),
+ website: { pages: ranking(pages), countries: ranking(countries) }
+ }
+}
+
+async function github(db: Kysely<FeedbackDatabase>, range: MetricsQuery, days: string[]) {
+ // One day earlier than the range, so its first day has something to grow from.
+ const from = parseDate(range.start).subtract({ days: 1 }).toString()
+ const [stars, downloads, traffic, lastReferrerDay] = await Promise.all([
+ db
+ .selectFrom('githubStars')
+ .selectAll()
+ .where('day', '>=', from)
+ .where('day', '<=', range.end)
+ .execute(),
+ db
+ .selectFrom('releaseDownloads')
+ .selectAll()
+ .where('day', '>=', from)
+ .where('day', '<=', range.end)
+ .execute(),
+ db
+ .selectFrom('repoTraffic')
+ .selectAll()
+ .where('day', '>=', range.start)
+ .where('day', '<=', range.end)
+ .orderBy('day')
+ .execute(),
+ db
+ .selectFrom('repoReferrers')
+ .select((eb) => eb.fn.max('day').as('day'))
+ .where('day', '<=', range.end)
+ .executeTakeFirst()
+ ])
+ const referrers = lastReferrerDay?.day
+ ? await db
+ .selectFrom('repoReferrers')
+ .select(['referrer as name', 'views as value'])
+ .where('day', '=', lastReferrerDay.day)
+ .orderBy('views', 'desc')
+ .limit(TOP)
+ .execute()
+ : []
+
+ const installers = downloads.filter((row) => INSTALLER_KINDS.has(row.kind))
+ const totalsByDay = (rows: typeof downloads) =>
+ new Map(
+ Object.entries(groupBy(rows, (row) => row.day)).map(([day, onDay]) => [
+ day,
+ sumBy(onDay, (row) => row.downloads)
+ ])
+ )
+ const installerTotals = totalsByDay(installers)
+ // ISO dates sort in calendar order, as D1 compares them too.
+ const lastDay = [...installerTotals.keys()].toSorted().at(-1)
+ const latestTag = newestStable(installers.map((row) => row.tag.replace(/^v/, '')))
+ const starTotals = new Map(stars.map((row) => [row.day, row.stars]))
+ const lastStars = stars.toSorted((a, b) => a.day.localeCompare(b.day)).at(-1)
+ return {
+ stars: { total: lastStars?.stars ?? null, daily: dailyGrowth(days, starTotals) },
+ downloads: {
+ total: lastDay ? (installerTotals.get(lastDay) ?? null) : null,
+ latestTag: latestTag ? `v${latestTag}` : null,
+ latestTotal:
+ lastDay && latestTag
+ ? sumBy(
+ installers.filter((row) => row.day === lastDay && row.tag === `v${latestTag}`),
+ (row) => row.downloads
+ )
+ : null,
+ daily: dailyGrowth(days, installerTotals),
+ updateChecks: dailyGrowth(
+ days,
+ totalsByDay(downloads.filter((row) => row.kind === 'update-check'))
+ )
+ },
+ traffic: traffic.map((row) => ({
+ day: row.day,
+ views: row.views,
+ uniqueViews: row.uniqueViews,
+ clones: row.clones
+ })),
+ referrers: ranking(referrers)
+ }
+}
+
+/** The range as sign-up timestamps: from the start day's UTC midnight up to the day after the end. */
+function timestampRange(range: MetricsQuery) {
+ const midnight = (day: string) => toZoned(parseDate(day), 'UTC').toDate().toISOString()
+ return {
+ from: midnight(range.start),
+ until: midnight(parseDate(range.end).add({ days: 1 }).toString())
+ }
+}
+
+async function waitlist(db: Kysely<FeedbackDatabase>, range: MetricsQuery) {
+ const { from, until } = timestampRange(range)
+ const [totals, recent] = await Promise.all([
+ db
+ .selectFrom('waitlist')
+ .select((eb) => [
+ eb.fn.countAll<number>().as('total'),
+ eb.fn.count<number>('confirmedAt').as('confirmed'),
+ eb.fn
+ .countAll<number>()
+ .filterWhere('createdAt', '>=', from)
+ .filterWhere('createdAt', '<', until)
+ .as('added')
+ ])
+ .executeTakeFirst(),
+ db
+ .selectFrom('waitlist')
+ .select(['email', 'createdAt', 'confirmedAt'])
+ .where('createdAt', '>=', from)
+ .where('createdAt', '<', until)
+ .orderBy('createdAt', 'desc')
+ .limit(RECENT_SIGNUPS)
+ .execute()
+ ])
+ return {
+ total: Number(totals?.total ?? 0),
+ confirmed: Number(totals?.confirmed ?? 0),
+ added: Number(totals?.added ?? 0),
+ // Only the domain leaves the database; the address itself never reaches the dashboard.
+ recent: recent.map((row) => ({
+ domain: row.email.slice(row.email.lastIndexOf('@') + 1).toLowerCase(),
+ signedUpAt: row.createdAt,
+ confirmed: row.confirmedAt !== null
+ }))
+ }
+}
+
+/**
+ * The dashboard's data for a range of UTC days: pings, snapshots, and the waitlist from D1, and
+ * usage from PostHog. PostHog failing leaves `usage` empty rather than failing the whole page.
+ */
+export async function buildSnapshot(
+ env: FeedbackBindings,
+ services: FeedbackServices,
+ query: MetricsQuery
+): Promise<MetricsSnapshot> {
+ const now = services.now()
+ const today = utcDayOf(now)
+ const end = minDate(parseDate(query.end), today) ?? today
+ const range = { start: query.start, end: end.toString() }
+ const days = eachDay(parseDate(range.start), end).map(String)
+ const db = createFeedbackDatabase(env.DB)
+ const [pinged, visited, repository, signups, usage] = await Promise.all([
+ pings(db, range, days),
+ site(db, env, range, days),
+ github(db, range, days),
+ waitlist(db, range),
+ fetchUsage(env, services, range).catch((error: unknown) => {
+ console.warn('PostHog usage unavailable', { error: String(error) })
+ return null
+ })
+ ])
+ return {
+ asOf: now.toISOString(),
+ today: today.toString(),
+ ...range,
+ ...pinged,
+ ...visited,
+ github: repository,
+ waitlist: signups,
+ usage
+ }
+}
diff --git a/packages/feedback/src/app.ts b/packages/feedback/src/app.ts
index 5ba6556a6..af7364fd7 100644
--- a/packages/feedback/src/app.ts
+++ b/packages/feedback/src/app.ts
@@ -1,6 +1,7 @@
import { Hono } from 'hono'
import { bodyLimit } from 'hono/body-limit'
+import { adminRoutes } from './admin/route'
import type { FeedbackEnv, FeedbackServices } from './env'
import { allowOpenPencilOrigins } from './http/cors'
import { ingestRoutes } from './ingest/route'
@@ -24,6 +25,7 @@ export function createFeedbackApp(services: FeedbackServices = defaultServices)
.route('/', pingRoutes(services))
.route('/', ingestRoutes(services))
.route('/', waitlistRoutes(services))
+ .route('/', adminRoutes(services))
}
/** The service's routes and request bodies, for `hc<FeedbackAPI>` clients. */
diff --git a/packages/feedback/src/contract/index.ts b/packages/feedback/src/contract/index.ts
index 7274ec306..2304087b6 100644
--- a/packages/feedback/src/contract/index.ts
+++ b/packages/feedback/src/contract/index.ts
@@ -1,3 +1,4 @@
export * from './schema'
export { describeBuildFields, describePingFields, describeUsageEvents } from './describe'
export type { FieldDescription, UsageEventDescription } from './describe'
+export * from './metrics'
diff --git a/packages/feedback/src/contract/metrics.ts b/packages/feedback/src/contract/metrics.ts
new file mode 100644
index 000000000..354013ea3
--- /dev/null
+++ b/packages/feedback/src/contract/metrics.ts
@@ -0,0 +1,116 @@
+import { type CalendarDate, parseDate } from '@internationalized/date'
+import * as v from 'valibot'
+
+/** The longest range one request covers; a year and a bit leaves room for "all time" for now. */
+export const MAX_METRICS_RANGE_DAYS = 400
+
+/** The day a `YYYY-MM-DD` string names, or `undefined` for one that does not exist (`2026-02-30`). */
+function calendarDay(day: string): CalendarDate | undefined {
+ try {
+ return parseDate(day)
+ } catch {
+ return undefined
+ }
+}
+
+// `isoDate` checks only the shape, so `2026-02-30` would pass without the calendar check.
+const IsoDay = v.pipe(
+ v.string(),
+ v.isoDate(),
+ v.check((day) => calendarDay(day) !== undefined, 'Not a calendar day.')
+)
+
+/**
+ * Days from `start` to `end`. Valibot runs the range checks even when a day failed its own
+ * check, so an impossible day counts as no span and only its own issue is reported.
+ */
+function span({ start, end }: { start: string; end: string }): number {
+ const from = calendarDay(start)
+ const to = calendarDay(end)
+ return from && to ? to.compare(from) : 0
+}
+
+/** The UTC days the dashboard asks about, both included. */
+export const MetricsQuerySchema = v.pipe(
+ v.object({ start: IsoDay, end: IsoDay }),
+ v.check((range) => span(range) >= 0, 'The range ends before it starts.'),
+ v.check((range) => span(range) < MAX_METRICS_RANGE_DAYS, 'The range is too long.')
+)
+
+export type MetricsQuery = v.InferOutput<typeof MetricsQuerySchema>
+
+// The answer is described once, as schemas: the Worker builds values of their types, and the
+// dashboard parses the network answer with them before using it.
+const Count = v.pipe(v.number(), v.minValue(0))
+
+const RankedCountSchema = v.object({ name: v.string(), value: Count })
+export type RankedCount = v.InferOutput<typeof RankedCountSchema>
+
+const DailyGrowthSchema = v.object({ day: IsoDay, added: v.number() })
+export type DailyGrowth = v.InferOutput<typeof DailyGrowthSchema>
+
+/** What PostHog knows about the installs that share usage stats; `null` when it could not be asked. */
+const MetricsUsageSchema = v.object({
+ /** Different installs that opened the app in the range. */
+ installs: Count,
+ daily: v.array(v.object({ day: IsoDay, installs: Count })),
+ /** Per first day: index 0 is how many installs started then, index n how many came back n days later. */
+ retention: v.array(v.object({ cohort: IsoDay, values: v.array(Count) })),
+ documents: v.array(RankedCountSchema),
+ exports: v.array(RankedCountSchema),
+ aiProviders: v.array(RankedCountSchema)
+})
+export type MetricsUsage = v.InferOutput<typeof MetricsUsageSchema>
+
+/**
+ * Everything the metrics dashboard shows for a range of UTC days. Days are ISO dates; `today`
+ * is still being counted, and snapshot-based numbers only reach the last finished day.
+ */
+export const MetricsSnapshotSchema = v.object({
+ asOf: v.pipe(v.string(), v.isoTimestamp()),
+ today: IsoDay,
+ start: IsoDay,
+ end: IsoDay,
+ /** Installs that pinged each day, by desktop and web. */
+ dailyActive: v.array(v.object({ day: IsoDay, desktop: Count, web: Count })),
+ /** Pings in the range by OS, desktop and web. */
+ platforms: v.array(v.object({ os: v.string(), desktop: Count, web: Count })),
+ /** Pings each day on the newest stable version and on everything else. */
+ versions: v.object({
+ latest: v.nullable(v.string()),
+ daily: v.array(v.object({ day: IsoDay, latest: Count, other: Count }))
+ }),
+ /** The first day each stable version sent a ping, within the range. */
+ releases: v.array(v.object({ day: IsoDay, version: v.string() })),
+ /** Cloudflare visits each day to the website and to the web app. */
+ visits: v.array(v.object({ day: IsoDay, site: Count, app: Count })),
+ website: v.object({ pages: v.array(RankedCountSchema), countries: v.array(RankedCountSchema) }),
+ github: v.object({
+ stars: v.object({ total: v.nullable(Count), daily: v.array(DailyGrowthSchema) }),
+ /** Installer downloads across every release, and update checks from running desktop apps. */
+ downloads: v.object({
+ total: v.nullable(Count),
+ latestTag: v.nullable(v.string()),
+ latestTotal: v.nullable(Count),
+ daily: v.array(DailyGrowthSchema),
+ updateChecks: v.array(DailyGrowthSchema)
+ }),
+ traffic: v.array(v.object({ day: IsoDay, views: Count, uniqueViews: Count, clones: Count })),
+ referrers: v.array(RankedCountSchema)
+ }),
+ waitlist: v.object({
+ total: Count,
+ confirmed: Count,
+ added: Count,
+ /** Newest first, by email domain only. */
+ recent: v.array(
+ v.object({
+ domain: v.string(),
+ signedUpAt: v.pipe(v.string(), v.isoTimestamp()),
+ confirmed: v.boolean()
+ })
+ )
+ }),
+ usage: v.nullable(MetricsUsageSchema)
+})
+export type MetricsSnapshot = v.InferOutput<typeof MetricsSnapshotSchema>
diff --git a/packages/feedback/src/env.ts b/packages/feedback/src/env.ts
index e60e7abe1..3d46000d5 100644
--- a/packages/feedback/src/env.ts
+++ b/packages/feedback/src/env.ts
@@ -28,6 +28,15 @@ export interface FeedbackBindings {
SITE_HOSTS: string
/** A Cloudflare API token that can read the zone's analytics. */
CLOUDFLARE_ANALYTICS_TOKEN: string
+ /** The Zero Trust team domain that issues Access tokens, `https://<team>.cloudflareaccess.com`. */
+ ACCESS_TEAM_DOMAIN: string
+ /** The Access application's audience tag; a token for any other application is refused. */
+ ACCESS_AUD: string
+ /** PostHog's app host for its query API, which is not the ingestion host. */
+ POSTHOG_APP_HOST: string
+ POSTHOG_PROJECT_ID: string
+ /** A PostHog personal API key limited to reading queries in that project. */
+ POSTHOG_PERSONAL_KEY: string
}
export type FeedbackEnv = { Bindings: FeedbackBindings }
diff --git a/packages/feedback/src/http/request.ts b/packages/feedback/src/http/request.ts
index 4a802a3de..d182db315 100644
--- a/packages/feedback/src/http/request.ts
+++ b/packages/feedback/src/http/request.ts
@@ -14,6 +14,14 @@ export function validatedJSON<TSchema extends v.GenericSchema>(schema: TSchema)
})
}
+/** The query string parsed with `schema`; a missing or malformed parameter gets a 400. */
+export function validatedQuery<TSchema extends v.GenericSchema>(schema: TSchema) {
+ return validator('query', (value, c) => {
+ const parsed = v.safeParse(schema, value)
+ return parsed.success ? parsed.output : c.body(null, 400)
+ })
+}
+
/**
* Counts the request against a rate limit, keyed by the client address Cloudflare reports. The
* address lives only in the limiter's memory; nothing here stores or forwards it.
diff --git a/packages/feedback/tests/admin.test.ts b/packages/feedback/tests/admin.test.ts
new file mode 100644
index 000000000..0a4c65787
--- /dev/null
+++ b/packages/feedback/tests/admin.test.ts
@@ -0,0 +1,401 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test'
+
+import { createTestService, type TestService } from '#feedback-tests/harness'
+import { MetricsSnapshotSchema, type MetricsSnapshot } from '#feedback/contract'
+import { createFeedbackDatabase } from '#feedback/db'
+import { exportJWK, generateKeyPair, SignJWT, type CryptoKey } from 'jose'
+import * as v from 'valibot'
+
+let service: TestService
+let signingKey: CryptoKey
+let strangerKey: CryptoKey
+
+const TEAM = 'https://openpencil.cloudflareaccess.com'
+const AUDIENCE = 'admin-audience'
+const POSTHOG_QUERY = 'https://eu.posthog.com/api/projects/267806/query/'
+const NOW = new Date('2026-10-20T12:00:00.000Z')
+const TABLES = [
+ 'usagePings',
+ 'waitlist',
+ 'githubStars',
+ 'releaseDownloads',
+ 'repoTraffic',
+ 'repoReferrers',
+ 'siteVisits',
+ 'sitePages',
+ 'siteCountries'
+] as const
+
+/** An Access token as Cloudflare would issue it, signed with `key`; `expiresIn` null leaves `exp` out. */
+function accessToken(
+ key: CryptoKey,
+ claims: { aud?: string; iss?: string; expiresIn?: number | null } = {}
+) {
+ const seconds = Math.floor(NOW.getTime() / 1000)
+ const token = new SignJWT({ email: '[email protected]' })
+ .setProtectedHeader({ alg: 'RS256', kid: 'current' })
+ .setIssuer(claims.iss ?? TEAM)
+ .setAudience(claims.aud ?? AUDIENCE)
+ .setIssuedAt(seconds - 7200)
+ const expiresIn = claims.expiresIn === undefined ? 3600 : claims.expiresIn
+ return (expiresIn === null ? token : token.setExpirationTime(seconds + expiresIn)).sign(key)
+}
+
+async function getSnapshot(query: string, token?: string) {
+ return service.request(`/admin/api/snapshot?${query}`, {
+ headers: token ? { 'cf-access-jwt-assertion': token } : {}
+ })
+}
+
+/** The snapshot through the typed client, as the dashboard asks for it. */
+async function snapshot(start = '2026-10-14', end = '2026-10-20'): Promise<MetricsSnapshot> {
+ const response = await service.client.admin.api.snapshot.$get(
+ { query: { start, end } },
+ { headers: { 'cf-access-jwt-assertion': await accessToken(signingKey) } }
+ )
+ if (response.status !== 200) throw new Error(`The snapshot answered ${response.status}`)
+ return response.json()
+}
+
+/** The service's D1 through the same typed Kysely the Worker uses. */
+const database = () => createFeedbackDatabase(service.db)
+
+/** A day's pings from one build, as the ping route counts them. */
+function ping(
+ day: string,
+ build: { version?: string; platform: string; arch?: string; app: string; browser?: string },
+ count: number
+) {
+ return database()
+ .insertInto('usagePings')
+ .values({
+ day,
+ version: build.version ?? '0.16.0',
+ platform: build.platform,
+ arch: build.arch ?? 'arm64',
+ app: build.app,
+ browser: build.browser ?? 'unknown',
+ usageStats: 'unset',
+ count
+ })
+ .execute()
+}
+
+/** PostHog answers the usage query, then the retention query. */
+function answerPostHog() {
+ service.respond(POSTHOG_QUERY, (call) => {
+ const body = String(call.init?.body)
+ if (body.includes('INNER JOIN'))
+ return Response.json({
+ results: [
+ ['2026-10-14', 0, 28],
+ ['2026-10-14', 1, 9],
+ ['2026-10-14', 3, 3],
+ ['2026-10-15', 0, 59]
+ ]
+ })
+ return Response.json({
+ results: [
+ ['installs', '2026-10-15', 68],
+ ['installs', '2026-10-14', 30],
+ ['unique', '', 216],
+ ['document_opened', 'fig', 496],
+ ['document_opened', 'pen', 19],
+ ['ai_reply_finished', 'openrouter', 22],
+ ['ai_reply_finished', 'openai-compatible', 85]
+ ]
+ })
+ })
+}
+
+beforeAll(async () => {
+ service = await createTestService()
+ const current = await generateKeyPair('RS256')
+ signingKey = current.privateKey
+ strangerKey = (await generateKeyPair('RS256')).privateKey
+ const publicKey = { ...(await exportJWK(current.publicKey)), kid: 'current', alg: 'RS256' }
+ service.respond(`${TEAM}/cdn-cgi/access/certs`, () => Response.json({ keys: [publicKey] }))
+})
+
+beforeEach(async () => {
+ for (const table of TABLES) await database().deleteFrom(table).execute()
+ service.setNow(NOW)
+ answerPostHog()
+})
+
+afterAll(async () => {
+ await service.dispose()
+})
+
+describe('admin access', () => {
+ test('refuses a request without an Access token', async () => {
+ expect((await getSnapshot('start=2026-10-14&end=2026-10-20')).status).toBe(403)
+ })
+
+ test('refuses a token Cloudflare did not sign', async () => {
+ const token = await accessToken(strangerKey)
+ expect((await getSnapshot('start=2026-10-14&end=2026-10-20', token)).status).toBe(403)
+ })
+
+ test('refuses a token for another Access application or team', async () => {
+ const otherApp = await accessToken(signingKey, { aud: 'another-app' })
+ const otherTeam = await accessToken(signingKey, {
+ iss: 'https://elsewhere.cloudflareaccess.com'
+ })
+ expect((await getSnapshot('start=2026-10-14&end=2026-10-20', otherApp)).status).toBe(403)
+ expect((await getSnapshot('start=2026-10-14&end=2026-10-20', otherTeam)).status).toBe(403)
+ })
+
+ test('refuses an expired token and one that never expires', async () => {
+ const expired = await accessToken(signingKey, { expiresIn: -60 })
+ const endless = await accessToken(signingKey, { expiresIn: null })
+ expect((await getSnapshot('start=2026-10-14&end=2026-10-20', expired)).status).toBe(403)
+ expect((await getSnapshot('start=2026-10-14&end=2026-10-20', endless)).status).toBe(403)
+ })
+
+ test('refuses everyone while Access is not configured', async () => {
+ const audience = service.env.ACCESS_AUD
+ service.env.ACCESS_AUD = ''
+ try {
+ const token = await accessToken(signingKey)
+ expect((await getSnapshot('start=2026-10-14&end=2026-10-20', token)).status).toBe(403)
+ } finally {
+ service.env.ACCESS_AUD = audience
+ }
+ })
+
+ test('answers a signed-in request without letting caches keep it', async () => {
+ const response = await getSnapshot(
+ 'start=2026-10-14&end=2026-10-20',
+ await accessToken(signingKey)
+ )
+ expect(response.status).toBe(200)
+ expect(response.headers.get('Cache-Control')).toBe('private, no-store')
+ })
+
+ test('rejects a missing, malformed, or reversed range', async () => {
+ const token = await accessToken(signingKey)
+ for (const query of [
+ 'start=2026-02-30&end=2026-03-02',
+ 'start=2026-10-14',
+ 'start=yesterday&end=2026-10-20',
+ 'start=2026-10-20&end=2026-10-14'
+ ])
+ expect((await getSnapshot(query, token)).status).toBe(400)
+ })
+})
+
+describe('metrics snapshot API', () => {
+ test('daily active installs cover every day, with no pings counting as zero', async () => {
+ await ping('2026-10-15', { platform: 'macos', app: 'desktop' }, 400)
+ await ping(
+ '2026-10-15',
+ { platform: 'windows', arch: 'x64', app: 'web', browser: 'chrome' },
+ 300
+ )
+ const { dailyActive } = await snapshot('2026-10-14', '2026-10-16')
+ expect(dailyActive).toEqual([
+ { day: '2026-10-14', desktop: 0, web: 0 },
+ { day: '2026-10-15', desktop: 400, web: 300 },
+ { day: '2026-10-16', desktop: 0, web: 0 }
+ ])
+ })
+
+ test('an end after today stops at today', async () => {
+ const result = await snapshot('2026-10-19', '2026-12-31')
+ expect(result.end).toBe('2026-10-20')
+ expect(result.dailyActive.map((day) => day.day)).toEqual(['2026-10-19', '2026-10-20'])
+ })
+
+ test('versions split the newest stable release from the rest and mark its first day', async () => {
+ for (const [day, version, count] of [
+ ['2026-10-13', '0.16.0-beta.3', 4],
+ ['2026-10-14', '0.15.1', 2],
+ ['2026-10-14', '0.16.0', 354],
+ ['2026-10-14', '0.16.0-beta.2', 9],
+ ['2026-10-15', '0.0.0-smoke', 1]
+ ] as const)
+ await ping(day, { version, platform: 'macos', app: 'desktop' }, count)
+ const { versions, releases } = await snapshot('2026-10-14', '2026-10-15')
+ expect(versions.latest).toBe('0.16.0')
+ expect(versions.daily).toEqual([
+ { day: '2026-10-14', latest: 354, other: 11 },
+ { day: '2026-10-15', latest: 0, other: 1 }
+ ])
+ expect(releases).toEqual([
+ { day: '2026-10-14', version: '0.15.1' },
+ { day: '2026-10-14', version: '0.16.0' }
+ ])
+ })
+
+ test('platforms add desktop and web per OS, largest first', async () => {
+ await ping('2026-10-15', { platform: 'linux', arch: 'x64', app: 'web', browser: 'firefox' }, 5)
+ await ping('2026-10-15', { platform: 'macos', app: 'desktop' }, 9)
+ await ping('2026-10-16', { platform: 'macos', app: 'web', browser: 'safari' }, 3)
+ expect((await snapshot()).platforms).toEqual([
+ { os: 'macos', desktop: 9, web: 3 },
+ { os: 'linux', desktop: 0, web: 5 }
+ ])
+ })
+
+ test('downloads and stars grow by the difference between end-of-day totals', async () => {
+ await database()
+ .insertInto('githubStars')
+ .values([
+ { day: '2026-10-13', stars: 9000, forks: 900 },
+ { day: '2026-10-14', stars: 9030, forks: 905 },
+ { day: '2026-10-15', stars: 9068, forks: 910 }
+ ])
+ .execute()
+ await database()
+ .insertInto('releaseDownloads')
+ .values([
+ { day: '2026-10-13', tag: 'v0.15.1', kind: 'windows-installer', downloads: 2000 },
+ { day: '2026-10-13', tag: 'v0.15.1', kind: 'update-check', downloads: 15000 },
+ { day: '2026-10-14', tag: 'v0.15.1', kind: 'windows-installer', downloads: 2010 },
+ { day: '2026-10-14', tag: 'v0.16.0', kind: 'macos-installer', downloads: 100 },
+ { day: '2026-10-14', tag: 'v0.16.0', kind: 'update-check', downloads: 1110 },
+ { day: '2026-10-14', tag: 'v0.15.1', kind: 'update-check', downloads: 15400 }
+ ])
+ .execute()
+ const { github } = await snapshot('2026-10-14', '2026-10-15')
+ expect(github.stars).toEqual({
+ total: 9068,
+ daily: [
+ { day: '2026-10-14', added: 30 },
+ { day: '2026-10-15', added: 38 }
+ ]
+ })
+ expect(github.downloads).toEqual({
+ total: 2110,
+ latestTag: 'v0.16.0',
+ latestTotal: 100,
+ daily: [{ day: '2026-10-14', added: 110 }],
+ updateChecks: [{ day: '2026-10-14', added: 1510 }]
+ })
+ })
+
+ test('visits pivot to the website and the web app, and rankings add up the range', async () => {
+ await database()
+ .insertInto('siteVisits')
+ .values([
+ { day: '2026-10-14', host: 'openpencil.dev', visits: 3884 },
+ { day: '2026-10-14', host: 'app.openpencil.dev', visits: 729 }
+ ])
+ .execute()
+ await database()
+ .insertInto('sitePages')
+ .values([
+ { day: '2026-10-14', path: '/', visits: 900 },
+ { day: '2026-10-15', path: '/', visits: 1000 },
+ { day: '2026-10-15', path: '/download', visits: 80 }
+ ])
+ .execute()
+ await database()
+ .insertInto('siteCountries')
+ .values([
+ { day: '2026-10-14', country: 'US', visits: 800 },
+ { day: '2026-10-15', country: 'CN', visits: 200 }
+ ])
+ .execute()
+ const result = await snapshot('2026-10-14', '2026-10-15')
+ expect(result.visits).toEqual([
+ { day: '2026-10-14', site: 3884, app: 729 },
+ { day: '2026-10-15', site: 0, app: 0 }
+ ])
+ expect(result.website).toEqual({
+ pages: [
+ { name: '/', value: 1900 },
+ { name: '/download', value: 80 }
+ ],
+ countries: [
+ { name: 'US', value: 800 },
+ { name: 'CN', value: 200 }
+ ]
+ })
+ })
+
+ test('the waitlist shows email domains only', async () => {
+ await database()
+ .insertInto('waitlist')
+ .values([
+ {
+ email: '[email protected]',
+ emailKey: '[email protected]',
+ note: null,
+ token: 't1',
+ createdAt: '2026-10-15T08:00:00.000Z',
+ confirmationSentAt: '2026-10-15T08:00:00.000Z',
+ confirmedAt: '2026-10-15T08:01:00.000Z'
+ },
+ {
+ email: '[email protected]',
+ emailKey: '[email protected]',
+ note: 'note',
+ token: 't2',
+ createdAt: '2026-10-01T08:00:00.000Z',
+ confirmationSentAt: '2026-10-01T08:00:00.000Z',
+ confirmedAt: null
+ }
+ ])
+ .execute()
+ const { waitlist } = await snapshot()
+ expect(waitlist).toEqual({
+ total: 2,
+ confirmed: 1,
+ added: 1,
+ recent: [{ domain: 'example.com', signedUpAt: '2026-10-15T08:00:00.000Z', confirmed: true }]
+ })
+ expect(JSON.stringify(waitlist)).not.toContain('@')
+ })
+
+ test('usage comes from PostHog with a read-only personal key', async () => {
+ const { usage } = await snapshot()
+ expect(usage).toEqual({
+ installs: 216,
+ daily: [
+ { day: '2026-10-14', installs: 30 },
+ { day: '2026-10-15', installs: 68 }
+ ],
+ retention: [
+ { cohort: '2026-10-14', values: [28, 9, 0, 3] },
+ { cohort: '2026-10-15', values: [59] }
+ ],
+ documents: [
+ { name: 'fig', value: 496 },
+ { name: 'pen', value: 19 }
+ ],
+ exports: [],
+ aiProviders: [
+ { name: 'openai-compatible', value: 85 },
+ { name: 'openrouter', value: 22 }
+ ]
+ })
+ const call = service.fetchCalls.findLast((candidate) => candidate.url === POSTHOG_QUERY)
+ expect(new Headers(call?.init?.headers).get('Authorization')).toBe('Bearer phx_test')
+ })
+
+ test('the answer matches the schema the dashboard parses it with', async () => {
+ await ping('2026-10-15', { platform: 'macos', app: 'desktop' }, 400)
+ await database()
+ .insertInto('siteVisits')
+ .values({ day: '2026-10-15', host: 'openpencil.dev', visits: 3000 })
+ .execute()
+ const response = await getSnapshot(
+ 'start=2026-10-14&end=2026-10-20',
+ await accessToken(signingKey)
+ )
+ const parsed = v.safeParse(
+ v.pipe(v.string(), v.parseJson(), MetricsSnapshotSchema),
+ await response.text()
+ )
+ expect(parsed.issues).toBeUndefined()
+ })
+
+ test('PostHog failing leaves usage empty and the rest of the page intact', async () => {
+ service.respond(POSTHOG_QUERY, () => new Response('busy', { status: 503 }))
+ const result = await snapshot()
+ expect(result.usage).toBeNull()
+ expect(result.dailyActive).toHaveLength(7)
+ })
+})
diff --git a/packages/feedback/tests/harness.ts b/packages/feedback/tests/harness.ts
index 56b8106ba..15ab55685 100644
--- a/packages/feedback/tests/harness.ts
+++ b/packages/feedback/tests/harness.ts
@@ -64,6 +64,9 @@ export async function createTestService() {
EMAIL_FROM: '[email protected]',
GITHUB_TOKEN: 'github-token',
CLOUDFLARE_ANALYTICS_TOKEN: 'cloudflare-token',
+ ACCESS_TEAM_DOMAIN: 'https://openpencil.cloudflareaccess.com',
+ ACCESS_AUD: 'admin-audience',
+ POSTHOG_PERSONAL_KEY: 'phx_test',
PING_LIMITER: limiters.ping,
INGEST_LIMITER: limiters.ingest,
WAITLIST_LIMITER: limiters.waitlist,
diff --git a/packages/feedback/worker-configuration.d.ts b/packages/feedback/worker-configuration.d.ts
index 8b3dd086a..0c2b20b68 100644
--- a/packages/feedback/worker-configuration.d.ts
+++ b/packages/feedback/worker-configuration.d.ts
@@ -1,5 +1,5 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --include-runtime=false` (hash: 160eb360e2ef5a7cbd4000dba7fe6462)
+// Generated by Wrangler by running `wrangler types --include-runtime=false` (hash: e85d17de9348939f8b2316b62003069d)
interface __BaseEnv_Env {
DB: D1Database;
EMAIL: SendEmail;
@@ -12,10 +12,15 @@ interface __BaseEnv_Env {
GITHUB_REPOSITORY: "open-pencil/open-pencil";
SITE_ZONE_ID: "6a1c3366d17c9cdefab66cf5dd4e1cbe";
SITE_HOSTS: "openpencil.dev,app.openpencil.dev";
+ POSTHOG_APP_HOST: "https://eu.posthog.com";
+ POSTHOG_PROJECT_ID: "267806";
POSTHOG_KEY: string;
TURNSTILE_SECRET: string;
GITHUB_TOKEN: string;
CLOUDFLARE_ANALYTICS_TOKEN: string;
+ POSTHOG_PERSONAL_KEY: string;
+ ACCESS_TEAM_DOMAIN: string;
+ ACCESS_AUD: string;
}
declare namespace Cloudflare {
interface GlobalProps {
@@ -28,7 +33,7 @@ type StringifyValues<EnvType extends Record<string, unknown>> = {
[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
};
declare namespace NodeJS {
- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "POSTHOG_HOST" | "EMAIL_FROM" | "TURNSTILE_HOSTNAMES" | "GITHUB_REPOSITORY" | "SITE_ZONE_ID" | "SITE_HOSTS" | "POSTHOG_KEY" | "TURNSTILE_SECRET" | "GITHUB_TOKEN" | "CLOUDFLARE_ANALYTICS_TOKEN">> {}
+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "POSTHOG_HOST" | "EMAIL_FROM" | "TURNSTILE_HOSTNAMES" | "GITHUB_REPOSITORY" | "SITE_ZONE_ID" | "SITE_HOSTS" | "POSTHOG_APP_HOST" | "POSTHOG_PROJECT_ID" | "POSTHOG_KEY" | "TURNSTILE_SECRET" | "GITHUB_TOKEN" | "CLOUDFLARE_ANALYTICS_TOKEN" | "POSTHOG_PERSONAL_KEY" | "ACCESS_TEAM_DOMAIN" | "ACCESS_AUD">> {}
}
declare module "*.txt" {
const value: string;
diff --git a/packages/feedback/wrangler.jsonc b/packages/feedback/wrangler.jsonc
index 6019f4b75..ff2d623d8 100644
--- a/packages/feedback/wrangler.jsonc
+++ b/packages/feedback/wrangler.jsonc
@@ -15,7 +15,10 @@
// and Cloudflare's visits to these hostnames in the openpencil.dev zone.
"GITHUB_REPOSITORY": "open-pencil/open-pencil",
"SITE_ZONE_ID": "6a1c3366d17c9cdefab66cf5dd4e1cbe",
- "SITE_HOSTS": "openpencil.dev,app.openpencil.dev"
+ "SITE_HOSTS": "openpencil.dev,app.openpencil.dev",
+ // The PostHog project the metrics dashboard's usage numbers come from.
+ "POSTHOG_APP_HOST": "https://eu.posthog.com",
+ "POSTHOG_PROJECT_ID": "267806"
},
// Created with `wrangler d1 create feedback --jurisdiction eu`, so rows stay in the EU.
"d1_databases": [
@@ -37,6 +40,15 @@
"triggers": { "crons": ["5 0 * * *", "17 3 * * *"] },
// Set with `wrangler secret put`; locally from `.dev.vars` (see `.dev.vars.example`).
"secrets": {
- "required": ["POSTHOG_KEY", "TURNSTILE_SECRET", "GITHUB_TOKEN", "CLOUDFLARE_ANALYTICS_TOKEN"]
+ "required": [
+ "POSTHOG_KEY",
+ "TURNSTILE_SECRET",
+ "GITHUB_TOKEN",
+ "CLOUDFLARE_ANALYTICS_TOKEN",
+ "POSTHOG_PERSONAL_KEY",
+ // Not secret, but set per deployment once the Access application in front of /admin exists.
+ "ACCESS_TEAM_DOMAIN",
+ "ACCESS_AUD"
+ ]
}
}