One line of HTML on someone else's site, every request hostile — and not one valid lead lost when the geo providers or the mail server go down.
A multi-tenant backend behind a one-line embeddable form widget, where every public request is treated as hostile and no valid lead is lost when geo or email fail.
Site owners sign up, build a form — a newsletter signup, a contact form — and get one line of HTML to paste into their website. Visitors fill it in, the leads land in the owner's private dashboard tagged with a rough location, and each visitor gets a confirmation email.
The form is the easy part. The hard part is everything that one line implies:
So the design rule from day one was one sentence: treat every request to the public endpoint as hostile, and never lose a valid lead because something optional broke.
The system is split by who is calling, because each caller needs different rules:
POST /submissions. No identity; open CORS, no caching; main risk is abuse and failure.CORS is not server security — it protects browsers, and curl ignores it. The public routes can safely send Access-Control-Allow-Origin: * because they never use cookies. What protects the owner API is the token, not a header.
Routes → services → repositories. Routes never touch SQL, services never touch req/res, and repositories are the only place SQL lives.
That turns tenant isolation into something you can verify with grep: every owner query has WHERE owner_id = $n.
Email and the daily IP clean-up run in a separate worker process through pg-boss, a job queue stored in the same Postgres, so slow background work never touches the API.
The owner pastes the script tag once and never touches it again — but we still need to ship fixes. So delivery is split in two:
/widget.js — a tiny loader on a fixed URL, cached for 5 minutes. Its only job is to insert the real bundle./widget.<hash>.js — the 4,595-byte bundle, named by a content hash and cached for a year as immutable.A deploy changes the hash, and within five minutes every visitor is on the new code. The hash reproduced byte-for-byte on a fresh clone, which is what makes a year-long cache safe.
The widget config is cached for 60 s with an ETag. Even a 404 is cached for 10 s, so a dead widget id on a busy page doesn't hit the database on every view; a 500 is never cached. Its SQL lists columns explicitly, so owner_id can never leak into a public response.
The widget renders inside a shadow root. A test site on a second origin applies !important crimson, 40px Comic Sans to every element — the widget is untouched.
textContent. A grep of the widget for innerHTML, insertAdjacentHTML, document.write, eval and new Function finds zero uses.#rrggbb and applied with style.setProperty.A real browser caught what curl couldn't: the rate-limit message always said "60 seconds", because Retry-After isn't a CORS-safelisted header and JavaScript read it as null. One Access-Control-Expose-Headers line later, it showed the real 32 seconds left.
POST /submissions is the one endpoint anyone can call. Each step rejects cheaply before the next, more expensive one runs:
415 unless JSON, then parse at most 10 kB.__proto__ is impossible.422 with a 201. A caught bot gets a fake 201 with the exact shape of a real one; nothing is stored or sent.Ownership comes from the database, never the request: the body carries only the public widget id, and the widget row decides the owner. The IP comes from the socket with trust proxy off, so a forged X-Forwarded-For is ignored.
The widget sends an Idempotency-Key per version of the form — the same key while the visitor retries the same answers, a new one the moment they edit anything.
The server inserts with ON CONFLICT (widget_id, idempotency_key) DO NOTHING. Check-then-insert has a race; a unique index makes it one atomic step, and a retry gets the original row back.
crypto.randomUUID() only works on HTTPS pages, and a customer's site might be plain HTTP, so the widget builds a v4 UUID from getRandomValues instead.
The lookup tries ip-api.com, then ipapi.co, then returns null — it never throws. Each provider gets its own 1.5 s timeout, so a slow first provider can't use up the second one's time.
Private and loopback addresses never leave the server. Failures are logged with the provider and reason, never the IP.
A failed lookup stores SQL NULL, not JSON.stringify(null) — that would be a JSON null, which WHERE geo IS NULL never finds.
Fault-injection flags (GEO_FORCE_DOWN, GEO_TEST_IP) prove the chain on demand, and the server refuses to boot with them when NODE_ENV=production.
Insert the lead first, then queue the email. If queuing fails, it's logged and the visitor still gets 201 — an early draft rethrew it, which would have turned a queue hiccup into a 500 for a lead that was already stored.
singletonKey turned out not to deduplicate on a standard queue, so the submission id is the job id instead — a second send returns null.ALERT line.The email is plain text, so there's no HTML to inject into, and the internal submission id was removed from it — the visitor had no use for it.
Passwords are hashed with Argon2id; a failed login gets one generic message. Another tenant's widget returns a 404 byte-for-byte identical to one that doesn't exist — a 403 would confirm the id is real. The owner API never returns a visitor's IP.
All counting happens in SQL, never by loading rows into Node:
LEFT JOIN from widgets with count(s.id), not count(*), so a widget with no leads shows 0, not 1.generate_series gives one row per day, so quiet days show as zero instead of disappearing from the chart.country: null, so the per-country numbers always add up to the total.err.client was added after a dropped DB connection logged the whole Postgres client — including a cancellation secret key.Bad input never crashes the server. I sent the public endpoint 32 requests, mixing valid ones with deliberately broken and malicious ones (empty bodies, wrong content types, invalid characters, a compressed "zip bomb"). Every bad request was rejected with a clear 4xx error explaining what was wrong, and none caused a 500. The test also found one real bug: a corrupted compressed body caused a 500. It was fixed and now returns a 400 on every route.
1 stored row from 5 parallel requests with the same Idempotency-Key: a double-click or network retry never creates a duplicate lead or a second email.
30 parallel submissions from one IP → 10 accepted, 20 rejected with 429 and Retry-After, and normal traffic accepted again once the window resets.
201 and the lead stored even with both geo providers down or the mail server failing. A failing email makes 4 attempts, lands in a dead-letter queue and raises exactly one ALERT. In two live runs the backup geo provider really did time out and return 429 — and the lead was still kept.
EXPLAIN on 100,000 rows found a full-table scan behind a correct number: 100,095 → 5,091 rows read and 13.6 ms → 4.7 ms, with no new index. The first page of leads reads 22 rows in 0.2 ms.
4,595-byte widget bundle whose content hash reproduced byte-for-byte on a fresh clone — cached for a year, while fixes still reach every visitor within 5 minutes.
0 raw IP addresses in API or worker logs across every end-to-end run; stored IPs are cleared after 90 days.
98 tests in 13 files passing on a fresh database every run — and proven able to fail: 3 deliberately injected bugs turned 2, 8 and 1 tests red.