跳到正文
DEV Community· ItsWempo·· 49 分鐘前AI 評分47

我在 Cloudflare Workers 上不用框架建了一個論壇

I built a forum with no framework on Cloudflare Workers

AI 導讀

作者為 Polytoria 遊戲社羣建成論壇,整個系統由一個 Cloudflare Worker、一個 D1 資料庫及瀏覽器原生 JavaScript 模組組成,前端毋須框架或建置步驟。論壇支援 41 種介面語言,並以統一的可見性檢查和跨路由測試防止隱藏、封禁或封鎖的內容外洩;分析功能只儲存頁面瀏覽次數,不記錄 IP、用戶代理、Cookie 或逐次瀏覽資料。

正文

I run a small forum for the Polytoria game
community: wempos-forum.com. It has boards,
threads, polls, a chat lobby, DMs, profiles, two-factor sign-in and 41
interface languages. The whole thing is one Cloudflare Worker, one D1
database, and plain JavaScript modules in the browser. No React, no
bundler, no build step for the front end.

This post is about the decisions that made that work, the parts that bit
me, and some code you can steal. The project is free software
(AGPL-3.0-or-later), so all of it is in
the repo.

The shape of it

browser ──► Worker (worker.mjs)
              ├── /api/*        JSON routes, one handler module per area
              ├── /mcp          a tool server for AI agents
              ├── discovery     /openapi.json, sitemap, markdown versions
              └── everything else → static files in public/, with a
                  per-page <head> injected on the way out
            D1 (SQLite)  ◄── every route, through bound statements

The router is a list of handlers. Each one answers the paths it owns and
returns null for everything else, so the next handler gets a turn:

const API_HANDLERS = [handleAuthRoutes, handlePostRoutes, handleProfileRoutes,
  /* …30 more… */ handleBrandingRoutes, handleAnalyticsRoutes];

Adding a feature means adding one module and one entry. There's no
framework to learn, and every route is a plain function you can call
from a test.

No front-end build step

