From 9efa7b0178f27855f090f10b0695f55eaac4dc6f Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 31 Jul 2026 12:07:05 -0400 Subject: [PATCH] feat(bskylink): persist link click events for analytics --- bskylink/package.json | 2 +- bskylink/src/db/migrations/004-link-event.ts | 49 ++++++++++++ bskylink/src/db/migrations/index.ts | 2 + bskylink/src/db/schema.ts | 24 +++++- bskylink/src/linkEvents.ts | 16 ++++ bskylink/src/metrics.ts | 4 + bskylink/src/routes/redirect.ts | 24 ++++-- bskylink/src/routes/shortLink.ts | 15 +++- bskylink/tests/index.ts | 83 +++++++++++++++++++- 9 files changed, 206 insertions(+), 13 deletions(-) create mode 100644 bskylink/src/db/migrations/004-link-event.ts create mode 100644 bskylink/src/linkEvents.ts diff --git a/bskylink/package.json b/bskylink/package.json index 23fb08aac..ab7358992 100644 --- a/bskylink/package.json +++ b/bskylink/package.json @@ -1,6 +1,6 @@ { "name": "bskylink", - "version": "0.0.0", + "version": "0.1.0", "type": "module", "main": "index.ts", "scripts": { diff --git a/bskylink/src/db/migrations/004-link-event.ts b/bskylink/src/db/migrations/004-link-event.ts new file mode 100644 index 000000000..3e9c1c593 --- /dev/null +++ b/bskylink/src/db/migrations/004-link-event.ts @@ -0,0 +1,49 @@ +import {type Kysely, sql} from 'kysely' + +export async function up(db: Kysely): Promise { + await db.schema + .createTable('link_event') + .addColumn('id', 'bigserial', col => col.primaryKey()) + .addColumn('event', 'varchar', col => col.notNull()) + .addColumn('link', 'varchar') + .addColumn('host', 'varchar') + .addColumn('linkId', 'varchar') + .addColumn('whitelisted', 'boolean', col => col.notNull().defaultTo(false)) + .addColumn('blocked', 'boolean', col => col.notNull().defaultTo(false)) + .addColumn('warned', 'boolean', col => col.notNull().defaultTo(false)) + .addColumn('utmSource', 'varchar') + .addColumn('utmMedium', 'varchar') + .addColumn('utmCampaign', 'varchar') + .addColumn('utmContent', 'varchar') + .addColumn('utmTerm', 'varchar') + .addColumn('referrer', 'varchar') + .addColumn('createdAt', 'timestamptz', col => + col.notNull().defaultTo(sql`now()`), + ) + .execute() + + await db.schema + .createIndex('link_event_host_created_at_idx') + .on('link_event') + .columns(['host', 'createdAt']) + .execute() + + await db.schema + .createIndex('link_event_link_id_created_at_idx') + .on('link_event') + .columns(['linkId', 'createdAt']) + .execute() + + await db.schema + .createIndex('link_event_created_at_idx') + .on('link_event') + .column('createdAt') + .execute() +} + +export async function down(db: Kysely): Promise { + await db.schema.dropIndex('link_event_created_at_idx').execute() + await db.schema.dropIndex('link_event_link_id_created_at_idx').execute() + await db.schema.dropIndex('link_event_host_created_at_idx').execute() + await db.schema.dropTable('link_event').execute() +} diff --git a/bskylink/src/db/migrations/index.ts b/bskylink/src/db/migrations/index.ts index 7a34b1001..0543196d3 100644 --- a/bskylink/src/db/migrations/index.ts +++ b/bskylink/src/db/migrations/index.ts @@ -1,9 +1,11 @@ import * as init from './001-init.js' import * as safelink from './002-safelink.js' import * as safelinkCursorConstraint from './003-safelink-cursor-constraint.js' +import * as linkEvent from './004-link-event.js' export default { '001': init, '002': safelink, '003': safelinkCursorConstraint, + '004': linkEvent, } diff --git a/bskylink/src/db/schema.ts b/bskylink/src/db/schema.ts index d13a28038..e3a1e2720 100644 --- a/bskylink/src/db/schema.ts +++ b/bskylink/src/db/schema.ts @@ -1,8 +1,9 @@ import {type ToolsOzoneSafelinkDefs} from '@atproto/api' -import {type Selectable} from 'kysely' +import {type Generated, type Selectable} from 'kysely' export type DbSchema = { link: Link + link_event: LinkEvent safelink_rule: SafelinkRule safelink_cursor: SafelinkCursor } @@ -17,6 +18,26 @@ export enum LinkType { StarterPack = 1, } +export type LinkEventType = 'redirect' | 'invalid_redirect' | 'shortlink' + +export interface LinkEvent { + id: Generated + event: LinkEventType + link: string | null + host: string | null + linkId: string | null + whitelisted: Generated + blocked: Generated + warned: Generated + utmSource: string | null + utmMedium: string | null + utmCampaign: string | null + utmContent: string | null + utmTerm: string | null + referrer: string | null + createdAt: Generated +} + export interface SafelinkRule { id: number eventType: ToolsOzoneSafelinkDefs.EventType @@ -33,5 +54,6 @@ export interface SafelinkCursor { } export type LinkEntry = Selectable +export type LinkEventEntry = Selectable export type SafelinkRuleEntry = Selectable export type SafelinkCursorEntry = Selectable diff --git a/bskylink/src/linkEvents.ts b/bskylink/src/linkEvents.ts new file mode 100644 index 000000000..55028106d --- /dev/null +++ b/bskylink/src/linkEvents.ts @@ -0,0 +1,16 @@ +import {type Insertable} from 'kysely' + +import {type AppContext} from './context.js' +import {type LinkEvent} from './db/schema.js' +import {dbLogger} from './logger.js' + +export async function trackLinkEvent( + ctx: AppContext, + event: Insertable, +): Promise { + try { + await ctx.db.db.insertInto('link_event').values(event).execute() + } catch (err) { + dbLogger.error({err, event}, 'failed to record link event') + } +} diff --git a/bskylink/src/metrics.ts b/bskylink/src/metrics.ts index d720a4c58..4317e7eda 100644 --- a/bskylink/src/metrics.ts +++ b/bskylink/src/metrics.ts @@ -20,6 +20,10 @@ type Events = { invalid_redirect: { link: string } + shortlink: { + linkId: string + path: string + } } type Event> = { diff --git a/bskylink/src/routes/redirect.ts b/bskylink/src/routes/redirect.ts index a49f9c401..54ad76ade 100644 --- a/bskylink/src/routes/redirect.ts +++ b/bskylink/src/routes/redirect.ts @@ -1,12 +1,12 @@ import assert from 'node:assert' -import {DAY, SECOND} from '@atproto/common' import {type Express} from 'express' import {type AppContext} from '../context.js' import {linkRedirectContents} from '../html/linkRedirectContents.js' import {linkWarningContents} from '../html/linkWarningContents.js' import {linkWarningLayout} from '../html/linkWarningLayout.js' +import {trackLinkEvent} from '../linkEvents.js' import {redirectLogger} from '../logger.js' import {handler} from './util.js' @@ -38,13 +38,14 @@ export default function (ctx: AppContext, app: Express) { INTERNAL_IP_REGEX.test(url.hostname) // isn't directing to an internal location ) { ctx.metrics.track('invalid_redirect', {link}) + await trackLinkEvent(ctx, {event: 'invalid_redirect', link}) res.setHeader('Cache-Control', 'no-store') res.setHeader('Location', `https://${ctx.cfg.service.appHostname}`) return res.status(302).end() } - // Default to a max age header - res.setHeader('Cache-Control', `max-age=${(7 * DAY) / SECOND}`) + // Never cache: every click must reach this service to be counted + res.setHeader('Cache-Control', 'no-store') res.status(200) res.type('html') @@ -69,7 +70,6 @@ export default function (ctx: AppContext, app: Express) { link: url.href, }), ) - res.setHeader('Cache-Control', 'no-store') redirectLogger.info({rule}, 'Block rule matched') blocked = true break @@ -81,7 +81,6 @@ export default function (ctx: AppContext, app: Express) { link: url.href, }), ) - res.setHeader('Cache-Control', 'no-store') redirectLogger.info({rule}, 'Warn rule matched') warned = true break @@ -108,6 +107,21 @@ export default function (ctx: AppContext, app: Express) { utm_term: req.query.utm_term?.toString(), }) + await trackLinkEvent(ctx, { + event: 'redirect', + link: url.href, + host: url.hostname.toLowerCase(), + whitelisted: whitelisted === 'yes', + blocked, + warned, + utmSource: req.query.utm_source?.toString(), + utmMedium: req.query.utm_medium?.toString(), + utmCampaign: req.query.utm_campaign?.toString(), + utmContent: req.query.utm_content?.toString(), + utmTerm: req.query.utm_term?.toString(), + referrer: req.get('referer'), + }) + return res.end(html) }), ) diff --git a/bskylink/src/routes/shortLink.ts b/bskylink/src/routes/shortLink.ts index 276aae1ca..b49862876 100644 --- a/bskylink/src/routes/shortLink.ts +++ b/bskylink/src/routes/shortLink.ts @@ -1,9 +1,9 @@ import assert from 'node:assert' -import {DAY, SECOND} from '@atproto/common' import {Express} from 'express' import {AppContext} from '../context.js' +import {trackLinkEvent} from '../linkEvents.js' import {handler} from './util.js' export default function (ctx: AppContext, app: Express) { @@ -43,12 +43,21 @@ export default function (ctx: AppContext, app: Express) { `https://${ctx.cfg.service.appHostname}`, ) url.pathname = found.path - res.setHeader('Cache-Control', `max-age=${(7 * DAY) / SECOND}`) + ctx.metrics.track('shortlink', {linkId: found.id, path: found.path}) + await trackLinkEvent(ctx, { + event: 'shortlink', + link: url.href, + host: url.hostname.toLowerCase(), + linkId: found.id, + referrer: req.get('referer'), + }) + // Never cache: every visit must reach this service to be counted + res.setHeader('Cache-Control', 'no-store') if (contentType === 'json') { return res.json({url: url.href}).end() } res.setHeader('Location', url.href) - return res.status(301).end() + return res.status(302).end() }), ) } diff --git a/bskylink/tests/index.ts b/bskylink/tests/index.ts index 7635cf3c5..0ab9c9adf 100644 --- a/bskylink/tests/index.ts +++ b/bskylink/tests/index.ts @@ -128,10 +128,10 @@ describe.skip('link service', async () => { assert.strictEqual(link1, link2) }) - it('serves permanent redirect, preserving query params.', async () => { + it('serves temporary redirect, preserving query params.', async () => { const link = await getLink('/start/did:example:carol/zzz/') const [status, location] = await getRedirect(`${link}?a=b`) - assert.strictEqual(status, 301) + assert.strictEqual(status, 302) const locationUrl = new URL(location) assert.strictEqual( locationUrl.pathname + locationUrl.search, @@ -243,7 +243,7 @@ describe.skip('link service', async () => { const res = await fetch(url, {redirect: 'manual'}) await res.arrayBuffer() // drain assert( - res.status === 301 || res.status === 303, + res.status === 302 || res.status === 303, 'response was not a redirect', ) return [res.status, res.headers.get('location') ?? ''] @@ -284,6 +284,7 @@ describe.skip('link service', async () => { describe('link service no safelink', async () => { let linkService: LinkService let baseUrl: string + let db: Database before(async () => { const env = readEnv() const cfg = envToCfg({ @@ -304,6 +305,10 @@ describe('link service no safelink', async () => { }) await migrateDb.migrateToLatestOrThrow() await migrateDb.close() + db = Database.postgres({ + url: cfg.db.url, + schema: cfg.db.schema, + }) linkService = await LinkService.create(cfg) await linkService.start() const {port} = linkService.server?.address() as AddressInfo @@ -311,6 +316,7 @@ describe('link service no safelink', async () => { }) after(async () => { await linkService?.destroy() + await db?.close() }) it('Wikipedia whitelisted, url restricted. Safelink is disabled, so redirect is always safe', async () => { const urlToRedirect = 'https://en.wikipedia.org/wiki/Fight_Club' @@ -377,4 +383,75 @@ describe('link service no safelink', async () => { // No blocked-site div, always safe assert.doesNotMatch(html, /"blocked-site"/) }) + + it('records a link_event for redirects and disables caching', async () => { + const urlToRedirect = `https://example.com/blog/post-${Date.now()}` + const url = new URL(`${baseUrl}/redirect`) + url.searchParams.set('u', urlToRedirect) + url.searchParams.set('utm_source', 'newsletter') + url.searchParams.set('utm_campaign', 'launch') + const res = await fetch(url, {redirect: 'manual'}) + assert.strictEqual(res.status, 200) + await res.text() + assert.strictEqual(res.headers.get('cache-control'), 'no-store') + const events = await db.db + .selectFrom('link_event') + .selectAll() + .where('link', '=', urlToRedirect) + .execute() + assert.strictEqual(events.length, 1) + assert.strictEqual(events[0].event, 'redirect') + assert.strictEqual(events[0].host, 'example.com') + assert.strictEqual(events[0].utmSource, 'newsletter') + assert.strictEqual(events[0].utmCampaign, 'launch') + assert.strictEqual(events[0].blocked, false) + assert.strictEqual(events[0].warned, false) + }) + + it('records a link_event for invalid redirects', async () => { + const badLink = `not-a-url-${Date.now()}` + const url = new URL(`${baseUrl}/redirect`) + url.searchParams.set('u', badLink) + const res = await fetch(url, {redirect: 'manual'}) + assert.strictEqual(res.status, 302) + assert.strictEqual(res.headers.get('location'), 'https://test.bsky.app') + const events = await db.db + .selectFrom('link_event') + .selectAll() + .where('link', '=', badLink) + .execute() + assert.strictEqual(events.length, 1) + assert.strictEqual(events[0].event, 'invalid_redirect') + assert.strictEqual(events[0].host, null) + }) + + it('records a link_event for shortlinks and serves temporary redirect', async () => { + const path = `/start/did:example:events/${Date.now()}` + const createRes = await fetch(new URL('/link', baseUrl), { + method: 'post', + headers: {'content-type': 'application/json'}, + body: JSON.stringify({path}), + }) + assert.strictEqual(createRes.status, 200) + const payload = await createRes.json() + assert(typeof payload.url === 'string') + const linkId = new URL(payload.url).pathname.split('/').filter(Boolean)[0] + const res = await fetch(new URL(`/${linkId}`, baseUrl), { + redirect: 'manual', + }) + assert.strictEqual(res.status, 302) + assert.strictEqual(res.headers.get('cache-control'), 'no-store') + const location = res.headers.get('location') + assert(location) + assert.strictEqual(new URL(location).pathname, path) + const events = await db.db + .selectFrom('link_event') + .selectAll() + .where('linkId', '=', linkId) + .execute() + assert.strictEqual(events.length, 1) + assert.strictEqual(events[0].event, 'shortlink') + assert.strictEqual(events[0].host, 'test.bsky.app') + assert.strictEqual(events[0].link, `https://test.bsky.app${path}`) + }) }) -- knotmirror 0.0.1