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:
parent
2434879804
commit
c14081d85f
14 changed files with 2306 additions and 0 deletions
116
server/src/app.ts
Normal file
116
server/src/app.ts
Normal 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;
|
||||
}
|
||||
50
server/src/auth.ts
Normal file
50
server/src/auth.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { timingSafeEqual } from 'node:crypto';
|
||||
|
||||
/** Constant-time string compare (guards the admin token check against timing attacks). */
|
||||
export function safeEqual(a: string, b: string): boolean {
|
||||
const ba = Buffer.from(a);
|
||||
const bb = Buffer.from(b);
|
||||
if (ba.length !== bb.length) return false;
|
||||
return timingSafeEqual(ba, bb);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks failed admin-auth attempts per IP and auto-blocks an IP for a cooldown
|
||||
* after too many failures in a rolling window. In-memory (resets on restart) —
|
||||
* complements the persistent manual denylist in the DB.
|
||||
*/
|
||||
export class AbuseGuard {
|
||||
private fails = new Map<string, number[]>();
|
||||
private blockedUntil = new Map<string, number>();
|
||||
|
||||
constructor(
|
||||
private readonly limit: number,
|
||||
private readonly windowMs: number,
|
||||
private readonly cooldownMs: number,
|
||||
) {}
|
||||
|
||||
isBlocked(ip: string, now: number): boolean {
|
||||
const until = this.blockedUntil.get(ip);
|
||||
if (until == null) return false;
|
||||
if (until > now) return true;
|
||||
this.blockedUntil.delete(ip);
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Returns true if this failure just tripped an auto-block. */
|
||||
recordFail(ip: string, now: number): boolean {
|
||||
const recent = (this.fails.get(ip) ?? []).filter((t) => now - t < this.windowMs);
|
||||
recent.push(now);
|
||||
if (recent.length >= this.limit) {
|
||||
this.blockedUntil.set(ip, now + this.cooldownMs);
|
||||
this.fails.delete(ip);
|
||||
return true;
|
||||
}
|
||||
this.fails.set(ip, recent);
|
||||
return false;
|
||||
}
|
||||
|
||||
recordSuccess(ip: string): void {
|
||||
this.fails.delete(ip);
|
||||
}
|
||||
}
|
||||
114
server/src/db.ts
Normal file
114
server/src/db.ts
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import Database from 'better-sqlite3';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
export type LabelKind = 'free_2h' | 'free_3h' | 'free_4h' | 'pay_immediate';
|
||||
export const LABEL_KINDS: LabelKind[] = ['free_2h', 'free_3h', 'free_4h', 'pay_immediate'];
|
||||
|
||||
export function isLabelKind(v: unknown): v is LabelKind {
|
||||
return typeof v === 'string' && (LABEL_KINDS as string[]).includes(v);
|
||||
}
|
||||
|
||||
export interface ZoneLabel {
|
||||
zoneId: string;
|
||||
customerId: string | null;
|
||||
zoneName: string | null;
|
||||
kind: LabelKind;
|
||||
note: string | null;
|
||||
updatedAt: number;
|
||||
updatedBy: string | null;
|
||||
}
|
||||
|
||||
interface Row {
|
||||
zone_id: string;
|
||||
customer_id: string | null;
|
||||
zone_name: string | null;
|
||||
kind: string;
|
||||
note: string | null;
|
||||
updated_at: number;
|
||||
updated_by: string | null;
|
||||
}
|
||||
|
||||
const toLabel = (r: Row): ZoneLabel => ({
|
||||
zoneId: r.zone_id,
|
||||
customerId: r.customer_id,
|
||||
zoneName: r.zone_name,
|
||||
kind: r.kind as LabelKind,
|
||||
note: r.note,
|
||||
updatedAt: r.updated_at,
|
||||
updatedBy: r.updated_by,
|
||||
});
|
||||
|
||||
/** SQLite-backed store for zone labels + a manual IP denylist. */
|
||||
export class LabelDb {
|
||||
private db: Database.Database;
|
||||
|
||||
constructor(path: string) {
|
||||
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
|
||||
this.db = new Database(path);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS zone_labels (
|
||||
zone_id TEXT PRIMARY KEY,
|
||||
customer_id TEXT,
|
||||
zone_name TEXT,
|
||||
kind TEXT NOT NULL,
|
||||
note TEXT,
|
||||
updated_at INTEGER NOT NULL,
|
||||
updated_by TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS blocked_ips (
|
||||
ip TEXT PRIMARY KEY,
|
||||
reason TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
}
|
||||
|
||||
all(): ZoneLabel[] {
|
||||
return (this.db.prepare('SELECT * FROM zone_labels ORDER BY zone_id').all() as Row[]).map(toLabel);
|
||||
}
|
||||
|
||||
get(zoneId: string): ZoneLabel | undefined {
|
||||
const r = this.db.prepare('SELECT * FROM zone_labels WHERE zone_id = ?').get(zoneId) as Row | undefined;
|
||||
return r ? toLabel(r) : undefined;
|
||||
}
|
||||
|
||||
upsert(label: ZoneLabel): void {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO zone_labels (zone_id, customer_id, zone_name, kind, note, updated_at, updated_by)
|
||||
VALUES (@zoneId, @customerId, @zoneName, @kind, @note, @updatedAt, @updatedBy)
|
||||
ON CONFLICT(zone_id) DO UPDATE SET
|
||||
customer_id = excluded.customer_id,
|
||||
zone_name = excluded.zone_name,
|
||||
kind = excluded.kind,
|
||||
note = excluded.note,
|
||||
updated_at = excluded.updated_at,
|
||||
updated_by = excluded.updated_by`,
|
||||
)
|
||||
.run(label);
|
||||
}
|
||||
|
||||
delete(zoneId: string): boolean {
|
||||
return this.db.prepare('DELETE FROM zone_labels WHERE zone_id = ?').run(zoneId).changes > 0;
|
||||
}
|
||||
|
||||
isBlocked(ip: string): boolean {
|
||||
return !!this.db.prepare('SELECT 1 FROM blocked_ips WHERE ip = ?').get(ip);
|
||||
}
|
||||
|
||||
block(ip: string, reason: string): void {
|
||||
this.db
|
||||
.prepare('INSERT OR REPLACE INTO blocked_ips (ip, reason, created_at) VALUES (?, ?, ?)')
|
||||
.run(ip, reason, Date.now());
|
||||
}
|
||||
|
||||
seedBlocked(ips: string[]): void {
|
||||
for (const ip of ips) this.block(ip, 'seed');
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
34
server/src/index.ts
Normal file
34
server/src/index.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { buildApp } from './app.js';
|
||||
|
||||
const adminToken = process.env.BBP_ADMIN_TOKEN ?? '';
|
||||
if (adminToken.length < 16) {
|
||||
console.error('FATAL: BBP_ADMIN_TOKEN is missing or shorter than 16 chars.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const app = await buildApp({
|
||||
adminToken,
|
||||
dbPath: process.env.BBP_DB_PATH ?? '/data/labels.db',
|
||||
trustProxy: true,
|
||||
seedBlockedIps: (process.env.BBP_BLOCKED_IPS ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
});
|
||||
|
||||
const port = Number(process.env.PORT ?? 8090);
|
||||
const host = process.env.HOST ?? '0.0.0.0';
|
||||
|
||||
try {
|
||||
await app.listen({ port, host });
|
||||
console.log(`bbp-labels listening on ${host}:${port}`);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
for (const sig of ['SIGINT', 'SIGTERM'] as const) {
|
||||
process.on(sig, () => {
|
||||
void app.close().then(() => process.exit(0));
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue