diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 0a6f06d..1edc57e 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -1,4 +1,5 @@ import { existsSync } from 'node:fs'; +import { withBotId } from 'botid/next/config'; import type { NextConfig } from 'next'; import { withWorkflow } from 'workflow/next'; @@ -24,4 +25,5 @@ const nextConfig: NextConfig = { ], }; -export default withWorkflow(nextConfig); +// BotID proxies its challenge through the app's own domain, so blockers don't break it. +export default withWorkflow(withBotId(nextConfig)); diff --git a/apps/web/package.json b/apps/web/package.json index e7da46c..c1e940b 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -22,6 +22,7 @@ "@drippa/stackprobe-core": "workspace:*", "@drippa/stackprobe-decider-typesafe": "workspace:*", "@drippa/stackprobe-store-postgres": "workspace:*", + "botid": "^1.5.11", "next": "^16.3.8", "react": "^19.3.0", "react-dom": "^19.3.0", diff --git a/apps/web/src/app/actions.ts b/apps/web/src/app/actions.ts index 100b04c..e6ebae7 100644 --- a/apps/web/src/app/actions.ts +++ b/apps/web/src/app/actions.ts @@ -1,39 +1,33 @@ 'use server'; -import { requestScan } from '@drippa/stackprobe-core'; +import { headers } from 'next/headers'; import { redirect } from 'next/navigation'; import { start } from 'workflow/api'; -import { getStore } from '../lib/services.ts'; +import { clientIp } from '../lib/keys-api.ts'; +import { getAccess, getBotCheck, getIpHashSecret, getStore } from '../lib/services.ts'; +import { startScan } from '../lib/start-scan.ts'; import { scanWorkflow } from '../workflows/scan.ts'; export interface ScanFormState { error: string | null; } +// Every scan form on the site: the home page, a report's "Scan again", not-found pages. export async function scanAction(_state: ScanFormState, form: FormData): Promise { - const input = String(form.get('url') ?? ''); - let domain: string; - try { - const scan = await requestScan( - input, - { - store: getStore(), - start: async (created) => { - await start(scanWorkflow, [created.id, created.url, created.createdAt]); - }, + const result = await startScan( + String(form.get('url') ?? ''), + { force: form.get('force') === '1' }, + { + store: getStore(), + access: getAccess(), + botCheck: getBotCheck(), + ip: clientIp(await headers()), + ipHashSecret: getIpHashSecret(), + start: async (created) => { + await start(scanWorkflow, [created.id, created.url, created.createdAt]); }, - { force: form.get('force') === '1' }, - ); - domain = scan.domain; - } catch (error) { - if (error instanceof TypeError) return { error: 'Enter a domain or URL, like example.com.' }; - throw error; - } - redirect(`/s/${encodeURIComponent(domain)}`); -} - -// "Scan again" on a results page: the URL came from a stored scan, so it is always valid. -export async function rescanAction(form: FormData): Promise { - form.set('force', '1'); - await scanAction({ error: null }, form); + }, + ); + if ('error' in result) return { error: result.error }; + redirect(`/s/${encodeURIComponent(result.domain)}`); } diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 22fea4a..fb0dcf6 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -249,9 +249,10 @@ a:hover { max-width: calc(var(--space-24) * 4.5); } +/* Messages from a form: what to fix, or a limit and when it resets. Calm, not alarming. */ .form-error { font-size: var(--text-label); - color: var(--fail-ink); + color: var(--ink-2); } /* Home */ @@ -669,10 +670,20 @@ details[open] > .tech-row { } .actions { - display: flex; + display: grid; + /* The JSON link, Copy link, Scan again; a message from Scan again spans them below. */ + grid-template-columns: repeat(3, auto); + justify-content: end; + align-items: center; gap: var(--space-2); } +.actions-error { + grid-column: 1 / -1; + max-width: 0; + min-width: 100%; +} + .actions form { display: contents; } @@ -900,6 +911,11 @@ details[open] > .tech-row { grid-template-columns: 1fr 1fr; } + .actions-error { + grid-column: 1 / -1; + margin: 0; + } + .json-link { grid-column: 1 / -1; align-self: start; diff --git a/apps/web/src/app/s/[domain]/report-sections.tsx b/apps/web/src/app/s/[domain]/report-sections.tsx index 328530c..9240145 100644 --- a/apps/web/src/app/s/[domain]/report-sections.tsx +++ b/apps/web/src/app/s/[domain]/report-sections.tsx @@ -12,11 +12,11 @@ import { verdict, verdictNames, } from '../../../lib/report-view.ts'; -import { rescanAction } from '../../actions.ts'; import { ScanBand } from '../../effects/scan-band.tsx'; import { ScanForm } from '../../scan-form.tsx'; import { AutoRefresh } from './auto-refresh.tsx'; import { CopyLink } from './copy-link.tsx'; +import { ScanAgain } from './scan-again.tsx'; // The report page's sections, apart from loading the scan, so they can be rendered in tests. @@ -151,12 +151,7 @@ export function ReportView({ {scan.domain}.json -
- - -
+ diff --git a/apps/web/src/app/s/[domain]/scan-again.tsx b/apps/web/src/app/s/[domain]/scan-again.tsx new file mode 100644 index 0000000..8a5b9b5 --- /dev/null +++ b/apps/web/src/app/s/[domain]/scan-again.tsx @@ -0,0 +1,28 @@ +'use client'; + +import { useActionState } from 'react'; +import { type ScanFormState, scanAction } from '../../actions.ts'; + +// "Scan again" on a report: a forced scan of the stored URL. When the daily limit is reached, +// says so here instead of failing the page. +export function ScanAgain({ url }: { url: string }) { + const [state, action, pending] = useActionState(scanAction, { + error: null, + }); + return ( + <> +
+ + + +
+ {state.error ? ( +

+ {state.error} +

+ ) : null} + + ); +} diff --git a/apps/web/src/instrumentation-client.ts b/apps/web/src/instrumentation-client.ts new file mode 100644 index 0000000..96c8a3e --- /dev/null +++ b/apps/web/src/instrumentation-client.ts @@ -0,0 +1,9 @@ +import { initBotId } from 'botid/client/core'; + +// Vercel BotID: marks the browser's requests to the pages that start scans, so the server action +// can tell people from bots (see lib/start-scan.ts). Only on Vercel production, matching +// getBotCheck in lib/services.ts. Scan forms post to the page they're on: home, reports, and any +// not-found address. +if (process.env.NEXT_PUBLIC_VERCEL_ENV === 'production') { + initBotId({ protect: [{ path: '/*', method: 'POST' }] }); +} diff --git a/apps/web/src/lib/services.ts b/apps/web/src/lib/services.ts index ff892d0..cca0d48 100644 --- a/apps/web/src/lib/services.ts +++ b/apps/web/src/lib/services.ts @@ -3,6 +3,8 @@ import type { AccessStore, Browser, Decider, Net, Store } from '@drippa/stackpro import { NodeNet } from '@drippa/stackprobe-core/node'; import { deciderFromEnv } from '@drippa/stackprobe-decider-typesafe'; import { connectPostgres } from '@drippa/stackprobe-store-postgres'; +import { checkBotId } from 'botid/server'; +import type { BotCheck } from './start-scan.ts'; // The one place the app picks its stores and network. Tests replace this module. let database: ReturnType | undefined; @@ -53,3 +55,12 @@ export async function getBrowser(): Promise { export function getNet(): Net { return new NodeNet(); } + +// Vercel BotID on Vercel production. Previews are behind Vercel's login already, and Drippa's +// product review drives a headless browser there that BotID would turn away. Self-hosted, there's +// no BotID service to ask. In both, every request counts as a person and only the daily +// allowance applies. +export function getBotCheck(): BotCheck { + if (process.env.VERCEL_ENV !== 'production') return { isBot: async () => false }; + return { isBot: async () => (await checkBotId()).isBot }; +} diff --git a/apps/web/src/lib/start-scan.test.ts b/apps/web/src/lib/start-scan.test.ts new file mode 100644 index 0000000..b5f7b76 --- /dev/null +++ b/apps/web/src/lib/start-scan.test.ts @@ -0,0 +1,107 @@ +import { MemoryAccessStore, MemoryStore, type ScanRecord } from '@drippa/stackprobe-core'; +import { describe, expect, test } from 'vitest'; +import { limitMessage, startScan } from './start-scan.ts'; + +function setup({ bot = false, at = '2026-10-12T19:00:00.000Z' } = {}) { + const now = () => new Date(at); + const store = new MemoryStore({ now }); + const access = new MemoryAccessStore({ now }); + const started: ScanRecord[] = []; + const deps = (ip = '203.0.113.7') => ({ + store, + access, + botCheck: { isBot: async () => bot }, + ip, + ipHashSecret: 'test-secret', + start: async (scan: ScanRecord) => { + started.push(scan); + }, + now, + }); + return { store, started, deps }; +} + +describe('startScan', () => { + test('a visitor can start 3 new scans a day; the 4th explains the limit and starts nothing', async () => { + const { deps, started } = setup(); + for (const domain of ['a.test', 'b.test', 'c.test']) { + expect(await startScan(domain, { force: false }, deps())).toEqual({ domain }); + } + expect(await startScan('d.test', { force: false }, deps())).toEqual({ + error: limitMessage('2026-10-13T00:00:00.000Z', () => new Date('2026-10-12T19:00:00.000Z')), + }); + expect(started.map((s) => s.domain)).toEqual(['a.test', 'b.test', 'c.test']); + }); + + test('opening a scan that already exists is free, even at the limit', async () => { + const { deps } = setup(); + for (const domain of ['a.test', 'b.test', 'c.test']) { + await startScan(domain, { force: false }, deps()); + } + expect(await startScan('a.test', { force: false }, deps())).toEqual({ domain: 'a.test' }); + }); + + test('"Scan again" on a finished scan starts a new one, so it counts', async () => { + const { deps, store, started } = setup(); + await startScan('a.test', { force: false }, deps()); + await startScan('b.test', { force: false }, deps()); + const first = started.find((scan) => scan.domain === 'b.test'); + await store.finishScan(first?.id ?? '', { + schemaVersion: '1', + domain: 'b.test', + scannedAt: '2026-10-12T19:00:00.000Z', + fingerprintsVersion: 'test', + surfaces: [], + layersRun: [], + }); + expect(await startScan('b.test', { force: true }, deps())).toEqual({ domain: 'b.test' }); + expect(await startScan('c.test', { force: false }, deps())).toHaveProperty('error'); + }); + + test('"Scan again" while the scan still runs returns it, and spends nothing', async () => { + const { deps } = setup(); + await startScan('a.test', { force: false }, deps()); + await startScan('a.test', { force: true }, deps()); + await startScan('b.test', { force: false }, deps()); + expect(await startScan('c.test', { force: false }, deps())).toEqual({ domain: 'c.test' }); + }); + + test('each visitor has their own allowance', async () => { + const { deps } = setup(); + for (const domain of ['a.test', 'b.test', 'c.test']) { + await startScan(domain, { force: false }, deps('203.0.113.7')); + } + expect(await startScan('d.test', { force: false }, deps('198.51.100.2'))).toEqual({ + domain: 'd.test', + }); + }); + + test('a bot is turned away before anything is created or spent', async () => { + const { deps, store, started } = setup({ bot: true }); + expect(await startScan('a.test', { force: false }, deps())).toEqual({ + error: "We couldn't confirm this is a browser. Reload the page and try again.", + }); + expect(await store.latestScan('a.test')).toBeNull(); + expect(started).toEqual([]); + }); + + test('input that is not a domain is explained, and spends nothing', async () => { + const { deps } = setup(); + expect(await startScan('not a domain', { force: false }, deps())).toEqual({ + error: 'Enter a domain or URL, like example.com.', + }); + for (const domain of ['a.test', 'b.test', 'c.test']) { + expect(await startScan(domain, { force: false }, deps())).toEqual({ domain }); + } + }); +}); + +test('limitMessage says when more scans are possible', () => { + const at = (iso: string) => () => new Date(iso); + expect(limitMessage('2026-10-13T00:00:00.000Z', at('2026-10-12T19:00:00.000Z'))).toBe( + "You've started 3 new scans today, the daily limit without a key. Scans that already exist are still free to open. You can start more at midnight UTC, in 5 hours.", + ); + expect(limitMessage('2026-10-13T00:00:00.000Z', at('2026-10-12T23:30:00.000Z'))).toContain( + 'in about an hour.', + ); +}); diff --git a/apps/web/src/lib/start-scan.ts b/apps/web/src/lib/start-scan.ts new file mode 100644 index 0000000..4ab1d40 --- /dev/null +++ b/apps/web/src/lib/start-scan.ts @@ -0,0 +1,76 @@ +import { + type AccessStore, + assertAllowance, + LimitError, + requestScan, + type ScanRecord, + type Store, + VISITOR_SCANS_PER_DAY, + visitorSubject, +} from '@drippa/stackprobe-core'; + +// Starting a scan from the website's forms: the bot check, the visitor's daily allowance, then +// requestScan. Apart from the server action so it can be tested without Next. + +// Whether the request comes from a person's browser. Vercel BotID on Vercel; everyone is a +// person when self-hosted (see services.ts). +export interface BotCheck { + isBot(): Promise; +} + +export interface StartScanDeps { + store: Store; + access: AccessStore; + botCheck: BotCheck; + ip: string; + ipHashSecret: string; + start(scan: ScanRecord): Promise; + now?: () => Date; +} + +export type StartScanResult = { domain: string } | { error: string }; + +export async function startScan( + input: string, + { force }: { force: boolean }, + deps: StartScanDeps, +): Promise { + if (await deps.botCheck.isBot()) { + return { error: "We couldn't confirm this is a browser. Reload the page and try again." }; + } + const subject = await visitorSubject(deps.ip, deps.ipHashSecret); + const clock = deps.now ? { now: deps.now } : {}; + const access = { store: deps.access, ...clock }; + try { + const scan = await requestScan( + input, + { + store: deps.store, + start: deps.start, + ...clock, + allowance: { + check: async () => { + await assertAllowance(subject, VISITOR_SCANS_PER_DAY, access); + }, + spend: () => deps.access.recordUsage({ subject, endpoint: 'scan form', newScan: true }), + }, + }, + { force }, + ); + return { domain: scan.domain }; + } catch (error) { + if (error instanceof TypeError) return { error: 'Enter a domain or URL, like example.com.' }; + if (error instanceof LimitError) return { error: limitMessage(error.resetAt, deps.now) }; + throw error; + } +} + +// "You've started 3 new scans today …, more in 5 hours." Reset is always midnight UTC. +export function limitMessage(resetAt: string, now: () => Date = () => new Date()): string { + const hours = Math.max(1, Math.ceil((Date.parse(resetAt) - now().getTime()) / 3_600_000)); + return ( + `You've started ${VISITOR_SCANS_PER_DAY} new scans today, the daily limit without a key. ` + + `Scans that already exist are still free to open. You can start more at midnight UTC, ` + + `in ${hours === 1 ? 'about an hour' : `${hours} hours`}.` + ); +} diff --git a/packages/core/src/request-scan.test.ts b/packages/core/src/request-scan.test.ts index 3b82d9c..b8bc279 100644 --- a/packages/core/src/request-scan.test.ts +++ b/packages/core/src/request-scan.test.ts @@ -81,6 +81,35 @@ describe('requestScan', () => { expect(started).toHaveLength(3); }); + test('an allowance is checked and spent only for new scans', async () => { + const calls: string[] = []; + const allowance = { + check: async () => { + calls.push('check'); + }, + spend: async () => { + calls.push('spend'); + }, + }; + await requestScan('acme.test', { ...deps(), allowance }); + expect(calls).toEqual(['check', 'spend']); + // The same domain again: the running scan is returned, nothing spent. + await requestScan('acme.test', { ...deps(), allowance }); + expect(calls).toEqual(['check', 'spend']); + }); + + test('an allowance that refuses stops the scan before anything is created', async () => { + const allowance = { + check: async () => { + throw new Error('limit'); + }, + spend: async () => {}, + }; + await expect(requestScan('acme.test', { ...deps(), allowance })).rejects.toThrow('limit'); + expect(await store.latestScan('acme.test')).toBeNull(); + expect(started).toEqual([]); + }); + test('rejects input that is not a domain or URL', async () => { await expect(requestScan('not a domain', deps())).rejects.toThrow(TypeError); await expect(requestScan('localhost', deps())).resolves.toBeDefined(); diff --git a/packages/core/src/request-scan.ts b/packages/core/src/request-scan.ts index cee56b5..85e1c14 100644 --- a/packages/core/src/request-scan.ts +++ b/packages/core/src/request-scan.ts @@ -12,6 +12,9 @@ export interface RequestScanDeps { store: Store; // Starts the scan's workflow. Called once per new scan. start(scan: ScanRecord): Promise; + // The caller's daily allowance, when they have one (see access.ts). Only new scans touch it: + // check() runs before one is created and throws to refuse it; spend() runs once it exists. + allowance?: { check(): Promise; spend(): Promise }; now?: () => Date; } @@ -32,7 +35,9 @@ export async function requestScan( if (now - Date.parse(latest.finishedAt) < FRESH_FOR_MS) return latest; } + await deps.allowance?.check(); const scan = await deps.store.createScan({ domain: target.host, url: target.url }); + await deps.allowance?.spend(); await deps.start(scan); return scan; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 293a028..19c5e09 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -38,6 +38,9 @@ importers: '@drippa/stackprobe-store-postgres': specifier: workspace:* version: link:../../packages/store-postgres + botid: + specifier: ^1.5.11 + version: 1.5.11(next@16.3.8(@types/node@22.20.5)(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(react@19.3.0) next: specifier: ^16.3.8 version: 16.3.8(@types/node@22.20.5)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) @@ -1595,6 +1598,17 @@ packages: resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==} engines: {node: '>=18'} + botid@1.5.11: + resolution: {integrity: sha512-KOO1A3+/vFVJk5aFoG3sNwiogKFPVR+x4aw4gQ1b2e0XoE+i5xp48/EZn+WqR07jRHeDGwHWQUOtV5WVm7xiww==} + peerDependencies: + next: '*' + react: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + next: + optional: true + react: + optional: true + bowser@2.14.1: resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==} @@ -4658,6 +4672,11 @@ snapshots: transitivePeerDependencies: - supports-color + botid@1.5.11(next@16.3.8(@types/node@22.20.5)(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(react@19.3.0): + optionalDependencies: + next: 16.3.8(@types/node@22.20.5)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + react: 19.3.0 + bowser@2.14.1: {} boxen@8.0.1: