Xer0x's Underground

Return of the Blog

Contents

License

Disclaimer & Intro


This post has been made as my notes, even though I attempt to explain what I have built and how, I do not owe anyone any explanation. Do NOT expect anything.


My blog is my garden.


WARNING: No AI was used in the making of this project. Not one token. Just source code, RFCs, and a free weekend.


A while ago I tore this blog down to studs and rebuilt it. Zero dependencies. Zero JavaScript in production. Under 14kB on the wire. default-src 'none'. A+ everywhere. I meant every word of it.


Then I wanted to know if anyone was reading.


That is the problem with principles. Reality eventually knocks. The moment you want a like button, a read counter, or any sense that the page is being seen by humans and not just crawlers, you are staring down the same fork in the road that produced the 2MB React blog in the first place: reach for a vendor, paste a tracking snippet, surrender the pipeline. Plausible. Google Analytics. A Disqus embed that ships 1.2MB and forty third-party requests to put a comment box under a 5kB article.


No. The whole point of owning the stack was to keep owning it. So the question became precise: how do you add live, stateful, interactive features to a static site without betraying a single thing the static site stood for?


This is that post.



The Constraints (Same Rules, Harder Game)


Before writing a line, I wrote the rules. A feature that breaks any of these does not ship:


  1. No third-party anything. No analytics SaaS. No comment widgets. No CDN-hosted scripts I do not control. If a request leaves my origin, I have a reason.
  2. No cookies. No localStorage tracking. No fingerprinting. A reader should be able to load a post, like it, and leave without a single identifier persisting on their machine.
  3. No raw PII. Ever. No IP address touches disk in plaintext. No "anonymised" data that de-anonymises with one join.
  4. JavaScript stays deferred. It may enhance the page. It may never block the page. The HTML still renders and reads with JS disabled.
  5. The 14kB budget holds for the critical HTML & CSS. Interactivity loads after first paint or not at all.
  6. The CSP stays strict. If I have to widen it, I widen it by the smallest possible amount.

Constraints are not the enemy of features. They are the spec for them.



The Honest Cost: One Line of CSP


Let me get the uncomfortable part out of the way first, because pretending it did not happen would be exactly the kind of vendor-brain dishonesty this blog exists to reject.


The old site shipped script-src 'none'. Nothing executed. An injected <script> was not just absent — it was forbidden at the browser level. That is the strongest posture there is, and I gave it up.


Here is the current policy, lifted straight from _headers:


Content-Security-Policy: default-src 'none'; script-src 'self' https://static.cloudflareinsights.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://bear-images.sfo2.cdn.digitaloceanspaces.com; font-src 'self'; connect-src 'self' https://cloudflareinsights.com; media-src 'none'; object-src 'none'; frame-src 'none'; frame-ancestors 'none'; worker-src 'none'; form-action 'self'; base-uri 'none'; manifest-src 'none'; navigate-to 'self'; upgrade-insecure-requests

Two directives moved:



That is the entire tax. One 'self' on script-src, one on connect-src. Everything that follows is built inside that box. If you cannot do it from your own origin with no inline code, it does not get done.



Where the State Lives: D1 at the Edge


A static site has no backend, by definition. To count a like you need somewhere to put the count. The trap is thinking "somewhere" means a server — a VPS, a Postgres box, a thing you patch at 2am when Mongo gets popped again.


It does not. Cloudflare D1 is SQLite running at the edge, addressable from a Pages Function. No server to harden. No port exposed to the internet. No connection string in an env file waiting to leak. The database lives next to the code that queries it, and the only thing that can reach it is a Function I wrote.


The schema is boring on purpose. This is the entire migration that powers every feature in this post:


-- country flags on likes, read-time telemetry, scrape log
ALTER TABLE likes ADD COLUMN country TEXT;

