lead-capture-platformcapstone

Embeddable Widget and Lead Capture Platform

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.

Node 22Express 5PostgreSQLpg-bossZodVitest
0
automated tests, fresh DB per run
0
server crashes in a 32-request attack test
0.0 kB
widget bundle, cached for a year
0.0 ms
first dashboard page at 100k rows

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.

01

Context & problem

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:

  • Our JavaScript runs inside someone else's page, next to CSS and scripts we have never seen.
  • The submission endpoint is public. Anyone can call it, with any body, as fast as they like, without ever loading our widget.
  • Location and email depend on third-party services we don't control — and they will fail.
  • Many owners share one database, and an owner must never see another owner's leads.

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.

02

Solution

01Three callers, three rule sets

The system is split by who is calling, because each caller needs different rules:

  • Owner — manages widgets and reads leads. Proves identity with a JWT; CORS closed; main risk is tenant isolation.
  • Customer's website — loads the widget and its config. No identity; open CORS, aggressive caching; main concern is speed.
  • Visitor — 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.

02Strict layering

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.

03Shipping code onto someone else's page

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.

04Surviving a hostile host page

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.

  • Text only enters the page through textContent. A grep of the widget for innerHTML, insertAdjacentHTML, document.write, eval and new Function finds zero uses.
  • The only CSS a tenant controls is a colour, validated server-side as exactly #rrggbb and applied with style.setProperty.
  • Shadow DOM is a styling boundary, not a security boundary — an injected script would still run with the host page's privileges. That's why the rules above exist.

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.

05The front door: order is the defence

POST /submissions is the one endpoint anyone can call. Each step rejects cheaply before the next, more expensive one runs:

  • Per-IP limit (10/min) — before the body is even read, so a flood of junk costs almost nothing.
  • 415 unless JSON, then parse at most 10 kB.
  • Per-widget limit (100/min) — keyed only on well-formed ids, so made-up ids share one bucket instead of each getting a fresh quota.
  • Validation against a Zod schema built at runtime from the widget's own fields — unknown keys rejected, lengths capped, field names restricted so __proto__ is impossible.
  • Honeypot — after validation, so a bot can't probe for it by comparing a 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.

06Idempotency: the double-click problem

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.

07Optional means optional: geo

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.

08Optional means optional: email

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.

  • The job carries only the submission id, so no personal data is copied into the queue table.
  • pg-boss's singletonKey turned out not to deduplicate on a standard queue, so the submission id is the job id instead — a second send returns null.
  • 3 retries with exponential backoff and jitter, then a dead-letter queue whose handler logs an 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.

09Tenant isolation and the dashboard

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.
  • Rows without geo count under country: null, so the per-country numbers always add up to the total.

10Privacy by default

  • The raw IP is never logged — every end-to-end run grepped all API and worker logs for addresses and found 0.
  • It's never returned to owners, and a daily job clears it after 90 days while keeping the lead and its location.
  • The logger redacts auth headers, cookies, passwords and tokens. err.client was added after a dropped DB connection logged the whole Postgres client — including a cancellation secret key.
// how a lead travels from a stranger's page to the owner's dashboard
customer site
one <script> tag
loaderwidget.js · 5 min cache
bundlewidget.<hash>.js · 1 year
widgetshadow DOM · textContent only
API processroutes → services → repositories
geo chainip-api → ipapi.co → null
PostgreSQLowner-scoped rows · pg-boss jobs
worker processemail · retries · dead letter
owner dashboardJWT · aggregated in SQL
// POST /submissions — the cheapest rejection always runs first
per-IP limit
10/min · before body is read
JSON only415 · max 10 kB
per-widget limit100/min · valid ids only
validationruntime Zod schema · 404 / 422
honeypotafter validation · fake 201
geo lookupnever throws
INSERT … ON CONFLICTatomic idempotency
queue email
failure only logged → 201
zsh
$ node scripts/attack.js
Burst: 30 parallel POST http://localhost:3000/submissions (widget lvuvcZeFr-42)
Done in 358 ms. Status counts: { '201': 10, '429': 20 }
Sample 429:
Retry-After: 60
RateLimit: "10-in-1min"; r=0; t=60
Body: {"error":{"code":"RATE_LIMITED","message":"Too many requests, try again later"}}
Waiting 61 s for the window to reset...
Normal request after the window: 201 {"id":"b913cd09-…","createdAt":"2026-11-13T23:41:04.860Z"}
PASS
src/repositories/submissionsRepository.js
// ON CONFLICT makes "does this key exist?" and "insert" ONE atomic step.
// With SELECT-then-INSERT, a double-click could insert twice.
export async function insertSubmission({ widgetId, ownerId, data, ip, geo, idempotencyKey }) {
const inserted = await pool.query(
`INSERT INTO submissions (widget_id, owner_id, data, ip, idempotency_key, geo)
VALUES ($1, $2, $3::jsonb, $4, $5, $6::jsonb)
ON CONFLICT (widget_id, idempotency_key) DO NOTHING
RETURNING id, created_at AS "createdAt"`,
[widgetId, ownerId, JSON.stringify(data), ip, idempotencyKey,
geo ? JSON.stringify(geo) : null] // SQL NULL, not JSON null
);
if (inserted.rows[0]) return inserted.rows[0];
// no row returned = a retry: return the row the first attempt stored
...
}
03

Measurable impact

◆

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.

$ ./say-hello.sh

Let's talk about your backend.

Open to backend and platform engineering roles, and to interesting infrastructure problems. Fastest reply is by email.

© 2026 Elyas BromandBuilt with ♥ by Elyas Bromand↑ back to top