server: zone-labels API (Fastify + SQLite) — Phase A

New server/ service classifying zones as free_2h/3h/4h street vs pay_immediate
lots. Public reads; writes require the admin bearer token (timing-safe compare).
@fastify/rate-limit (120/min global, 20/min writes), manual IP denylist +
auto-block on repeated auth failures. SQLite via better-sqlite3. Dockerfile +
compose (loopback-only, mem/cpu capped) + nginx block + README. 9 tests pass.

Deployed live at https://bigbrainparking.mowden.top (behind nginx + certbot).
Not an npm workspace — kept out of the app/CI install to avoid the native dep.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Erik 2026-07-24 18:09:03 +00:00
parent 2434879804
commit c14081d85f
14 changed files with 2306 additions and 0 deletions

116
server/src/app.ts Normal file
View file

@ -0,0 +1,116 @@
import Fastify, { type FastifyReply, type FastifyRequest } from 'fastify';
import rateLimit from '@fastify/rate-limit';
import { LabelDb, LABEL_KINDS, isLabelKind, type ZoneLabel } from './db.js';
import { AbuseGuard, safeEqual } from './auth.js';
export interface BuildOptions {
adminToken: string;
/** File path for the SQLite DB, or ':memory:' (tests). Ignored if `db` is given. */
dbPath?: string;
db?: LabelDb;
trustProxy?: boolean;
rateLimitMax?: number;
rateLimitWindow?: string;
writeRateLimitMax?: number;
authFailLimit?: number;
authFailWindowMs?: number;
blockCooldownMs?: number;
seedBlockedIps?: string[];
}
interface ZoneParams {
zoneId: string;
}
interface PutBody {
kind?: unknown;
zoneName?: unknown;
customerId?: unknown;
note?: unknown;
}
const str = (v: unknown): string | null => (v == null ? null : String(v));
export async function buildApp(opts: BuildOptions) {
const db = opts.db ?? new LabelDb(opts.dbPath ?? ':memory:');
if (opts.seedBlockedIps?.length) db.seedBlocked(opts.seedBlockedIps);
const guard = new AbuseGuard(
opts.authFailLimit ?? 8,
opts.authFailWindowMs ?? 15 * 60 * 1000,
opts.blockCooldownMs ?? 60 * 60 * 1000,
);
const app = Fastify({ trustProxy: opts.trustProxy ?? true, logger: false, bodyLimit: 16 * 1024 });
await app.register(rateLimit, {
max: opts.rateLimitMax ?? 120,
timeWindow: opts.rateLimitWindow ?? '1 minute',
});
// Reject blocked IPs (manual denylist + auto-block) before anything else.
app.addHook('onRequest', async (req: FastifyRequest, reply: FastifyReply) => {
if (guard.isBlocked(req.ip, Date.now()) || db.isBlocked(req.ip)) {
return reply.code(403).send({ error: 'forbidden' });
}
});
const requireAdmin = async (req: FastifyRequest, reply: FastifyReply) => {
const hdr = req.headers.authorization ?? '';
const token = /^Bearer\s+(.+)$/i.exec(hdr)?.[1] ?? '';
if (!token || !safeEqual(token, opts.adminToken)) {
const tripped = guard.recordFail(req.ip, Date.now());
return reply.code(401).send({ error: 'unauthorized', blocked: tripped });
}
guard.recordSuccess(req.ip);
};
const writeLimit = {
config: { rateLimit: { max: opts.writeRateLimitMax ?? 20, timeWindow: '1 minute' } },
};
app.get('/healthz', async () => ({ ok: true }));
app.get('/api/whoami', { preHandler: requireAdmin }, async () => ({ admin: true }));
app.get('/api/labels', async () => ({ labels: db.all() }));
app.get('/api/labels/:zoneId', async (req: FastifyRequest<{ Params: ZoneParams }>, reply) => {
const label = db.get(req.params.zoneId);
if (!label) return reply.code(404).send({ error: 'not_found' });
return label;
});
app.put(
'/api/labels/:zoneId',
{ preHandler: requireAdmin, ...writeLimit },
async (req: FastifyRequest<{ Params: ZoneParams; Body: PutBody }>, reply) => {
const body = req.body ?? {};
if (!isLabelKind(body.kind)) {
return reply.code(400).send({ error: 'bad_kind', allowed: LABEL_KINDS });
}
const label: ZoneLabel = {
zoneId: String(req.params.zoneId),
customerId: str(body.customerId),
zoneName: str(body.zoneName),
kind: body.kind,
note: body.note == null ? null : String(body.note).slice(0, 500),
updatedAt: Date.now(),
updatedBy: 'admin',
};
db.upsert(label);
return label;
},
);
app.delete(
'/api/labels/:zoneId',
{ preHandler: requireAdmin, ...writeLimit },
async (req: FastifyRequest<{ Params: ZoneParams }>, reply) => {
if (!db.delete(req.params.zoneId)) return reply.code(404).send({ error: 'not_found' });
return { deleted: true };
},
);
app.addHook('onClose', async () => db.close());
return app;
}