CREATE TABLE IF NOT EXISTS read_times (
  slug    TEXT    NOT NULL,
  ip_hash TEXT    NOT NULL,
  seconds INTEGER NOT NULL,
  ts      INTEGER NOT NULL DEFAULT 0
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_rt ON read_times (slug, ip_hash);

CREATE TABLE IF NOT EXISTS scrape_log (
  id      INTEGER PRIMARY KEY AUTOINCREMENT,
  slug    TEXT    NOT NULL,
  ip_hash TEXT    NOT NULL,
  ua_hash TEXT    NOT NULL,
  country TEXT,
  ts      INTEGER NOT NULL
);

Note what is not there. No email. No user_id. No ip_address. No session_token. The only thing resembling an identity is the string ip_hash, and as you will see, that is not an identity at all.



Likes Without Accounts, Without Cookies


A like button has exactly one hard requirement: the same person should not be able to inflate the count by mashing the button. Solve that and you are done. Everyone reaches for accounts or cookies to solve it. Both are overkill, and both leave a trail.


Here is the trick. I never need to know who you are. I only need to know whether this request has already liked this post. That is a far weaker question, and it has a far cheaper answer: hash the IP with a server-side secret and check for the hash.


async function hashIp(salt, ip) {
  const data = new TextEncoder().encode(salt + ip);
  const buf  = await crypto.subtle.digest('SHA-256', data);
  return Array.from(new Uint8Array(buf))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
}

Three properties make this safe:



With that, the like endpoint is almost insultingly simple. INSERT OR IGNORE does the dedup for free at the database level — if the (slug, ip_hash) pair already exists, the insert is silently a no-op:


export async function onRequestPost({ request, env, params }) {
  const slug = params.slug;
  if (!SLUG_RE.test(slug)) return json({ error: 'Invalid slug' }, 400);

  const ip      = request.headers.get('CF-Connecting-IP') ?? '0.0.0.0';
  const ipHash  = await hashIp(env.SECRET_SALT ?? '', ip);
  const country = request.cf?.country ?? null;   // free at the edge — see below
  const db      = env.LIKES_DB;

  await db.prepare(
    'INSERT OR IGNORE INTO likes (slug, ip_hash, ts, country) VALUES (?, ?, ?, ?)'
  ).bind(slug, ipHash, Date.now(), country).run();

  const count = await countLikes(db, slug);
  return json({ slug, count, liked: true }, 200);
}

No session. No cookie set on the response. No Set-Cookie header at all. A reader likes a post and walks away carrying nothing. The server remembers a salted hash that means nothing to anyone who steals the database, and a like count that means everything to me.



Country Flags Without a GeoIP Database


This is my favourite part, because it is two cheap tricks stacked into something that looks expensive.


Trick one: the country is already there. When Cloudflare terminates the TLS connection at the edge, it already knows which datacentre the request hit and which country it came from. It hands you that as a two-letter ISO code on request.cf.country — for free, with no lookup. No MaxMind database to license and ship. No IP-to-geo API call adding latency and a third-party dependency. The IP never even leaves the edge to get geolocated. It was captured in the endpoint above: request.cf?.country. One property access.


Trick two: you do not need flag images. Every country flag emoji already exists in Unicode, and it is not a single codepoint — it is two regional indicator symbols glued together. U+1F1E6 is regional indicator A, U+1F1E7 is B, and so on through Z. The renderer sees two of them in a row and draws the flag. So IN becomes 🇮🇳 with pure arithmetic — no asset, no request, no sprite sheet:


// Regional indicator symbols: U+1F1E6 = 'A'. Each letter is an alphabet offset.
function flag(code) {
  if (!code || code.length !== 2) return '';
  const c = code.toUpperCase();
  return String.fromCodePoint(0x1F1E6 - 65 + c.charCodeAt(0)) +
         String.fromCodePoint(0x1F1E6 - 65 + c.charCodeAt(1));
}

flag('IN'); // 🇮🇳
flag('JP'); // 🇯🇵
flag('BR'); // 🇧🇷

The - 65 cancels the ASCII offset of 'A' (charCodeAt('A') === 65), so 'A' maps to 0x1F1E6, 'B' to 0x1F1E7, and the whole thing falls out as one subtraction per letter. Zero bytes of image. Zero network. The flag is computed in the reader's browser from a two-character string.


So the "country flags on likes" feature — which sounds like it needs a geolocation service and a flag CDN — needs neither. It is a property Cloudflare already populated, run through six lines of integer math.



Keeping D1 Cheap: The 30-Minute Edge Cache


There was one ugly moment. The first version computed the average read time and the country list inside the same request that rendered the button. That meant every single page load fired four D1 queries — count, has-this-reader-liked, AVG() over read times, and a GROUP BY over countries. The button sat on LOADING for a small eternity while SQLite churned aggregate queries on every refresh.


The fix is the oldest one in the book: do not compute the expensive thing on every request. The expensive numbers — average read time, country breakdown — change slowly and nobody cares if they lag by half an hour. So I split the work into two endpoints. The fast one answers instantly with just the count. The slow one runs the aggregates at most once every 30 minutes and serves the rest from Cloudflare's edge cache:


const CACHE_TTL = 30 * 60; // seconds

export async function onRequestGet(context) {
  const { request, env, params } = context;
  const slug = params.slug;

  // Check the CF edge cache first — a hit costs ZERO D1 queries
  const cache = caches.default;
  const hit   = await cache.match(request);
  if (hit) return hit;

  // Cache miss — run the expensive aggregates exactly once, then cache
  const db = env.LIKES_DB;
  const [avgRow, countryRows] = await Promise.all([
    db.prepare('SELECT ROUND(AVG(seconds)) AS avg FROM read_times WHERE slug = ?')
      .bind(slug).first(),
    db.prepare(`SELECT country FROM likes
                WHERE slug = ? AND country IS NOT NULL
                GROUP BY country ORDER BY MAX(ts) DESC LIMIT 5`)
      .bind(slug).all(),
  ]);

  const avgReadSeconds = avgRow?.avg ? Number(avgRow.avg) : null;
  const countries      = (countryRows?.results ?? []).map(r => r.country);

  const response = jsonResp({ slug, avgReadSeconds, countries });
  // waitUntil repopulates the cache without making the reader wait for it
  context.waitUntil(cache.put(request, response.clone()));
  return response;
}

The response carries its own cache contract in the header:


Cache-Control: public, s-maxage=1800, stale-while-revalidate=3600

s-maxage=1800 tells the edge to hold it for 30 minutes. stale-while-revalidate=3600 (RFC 5861, the same family as the caching tricks from the last post) says: for the hour after that, serve the stale copy instantly and refresh it in the background. The reader never waits on a database. SQLite at the edge does aggregate work twice an hour per post instead of on every pageview.


On the client, the two endpoints run in parallel. The button shows the instant the fast one returns; the flags and average fill in whenever the cached one resolves. The stats request can never block the button:


// Fire stats in the background — never blocks the button
fetch(statsApi)
  .then(r => r.ok ? r.json() : null)
  .catch(() => null)
  .then(data => { if (data) renderStats(data.avgReadSeconds, data.countries); });

// Fast path: show the button as soon as count + liked arrive
const res  = await fetch(api);
const data = await res.json();
renderBtn(data.count, data.liked);

And renderStats is where the flag math from earlier actually lands on the page:


function renderStats(avgReadSeconds, countries) {
  const flagsEl = document.getElementById('like-flags');
  if (flagsEl && countries?.length) {
    flagsEl.textContent = countries.map(flag).filter(Boolean).join('');
    flagsEl.title = countries.join(', ');     // hover shows the codes
  }
}


Read-Time Telemetry You Actually Own


I wanted to know how long people read, not because I am going to "optimise engagement" — I find that phrase nauseating — but because it is genuinely interesting to know whether a 15-minute post gets read or bounced. Every analytics vendor on earth will sell you this number. None of them should have it.


So I measure it myself, on the client, and beacon it home. The key is navigator.sendBeacon — a browser API built precisely for this: fire a tiny POST on the way out the door, fire-and-forget, no response awaited, does not delay the page unload. And I only count time the tab is actually visible, using the visibilitychange event, so a post left open in a background tab for three hours does not register as a three-hour read:


let accumulated = 0;
let visibleSince = null;

const activate = () => { if (!visibleSince) visibleSince = Date.now(); };
const suspend  = () => {
  if (visibleSince !== null) {
    accumulated += (Date.now() - visibleSince) / 1000;
    visibleSince = null;
  }
};

function flush() {
  suspend();
  const s = Math.round(accumulated);
  if (s < 5) return;                       // ignore bounces
  navigator.sendBeacon(api, JSON.stringify({ seconds: s }));
}

if (document.visibilityState === 'visible') activate();
document.addEventListener('visibilitychange',
  () => document.visibilityState === 'visible' ? activate() : suspend());
window.addEventListener('pagehide', flush);

The endpoint hashes the IP (same one-way function as likes — no identity stored) and keeps only the longest session per reader per post, clamping out noise on the way in. Anything under 5 seconds is a bounce; anything over an hour is a tab someone forgot about. Both are discarded:


// Silently discard noise (< 5s bounces, > 1h outliers)
if (!Number.isFinite(seconds) || seconds < 5 || seconds > 3600) {
  return new Response(null, { status: 204 });
}

await env.LIKES_DB.prepare(`
  INSERT INTO read_times (slug, ip_hash, seconds, ts) VALUES (?, ?, ?, ?)
  ON CONFLICT (slug, ip_hash) DO UPDATE SET
    seconds = MAX(seconds, excluded.seconds),
    ts      = excluded.ts
`).bind(slug, ipHash, seconds, Date.now()).run();

ON CONFLICT … DO UPDATE SET seconds = MAX(...) means re-reads never shrink the recorded time — they only grow it. The result is one honest number per post, computed from real visible attention, stored against a hash that is not a person, owned entirely by me. Google never sees it. Plausible never sees it. You do, on the page.



A Watermark for the Scrapers


The last post wore its CC BY-ND license in red at the top of every page. Licenses are words. Words do not stop a content farm from lifting the whole post into their SEO slop mill. So I added something with teeth — at the edge, in a Pages Function _middleware.js that runs before any blog page is served.


It looks for the tells of a scraper: a known bot User-Agent, or the absence of an Accept-Language header that every real browser sends. A human gets context.next() immediately — zero overhead, zero change. A scraper gets the page plus an invisible, per-fetch watermark stitched in before </body>:


// Invisible to readers, survives copy-paste and raw-HTML downloads
const wmId = `${ipHash.slice(0, 8)}.${ts}`;
const wm   = `<span style="position:absolute;width:1px;height:1px;` +
             `clip:rect(0,0,0,0);overflow:hidden" aria-hidden="true" ` +
             `data-wm="${wmId}">xer0x.in</span>`;

const html     = await response.text();
const modified  = html.replace('</body>', `${wm}</body>`);

The watermark encodes a truncated hash of the scraper's own IP and the timestamp of the fetch. It is screen-reader hidden, visually clipped to a single pixel, and it rides along into any copy-paste or raw download. The fetch is also logged to the scrape_log table — UA hashed, IP hashed, country attached — so I can watch the bots come through without storing anything that identifies a human. If my words show up somewhere they should not, the watermark says exactly which scrape they came from.


Same privacy discipline as everything else: nothing raw, nothing reversible, nothing that follows a real reader around.



What I Am Considering Next


A garden is never finished. A few things I have been sketching, in rough order of how much they make me grin:


Canary tokens in the page. The watermark is passive. The next step is active: a unique, invisible tracking pixel minted per post, so that if a thief re-hosts my content, the pixel phones home with their readers' requests — and I learn about the theft from the thief's own audience. The scrape_log plumbing is already 80-85% of it.


Proof-of-work comments. I refuse to ship Disqus, and I refuse to run a CAPTCHA farm for Google. So: a comment box gated by a client-side hashcash-style puzzle. To post, your browser burns a few hundred milliseconds finding a hash with N leading zeros. Invisible to a human leaving one comment. Economically ruinous to a spam bot leaving ten thousand. No accounts, no CAPTCHA, no third party — just arithmetic that costs the spammer more than it costs you - maybe??


A dead drop. A single endpoint where someone can leave me an anonymous note, encrypted in the browser against my public key PGP before it ever crosses the wire, stored as ciphertext in D1 that only my private key opens. An anonymous tip line for a security blog, with no plaintext ever sitting on any server I run. If it leaks, it leaks noise.


Self-destructing posts. Burn-after-reading at the article level — a post that grants the first visitor the content and then, after N reads, returns a 💀 instead. The reader who arrived is always served; the next one finds ash. Useful for coordinated-disclosure countdowns and things that are meant to be seen once.

None of these need a server. All of them fit inside script-src 'self'. That is the constraint, and the constraint is the fun.



Maybe I Open-Source the Engine


People keep asking how the blog is built, and "read the last post" only answers half of it now. There is a real argument for putting the whole thing on CodeBerg: the static generator, the templates, the D1 migrations, the Pages Functions, the privacy-preserving likes-and-flags machinery — the entire zero-dependency engine, MIT or thereabouts, clone-and-deploy.


I have not decided. The hesitation is not secrecy — there is nothing secret in here, you have read most of the core source in this very post. It is that the moment you publish an engine, you have implicitly signed up to be its maintainer, and a garden tended for an audience stops being a garden. But the pull is real, because the entire thesis of the last post was you do not need the vendor's framework — and the most honest way to prove that is to hand you the thing that replaced it.


If you would actually run this, the like button below is, fittingly, the telemetry I will use to decide. No survey. No form. Just the feature deciding its own future.



Final Word


The last post was about subtraction — ripping out frameworks, dependencies, runtimes, and vendors until nothing was left but HTML, CSS, and the specs that define them.


This one was about addition without regression. I added likes, country flags, read-time, and scraper watermarks — real, live, stateful features — and the site is still under budget, still cookie-free, still tracker-free, still A+, still mine. The CSP widened by exactly one keyword and I told you about it. No IP was stored. No reader left carrying an identifier. No third party learned a thing.


You do not have to choose between interactive and principled. That trade is something the industry sells you so it can keep selling you the rest. Edge functions, a one-way hash, a salted secret, and six lines of Unicode arithmetic — that is the whole "platform." The rest is reading the docs and refusing to surrender the pipeline.


Interactive does not require surrender. Build it yourself.


Jai Hind.


Hash the IP. Keep the Pipeline. 🛰️
Interactive does not mean surveilled.


Wake up. Dig deeper.



gladgers-hacker-gers-guardians-of-galaxy



Twitter LinkedIn Contact me on Signal

Contact me via email


#Web Hosting #cyber security #development #privacy #cloudflare #edge #research

🔑 Verify authenticity

PGP key xer0x-public.asc · id e8270d03
sha256(post) d13fa31ea766d9c11ebc1109268ccde090aef8f78a2dbfde49ba6536cbe99211

Confirm this post is byte-for-byte authentic — paste into any macOS or Linux terminal:

curl -fsSL https://xer0x.in/blog/return-of-the-blog/content.txt | openssl dgst -sha256 | grep -qi d13fa31ea766d9c11ebc1109268ccde090aef8f78a2dbfde49ba6536cbe99211 && echo "signature ok" || echo "TAMPERED"

← Back to blog