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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,8 @@ DATABASE_URL=postgresql://postgres.<project-ref>:<password>@<region>.pooler.supa
# Optional. TypeSafe API key for Jev, which decides what kind a surface is when the rules can't
# tell. Without it, scans classify by rules only. https://typesafe.ai
TYPESAFE_API_KEY=

# Required in production. A long random secret that IP addresses are hashed with, so API key
# creation and anonymous scans can be limited per visitor without storing anyone's IP.
# Generate one with: openssl rand -base64 32
STACKPROBE_IP_HASH_SECRET=
10 changes: 10 additions & 0 deletions apps/web/src/app/api/keys/current/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { revokeKeyResponse } from '../../../../lib/keys-api.ts';
import { getAccess } from '../../../../lib/services.ts';

// Revokes the key the request is made with. See lib/keys-api.ts.
export async function DELETE(request: Request) {
const { status, body, headers } = await revokeKeyResponse(request.headers.get('authorization'), {
store: getAccess(),
});
return Response.json(body, { status, headers });
}
12 changes: 12 additions & 0 deletions apps/web/src/app/api/keys/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { clientIp, createKeyResponse } from '../../../lib/keys-api.ts';
import { getAccess, getIpHashSecret } from '../../../lib/services.ts';

// Agents get their own key here, with no sign-up. See lib/keys-api.ts.
export async function POST(request: Request) {
const { status, body, headers } = await createKeyResponse(
clientIp(request.headers),
getIpHashSecret(),
{ store: getAccess() },
);
return Response.json(body, { status, headers });
}
88 changes: 88 additions & 0 deletions apps/web/src/lib/keys-api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { hashKey, KEYS_PER_IP_PER_DAY, MemoryAccessStore } from '@drippa/stackprobe-core';
import { describe, expect, test } from 'vitest';
import { clientIp, createKeyResponse, revokeKeyResponse } from './keys-api.ts';

const SECRET = 'test-secret';

function setup(at = '2026-10-12T22:00:00.000Z') {
let now = new Date(at);
const clock = () => now;
const store = new MemoryAccessStore({ now: clock });
return {
store,
deps: { store, now: clock },
setTime: (iso: string) => {
now = new Date(iso);
},
};
}

describe('POST /api/keys', () => {
test('creates a key and returns it once, with its limits and how to use it', async () => {
const { deps, store } = setup();
const { status, body, headers } = await createKeyResponse('203.0.113.7', SECRET, deps);
expect(status).toBe(201);
expect(body).toMatchObject({
key: expect.stringMatching(/^sp_/),
prefix: (body.key as string).slice(0, 10),
limits: { scansPerDay: 10 },
});
expect(headers['cache-control']).toBe('no-store');
expect(await store.findKey(await hashKey(body.key as string))).not.toBeNull();
});

test(`a fourth key from one IP in a UTC day gets 429 with when to retry`, async () => {
const { deps } = setup('2026-10-12T22:00:00.000Z');
for (let i = 0; i < KEYS_PER_IP_PER_DAY; i++) {
expect((await createKeyResponse('203.0.113.7', SECRET, deps)).status).toBe(201);
}
const { status, body, headers } = await createKeyResponse('203.0.113.7', SECRET, deps);
expect(status).toBe(429);
expect(body).toEqual({
error: 'rate_limited',
message:
'At most 3 new keys a day from one address. Try again after 2026-10-13T00:00:00.000Z.',
resetAt: '2026-10-13T00:00:00.000Z',
});
expect(headers['retry-after']).toBe('7200');
expect((await createKeyResponse('203.0.113.8', SECRET, deps)).status).toBe(201);
});
});

