Files
OpenFrame/tests/unit/lib/analytics-channel.test.ts
T
yusufipk 33c845636c fix(analytics): sign the acquisition cookies and bound what they can write
Both cookies were read straight into database columns after nothing more than a
format check. httpOnly keeps JavaScript out of them and does nothing about curl,
so the anonymous id was a string the caller picked: enough to write a first-touch
row for a visitor who never existed, to file it under a channel of their
choosing, and to claim that id's events at signup, since the backfill matches on
the id alone.

They are now signed with an HMAC over AUTH_SECRET, through Web Crypto rather than
node:crypto because the proxy runs on the edge and the pages that read the
cookies back run in Node. The first-touch body moved to base64url on the way:
cookie values are percent-encoded and decoded by several layers that do not agree
on how many times, and a payload carrying its own percent escapes comes back
subtly different and takes the signature with it.

Signing stops a caller choosing an id, not collecting one, since dropping the
cookie and asking for the landing page again mints another. So the bot and
prefetch filters moved to where the rows are written rather than only where the
cookies are issued, which also fixes a returning visitor's prefetch of /register
recording a signup start, and a per-client hourly ceiling now sits in front of
the write. The ceiling is skipped when TRUSTED_PROXY_MODE is unset, where every
caller resolves to 127.0.0.1 and the bucket would empty on real traffic long
before it emptied on a flood.

Four smaller things around it:

- /api/events checked the flag and the origin after paying for a rate-limit
  write, so a host who never turned analytics on was still writing a row per
  anonymous POST. Both checks are free and now come first, and the limiter
  answers 204 rather than 429: a beacon has nobody to tell, and a flooder should
  not be handed the reset time.
- /api/onboarding/source was keyed by IP on an authenticated route. Without
  TRUSTED_PROXY_MODE that is five answers an hour for the whole deployment, and
  with it a shared office address locks out everyone after one colleague
  answered. Keyed by account, like /api/onboarding/complete beside it.
- The cookies took their Secure flag from request.nextUrl.protocol, which behind
  a TLS-terminating reverse proxy is the container-internal http address. It
  comes off the configured public origin now.
- sanitizeLandingPath took anything that started with a slash, including from the
  cookie, so a hand-written one could put newlines and markup into a column an
  admin table may render one day.

Also: the paid-account query had no LIMIT and returned every active account's
name and email, the growth route answered 403 where it meant 401, and the schema
claimed no free text is stored when self_reported_note holds 200 characters of it.
2026-08-01 20:29:28 +03:00

