Files
ins-landing-page/server.test.js
T
ngqileandClaude Opus 5.5 f75da6d928 fix: harden server per final review
- 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
2026-12-01 10:43:30 +08:00

133 lines
4.5 KiB
JavaScript

const { test, before, after } = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { DatabaseSync } = require('node:sqlite');
const { createServer } = require('./server');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-leads-'));
const dbPath = path.join(dir, 'leads.db');
let server, base;
before(async () => {
server = createServer(dbPath);
await new Promise((r) => server.listen(0, r));
base = `http://127.0.0.1:${server.address().port}`;
});
after(() => {
server.close();
fs.rmSync(dir, { recursive: true, force: true });
});
const valid = {
name: 'Aisyah Rahman',
email: 'aisyah@example.com',
phone: '+60 12-345 6789',
company: 'Hotel Seri Pinang',
industry: 'Hospitality',
message: 'Need guest Wi-Fi for 120 rooms',
utm_source: 'google',
referrer: 'https://www.google.com/',
};
const post = (body) =>
fetch(`${base}/api/leads`, {
method: 'POST',
headers: { 'content-type': 'application/json', referer: 'https://ads.example.com/' },
body: typeof body === 'string' ? body : JSON.stringify(body),
});
const rows = () => {
const db = new DatabaseSync(dbPath);
const r = db.prepare('SELECT * FROM leads').all();
db.close();
return r;
};
test('serves the landing page', async () => {
const res = await fetch(`${base}/`);
assert.strictEqual(res.status, 200);
assert.match(res.headers.get('content-type'), /text\/html/);
});
test('valid lead is stored', async () => {
const res = await post(valid);
assert.strictEqual(res.status, 201);
const r = rows();
assert.strictEqual(r.length, 1);
assert.strictEqual(r[0].name, valid.name);
assert.strictEqual(r[0].company, valid.company);
assert.strictEqual(r[0].utm_source, 'google');
assert.strictEqual(r[0].referrer, 'https://www.google.com/');
assert.ok(r[0].created_at);
});
test('missing required field is rejected', async () => {
const before = rows().length;
const res = await post({ ...valid, phone: '' });
assert.strictEqual(res.status, 400);
assert.ok((await res.json()).error);
assert.strictEqual(rows().length, before);
});
test('invalid email is rejected', async () => {
assert.strictEqual((await post({ ...valid, email: 'abc' })).status, 400);
});
test('over-long field is rejected', async () => {
assert.strictEqual((await post({ ...valid, name: 'x'.repeat(201) })).status, 400);
});
test('non-JSON body is rejected', async () => {
assert.strictEqual((await post('not json')).status, 400);
});
test('oversized body is rejected', async () => {
assert.strictEqual((await post({ ...valid, message: 'x'.repeat(11000) })).status, 413);
});
test('honeypot submission is accepted but not stored', async () => {
const before = rows().length;
const res = await post({ ...valid, website: 'http://spam.example' });
assert.strictEqual(res.status, 200);
assert.strictEqual(rows().length, before);
});
const { spawn } = require('node:child_process');
test('missing page file fails at startup, not on a request', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-nopage-'));
fs.copyFileSync(path.join(__dirname, 'server.js'), path.join(tmp, 'server.js'));
const { createServer: create } = require(path.join(tmp, 'server.js'));
assert.throws(() => create(path.join(tmp, 'leads.db')), /ENOENT/);
fs.rmSync(tmp, { recursive: true, force: true });
});
test('insert waits for a lock held by another process (e.g. an export)', async () => {
const lock = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', '-e', `
const { DatabaseSync } = require('node:sqlite');
const db = new DatabaseSync(${JSON.stringify(dbPath)});
db.exec('BEGIN EXCLUSIVE');
console.log('locked');
setTimeout(() => { db.exec('COMMIT'); db.close(); }, 500);
`]);
await new Promise((r) => lock.stdout.once('data', r));
const res = await post(valid);
assert.strictEqual(res.status, 201);
});
test('exits promptly on SIGTERM', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-term-'));
const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', path.join(__dirname, 'server.js')], {
env: { ...process.env, PORT: '0', DB_PATH: path.join(tmp, 'leads.db') },
});
await new Promise((r) => child.stdout.once('data', r));
const start = Date.now();
child.kill('SIGTERM');
const code = await new Promise((r) => child.on('exit', (c) => r(c)));
assert.strictEqual(code, 0);
assert.ok(Date.now() - start < 2000);
fs.rmSync(tmp, { recursive: true, force: true });
});