From 104310a6f108d8c1bc620a5fc9bed68b8b6ef5e2 Mon Sep 17 00:00:00 2001 From: Marius Maaland Date: Mon, 12 Oct 2026 21:33:07 +0200 Subject: [PATCH] Let agents start and poll scans over HTTP (#37) POST /api/scans with an API key starts a scan, or returns the running or recent one, by the same rules as the website: 202 while it runs, 200 when finished, with a poll URL. New scans spend the key's 10 a day; every request is logged against the key. GET /api/scans/:id returns the status and, once finished, the report; reading needs no key. Bodies are the same shape as /s/.json. Clear JSON errors: 400, 401, 404, 429 with Retry-After. CORS allowed, preflight answered. The README documents it, until the agents page (#39) exists. Closes #37 Co-Authored-By: Claude Opus 5.5 --- README.md | 43 ++++++ apps/web/src/app/actions.ts | 7 +- apps/web/src/app/api/scans/[id]/route.ts | 14 ++ apps/web/src/app/api/scans/route.ts | 22 ++++ apps/web/src/lib/scans-api.test.ts | 161 +++++++++++++++++++++++ apps/web/src/lib/scans-api.ts | 134 +++++++++++++++++++ apps/web/src/lib/start-workflow.ts | 8 ++ 7 files changed, 384 insertions(+), 5 deletions(-) create mode 100644 apps/web/src/app/api/scans/[id]/route.ts create mode 100644 apps/web/src/app/api/scans/route.ts create mode 100644 apps/web/src/lib/scans-api.test.ts create mode 100644 apps/web/src/lib/scans-api.ts create mode 100644 apps/web/src/lib/start-workflow.ts diff --git a/README.md b/README.md index 5f4210b..590531a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,45 @@ # stackprobe Probe the tech stacks of any product + +## HTTP API + +Agents and scripts can use stackprobe over HTTP. Reading is free; starting scans needs a key, which you can create yourself. + +**1. Get a key** (at most 3 a day per address; the key is shown once): + +```sh +curl -X POST https://stackprobe.tech/api/keys +# {"key":"sp_…","prefix":"sp_…","limits":{"scansPerDay":10},"note":"…"} +``` + +**2. Start a scan** (10 new scans a day per key; getting back a scan from the last 24 hours is free): + +```sh +curl -X POST https://stackprobe.tech/api/scans \ + -H "Authorization: Bearer sp_…" \ + -H "Content-Type: application/json" \ + -d '{"domain": "example.com"}' +# 202 while it runs: {"scanId":"…","status":"running","report":null,"reused":false,"poll":"https://stackprobe.tech/api/scans/…",…} +``` + +Add `"force": true` to scan again even if a recent scan exists. + +**3. Poll** until `status` is `done` or `partial` (a few seconds apart; no key needed): + +```sh +curl https://stackprobe.tech/api/scans/ +# 200 when finished: {"status":"done","report":{…},…} +``` + +**Or read the latest report for a domain** without a key: `https://stackprobe.tech/s/example.com.json`. + +The `report` field follows [`schema/report.v1.json`](schema/report.v1.json). + +| Status | Meaning | +|---|---| +| `400` | The body isn't JSON, or `domain` isn't a domain or URL | +| `401` | Missing, unknown or revoked key | +| `404` | No scan with that id | +| `429` | Daily limit reached; `resetAt` and `Retry-After` say when to try again | + +Revoke a key with `curl -X DELETE https://stackprobe.tech/api/keys/current -H "Authorization: Bearer sp_…"`. diff --git a/apps/web/src/app/actions.ts b/apps/web/src/app/actions.ts index e6ebae7..7f0be99 100644 --- a/apps/web/src/app/actions.ts +++ b/apps/web/src/app/actions.ts @@ -2,11 +2,10 @@ import { headers } from 'next/headers'; import { redirect } from 'next/navigation'; -import { start } from 'workflow/api'; 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'; +import { startScanWorkflow } from '../lib/start-workflow.ts'; export interface ScanFormState { error: string | null; @@ -23,9 +22,7 @@ export async function scanAction(_state: ScanFormState, form: FormData): Promise botCheck: getBotCheck(), ip: clientIp(await headers()), ipHashSecret: getIpHashSecret(), - start: async (created) => { - await start(scanWorkflow, [created.id, created.url, created.createdAt]); - }, + start: startScanWorkflow, }, ); if ('error' in result) return { error: result.error }; diff --git a/apps/web/src/app/api/scans/[id]/route.ts b/apps/web/src/app/api/scans/[id]/route.ts new file mode 100644 index 0000000..c614ca3 --- /dev/null +++ b/apps/web/src/app/api/scans/[id]/route.ts @@ -0,0 +1,14 @@ +import { getScanResponse } from '../../../../lib/scans-api.ts'; +import { getAccess, getStore } from '../../../../lib/services.ts'; +import { startScanWorkflow } from '../../../../lib/start-workflow.ts'; + +// A scan's status, and its report once finished. See lib/scans-api.ts. +export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) { + const { status, body, headers } = await getScanResponse((await params).id, { + store: getStore(), + access: getAccess(), + start: startScanWorkflow, + origin: new URL(request.url).origin, + }); + return Response.json(body, { status, headers }); +} diff --git a/apps/web/src/app/api/scans/route.ts b/apps/web/src/app/api/scans/route.ts new file mode 100644 index 0000000..4747c27 --- /dev/null +++ b/apps/web/src/app/api/scans/route.ts @@ -0,0 +1,22 @@ +import { CORS_PREFLIGHT, createScanResponse } from '../../../lib/scans-api.ts'; +import { getAccess, getStore } from '../../../lib/services.ts'; +import { startScanWorkflow } from '../../../lib/start-workflow.ts'; + +// Starts a scan for an agent or script. See lib/scans-api.ts. +export async function POST(request: Request) { + const { status, body, headers } = await createScanResponse( + request.headers.get('authorization'), + await request.text(), + { + store: getStore(), + access: getAccess(), + start: startScanWorkflow, + origin: new URL(request.url).origin, + }, + ); + return Response.json(body, { status, headers }); +} + +export function OPTIONS() { + return new Response(null, { status: 204, headers: CORS_PREFLIGHT }); +} diff --git a/apps/web/src/lib/scans-api.test.ts b/apps/web/src/lib/scans-api.test.ts new file mode 100644 index 0000000..e6c8df9 --- /dev/null +++ b/apps/web/src/lib/scans-api.test.ts @@ -0,0 +1,161 @@ +import { + createApiKey, + hashKey, + MemoryAccessStore, + MemoryStore, + type Report, + type ScanRecord, +} from '@drippa/stackprobe-core'; +import { describe, expect, test } from 'vitest'; +import { createScanResponse, getScanResponse } from './scans-api.ts'; + +const origin = 'https://stackprobe.tech'; + +async function setup() { + const now = () => new Date('2026-10-12T19:00:00.000Z'); + const store = new MemoryStore({ now }); + const access = new MemoryAccessStore({ now }); + const started: ScanRecord[] = []; + const deps = { + store, + access, + origin, + now, + start: async (scan: ScanRecord) => { + started.push(scan); + }, + }; + const { key, record } = await createApiKey('ip-hash', { store: access, now }); + return { + deps, + store, + access, + started, + auth: `Bearer ${key}`, + subject: `key:${record.id}` as const, + }; +} + +const report = (domain: string): Report => ({ + schemaVersion: '1', + domain, + scannedAt: '2026-10-12T19:00:00.000Z', + fingerprintsVersion: 'test', + surfaces: [], + layersRun: [], +}); + +const post = (domain: string, extra = {}) => JSON.stringify({ domain, ...extra }); + +describe('POST /api/scans', () => { + test('starts a scan: 202, the scan, and where to poll', async () => { + const { deps, started, access, auth, subject } = await setup(); + const { status, body, headers } = await createScanResponse( + auth, + post('https://Acme.test/pricing'), + deps, + ); + expect(status).toBe(202); + expect(body).toMatchObject({ + domain: 'acme.test', + status: 'running', + report: null, + reused: false, + page: 'https://stackprobe.tech/s/acme.test', + poll: `https://stackprobe.tech/api/scans/${body.scanId}`, + }); + expect(headers['retry-after']).toBe('3'); + expect(headers['cache-control']).toBe('no-store'); + expect(started).toHaveLength(1); + expect(await access.countNewScans(subject, '2000-01-01T00:00:00.000Z')).toBe(1); + }); + + test('a fresh finished scan is returned, not redone, and spends nothing', async () => { + const { deps, store, access, auth, subject, started } = await setup(); + const first = await createScanResponse(auth, post('acme.test'), deps); + await store.finishScan(String(first.body.scanId), report('acme.test')); + const again = await createScanResponse(auth, post('acme.test'), deps); + expect(again.status).toBe(200); + expect(again.body).toMatchObject({ scanId: first.body.scanId, status: 'done', reused: true }); + expect(again.body.report).toEqual(report('acme.test')); + expect(started).toHaveLength(1); + expect(await access.countNewScans(subject, '2000-01-01T00:00:00.000Z')).toBe(1); + // force: a new scan, which spends. + const forced = await createScanResponse(auth, post('acme.test', { force: true }), deps); + expect(forced).toMatchObject({ status: 202, body: { reused: false } }); + expect(await access.countNewScans(subject, '2000-01-01T00:00:00.000Z')).toBe(2); + }); + + test('every request is logged against the key, new scan or not', async () => { + const { deps, access, auth } = await setup(); + await createScanResponse(auth, post('acme.test'), deps); + await createScanResponse(auth, post('acme.test'), deps); + expect(await access.pruneUsage('2100-01-01T00:00:00.000Z')).toBe(2); + }); + + test('after 10 new scans in a day: 429 with when it resets', async () => { + const { deps, auth } = await setup(); + for (let i = 0; i < 10; i++) { + expect((await createScanResponse(auth, post(`site${i}.test`), deps)).status).toBe(202); + } + const { status, body, headers } = await createScanResponse(auth, post('one-more.test'), deps); + expect(status).toBe(429); + expect(body).toMatchObject({ error: 'rate_limited', resetAt: '2026-10-13T00:00:00.000Z' }); + expect(headers['retry-after']).toBe('18000'); + // Scans that exist are still free to fetch. + expect((await createScanResponse(auth, post('site0.test'), deps)).status).toBe(202); + }); + + test('400 for a body that is not JSON, has no domain, or names no domain', async () => { + const { deps, auth, started } = await setup(); + expect(await createScanResponse(auth, '{nope', deps)).toMatchObject({ + status: 400, + body: { error: 'invalid_json' }, + }); + expect(await createScanResponse(auth, '{}', deps)).toMatchObject({ + status: 400, + body: { error: 'invalid_domain' }, + }); + expect(await createScanResponse(auth, post('not a domain'), deps)).toMatchObject({ + status: 400, + body: { error: 'invalid_domain', message: '"not a domain" isn\'t a domain or URL.' }, + }); + expect(started).toHaveLength(0); + }); + + test('401 for a missing, malformed, unknown or revoked key', async () => { + const { deps, access, auth } = await setup(); + for (const header of [null, 'sp_x', 'Bearer sp_unknown']) { + expect((await createScanResponse(header, post('acme.test'), deps)).status).toBe(401); + } + const record = await access.findKey(await hashKey(auth.slice('Bearer '.length))); + await access.revokeKey(record?.id ?? ''); + expect((await createScanResponse(auth, post('acme.test'), deps)).status).toBe(401); + }); +}); + +describe('GET /api/scans/:id', () => { + test('poll until done: 202 while running, then 200 with the report', async () => { + const { deps, store, auth } = await setup(); + const started = await createScanResponse(auth, post('acme.test'), deps); + const id = String(started.body.scanId); + const running = await getScanResponse(id, deps); + expect(running).toMatchObject({ status: 202, body: { status: 'running', report: null } }); + expect(running.headers['cache-control']).toBe('public, max-age=0, s-maxage=2'); + expect(running.body).not.toHaveProperty('reused'); + await store.finishScan(id, report('acme.test')); + const done = await getScanResponse(id, deps); + expect(done).toMatchObject({ + status: 200, + body: { status: 'done', report: report('acme.test') }, + }); + }); + + test('404 for an unknown id', async () => { + const { deps } = await setup(); + expect(await getScanResponse('nope', deps)).toMatchObject({ + status: 404, + body: { error: 'not_found' }, + }); + }); +}); diff --git a/apps/web/src/lib/scans-api.ts b/apps/web/src/lib/scans-api.ts new file mode 100644 index 0000000..0bfd27a --- /dev/null +++ b/apps/web/src/lib/scans-api.ts @@ -0,0 +1,134 @@ +import { + type AccessStore, + assertAllowance, + findApiKey, + keySubject, + LimitError, + requestScan, + type ScanRecord, + type Store, +} from '@drippa/stackprobe-core'; +import { type ApiResponse, invalidKey, limited } from './keys-api.ts'; +import { reportJson } from './report-json.ts'; + +// The HTTP scan API, apart from Next's route handlers so it can be tested directly. +// POST /api/scans start a scan (or get the running / recent one); needs an API key +// GET /api/scans/:id a scan's status, and its report once finished; free to read +// Bodies are the same shape as the report's JSON twin (/s/.json), plus `poll`. + +export interface ScansApiDeps { + store: Store; + access: AccessStore; + start(scan: ScanRecord): Promise; + origin: string; + now?: () => Date; +} + +const HEADERS = { 'access-control-allow-origin': '*' }; + +// What a browser must be allowed to send for the API to work from another site. +export const CORS_PREFLIGHT = { + ...HEADERS, + 'access-control-allow-methods': 'GET, POST, OPTIONS', + 'access-control-allow-headers': 'authorization, content-type', + 'access-control-max-age': '86400', +}; + +export async function createScanResponse( + authorization: string | null, + body: string, + deps: ScansApiDeps, +): Promise { + const clock = deps.now ? { now: deps.now } : {}; + const access = { store: deps.access, ...clock }; + const key = authorization?.match(/^Bearer\s+(\S+)$/i)?.[1]; + const record = key ? await findApiKey(key, access) : null; + if (!record) return invalidKey(); + const subject = keySubject(record); + + let input: { domain?: unknown; force?: unknown }; + try { + input = JSON.parse(body || '{}'); + } catch { + return badRequest('invalid_json', 'Send a JSON body like {"domain": "example.com"}.'); + } + if (typeof input?.domain !== 'string') { + return badRequest('invalid_domain', 'Send a JSON body like {"domain": "example.com"}.'); + } + + // Exactly one usage row per request: spent as a new scan, or logged as a reuse. + let spent = false; + try { + const scan = await requestScan( + input.domain, + { + store: deps.store, + start: deps.start, + ...clock, + allowance: { + check: async () => { + await assertAllowance(subject, record.scansPerDay, access); + }, + spend: async () => { + spent = true; + await deps.access.recordUsage({ subject, endpoint: 'POST /api/scans', newScan: true }); + }, + }, + }, + { force: input.force === true }, + ); + if (!spent) { + await deps.access.recordUsage({ subject, endpoint: 'POST /api/scans', newScan: false }); + } + return scanResponse(scan, deps.origin, { reused: !spent, cache: false }); + } catch (error) { + if (error instanceof TypeError) { + return badRequest('invalid_domain', `"${input.domain}" isn't a domain or URL.`); + } + if (error instanceof LimitError) return limited(error, access); + throw error; + } +} + +export async function getScanResponse(id: string, deps: ScansApiDeps): Promise { + const scan = await deps.store.getScan(id); + if (!scan) { + return { + status: 404, + headers: { ...HEADERS, 'cache-control': 'no-store' }, + body: { error: 'not_found', message: `No scan with id ${id}.` }, + }; + } + return scanResponse(scan, deps.origin, { cache: true }); +} + +function scanResponse( + scan: ScanRecord, + origin: string, + { reused, cache }: { reused?: boolean; cache: boolean }, +): ApiResponse { + const twin = reportJson(scan.domain, scan, origin); + const running = scan.status === 'running'; + return { + status: running ? 202 : 200, + headers: { + ...HEADERS, + // Starting a scan is never cached; reading one is, briefly while it runs. + 'cache-control': cache ? (twin.headers['cache-control'] ?? 'no-store') : 'no-store', + ...(running ? { 'retry-after': '3' } : {}), + }, + body: { + ...twin.body, + ...(reused === undefined ? {} : { reused }), + poll: `${origin}/api/scans/${scan.id}`, + }, + }; +} + +function badRequest(error: string, message: string): ApiResponse { + return { + status: 400, + headers: { ...HEADERS, 'cache-control': 'no-store' }, + body: { error, message }, + }; +} diff --git a/apps/web/src/lib/start-workflow.ts b/apps/web/src/lib/start-workflow.ts new file mode 100644 index 0000000..f72e2a2 --- /dev/null +++ b/apps/web/src/lib/start-workflow.ts @@ -0,0 +1,8 @@ +import type { ScanRecord } from '@drippa/stackprobe-core'; +import { start } from 'workflow/api'; +import { scanWorkflow } from '../workflows/scan.ts'; + +// Runs a new scan in the background. Shared by the website's forms and the HTTP API. +export async function startScanWorkflow(scan: ScanRecord): Promise { + await start(scanWorkflow, [scan.id, scan.url, scan.createdAt]); +}