- load static files at startup so a missing file fails fast instead of crashing on request - WAL + busy_timeout so a manual export cannot fail live submissions - exit cleanly on SIGTERM (node is PID 1 in the container) - honour PORT=0 - document a required ingress rate limit - square card corners and larger card titles Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfmHGGiYUjNcvJoyzdf
116 lines
4.6 KiB
JavaScript
116 lines
4.6 KiB
JavaScript
const http = require('node:http');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { DatabaseSync } = require('node:sqlite');
|
|
|
|
const MAX_BODY = 10 * 1024;
|
|
const REQUIRED = ['name', 'email', 'phone', 'company'];
|
|
const OPTIONAL = ['industry', 'message', 'referrer', 'utm_source', 'utm_medium', 'utm_campaign'];
|
|
const MAX_LEN = { message: 2000, referrer: 500 };
|
|
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
const PAGES = { '/': ['index.html', 'text/html; charset=utf-8'], '/logo.png': ['logo.png', 'image/png'] };
|
|
|
|
function openDb(dbPath) {
|
|
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
|
const db = new DatabaseSync(dbPath);
|
|
// WAL: an export (reader) never blocks inserts. busy_timeout blocks the event loop while waiting,
|
|
// ponytail: fine for one low-traffic pod; move to Postgres if this ever needs concurrency.
|
|
db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');
|
|
db.exec(`CREATE TABLE IF NOT EXISTS leads (
|
|
id INTEGER PRIMARY KEY,
|
|
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
name TEXT NOT NULL, email TEXT NOT NULL, phone TEXT NOT NULL, company TEXT NOT NULL,
|
|
industry TEXT, message TEXT, referrer TEXT,
|
|
utm_source TEXT, utm_medium TEXT, utm_campaign TEXT
|
|
)`);
|
|
return db;
|
|
}
|
|
|
|
function validate(lead) {
|
|
for (const f of REQUIRED) {
|
|
if (typeof lead[f] !== 'string' || !lead[f].trim()) return `${f} is required`;
|
|
}
|
|
for (const f of [...REQUIRED, ...OPTIONAL]) {
|
|
const v = lead[f];
|
|
if (v != null && typeof v !== 'string') return `${f} must be text`;
|
|
if (v && v.length > (MAX_LEN[f] || 200)) return `${f} is too long`;
|
|
}
|
|
if (!EMAIL.test(lead.email.trim())) return 'email is invalid';
|
|
return null;
|
|
}
|
|
|
|
function send(res, status, body) {
|
|
res.writeHead(status, { 'content-type': 'application/json' });
|
|
res.end(JSON.stringify(body));
|
|
}
|
|
|
|
function readBody(req) {
|
|
return new Promise((resolve, reject) => {
|
|
let size = 0;
|
|
const chunks = [];
|
|
req.on('data', (c) => {
|
|
size += c.length;
|
|
// keep draining (not destroy) so the 413 reaches the client; the ingress body limit (nginx default 1m) caps abuse
|
|
if (size > MAX_BODY) reject(Object.assign(new Error('too large'), { status: 413 }));
|
|
else chunks.push(c);
|
|
});
|
|
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
req.on('error', reject);
|
|
});
|
|
}
|
|
|
|
function createServer(dbPath) {
|
|
// load static files up front: a missing file fails at startup instead of crashing on a request
|
|
const files = {};
|
|
for (const [url, [file, type]] of Object.entries(PAGES)) {
|
|
files[url] = { body: fs.readFileSync(path.join(__dirname, 'public', file)), type };
|
|
}
|
|
const db = openDb(dbPath);
|
|
const insert = db.prepare(`INSERT INTO leads
|
|
(name, email, phone, company, industry, message, referrer, utm_source, utm_medium, utm_campaign)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
const url = req.url.split('?')[0];
|
|
|
|
if (req.method === 'GET' && files[url]) {
|
|
res.writeHead(200, { 'content-type': files[url].type });
|
|
return res.end(files[url].body);
|
|
}
|
|
if (req.method === 'POST' && url === '/api/leads') {
|
|
let lead;
|
|
try {
|
|
lead = JSON.parse(await readBody(req));
|
|
} catch (e) {
|
|
return send(res, e.status || 400, { error: e.status ? 'Request too large' : 'Invalid request' });
|
|
}
|
|
if (!lead || typeof lead !== 'object') return send(res, 400, { error: 'Invalid request' });
|
|
if (lead.website) return send(res, 200, { ok: true }); // honeypot: pretend success, store nothing
|
|
const error = validate(lead);
|
|
if (error) return send(res, 400, { error });
|
|
try {
|
|
const t = (f) => (lead[f] ? lead[f].trim() : null);
|
|
insert.run(t('name'), t('email'), t('phone'), t('company'), t('industry'), t('message'),
|
|
t('referrer'), t('utm_source'), t('utm_medium'), t('utm_campaign'));
|
|
} catch (e) {
|
|
console.error('lead insert failed:', e.message);
|
|
return send(res, 500, { error: 'Could not save, please try again' });
|
|
}
|
|
return send(res, 201, { ok: true });
|
|
}
|
|
send(res, 404, { error: 'Not found' });
|
|
});
|
|
server.on('close', () => db.close());
|
|
return server;
|
|
}
|
|
|
|
module.exports = { createServer };
|
|
|
|
if (require.main === module) {
|
|
const port = Number(process.env.PORT ?? 3000);
|
|
const server = createServer(process.env.DB_PATH || path.join(__dirname, 'data', 'leads.db'));
|
|
server.listen(port, () => console.log(`listening on :${port}`));
|
|
// node as PID 1 ignores SIGTERM by default; exit cleanly so k8s rollouts don't wait 30s
|
|
process.on('SIGTERM', () => server.close(() => process.exit(0)));
|
|
}
|