Files
CatoandClaude Opus 5 2b91f484f9 fix(api): stop an unknown model id and an anonymous fact-check from spending our budget (#57)
Two ways in, both found by auditing the new assistant against the live site.

**The model id was not an allowlist.** `/api/chat` accepted any string under
120 characters and handed it to ai-kit, which resolves a model it cannot find
in the chain by PREPENDING it — so an unrecognised id is the first thing tried,
against our key. The chain is free only because every id in it is free; the same
OpenRouter key will happily serve a paid model. Probing live confirmed it: a
fabricated id was accepted without complaint, and unauthenticated GET /api/chat
advertises that OpenRouter is keyed, which is the reconnaissance step. The only
other gate is Origin header equality, which curl forges.

Now `isOfferedModel()` is the single answer to "may we send this", the route
refuses anything else with a 400, and `answerQuestion` forwards only an id it
matched in the chain — so even a future caller that skips the route cannot pass
a string through to a provider.

**Fact-check was an anonymous write to public content.** It took no session,
spent one or two completions per call, and inserted into the same thread a human
needs an account to post in — because page-thread only enforces `canWrite` for
human authors, so the `ai` kind was never a second gate. Any visitor could put
machine-written comments on every note and learn page, permanently, 20 an hour,
and bill us for it. It needs a session now.

Also: `allowRequest` throws when AUTH_SECRET is unset, and in comments and
fact-check it sat outside the try, turning a missing variable into a raw 500
instead of the 503 the rest of each file is written to produce. And /api/follow
was the one authenticated write with no throttle, on a read-modify-write of a
row the caller controls.

The guard is proved by mutation: make `isOfferedModel` return true and two tests
fail.


Claude-Session: https://claude.ai/code/session_01Y6ecRd91ZsPPcjuNkKTFV2

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 23:42:26 -07:00

62 lines
2.2 KiB
TypeScript

import { currentSession } from '@/lib/auth';
import { addMessage, loadMessages, publicMessages } from '@/lib/page-thread';
import { allowRequest, boundedJson, sameOrigin } from '@/lib/request-guards';
export const dynamic = 'force-dynamic';
export async function GET(request: Request) {
const path = new URL(request.url).searchParams.get('path') ?? '';
if (!path.startsWith('/')) return Response.json({ error: 'Bad path' }, { status: 400 });
try {
const messages = publicMessages(path, await loadMessages(path));
return Response.json({
data: messages.map((m) => ({
id: m.id,
authorId: m.authorId,
body: m.body,
createdAt: m.createdAt,
})),
});
} catch {
return Response.json({ data: [] });
}
}
export async function POST(request: Request) {
if (!sameOrigin(request)) return Response.json({ error: 'Origin not allowed' }, { status: 403 });
const session = await currentSession();
if (!session?.actorId) return Response.json({ error: 'Sign in to comment.' }, { status: 401 });
try {
// `allowRequest` throws when AUTH_SECRET is unset; answer like the rest of
// the file instead of surfacing a Next.js digest.
if (!(await allowRequest(request, 'comment', 20)))
return Response.json({ error: 'Hourly comment limit reached.' }, { status: 429 });
} catch {
return Response.json({ error: 'Comments are not available yet.' }, { status: 503 });
}
let input: { path?: string; body?: string };
try {
input = (await boundedJson(request)) as { path?: string; body?: string };
} catch {
return Response.json({ error: 'Invalid request' }, { status: 400 });
}
if (
!input.path?.startsWith('/') ||
typeof input.body !== 'string' ||
input.body.trim().length < 3
)
return Response.json({ error: 'Write a short comment.' }, { status: 400 });
try {
const saved = await addMessage(
input.path,
session.actorId,
input.body.trim().slice(0, 4000),
'human',
);
return Response.json({ success: true, data: saved });
} catch (error) {
console.error('comment write failed', error instanceof Error ? error.name : 'unknown');
return Response.json({ error: 'Comments are not available yet.' }, { status: 503 });
}
}