Files
ins-landing-page/server.js
T
ngqileandClaude Opus 5.5 c2ebee08df feat: hotel technology landing page per owner brief
- new copy and sections for the five hotel services
- form fields: name, work email, phone, company, service
- reject free email providers on page and server
- second form in the final CTA, mobile WhatsApp/call bar
- schema: industry and message replaced by service

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfmHGGiYUjNcvJoyzdf
2026-12-01 11:12:04 +08:00

122 lines
5.1 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 = ['service', 'referrer', 'utm_source', 'utm_medium', 'utm_campaign'];
const MAX_LEN = { referrer: 500 };
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const SERVICES = ['WiFi Managed Services', 'Cloud IP PABX', 'GRE IPTV', 'Digital Signage', 'QR Door Locks', 'Not sure yet'];
// matches the domain's first label, so yahoo.com.my, hotmail.co.uk etc. are covered.
// ponytail: fixed list of the common providers; extend if sales sees others slip through.
const FREE_EMAIL = /@(gmail|googlemail|yahoo|ymail|rocketmail|hotmail|outlook|live|msn|icloud|me|mac|aol|protonmail|proton|gmx|yandex|zoho)\.[a-z.]+$/i;
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,
service 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';
if (FREE_EMAIL.test(lead.email.trim())) return 'Please use your work email address';
if (lead.service && !SERVICES.includes(lead.service)) return 'service 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, service, 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('service'),
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)));
}