CI / build (push) Failing after 0s
Both images converted to WebP (1.4 MB and 2.0 MB PNG down to 60 KB and 100 KB) and served from the PAGES map. The photo already carries the network lines, so the inline SVG pattern is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfjzaeuedkpHBD7LkFm
150 lines
6.1 KiB
JavaScript
150 lines
6.1 KiB
JavaScript
const http = require('node:http');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { Pool } = require('pg');
|
|
|
|
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'],
|
|
// tab icons from infinitynetworks.com.my; /favicon.ico is what browsers try when no <link> is found
|
|
'/favicon.ico': ['favicon-32.png', 'image/png'],
|
|
'/favicon-32.png': ['favicon-32.png', 'image/png'],
|
|
'/favicon-192.png': ['favicon-192.png', 'image/png'],
|
|
'/apple-touch-icon.png': ['apple-touch-icon.png', 'image/png'],
|
|
'/hero-bg.webp': ['hero-bg.webp', 'image/webp'],
|
|
'/why-iptv.webp': ['why-iptv.webp', 'image/webp'],
|
|
};
|
|
|
|
// Kept identical to docs/schema.sql (a test compares the two).
|
|
const SCHEMA = `CREATE TABLE IF NOT EXISTS leads (
|
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
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
|
|
)`;
|
|
|
|
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; Cloudflare's body limit 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);
|
|
});
|
|
}
|
|
|
|
async function createServer(databaseUrl) {
|
|
// 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 };
|
|
}
|
|
// query_timeout: a Postgres that accepts connections but never answers must not hang requests
|
|
const pool = new Pool({ connectionString: databaseUrl, max: 5, connectionTimeoutMillis: 5000, query_timeout: 10000 });
|
|
// an idle connection dropped by Postgres (restart, failover) must not crash the process
|
|
pool.on('error', (e) => console.error('postgres pool error:', e.message));
|
|
try {
|
|
await pool.query(SCHEMA);
|
|
} catch (e) {
|
|
await pool.end();
|
|
throw e;
|
|
}
|
|
|
|
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);
|
|
await pool.query(`INSERT INTO leads
|
|
(name, email, phone, company, service, referrer, utm_source, utm_medium, utm_campaign)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
|
[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.pool = pool; // callers end it after server.close (see SIGTERM below)
|
|
return server;
|
|
}
|
|
|
|
module.exports = { createServer };
|
|
|
|
if (require.main === module) {
|
|
const port = Number(process.env.PORT ?? 3000);
|
|
if (!process.env.DATABASE_URL) {
|
|
console.error('DATABASE_URL is not set');
|
|
process.exit(1);
|
|
}
|
|
createServer(process.env.DATABASE_URL).then((server) => {
|
|
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
|
|
// finish in-flight requests, then close the database connections, then exit
|
|
process.on('SIGTERM', () => server.close(() => server.pool.end().finally(() => process.exit(0))));
|
|
}, (e) => {
|
|
// message only: the error never contains the password, but the URL would
|
|
console.error('startup failed:', e.message);
|
|
process.exit(1);
|
|
});
|
|
}
|