145 lines
5.6 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import {
classifyChannel,
extractReferrerHost,
normalizeHost,
sanitizeLandingPath,
sanitizeTag,
} from '@/lib/analytics/channel';
// Every expected value below is written by hand. Deriving them from the lookup
// tables in the module would mean deleting an entry from a table also deletes
// its own test case.
describe('sanitizeTag', () => {
it('lowercases and trims', () => {
expect(sanitizeTag(' GitHub ')).toBe('github');
});
it('rejects a tag carrying markup or control characters', () => {
expect(sanitizeTag('<script>')).toBeNull();
expect(sanitizeTag('news\nletter')).toBeNull();
});
it('caps the length at 64 characters', () => {
expect(sanitizeTag('a'.repeat(200))).toHaveLength(64);
});
it('treats an empty or non-string value as absent', () => {
expect(sanitizeTag(' ')).toBeNull();
expect(sanitizeTag(null)).toBeNull();
expect(sanitizeTag(undefined)).toBeNull();
});
});
describe('normalizeHost', () => {
it('drops the www prefix and the port', () => {
expect(normalizeHost('WWW.GitHub.com:443')).toBe('github.com');
});
it('rejects a value that is not a host', () => {
expect(normalizeHost('not a host')).toBeNull();
expect(normalizeHost('https://github.com')).toBeNull();
});
});
describe('extractReferrerHost', () => {
it('returns the host of a full referrer URL', () => {
expect(extractReferrerHost('https://news.ycombinator.com/item?id=1')).toBe(
'news.ycombinator.com'
);
});
it('drops the path and query, so a share token cannot be stored', () => {
expect(extractReferrerHost('https://example.com/share/[email protected]')).toBe(
'example.com'
);
});
it('ignores our own host, because that is a click inside the site', () => {
expect(extractReferrerHost('https://open-frame.net/pricing', 'open-frame.net')).toBeNull();
expect(extractReferrerHost('https://www.open-frame.net/pricing', 'open-frame.net')).toBeNull();
});
it('returns null for a missing or unparseable referrer', () => {
expect(extractReferrerHost(null)).toBeNull();
expect(extractReferrerHost('android-app://com.example')).toBeNull();
});
});
describe('sanitizeLandingPath', () => {
it('keeps the path and drops the query string', () => {
expect(sanitizeLandingPath('/vs/frameio')).toBe('/vs/frameio');
});
it('falls back to / for anything that is not a path', () => {
expect(sanitizeLandingPath('https://open-frame.net/x')).toBe('/');
expect(sanitizeLandingPath(null)).toBe('/');
});
it('keeps what a real route can carry', () => {
expect(sanitizeLandingPath('/vs/frame.io')).toBe('/vs/frame.io');
expect(sanitizeLandingPath('/watch/cm4x-01_a')).toBe('/watch/cm4x-01_a');
expect(sanitizeLandingPath('/blog/%C3%BCr%C3%BCn')).toBe('/blog/%C3%BCr%C3%BCn');
});
it('drops a path that could only have come from a hand-written cookie', () => {
// The proxy feeds this a real pathname. The cookie reader feeds it whatever
// the cookie said, and that value ends up in a database column.
expect(sanitizeLandingPath('/<script>alert(1)</script>')).toBe('/');
expect(sanitizeLandingPath('/ok\nX-Injected: 1')).toBe('/');
expect(sanitizeLandingPath('/a b')).toBe('/');
});
});
describe('classifyChannel', () => {
it('is DIRECT with no tags and no referrer', () => {
expect(classifyChannel({})).toBe('DIRECT');
});
it('reads the referring host when there are no tags', () => {
expect(classifyChannel({ referrerHost: 'github.com' })).toBe('GITHUB');
expect(classifyChannel({ referrerHost: 'gist.github.com' })).toBe('GITHUB');
expect(classifyChannel({ referrerHost: 'youtu.be' })).toBe('YOUTUBE');
expect(classifyChannel({ referrerHost: 'www.producthunt.com' })).toBe('REVIEW_LINK');
expect(classifyChannel({ referrerHost: 'news.ycombinator.com' })).toBe('COMMUNITY');
});
it('treats every Google country domain as search', () => {
expect(classifyChannel({ referrerHost: 'google.com' })).toBe('GOOGLE');
expect(classifyChannel({ referrerHost: 'google.com.tr' })).toBe('GOOGLE');
expect(classifyChannel({ referrerHost: 'news.google.co.uk' })).toBe('GOOGLE');
});
it('does not mistake a lookalike domain for the real one', () => {
expect(classifyChannel({ referrerHost: 'notgithub.com' })).toBe('REFERRAL');
expect(classifyChannel({ referrerHost: 'google.com.evil.example' })).toBe('REFERRAL');
});
it('counts an unrecognised site that links to us as a referral', () => {
expect(classifyChannel({ referrerHost: 'someblog.example' })).toBe('REFERRAL');
});
it('prefers an explicit utm_source over the referring host', () => {
expect(classifyChannel({ utmSource: 'youtube', referrerHost: 'google.com' })).toBe('YOUTUBE');
});
it('reads a utm_source that was written as a domain', () => {
expect(classifyChannel({ utmSource: 'github.com' })).toBe('GITHUB');
});
it('files a tagged campaign we do not recognise as OTHER, not DIRECT', () => {
expect(classifyChannel({ utmSource: 'conference-flyer' })).toBe('OTHER');
});
it('lets the medium that names the motion win over the source that names the place', () => {
expect(classifyChannel({ utmSource: 'linkedin', utmMedium: 'outbound' })).toBe('OUTBOUND');
expect(classifyChannel({ utmSource: 'github', utmMedium: 'email' })).toBe('OUTBOUND');
expect(classifyChannel({ utmSource: 'someone', utmMedium: 'referral' })).toBe('REFERRAL');
});
it('ignores a source that fails sanitizing and falls back to the referrer', () => {
expect(classifyChannel({ utmSource: '<script>', referrerHost: 'youtube.com' })).toBe('YOUTUBE');
});
});