The browser loads public/js/*.js exactly as written, as ES modules.
That sounded like a constraint at first. In practice it means:

  • What you read in the repo is what runs. No source maps to decode when a member reports a bug.
  • The client router is also the server's source of truth. The Worker imports the same public/js/router.js the browser uses, so a URL the client can't route gets a real 404 from the server too. One list of page routes, no drift.
  • A strict Content-Security-Policy is easy. No inline scripts, no eval, script-src 'self'. There's nothing to whitelist because there's nothing generated.

The cost is that I write a bit more DOM code by hand. The rule that keeps
it safe: user text goes in with textContent, never innerHTML, and a
test fails the build if a new HTML sink shows up.

One visibility rule, everywhere

Forums leak in boring ways. A post gets hidden by a moderator, but it
still shows in search. A member blocks someone, but that person's replies
still appear in a notification. A banned account's posts vanish from the
feed but not from the sitemap.

So there's exactly one module that decides "can this viewer see this
post?", covering hidden posts, active bans and block pairs in both
directions. Every route that returns post text or member names goes
through it. Then there's a test that seeds one of each forbidden thing
(a hidden post, a banned author, a blocked pair, a deleted post, a
staff-only record) and sweeps every route, the agent tool server and
the page heads, asserting none of that text ever comes back.

That sweep has paid for itself. In the last release it caught a subtle
one: the structured data on a thread page counted replies from someone the
viewer had blocked, while the feed (correctly) didn't. Same SQL, one
missing filter. Without the sweep, nobody would have noticed for months.

Link previews that respect hidden posts

When someone pastes a thread link into Discord, it should show the
thread's title and first lines. When the thread is hidden, it must show
nothing about it, and it must not even reveal whether the thread
exists.

The Worker rewrites the HTML shell's <head> per request. The important
part is the order: the visibility check runs first, as an ordinary
member, even for staff, so a moderator's session can't leak a hidden post
into a cached preview:

const row = await env.FORUM_DB.prepare(POST_ROW_SQL).bind(id).first();
if (!row || !(await canViewPost(env, row, viewer))) return null; // → generic head

Hidden, banned, blocked, deleted and missing all fall back to the same
generic head with noindex, and a test asserts the bytes are identical.

The structured data for search engines goes in a
<script type="application/ld+json"> block. That's a trap, because a
post body containing </script> would close the tag early. The fix is to
escape after serializing:

export function jsonLdBlock(data) {
  const text = JSON.stringify(data)
    .replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026")
    .replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
  return `<script type="application/ld+json">${text}</script>`;
}

It's still valid JSON (\u003c is just < to a JSON parser), but an
HTML parser never sees a <. There's a test that posts
</script><script>alert(1)</script> and checks every block still parses
and nothing gets injected.

Analytics with nothing to leak

I wanted to know which pages people use, without tracking people. The
answer was to store counts, not visits:

CREATE TABLE page_view_counts (
  day TEXT NOT NULL, route TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0,
  PRIMARY KEY (day, route)
);

route is the router's page name: home, post, profile. It's
never the path, so no post id, username or search query ever lands in a
row. There's no IP, user agent, cookie or per-visit row. The decision to
count is one small function:

export function pageViewPlan(request, env, url, response) {
  if (!analyticsEnabled(env) || !env.FORUM_DB) return null;
  if (request.method.toUpperCase() !== "GET" || isPrefetch(request)) return null;
  if (optedOut(request) || looksLikeBot(request)) return null; // DNT / Sec-GPC
  if (!response || response.status !== 200) return null;
  if (!(response.headers.get("Content-Type") || "").includes("text/html")) return null;
  const route = routeForPath(url.pathname, url.search).name;
  if (!route || route === "not-found") return null;
  return { day: utcDay(), route, referrer: referrerHost(request, url, env) };
}

A few details I'm happy with:

  • Do Not Track and Global Privacy Control are honored, not just read.
  • Referrers are kept as a host only (reddit.com, never the full URL), and only when it's someone else's site. The number of distinct hosts per day is capped, so a flood of junk referrers can't bloat the table.
  • The write never slows the page. It runs on ctx.waitUntil after the response is built, and any error becomes a log line, not a broken page.
  • Old data deletes itself. Rows older than 90 days are removed in small bounded batches whenever staff open the Visits page.

The staff view is a plain table of daily totals, top page types and top
referring sites. That's enough to see whether a Reddit post worked, and
it holds nothing worth stealing.

D1 lessons (the expensive ones)

D1 is SQLite, and mostly it's lovely. A few things cost me real time:

  • Foreign keys are enforced by the migration runner. The classic SQLite "rename the table, create a new one, copy, drop the old one" rebuild can fail on the DROP, or worse, silently cascade-delete rows in tables that reference it. For schema changes I now add a new column, backfill it, and switch reads over, instead of rebuilding tables.
  • Every migration is CREATE-only or column-additive, and released ones are never edited. Self-hosters can apply them in order from any older version.
  • Check migrations by name, not by count. Before and after applying a migration to production, I check that the expected migration name is in the ledger exactly once, and that a reference table's row count didn't change. "Exit code 0" is not proof.
  • Bound parameters only, with real limits. Every query is prepare(...).bind(...), every LIMIT is a bound number, and list sizes stay under D1's bound-parameter cap.

Knowing what's actually deployed

Every deploy stamps the commit hash into the HTML and into
/api/version:

wrangler deploy --keep-vars --var COMMIT_SHA:$(git rev-parse --short HEAD)

The browser compares its own build against /api/version and shows a
"new version available" banner when they differ, and the stamp doubles as
a cache-buster for scripts. It also caught a nasty problem: a git push can
trigger a hosted build that deploys without the stamp. So the rule is
that the stamped deploy always runs last, from a checkout at the pushed
commit, and I probe /api/version until it reports that commit.

Testing without a browser

The suite (about 1,200 tests) runs with Node's built-in test runner. Routes
run against an in-memory SQLite that behaves like D1, and front-end
modules run against a small fake DOM. No headless browser, so the whole
suite takes seconds and runs on every push. Fuzz tests (fast-check)
throw thousands of malformed inputs at sign-in, search and posting.

New features land red-first: the test commit goes in failing, then the
code that makes it pass. When a change touches visibility, I break the
fix on purpose to confirm the test notices. If removing the check doesn't
fail a test, the test is wrong.

What I'd tell you if you're building one

  1. Pick the boring, inspectable stack. One Worker, one database, plain modules. Debugging is reading.
  2. Write the visibility rule once and sweep every route against it. Leaks hide in the routes you forgot existed.
  3. Count, don't track. You can learn what you need from aggregates.
  4. Make "what's deployed?" a URL you can curl.

The forum is at wempos-forum.com. If you play
Polytoria or build games, come say hi. The code, self-hosting guide and
security docs are on
GitHub. I'd love
feedback on any of the above.

來源:DEV Community · dev.to