describe('DELETE /api/keys/current', () => {
test('revokes the key it is called with, and the key stops working', async () => {
const { deps } = setup();
const created = await createKeyResponse('203.0.113.7', SECRET, deps);
const key = created.body.key as string;
const revoked = await revokeKeyResponse(`Bearer ${key}`, deps);
expect(revoked).toMatchObject({ status: 200, body: { revoked: key.slice(0, 10) } });
expect(JSON.stringify(revoked)).not.toContain(key);
expect((await revokeKeyResponse(`Bearer ${key}`, deps)).status).toBe(401);
});

test('a missing, malformed or unknown key gets 401 and how to get one', async () => {
const { deps } = setup();
for (const header of [null, 'sp_nope', 'Bearer', 'Bearer sp_unknown', 'Basic abc']) {
const { status, body, headers } = await revokeKeyResponse(header, deps);
expect(status).toBe(401);
expect(body.error).toBe('invalid_key');
expect(headers['www-authenticate']).toBe('Bearer');
}
});

test('each request made with a key is logged against it, without the key', async () => {
const { deps, store } = setup();
const created = await createKeyResponse('203.0.113.7', SECRET, deps);
const record = await store.findKey(await hashKey(created.body.key as string));
await revokeKeyResponse(`Bearer ${created.body.key}`, deps);
// Logged, but not as a new scan: revoking spends nothing.
expect(await store.countNewScans(`key:${record?.id}`, '2000-01-01T00:00:00.000Z')).toBe(0);
expect(await store.pruneUsage('2100-01-01T00:00:00.000Z')).toBe(1);
});
});

test('clientIp takes the first forwarded address, then x-real-ip', () => {
expect(clientIp(new Headers({ 'x-forwarded-for': '203.0.113.7, 10.0.0.1' }))).toBe('203.0.113.7');
expect(clientIp(new Headers({ 'x-real-ip': '198.51.100.2' }))).toBe('198.51.100.2');
expect(clientIp(new Headers())).toBe('unknown');
});
94 changes: 94 additions & 0 deletions apps/web/src/lib/keys-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import {
type AccessDeps,
createApiKey,
findApiKey,
hashIp,
keySubject,
LimitError,
} from '@drippa/stackprobe-core';

// The API key endpoints, apart from Next's route handlers so they can be tested directly.
// Keys only ever appear in the response that creates them: never in logs or later responses.

export interface ApiResponse {
status: number;
body: Record<string, unknown>;
headers: Record<string, string>;
}

// Nothing here may be cached by anyone, and any site may call it.
const HEADERS = { 'cache-control': 'no-store', 'access-control-allow-origin': '*' };

// The caller's IP as the platform reports it: the first x-forwarded-for entry (Vercel and most
// proxies set it), else x-real-ip. Self-hosted setups must run behind a proxy that sets one.
export function clientIp(headers: Headers): string {
const forwarded = headers.get('x-forwarded-for')?.split(',')[0]?.trim();
return forwarded || headers.get('x-real-ip')?.trim() || 'unknown';
}

// POST /api/keys: a new key, returned once.
export async function createKeyResponse(
ip: string,
secret: string,
deps: AccessDeps,
): Promise<ApiResponse> {
try {
const { key, record } = await createApiKey(await hashIp(ip, secret), deps);
return {
status: 201,
headers: HEADERS,
body: {
key,
prefix: record.prefix,
limits: { scansPerDay: record.scansPerDay },
note: 'Store this key now: it is not shown again. Send it as "Authorization: Bearer <key>". Revoke it with DELETE /api/keys/current.',
},
};
} catch (error) {
if (error instanceof LimitError) return limited(error, deps);
throw error;
}
}

// DELETE /api/keys/current: revokes the key the request is made with.
export async function revokeKeyResponse(
authorization: string | null,
deps: AccessDeps,
): Promise<ApiResponse> {
const key = bearer(authorization);
const record = key ? await findApiKey(key, deps) : null;
if (!record) return invalidKey();
await deps.store.revokeKey(record.id);
await deps.store.recordUsage({
subject: keySubject(record),
endpoint: 'DELETE /api/keys/current',
newScan: false,
});
return { status: 200, headers: HEADERS, body: { revoked: record.prefix } };
}

export function invalidKey(): ApiResponse {
return {
status: 401,
headers: { ...HEADERS, 'www-authenticate': 'Bearer' },
body: {
error: 'invalid_key',
message: 'Send a live API key as "Authorization: Bearer <key>". Get one with POST /api/keys.',
},
};
}

