Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/web/next.config.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -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));
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
46 changes: 20 additions & 26 deletions apps/web/src/app/actions.ts
Original file line number Diff line number Diff line change
@@ -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<ScanFormState> {
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<void> {
form.set('force', '1');
await scanAction({ error: null }, form);
},
);
if ('error' in result) return { error: result.error };
redirect(`/s/${encodeURIComponent(result.domain)}`);
}
20 changes: 18 additions & 2 deletions apps/web/src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand Down
9 changes: 2 additions & 7 deletions apps/web/src/app/s/[domain]/report-sections.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -151,12 +151,7 @@ export function ReportView({
{scan.domain}.json
</a>
<CopyLink />
<form action={rescanAction}>
<input type="hidden" name="url" value={scan.url} />
<button type="submit" className="button">
Scan again
</button>
</form>
<ScanAgain url={scan.url} />
</div>
</section>
</>
Expand Down
28 changes: 28 additions & 0 deletions apps/web/src/app/s/[domain]/scan-again.tsx
Original file line number Diff line number Diff line change
@@ -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<ScanFormState, FormData>(scanAction, {
error: null,
});
return (
<>
<form action={action}>
<input type="hidden" name="url" value={url} />
<input type="hidden" name="force" value="1" />
<button type="submit" className="button" disabled={pending}>
{pending ? 'Starting…' : 'Scan again'}
</button>
</form>
{state.error ? (
<p role="alert" className="form-error actions-error">
{state.error}
</p>
) : null}
</>
);
}
9 changes: 9 additions & 0 deletions apps/web/src/instrumentation-client.ts
Original file line number Diff line number Diff line change
@@ -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' }] });
}
11 changes: 11 additions & 0 deletions apps/web/src/lib/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof connectPostgres> | undefined;
Expand Down Expand Up @@ -53,3 +55,12 @@ export async function getBrowser(): Promise<Browser | undefined> {
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 };
}
107 changes: 107 additions & 0 deletions apps/web/src/lib/start-scan.test.ts
Original file line number Diff line number Diff line change
@@ -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.',
);
});
76 changes: 76 additions & 0 deletions apps/web/src/lib/start-scan.ts
Original file line number Diff line number Diff line change
@@ -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<boolean>;
}

export interface StartScanDeps {
store: Store;
access: AccessStore;
botCheck: BotCheck;
ip: string;
ipHashSecret: string;
start(scan: ScanRecord): Promise<void>;
now?: () => Date;
}

export type StartScanResult = { domain: string } | { error: string };

export async function startScan(
input: string,
{ force }: { force: boolean },
deps: StartScanDeps,
): Promise<StartScanResult> {
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`}.`
);
}
Loading
Loading