Architecture
DragonslairCMS is a single Cloudflare Worker written in plain JavaScript ES modules. It serves the public site, the admin at /admin, the reader account pages and the form endpoints, rendering every page at request time from a D1 database. There’s no build step, no framework and no ORM: the Worker runs the files in src/ as they are, and the browser gets server-rendered HTML with a few small scripts for the editors.
The pieces
Section titled “The pieces”| Piece | What it is | Binding |
|---|---|---|
| Worker | src/index.js and everything it imports |
|
| Static files | public/ (CSS, editor JavaScript, icons), served by the Workers assets binding |
ASSETS |
| Database | D1 (SQLite), hand-written SQL through prepare().bind() |
DB |
| Media | R2, holding uploads, served by the Worker at /media/<key> |
MEDIA |
The send_email binding (optional) |
EMAIL |
|
| Scheduled job | A Cron Trigger every 15 minutes, for scheduled publishing |
The Worker doesn’t import anything from node_modules, and package.json has no runtime dependencies. Wrangler, a dev dependency, is the only package you need.
How a request is handled
Section titled “How a request is handled”Requests for files that exist in public/ are answered by the assets binding before the Worker runs. Everything else reaches the fetch handler in src/index.js, which:
-
Refuses a cross-site request that could change something (
crossSiteRequestinsrc/csp.js): any method other thanGETorHEADwhoseOriginheader isnull, unparseable or another host gets a plain403 Forbiddenbefore any handler runs. A request with noOriginat all is allowed.SameSite=Laxcookies alone aren’t enough, because every app on the same registrable domain counts as the same site. -
Answers
/theme.css(the generated theme stylesheet) and/emoticons.json(the public emoticon list) directly. -
Builds a per-request copy of
envwith the effective settings (resolveEnv): the Site URL and Email “From” address from the admin’s Settings overrideSITE_URLandSITE_EMAIL_FROMfromwrangler.jsonc. The Site URL is never taken from the request’s host, and a value that failssiteUrlErrorinsrc/site-url.jscounts as unset, which leavesenv.SITE_URLempty and email off. Public pages that need an absolute address without one (canonical tags, the feed, the sitemap, exports) use the request’s origin throughpublicOrigin()insrc/site-url.js; email never does. The session secrets are resolved (see Sessions). The sharedenvis never mutated. -
Sends anything under
/admintohandleAdmininsrc/routes/admin.js. -
Otherwise tries each public handler in turn. A handler returns a
Responseif the path is its own, ornullto pass:Order Handler Paths 1 routes/discovery.js/feed.xml,/rss.xml,/sitemap.xml,/robots.txt2 routes/api.jsPOST /api/*(comments, replies, corrections, subscribe)3 routes/reader.js/reader/*4 routes/media.js/media/*from R25 routes/search.js/search6 routes/public-articles.js/in article-feed mode,/posts,/category/*,/series,/tags/*, and redirects from the old/blogand/newspaths7 routes/public-people.js/people,/people/*8 routes/public-pages.jsany other path, matched against page slugs ( /is the page with slughome) -
Falls through to a 404, or, for
/on a site with nohomepage yet, a placeholder showing the organisation name and tagline.
An unhandled exception is logged with console.error (method, path and stack) and returns serverError() from src/errors.js: a self-contained 500 page with inline styles that touches neither D1 nor the session, and never says what went wrong.
Every response the Worker makes, errors and redirects included, passes through withSecurityHeaders in src/csp.js, which adds Strict-Transport-Security, X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin, a Permissions-Policy that turns off the camera, microphone, geolocation and payment, and Cross-Origin-Opener-Policy: same-origin. A header the response already set is kept, which is how /media/ files keep their own policy. The print routes (/admin/pages/<id>/print and /admin/articles/<id>/print) get X-Frame-Options: SAMEORIGIN, because the PDF export loads them in a hidden iframe. Static files get the same headers from public/_headers, since the Worker never sees those requests. There’s no Content-Security-Policy on pages yet.
The scheduled handler runs publishScheduledArticles from src/routes/admin-articles.js on each Cron Trigger.
The admin
Section titled “The admin”src/routes/admin.js is the admin’s gatekeeper. Before checking for a session it handles:
/admin/setup: the first-run screen that creates the first admin. It only works while theuserstable is empty./admin/login,/admin/forgotand/admin/reset.
Every other /admin path needs a valid session. /admin/logout (and the reader’s /reader/logout) only sign out on POST; a GET just redirects. The dispatcher then hands the request to a section module by the first path segment (/admin/pages/… to admin-pages.js, and so on); each src/routes/admin-*.js module does its own sub-routing. Role checks live in the modules, using roleAtLeast(user, 'publisher') from src/auth.js; the roles, from least to most, are editor, publisher and admin. Deleting comments, replies and corrections needs publisher; Readers (admin-readers.js), Email templates and changing the Site URL need admin. Those checks return null for anyone below, which gives the admin’s 404, the same answer as a page that doesn’t exist. /admin/badges.json supplies the sidebar’s moderation counts.
HTML comes from template functions in src/templates/base.js (sitePage for public pages, adminPage for the admin) and src/templates/blocks.js (the block renderer). Every value from the database is escaped with escapeHtml/escapeAttr, except rich text written by CMS users, which is trusted and output as it is. Link targets typed by staff (navigation, footer, block buttons and links, social links) also go through safeUrl in src/templates/base.js, which keeps http(s):, mailto:, tel:, #fragments and paths on the site, and turns anything else (including //host and javascript:) into #. The navigation and footer savers refuse such links with isSafeUrl. Comments from the public are rebuilt from an allowlist in src/sanitize.js before they’re stored. The sanitiser scans in linear time: a tag must close within 256 characters, or its < is kept as text. Public text fields have maximums in src/routes/api.js (MAX_BODY 10,000, MAX_NAME 80, MAX_EMAIL 254), and anything longer is refused with ?error=too_long, not cut.
Drafts, snapshots and revisions
Section titled “Drafts, snapshots and revisions”Pages and articles share a publish model:
statusisdraft,publishedormodified.- Publish writes the content to the row and freezes a copy in
published_snapshot(JSON). - Save on a live item updates the row and sets
modified; the public site keeps renderingpublished_snapshot, so unpublished edits never leak. - Revert copies the snapshot back over the row. Unpublish sets
draftand keeps everything. - Every save also writes a JSON copy to
revisions, deduplicated against the previous one and capped at 50 per item.
Series membership (article_series) is deliberately live rather than frozen, so reordering a series takes effect immediately.
Sessions and secrets
Section titled “Sessions and secrets”There are two separate login realms, each with its own tables, cookie and signing secret, so a reader session can never be replayed against the admin:
| Realm | Tables | Cookie | Secret |
|---|---|---|---|
| CMS users | users, sessions |
dlc_session |
ADMIN_SESSION_SECRET |
| Readers | reader_accounts, reader_sessions |
dlc_reader |
READER_SESSION_SECRET |
A session is a random ID stored in D1, sent as a cookie with an HMAC-SHA256 signature. Cookies are HttpOnly, Secure and SameSite=Lax, and last 30 days. Signing fails closed: with no secret, nothing is signed or verified. Passwords are hashed with PBKDF2-SHA256 (100,000 iterations). Failed logins are counted per IP address in login_attempts: five failures lock that address out for 15 minutes. A login for an address with no account is checked against a dummy hash (burnTime), so the timing doesn’t reveal whether the account exists.
Every new password goes through passwordError in src/auth.js: 12 to 256 characters, and not in Have I Been Pwned’s breach list. The breach check uses the range API by k-anonymity (only the first five hex characters of the SHA-1 leave the Worker), times out after two seconds, and fails open. Setting a password ends the account’s other sessions, and so does deactivating a CMS user or rejecting a reader (destroyUserSessionsStmt, destroyReaderSessionsStmt), in the same batch as the change. A reader session also needs a confirmed email address, as well as approved status.
Neither secret has to be configured. src/secrets.js uses a Worker secret if one is set, and otherwise mints a random 32-byte value on first use and stores it in site_config. See Configuration.
Where things are stored
Section titled “Where things are stored”- Settings from the admin’s Settings page are key/value rows in
site_settings. - Structured config is JSON in
site_config, keyed bynav,footer,fonts,surfaces,media_foldersandemoticon_categories, plus the generated session secrets. - Theme tokens changed in Branding are rows in
theme_tokens, overlaid on the defaults insrc/tokens.js. - Media lives in R2. Keys look like
media/<yyyymm>/<timestamp>-<name>, with people’s photos undermedia/people/, fonts uploaded from Fonts undermedia/fonts/, and emoticons atmedia/emoticons/<slug>.png. The media route only serves keys undermedia/. There’s no media table: the library lists the bucket directly, and folders are labels stored insite_config.
Uploads
Section titled “Uploads”src/sniff.js decides what an upload is from its own bytes (sniffType), ignoring the browser’s type and the file name; the stored key takes the sniffed extension (nameWithSniffedExt) and the object’s Content-Type is the sniffed type. readUpload refuses a request with no Content-Length (411) or one over MAX_UPLOAD_REQUEST (51 MB) before reading the body, then applies uploadError:
| Kind | Cap |
|---|---|
image (JPEG, PNG, GIF, WebP, AVIF) |
8 MB |
video (MP4, MOV, WebM) |
50 MB |
pdf |
25 MB |
svg, html |
2 MB, admins only |
other |
25 MB |
HEIC is refused with a message. People’s photos (admin-people.js) accept images only. Replace applies the same checks, and the sniffed type must match the key’s extension.
src/routes/media.js serves every file with Content-Security-Policy: default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox (MEDIA_CSP), so an SVG or HTML file opened directly can’t run script or act as the site, plus X-Frame-Options: SAMEORIGIN so the embed block can frame PDFs and HTML on the same site. Anything whose type isn’t image, video, font, PDF or HTML (servedInline) is sent as application/octet-stream with Content-Disposition: attachment.
The full schema is described in Database and schema changes.
The theme stylesheet
Section titled “The theme stylesheet”Every page loads /theme.css, which the Worker generates from the database on each request (cached for 60 seconds):
@font-facerules for fonts added in the admin.- The design tokens as CSS custom properties:
--color-*,--font-*,--radius-*,--size-*and--weight-*, with dark-mode overrides. - One
.surface-<key>class per palette surface, mapping roles such as--c-bgand--c-linkto colour tokens.
The static stylesheets in public/css/ only ever use these variables, never fixed colours, which is how the admin can restyle the whole site. See Blocks and theming.
Caching
Section titled “Caching”| Response | Cache-Control |
|---|---|
/theme.css, /emoticons.json |
60 seconds |
/feed.xml, /sitemap.xml |
5 minutes |
/robots.txt |
1 hour |
Images under /media/ |
1 year, immutable |
Other files under /media/ |
60 seconds, must-revalidate, with ETags |
| Pages, articles, the admin | Not cached |
