Audit pass with the threats that actually apply to a self-hosted, account-less app: getting the Ollama key throttled or banned, and someone grinding the app down. Per-route windows already existed; these are the missing layers. - lib/model-guard.ts: every route that spends a model call now takes a slot — 60 calls per window across all clients (RATE_LIMIT_MODEL_TOTAL), 3 in flight per IP, 6 in total — and the slot is released when the call finishes, on errors and on client disconnects. Over the concurrency cap answers 429 kind=busy, not a punishment. Slots are taken after every cheap rejection so a malformed request cannot hold one (found by the new suite: early 400s were leaking slots). - Images must be base64 data URLs (dataUrlSchema in lib/schemas): a plain URL in an images field made Ollama fetch an arbitrary address on our behalf. - Push endpoints must be a real push service (PUSH_ALLOWED_HOSTS, defaulting to FCM/Mozilla/Apple/WNS): the server POSTs to whatever is stored. - The rate-limit identity is the LAST x-forwarded-for hop. Reading the first let a client spoof its own IP and dodge every per-IP limit. - Disk guards: reports.jsonl stops at REPORTS_MAX_BYTES (8 MB), reminder devices cap at PUSH_MAX_SUBSCRIPTIONS (50). - Security headers: frame-ancestors 'none' + X-Frame-Options DENY, nosniff, a referrer policy and a Permissions-Policy without camera/mic/geo/payment. New tests/security-test.mjs (13 checks, registered in run-all) proves each guard against a slow stub Ollama with deliberately tiny limits. README: security notes + rate-limit tables updated. Version 0.1.3, SW -> v51.
69 lines
2.7 KiB
TypeScript
69 lines
2.7 KiB
TypeScript
import { promises as fs } from "node:fs";
|
|
import path from "node:path";
|
|
import { z } from "zod";
|
|
|
|
import { getServerConfig } from "@/lib/config";
|
|
import { rejectCrossOrigin, rejectOversizedBody, requestLocale } from "@/lib/http-guard";
|
|
import { clientKey, rateLimit, rateLimitResponse } from "@/lib/rate-limit";
|
|
|
|
export const runtime = "nodejs";
|
|
export const dynamic = "force-dynamic";
|
|
|
|
/**
|
|
* Question reports. Write-only on purpose: the app has no auth, so nothing
|
|
* here is readable over HTTP. Every report is appended as one JSON line to
|
|
* `<reports dir>/reports.jsonl` under the shared data directory, where the
|
|
* operator can inspect it:
|
|
*
|
|
* tail -f ~/freezmo-prod/shared/freezmo/reports/reports.jsonl
|
|
*
|
|
* The browser keeps its own copy of the reports — it is the source of truth
|
|
* for skipping and Undo. This file is the cross-device record for tuning the
|
|
* generation prompts.
|
|
*/
|
|
|
|
const reportSchema = z.object({
|
|
deckId: z.string().min(1).max(80),
|
|
deckTitle: z.string().max(200).optional(),
|
|
activityId: z.string().min(1).max(80),
|
|
type: z.string().min(1).max(40),
|
|
question: z.string().min(1).max(600),
|
|
at: z.number(),
|
|
});
|
|
|
|
/** A report is tiny; anything bigger is not one. */
|
|
const MAX_BODY_BYTES = 4096;
|
|
|
|
export async function POST(request: Request) {
|
|
const locale = requestLocale(request);
|
|
const crossOrigin = rejectCrossOrigin(request);
|
|
if (crossOrigin) return crossOrigin;
|
|
const oversized = rejectOversizedBody(request, MAX_BODY_BYTES);
|
|
if (oversized) return oversized;
|
|
|
|
const config = getServerConfig();
|
|
const limit = rateLimit(`reports:${clientKey(request)}`, config.rateLimits.reports, config.rateLimits.windowMs);
|
|
if (!limit.allowed) return rateLimitResponse(limit, locale);
|
|
|
|
const parsed = reportSchema.safeParse(await request.json().catch(() => null));
|
|
if (!parsed.success) return Response.json({ error: "invalid report" }, { status: 400 });
|
|
|
|
const line = JSON.stringify({ ...parsed.data, receivedAt: new Date().toISOString() });
|
|
try {
|
|
await fs.mkdir(config.reports.dir, { recursive: true });
|
|
const file = path.join(config.reports.dir, "reports.jsonl");
|
|
/* Disk guard: reports are a convenience for the operator, so once the
|
|
file passes the cap the app stops appending (the browser's own list is
|
|
still the source of truth for skipping). */
|
|
const size = await fs.stat(file).then((stats) => stats.size).catch(() => 0);
|
|
if (size >= config.reports.maxBytes) {
|
|
console.warn("[api/reports] reports.jsonl is at its size cap — not appending");
|
|
return Response.json({ ok: true });
|
|
}
|
|
await fs.appendFile(file, `${line}\n`, "utf8");
|
|
} catch {
|
|
return Response.json({ error: "could not store the report" }, { status: 500 });
|
|
}
|
|
|
|
return Response.json({ ok: true });
|
|
}
|