export function limited(error: LimitError, deps: Pick<AccessDeps, 'now'>): ApiResponse {
const now = (deps.now?.() ?? new Date()).getTime();
const seconds = Math.max(1, Math.ceil((Date.parse(error.resetAt) - now) / 1000));
return {
status: 429,
headers: { ...HEADERS, 'retry-after': String(seconds) },
body: { error: 'rate_limited', message: error.message, resetAt: error.resetAt },
};
}

function bearer(authorization: string | null): string | null {
const match = authorization?.match(/^Bearer\s+(\S+)$/i);
return match?.[1] ?? null;
}
34 changes: 27 additions & 7 deletions apps/web/src/lib/services.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,39 @@
import { sandboxBrowserFromEnv } from '@drippa/stackprobe-browser-vercel-sandbox';
import type { Browser, Decider, Net, Store } from '@drippa/stackprobe-core';
import type { AccessStore, Browser, Decider, Net, Store } from '@drippa/stackprobe-core';
import { NodeNet } from '@drippa/stackprobe-core/node';
import { deciderFromEnv } from '@drippa/stackprobe-decider-typesafe';
import { connectPostgres } from '@drippa/stackprobe-store-postgres';

// The one place the app picks its store and network. Tests replace this module.
let store: Store | undefined;
// The one place the app picks its stores and network. Tests replace this module.
let database: ReturnType<typeof connectPostgres> | undefined;

export function getStore(): Store {
if (!store) {
function connect(): ReturnType<typeof connectPostgres> {
if (!database) {
const url = process.env.DATABASE_URL;
if (!url) throw new Error('DATABASE_URL is not set. See .env.example.');
store = connectPostgres(url).store;
database = connectPostgres(url);
}
return database;
}

export function getStore(): Store {
return connect().store;
}

// API keys and the daily allowance, in the same database.
export function getAccess(): AccessStore {
return connect().access;
}

// The secret IPs are hashed with, so visitors can be counted without keeping their address.
// Required in production; a fixed value stands in during development.
export function getIpHashSecret(): string {
const secret = process.env.STACKPROBE_IP_HASH_SECRET;
if (secret) return secret;
if (process.env.NODE_ENV === 'production') {
throw new Error('STACKPROBE_IP_HASH_SECRET is not set. See .env.example.');
}
return store;
return 'development-only-ip-hash-secret';
}

// Jev when TYPESAFE_API_KEY is set; without it, classification runs on rules only.
Expand Down
124 changes: 124 additions & 0 deletions packages/core/src/access.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { describe, expect, test } from 'vitest';
import { describeAccessStore } from '../test/access-contract.ts';
import {
allowance,
assertAllowance,
createApiKey,
dayWindow,
findApiKey,
hashIp,
hashKey,
KEY_SCANS_PER_DAY,
KEYS_PER_IP_PER_DAY,
keySubject,
LimitError,
MemoryAccessStore,
visitorSubject,
} from './access.ts';

describeAccessStore('MemoryAccessStore', async () => new MemoryAccessStore());

// A clock the tests move by hand.
function clock(start: string) {
let now = new Date(start);
return {
now: () => now,
set: (iso: string) => {
now = new Date(iso);
},
};
}

describe('API keys', () => {
test('a new key is sp_ and 43 url-safe characters, stored only hashed', async () => {
const store = new MemoryAccessStore();
const { key, record } = await createApiKey('ip-1', { store });
expect(key).toMatch(/^sp_[A-Za-z0-9_-]{43}$/);
expect(record.prefix).toBe(key.slice(0, 10));
expect(record.scansPerDay).toBe(KEY_SCANS_PER_DAY);
expect(JSON.stringify(record)).not.toContain(key.slice(10));
expect(await store.findKey(await hashKey(key))).toEqual(record);
});

test('a key is found by itself, and not once revoked', async () => {
const store = new MemoryAccessStore();
const { key, record } = await createApiKey('ip-1', { store });
expect(await findApiKey(key, { store })).toEqual(record);
expect(await findApiKey(`${key}x`, { store })).toBeNull();
expect(await findApiKey('not-a-key', { store })).toBeNull();
await store.revokeKey(record.id);
expect(await findApiKey(key, { store })).toBeNull();
});

test(`at most ${KEYS_PER_IP_PER_DAY} keys a day from one IP; the next UTC day allows more`, async () => {
const time = clock('2026-10-12T22:00:00.000Z');
const store = new MemoryAccessStore({ now: time.now });
const deps = { store, now: time.now };
for (let i = 0; i < KEYS_PER_IP_PER_DAY; i++) await createApiKey('ip-1', deps);
await expect(createApiKey('ip-1', deps)).rejects.toThrow(LimitError);
await expect(createApiKey('ip-1', deps)).rejects.toMatchObject({
resetAt: '2026-10-13T00:00:00.000Z',
});
await expect(createApiKey('ip-2', deps)).resolves.toBeDefined();
time.set('2026-10-13T00:00:01.000Z');
await expect(createApiKey('ip-1', deps)).resolves.toBeDefined();
});

test('making a key drops usage older than 30 days', async () => {
const time = clock('2026-09-01T12:00:00.000Z');
const store = new MemoryAccessStore({ now: time.now });
await store.recordUsage({ subject: 'key:old', endpoint: 'x', newScan: true });
time.set('2026-10-12T12:00:00.000Z');
await store.recordUsage({ subject: 'key:new', endpoint: 'x', newScan: true });
await createApiKey('ip-1', { store, now: time.now });
expect(await store.countNewScans('key:old', '2000-01-01T00:00:00.000Z')).toBe(0);
expect(await store.countNewScans('key:new', '2000-01-01T00:00:00.000Z')).toBe(1);
});
});

describe('daily allowance', () => {
test('counts new scans today, ignores reused ones, and resets at UTC midnight', async () => {
const time = clock('2026-10-12T09:00:00.000Z');
const store = new MemoryAccessStore({ now: time.now });
const deps = { store, now: time.now };
const subject = 'key:k1' as const;
await store.recordUsage({ subject, endpoint: 'POST /api/scans', newScan: true });
await store.recordUsage({ subject, endpoint: 'POST /api/scans', newScan: false });
expect(await allowance(subject, 2, deps)).toEqual({
limit: 2,
used: 1,
remaining: 1,
resetAt: '2026-10-13T00:00:00.000Z',
});
await store.recordUsage({ subject, endpoint: 'POST /api/scans', newScan: true });
await expect(assertAllowance(subject, 2, deps)).rejects.toThrow(
'Daily limit of 2 new scans reached. Recent scans are still free to read. Resets at 2026-10-13T00:00:00.000Z.',
);
time.set('2026-10-13T00:00:00.000Z');
await expect(assertAllowance(subject, 2, deps)).resolves.toMatchObject({ remaining: 2 });
});

test('dayWindow is the UTC day around a moment', () => {
expect(dayWindow(new Date('2026-10-12T23:59:59.999Z'))).toEqual({
start: '2026-10-12T00:00:00.000Z',
resetAt: '2026-10-13T00:00:00.000Z',
});
});
});

describe('subjects', () => {
test('a key spends as key:<id>', () => {
expect(
keySubject({ id: 'k1', prefix: 'sp_x', scansPerDay: 10, createdAt: '', revokedAt: null }),
).toBe('key:k1');
});

test('a visitor is a keyed hash of the IP: stable, secret-dependent, never the IP', async () => {
const a = await visitorSubject('203.0.113.7', 'secret-1');
expect(a).toMatch(/^visitor:[0-9a-f]{64}$/);
expect(a).not.toContain('203.0.113.7');
expect(await visitorSubject('203.0.113.7', 'secret-1')).toBe(a);
expect(await visitorSubject('203.0.113.7', 'secret-2')).not.toBe(a);
expect(await hashIp('203.0.113.8', 'secret-1')).not.toBe(a.slice('visitor:'.length));
});
});
Loading
Loading