Dough Git

commit

first commit

commit
fafce9f714d93cd7b064760425a7ab7ea220a02f
author
Clove Twilight <[email protected]>
date
2026-09-18 23:57

diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..de15280
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,7 @@
+node_modules
+data
+.env
+.git
+.github
+*.md
+!LICENCE.md
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..101671f
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,35 @@
+# Copy to .env and fill in. Everything without a default is required.
+
+# Public origin of this pastebin. It is what paste links look like and what the
+# redirect URI is built from, so it must match what the auth server has
+# registered for this client.
+ORIGIN=http://localhost:3000
+
+# Shown in the header and page titles.
+SITE_NAME=Doughmination Paste
+
+# Where Bun listens. Behind a reverse proxy, bind loopback: HOST=127.0.0.1
+PORT=3000
+HOST=0.0.0.0
+
+# SQLite file. Its directory is created at start-up.
+DATABASE_FILE=data/pastebin.db
+
+# --- Doughmination SSO ---------------------------------------------------------
+# The auth-server's public origin: its OIDC issuer.
+OIDC_ISSUER=https://auth.doughmination.gay
+
+# Register this pastebin at the auth server's /admin -> Applications, with
+# redirect URI  <ORIGIN>/auth/callback  and post-logout redirect  <ORIGIN>/
+OIDC_CLIENT_ID=pastebin
+
+# Leave empty for a public client (PKCE only). Set it for a confidential one.
+OIDC_CLIENT_SECRET=
+
+# --- limits --------------------------------------------------------------------
+# Largest paste accepted, in bytes.
+MAX_BODY_BYTES=524288
+
+# Pastes larger than this are shown as plain text: tokenizing megabytes of code
+# stalls the server for everyone else.
+MAX_HIGHLIGHT_BYTES=196608
diff --git a/.github/workflows/mirror.yml b/.github/workflows/mirror.yml
new file mode 100644
index 0000000..9843d42
--- /dev/null
+++ b/.github/workflows/mirror.yml
@@ -0,0 +1,71 @@
+name: Mirror
+
+on:
+  push:
+
+jobs:
+  mirror:
+    runs-on: ubuntu-latest
+
+    permissions:
+      contents: read
+
+    concurrency:
+      group: mirror-${{ github.repository }}
+      cancel-in-progress: false
+
+    env:
+      MIRROR_HOST: backup.doughmination.gay
+      MIRROR_USERNAME: clove
+      MIRROR_REPO: pastebin
+      MIRROR_TOKEN: ${{ secrets.MIRROR_TOKEN }}
+
+    steps:
+      - name: Clone every ref
+        env:
+          SOURCE_TOKEN: ${{ github.token }}
+          SERVER_URL: ${{ github.server_url }}
+        run: |
+          set -euo pipefail
+
+          sourceHost="${SERVER_URL#https://}"
+
+          git clone --mirror \
+            "https://x-access-token:${SOURCE_TOKEN}@${sourceHost}/${GITHUB_REPOSITORY}.git" \
+            source.git
+
+      - name: Drop pull-request refs
+        working-directory: source.git
+        run: |
+          set -euo pipefail
+
+          git for-each-ref --format='%(refname)' 'refs/pull/*' \
+            | while read -r ref; do
+                git update-ref -d "$ref"
+              done
+
+      - name: Push mirror
+        working-directory: source.git
+        run: |
+          set -euo pipefail
+
+          if [ -z "$MIRROR_USERNAME" ]; then
+            echo "MIRROR_USERNAME is not set" >&2
+            exit 1
+          fi
+
+          if [ -z "$MIRROR_REPO" ]; then
+            echo "MIRROR_REPO is not set" >&2
+            exit 1
+          fi
+
+          targetUrl="https://${MIRROR_HOST}/${MIRROR_USERNAME}/${MIRROR_REPO}.git"
+
+          echo "Mirroring ${GITHUB_REPOSITORY} -> ${targetUrl}"
+
+          git remote add mirror "$targetUrl"
+
+          # Credentials go through a helper so the token never lands in .git/config
+          git -c credential.helper= \
+              -c "credential.helper=!f() { echo username=\"\$MIRROR_USERNAME\"; echo password=\"\$MIRROR_TOKEN\"; }; f" \
+              push --mirror mirror
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c059056
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,39 @@
+# dependencies (bun install)
+node_modules
+bun.lock
+
+# output
+out
+dist
+*.tgz
+
+# code coverage
+coverage
+*.lcov
+
+# logs
+logs
+_.log
+report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
+
+# dotenv environment variable files
+.env
+.env.development.local
+.env.test.local
+.env.production.local
+.env.local
+
+# caches
+.eslintcache
+.cache
+*.tsbuildinfo
+
+# IntelliJ based IDEs
+.idea
+
+# Finder (MacOS) folder config
+.DS_Store
+
+# runtime
+data
+.env
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..f3acc4d
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,32 @@
+# Dockerfile
+# Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+# Licensed under the DASL-1.2 Licence.
+# See LICENCE.md in the project root for full licence information.
+
+FROM oven/bun:1.4-alpine AS deps
+WORKDIR /app
+# bun.lock is gitignored in this repo, so tolerate it being absent.
+COPY package.json bun.lock* ./
+RUN bun install --production
+
+FROM oven/bun:1.4-alpine
+WORKDIR /app
+ENV NODE_ENV=production
+
+COPY --from=deps /app/node_modules ./node_modules
+COPY package.json tsconfig.json ./
+COPY src ./src
+COPY public ./public
+COPY syntaxes ./syntaxes
+
+# The database lives here; mount a volume over it to keep the pastes.
+RUN mkdir -p /app/data && chown -R bun:bun /app/data
+VOLUME /app/data
+
+USER bun
+EXPOSE 3000
+
+HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \
+  CMD bun -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
+
+CMD ["bun", "src/index.ts"]
diff --git a/LICENCE.md b/LICENCE.md
new file mode 100644
index 0000000..640ddfb
--- /dev/null
+++ b/LICENCE.md
@@ -0,0 +1,316 @@
+# Doughmination Authorised Source Licence
+
+**Version 1.2**
+
+This Licence may be referred to as the **Doughmination Authorised Source Licence (DASL)**. This version may be referred to as **DASL-1.2**.
+
+Copyright © 2026 Clove Nytrix Doughmination Twilight.
+
+---
+
+# 1. Definitions
+
+For the purposes of this Licence:
+
+**"Software"** means the source code, object code, documentation, configuration, assets, and any associated files distributed under this Licence.
+
+**"Authorisation"** means explicit written permission granted by Clove Nytrix Doughmination Twilight permitting specific use of the Software.
+
+**"Authorised Person"** means a person or organisation expressly identified as authorised in an official licensing record maintained by Clove Nytrix Doughmination Twilight, including the `PEOPLE.md` file of an Official Licensing Repository or, where applicable, the `README.md` file of the relevant Software project.
+
+**"Contributor"** means any person or organisation that has received Authorisation, or is otherwise expressly authorised under this Licence, to modify, contribute to, or submit changes to the Software.
+
+**"Contribution"** means any source code, object code, documentation, configuration, assets, or other material submitted, provided, or incorporated into the Software by a Contributor.
+
+**"Fork"** means a copy or repository of the Software created through a version-control forking mechanism or an equivalent process, including forks hosted on third-party platforms.
+
+**"Contribution Fork"** means a Fork created and used solely for the purpose of preparing, reviewing, testing, or submitting Contributions to the original Software.
+
+**"Official Licensing Repositories"** means the repositories maintained by Clove Nytrix Doughmination Twilight for the administration and publication of licensing information:
+
+* GitHub: https://github.com/doughmination/licencing
+* Codeberg: https://codeberg.org/clove/licencing
+* Backup Forge: https://backup.doughmination.gay/clove/licencing
+
+**"Official Licensing Records"** means licensing records published within an Official Licensing Repository, including `PEOPLE.md`, or other records expressly identified as authoritative by Clove Nytrix Doughmination Twilight.
+
+**"Artificial Intelligence System"** means any artificial intelligence, machine-learning, generative, automated code-generation, or substantially similar system capable of generating, modifying, analysing, or transforming Software or other material.
+
+**"Meaningful Human Contribution"** means substantive human involvement in the creation, review, understanding, testing, modification, or approval of a Contribution sufficient for the Contributor to reasonably understand and take responsibility for the resulting Contribution.
+
+**"Trademarked Components"** means any trademarks, trade names, service marks, logos, branding, identifiers, product names, system names, or other distinctive branding owned or claimed by Clove Nytrix Doughmination Twilight, whether registered or unregistered.
+
+---
+
+# 2. Grant of Rights
+
+Except where expressly permitted by this Licence, by an applicable Official Licensing Record, or by separate written Authorisation, no licence or permission is granted to use, copy, modify, merge, publish, distribute, sublicense, host, deploy, execute, sell, create derivative works from, or otherwise exploit the Software.
+
+The Software is made available solely for inspection and review of its source code, subject to the specific permissions expressly granted by this Licence.
+
+All rights not expressly granted are reserved.
+
+---
+
+# 3. Forking and Contribution Forks
+
+Forking of the Software is expressly permitted to **all persons and organisations**, without requiring prior written Authorisation.
+
+This permission to fork is granted **solely to facilitate contribution to the original Software**.
+
+An unauthorised Fork does **not** constitute an authorised copy of the Software and does not grant the person or organisation creating the Fork any general right to use, operate, deploy, distribute, publish, commercialise, or otherwise exploit the Software.
+
+An unauthorised Fork may be used only for activities directly connected with contributing to the original Software, including:
+
+* inspecting and studying the Software;
+* preparing proposed changes to the Software;
+* modifying the Software for the purpose of preparing a Contribution;
+* testing or validating proposed Contributions;
+* submitting pull requests, patches, merge requests, or equivalent proposals to the original Software; and
+* performing other activities reasonably necessary to prepare or submit Contributions to the original Software.
+
+Without separate Authorisation, an unauthorised Fork **must not** be:
+
+* operated as an independent instance of the Software;
+* deployed for personal, private, public, organisational, or production use;
+* used to provide services to the Fork creator or to third parties;
+* made available to third parties for use;
+* distributed as an independent application or product;
+* published as an independent project;
+* used as the basis of a competing or replacement service;
+* commercially exploited;
+* sublicensed;
+* used to create or distribute derivative works for purposes unrelated to contributing to the original Software; or
+* otherwise used in any manner that constitutes independent use of the Software.
+
+The fact that a version-control platform permits a person to create, access, host, or publish a Fork does not constitute Authorisation to use that Fork for any purpose beyond those expressly permitted by this Section.
+
+The person or organisation creating an unauthorised Fork is responsible for ensuring that the Fork remains within the scope of this Section.
+
+Where a person or organisation wishes to use a Fork for any purpose other than contributing to the original Software, they must first obtain separate Authorisation from Clove Nytrix Doughmination Twilight or hold an applicable Authorisation recorded in an Official Licensing Record.
+
+A Contribution Fork may contain modifications that are necessary to prepare or test a Contribution, provided that those modifications remain within the scope of this Section.
+
+The permission to create a Fork does **not** constitute general permission to use the Software and does not grant any rights beyond those expressly stated in this Section.
+
+---
+
+# 4. Authorised Use
+
+Any person or organisation wishing to use the Software for purposes other than the permitted inspection, review, or Contribution Fork activities described in this Licence must first obtain written Authorisation from Clove Nytrix Doughmination Twilight, unless an applicable Official Licensing Record expressly grants the required permission.
+
+Authorisation may:
+
+* permit commercial or non-commercial use;
+* permit modification or contribution to the Software;
+* permit use of a Fork beyond Contribution Fork activities;
+* impose conditions or limitations;
+* restrict fields of use, duration, territory, or distribution;
+* specify particular projects, repositories, components, or versions;
+* require attribution, reporting, licensing fees, revenue sharing, or other obligations; or
+* be refused entirely.
+
+Authorisation to contribute to the Software does not, by itself, grant permission to redistribute, publish, deploy, sublicense, commercially exploit, or otherwise use the Software outside the scope of the authorised contribution activity.
+
+Any Authorisation permitting contribution is subject to the Contributor and Human Authorship Requirements set out in Section 8 unless expressly stated otherwise in writing.
+
+No Authorisation shall be implied through publication of the Software, possession of the Software, creation of a Fork, prior communications, or previous permissions granted to other parties.
+
+---
+
+# 5. Trusted Persons and Allowlist
+
+Clove Nytrix Doughmination Twilight may maintain an allowlist of trusted persons or organisations who are authorised to perform specified activities relating to the Software.
+
+The allowlist may be published in:
+
+* `PEOPLE.md` within an Official Licensing Repository; or
+* the `README.md` of the relevant Software project where that file expressly identifies the applicable Authorisation and scope.
+
+The allowlist may specify, for each Authorised Person:
+
+* the identity or account of the Authorised Person;
+* the projects or repositories to which the Authorisation applies;
+* the activities they may perform;
+* whether they may modify or contribute to the Software;
+* whether they may create or maintain Contribution Forks;
+* whether they may operate or deploy the Software;
+* whether they may use a Fork for purposes beyond contributing to the original Software;
+* whether they may review or approve Contributions;
+* whether they may distribute or publish particular material;
+* whether they may exercise additional rights beyond those granted to ordinary Contributors;
+* any restrictions or conditions applicable to their Authorisation; and
+* the duration or status of the Authorisation.
+
+An Authorised Person is permitted only to the extent expressly specified by the applicable allowlist entry.
+
+Being listed as an Authorised Person does not grant unrestricted rights to the Software.
+
+Clove Nytrix Doughmination Twilight may add, modify, restrict, suspend, or remove an Authorised Person or their authorised scope at any time.
+
+Where an Authorised Person is listed in both `PEOPLE.md` and a project's `README.md`, the more specific project-level scope shall apply to that project unless the applicable record expressly states otherwise.
+
+Where multiple Official Licensing Records contain conflicting entries concerning the same person or project, the most recently published applicable record shall control, unless the applicable record specifies another precedence rule.
+
+An allowlist entry constitutes Authorisation for the scope expressly stated in that entry and does not require separate written permission for activities falling within that scope.
+
+---
+
+# 6. Requesting Authorisation
+
+Requests for Authorisation should be submitted to:
+
+**[[email protected]](mailto:[email protected])**
+
+Clove Nytrix Doughmination Twilight may maintain Official Licensing Records identifying authorised persons, organisations, and licensing conditions.
+
+The Official Licensing Repositories are:
+
+* GitHub: https://github.com/doughmination/licencing
+* Codeberg: https://codeberg.org/clove/licencing
+* Backup Forge: https://backup.doughmination.gay/clove/licencing
+
+Where an individual or organisation is expressly listed as authorised within an applicable Official Licensing Record, that listing constitutes evidence of an active Authorisation subject to any accompanying conditions.
+
+Absence from the Official Licensing Records shall not be interpreted as evidence that permission has been granted.
+
+---
+
+# 7. Attribution
+
+Where Authorisation permits redistribution of the Software, all copies or substantial portions of the Software must include:
+
+* this Licence;
+* the copyright notice; and
+* reasonable attribution to **Clove Nytrix Doughmination Twilight**.
+
+Modified versions must clearly indicate that they have been modified.
+
+---
+
+# 8. Contributor and Human Authorship Requirements
+
+Where Authorisation permits a Contributor to modify, contribute to, or submit changes to the Software, the Contributor must retain Meaningful Human Contribution and responsibility for each Contribution.
+
+Artificial Intelligence Systems may be used as development tools or aids. Permitted uses may include, but are not limited to:
+
+* explaining programming concepts or existing code;
+* assisting with research;
+* identifying potential bugs or errors;
+* suggesting implementations or approaches;
+* assisting with debugging;
+* suggesting refactoring;
+* generating or assisting with tests;
+* assisting with documentation; and
+* other development activities where the Contributor retains meaningful human involvement and responsibility.
+
+The use of an Artificial Intelligence System must not replace the Contributor's substantive development work, judgement, understanding, review, testing, or responsibility for a Contribution.
+
+A Contributor must not submit or incorporate a Contribution where the Contributor has not meaningfully reviewed, understood, and taken responsibility for the resulting Contribution.
+
+Submitting substantially AI-generated material with little or no Meaningful Human Contribution is prohibited.
+
+In particular, a Contributor must not delegate the substantive development of a Contribution to an Artificial Intelligence System and submit the resulting material with only superficial or cursory human review.
+
+The use of an Artificial Intelligence System does not transfer responsibility for a Contribution away from the Contributor. The Contributor remains responsible for ensuring that every Contribution complies with this Licence and any applicable Authorisation.
+
+A Contributor may be required, as a condition of Authorisation, to disclose material use of Artificial Intelligence Systems in a Contribution where reasonably requested by Clove Nytrix Doughmination Twilight.
+
+Nothing in this Section prohibits ordinary use of automated development tooling where such tooling does not materially replace the Contributor's Meaningful Human Contribution.
+
+Violation of this Section constitutes a breach of the applicable Authorisation.
+
+---
+
+# 9. Representation and Branding
+
+You must not:
+
+* misrepresent the origin of the Software;
+* claim authorship of the original Software;
+* imply endorsement, sponsorship, certification, or affiliation by Clove Nytrix Doughmination Twilight; or
+* represent modified versions as official releases without prior written Authorisation.
+
+---
+
+# 10. Trademarked Components
+
+This Licence grants no rights to use any Trademarked Components.
+
+Without prior written Authorisation, you may not use any Trademarked Components in a manner that suggests endorsement, official status, compatibility certification, partnership, or origin.
+
+Current trademarks include, but are not limited to:
+
+* **Doughmination System®** (United Kingdom, UK00004263144)
+
+This list is non-exhaustive.
+
+---
+
+# 11. No Implied Rights
+
+No rights, licences, permissions, waivers, or immunities shall arise by implication, estoppel, or otherwise.
+
+Publication of the Software does not constitute permission to use the Software beyond the rights expressly granted by this Licence.
+
+The creation of a Fork does not constitute permission to use the Software independently of the original Software.
+
+The ability to access, clone, fork, download, or host the Software through a version-control platform does not constitute additional Authorisation.
+
+---
+
+# 12. Source-Available Status
+
+The Software is source-available.
+
+It is **not** open-source software.
+
+This Licence is not an Open Source Initiative-approved licence and should not be interpreted as granting the freedoms commonly associated with open-source licences.
+
+---
+
+# 13. Revocation
+
+Unless otherwise agreed in writing, any Authorisation granted under this Licence may be revoked by Clove Nytrix Doughmination Twilight.
+
+An allowlist entry may likewise be modified, suspended, or removed.
+
+Upon revocation or removal of Authorisation, all use relying upon that Authorisation must cease immediately unless otherwise specified within the revocation notice, applicable Official Licensing Record, or written agreement.
+
+The general permission to create Contribution Forks under Section 3 is not an individual Authorisation and may only be restricted or withdrawn by a subsequent version of this Licence or another legally applicable notice issued by Clove Nytrix Doughmination Twilight.
+
+Revocation does not affect obligations that, by their nature, survive termination.
+
+---
+
+# 14. Disclaimer of Warranty
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, OR NON-INFRINGEMENT.
+
+TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE ENTIRE RISK ARISING OUT OF THE USE OF THE SOFTWARE REMAINS WITH THE USER.
+
+---
+
+# 15. Limitation of Liability
+
+TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL CLOVE NYTRIX DOUGHMINATION TWILIGHT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR FOR ANY LOSS OF PROFITS, REVENUE, DATA, GOODWILL, BUSINESS INTERRUPTION, OR OTHER COMMERCIAL LOSS ARISING FROM OR RELATING TO THE SOFTWARE OR ITS USE, WHETHER BASED IN CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY, OR OTHERWISE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+---
+
+# 16. Governing Law
+
+This Licence shall be governed by and construed in accordance with the laws of England and Wales.
+
+The courts of England and Wales shall have exclusive jurisdiction over disputes arising from or relating to this Licence unless otherwise required by applicable law.
+
+---
+
+# 17. Derivative Licences
+
+No person may publish, distribute, or present a licence derived from, based upon, or substantially similar to this Licence without prior written Authorisation from Clove Nytrix Doughmination Twilight.
+
+Where such permission is granted, the derivative licence must prominently state that it is derived from the Doughmination Authorised Source Licence (DASL) and must credit Clove Nytrix Doughmination Twilight as the original author.
+
+---
+
+**End of Licence**
diff --git a/compose.yml b/compose.yml
new file mode 100644
index 0000000..f9506f4
--- /dev/null
+++ b/compose.yml
@@ -0,0 +1,23 @@
+# compose.yml
+# Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+# Licensed under the DASL-1.2 Licence.
+# See LICENCE.md in the project root for full licence information.
+
+services:
+  pastebin:
+    build: .
+    restart: unless-stopped
+    # ORIGIN, OIDC_ISSUER and OIDC_CLIENT_ID are required; see .env.example.
+    env_file: .env
+    environment:
+      HOST: 0.0.0.0
+      PORT: 3000
+      DATABASE_FILE: /app/data/pastebin.db
+    ports:
+      # Behind a reverse proxy, bind loopback instead: "127.0.0.1:3000:3000"
+      - "3000:3000"
+    volumes:
+      - pastes:/app/data
+
+volumes:
+  pastes:
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..4560c42
--- /dev/null
+++ b/package.json
@@ -0,0 +1,27 @@
+{
+  "name": "pastebin",
+  "version": "1.0.0",
+  "module": "src/index.ts",
+  "type": "module",
+  "private": true,
+  "author": "Doughmination",
+  "devDependencies": {
+    "@types/bun": "latest"
+  },
+  "peerDependencies": {
+    "typescript": "^7"
+  },
+  "dependencies": {
+    "hono": "^4.13.8",
+    "jose": "^6.2.12",
+    "jpml-lang": "^1.1.1",
+    "shiki": "^4.4.3"
+  },
+  "description": "Self-hosted pastebin for Doughmination: public to read, Doughmination SSO to write, with JPML syntax highlighting.",
+  "scripts": {
+    "dev": "bun --watch src/index.ts",
+    "start": "bun src/index.ts",
+    "typecheck": "tsc --noEmit",
+    "sync:jpml": "bun run scripts/sync-jpml-grammar.ts"
+  }
+}
diff --git a/public/static/app.js b/public/static/app.js
new file mode 100644
index 0000000..37559ac
--- /dev/null
+++ b/public/static/app.js
@@ -0,0 +1,164 @@
+/* public/static/app.js
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+// Progressive enhancement only: every page here works with this file blocked.
+// Nothing below touches the network.
+
+(function () {
+  "use strict";
+
+  const page = document.body.dataset.page;
+
+  if (page === "paste") setUpPaste();
+  if (page === "composer") setUpComposer();
+
+  // --- a paste --------------------------------------------------------------
+
+  function setUpPaste() {
+    const code = document.querySelector(".code");
+    if (!code) return;
+
+    const copyButton = document.querySelector("[data-copy-body]");
+    if (copyButton && navigator.clipboard) {
+      copyButton.addEventListener("click", async () => {
+        const text = code.innerText.replace(/\n$/, "");
+        try {
+          await navigator.clipboard.writeText(text);
+          flash(copyButton, "Copied");
+        } catch {
+          flash(copyButton, "Press Ctrl+C");
+        }
+      });
+    } else if (copyButton) {
+      copyButton.remove();
+    }
+
+    let anchorLine = null;
+
+    // Clicking a line number selects that line and puts it in the address bar,
+    // so the URL can be shared as a pointer at one line. Shift-click extends.
+    code.addEventListener("click", (event) => {
+      const line = event.target.closest(".line");
+      if (!line || !line.id) return;
+
+      // Only the number gutter reacts, so selecting code still works normally.
+      const gutter = parseFloat(getComputedStyle(line).paddingLeft);
+      if (!(event.offsetX >= 0 && event.offsetX < gutter && event.target === line)) return;
+
+      const number = Number(line.id.slice(1));
+      if (!Number.isFinite(number)) return;
+
+      if (event.shiftKey && anchorLine !== null) {
+        light(Math.min(anchorLine, number), Math.max(anchorLine, number));
+      } else {
+        anchorLine = number;
+        light(number, number);
+      }
+      event.preventDefault();
+    });
+
+    function light(from, to) {
+      for (const lit of code.querySelectorAll(".line.lit")) lit.classList.remove("lit");
+      for (let n = from; n <= to; n++) {
+        const line = document.getElementById("L" + n);
+        if (line) line.classList.add("lit");
+      }
+      const hash = from === to ? "#L" + from : "#L" + from + "-L" + to;
+      history.replaceState(null, "", hash);
+    }
+
+    // Restore a range that arrived in the URL, e.g. #L12-L20.
+    const range = /^#L(\d+)(?:-L(\d+))?$/.exec(location.hash);
+    if (range) {
+      const from = Number(range[1]);
+      const to = range[2] ? Number(range[2]) : from;
+      anchorLine = from;
+      if (to > from) light(from, to);
+      const first = document.getElementById("L" + from);
+      if (first) first.scrollIntoView({ block: "center" });
+    }
+
+    // Deleting a paste can't be undone, so ask once. The form still submits
+    // normally for anyone without scripting.
+    const deleteForm = document.querySelector("[data-confirm-delete]");
+    if (deleteForm) {
+      let armed = false;
+      const button = deleteForm.querySelector("button");
+      deleteForm.addEventListener("submit", (event) => {
+        if (armed) return;
+        event.preventDefault();
+        armed = true;
+        button.textContent = "Really delete?";
+        setTimeout(() => {
+          armed = false;
+          button.textContent = "Delete";
+        }, 4000);
+      });
+    }
+  }
+
+  function flash(button, text) {
+    const original = button.textContent;
+    button.textContent = text;
+    setTimeout(() => {
+      button.textContent = original;
+    }, 1500);
+  }
+
+  // --- the composer ---------------------------------------------------------
+
+  function setUpComposer() {
+    const form = document.querySelector(".composer");
+    if (!form) return;
+
+    const textarea = form.querySelector("textarea[name=body]");
+    const counter = form.querySelector("[data-counter]");
+    const maxBytes = Number(form.dataset.maxBytes || 0);
+
+    if (textarea && counter) {
+      const encoder = new TextEncoder();
+      const update = () => {
+        const size = encoder.encode(textarea.value).length;
+        counter.textContent = humanBytes(size);
+        counter.classList.toggle("over", maxBytes > 0 && size > maxBytes);
+      };
+      textarea.addEventListener("input", update);
+      update();
+    }
+
+    // Tab inserts an indent instead of leaving the field. Shift+Tab and Escape
+    // still move focus, so the form stays keyboard-navigable.
+    if (textarea) {
+      textarea.addEventListener("keydown", (event) => {
+        if (event.key !== "Tab" || event.shiftKey) return;
+        event.preventDefault();
+        const { selectionStart: start, selectionEnd: end, value } = textarea;
+        textarea.value = value.slice(0, start) + "  " + value.slice(end);
+        textarea.selectionStart = textarea.selectionEnd = start + 2;
+      });
+    }
+
+    // Picking a custom colour is what you meant by choosing "Custom".
+    const customColour = form.querySelector("input[name=accent_custom]");
+    if (customColour) {
+      customColour.addEventListener("input", () => {
+        const radio = form.querySelector("input[name=accent_choice][value=custom]");
+        if (radio) radio.checked = true;
+      });
+    }
+
+    // Ctrl/Cmd+Enter publishes, the way a commit message field would.
+    form.addEventListener("keydown", (event) => {
+      if ((event.ctrlKey || event.metaKey) && event.key === "Enter") form.requestSubmit();
+    });
+  }
+
+  function humanBytes(count) {
+    if (count < 1024) return count + " B";
+    if (count < 1024 * 1024) return (count / 1024).toFixed(1) + " KB";
+    return (count / (1024 * 1024)).toFixed(1) + " MB";
+  }
+})();
diff --git a/public/static/favicon.svg b/public/static/favicon.svg
new file mode 100644
index 0000000..64692b4
--- /dev/null
+++ b/public/static/favicon.svg
@@ -0,0 +1,13 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
+  <defs>
+    <linearGradient id="trans" x1="0" y1="0" x2="0" y2="1">
+      <stop offset="0%" stop-color="#5BCEFA"/>
+      <stop offset="25%" stop-color="#F5A9B8"/>
+      <stop offset="50%" stop-color="#FFFFFF"/>
+      <stop offset="75%" stop-color="#F5A9B8"/>
+      <stop offset="100%" stop-color="#5BCEFA"/>
+    </linearGradient>
+  </defs>
+  <rect width="24" height="24" rx="5" fill="#07050a"/>
+  <path d="M6 3h8l4 4v14H6zm8 1.5V7h2.5zM8 10h8v1.5H8zm0 3h8v1.5H8zm0 3h5v1.5H8z" fill="url(#trans)"/>
+</svg>
diff --git a/public/static/style.css b/public/static/style.css
new file mode 100644
index 0000000..8921003
--- /dev/null
+++ b/public/static/style.css
@@ -0,0 +1,654 @@
+/* public/static/style.css
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/* The palette is the auth server's, so signing in and coming back doesn't feel
+ * like leaving the site. A paste may override --accent and the tints derived
+ * from it on <body>; everything below reads through those variables so one
+ * colour re-themes a page. */
+:root {
+  --bg: #07050a;
+  --surface: #100a10;
+  --surface-2: #1a1016;
+  --border: #34141c;
+  --border-strong: #5c1c28;
+  --text: #ece3e6;
+  --muted: #9c848c;
+  --accent: #9c1f34;
+  --accent-strong: #c22a44;
+  --accent-text: #fff2f2;
+  --ok: #5f9e78;
+  --ok-bg: rgba(95, 158, 120, 0.12);
+  --danger: #ff4d5e;
+  --danger-bg: rgba(255, 77, 94, 0.12);
+  --focus: #e23a52;
+  --focus-glow: rgba(226, 58, 82, 0.35);
+  --accent-wash: rgba(156, 31, 52, 0.16);
+  --accent-wash-soft: rgba(92, 28, 40, 0.12);
+  --radius: 8px;
+  --display-font: Georgia, "Iowan Old Style", "Palatino Linotype", serif;
+  --mono-font: ui-monospace, "Cascadia Code", Menlo, monospace;
+  color-scheme: dark;
+}
+
+*,
+*::before,
+*::after {
+  box-sizing: border-box;
+}
+
+html {
+  -webkit-text-size-adjust: 100%;
+}
+
+body {
+  margin: 0;
+  min-height: 100vh;
+  background:
+    radial-gradient(ellipse 900px 480px at 50% -12%, var(--accent-wash), transparent 60%),
+    radial-gradient(ellipse 700px 500px at 100% 110%, var(--accent-wash-soft), transparent 60%),
+    var(--bg);
+  background-attachment: fixed;
+  color: var(--text);
+  font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+  cursor: url("https://m.doughmination.gay/cursors/sandrone/Normal.png") 0 0, default;
+}
+
+a,
+button,
+.btn,
+select,
+summary,
+label[for],
+.swatch {
+  cursor: url("https://m.doughmination.gay/cursors/sandrone/Link.png") 4 0, pointer;
+}
+
+input[type="text"],
+input[type="password"],
+input[type="email"],
+input[type="url"],
+textarea {
+  cursor: url("https://m.doughmination.gay/cursors/sandrone/Text.png") 4 9, text;
+}
+
+button:disabled,
+input:disabled,
+select:disabled,
+textarea:disabled,
+[aria-disabled="true"] {
+  cursor: url("https://m.doughmination.gay/cursors/sandrone/Unavailable.png") 0 0, not-allowed;
+}
+
+a {
+  color: var(--accent-strong);
+}
+
+a:hover {
+  color: var(--focus);
+}
+
+code {
+  font-family: var(--mono-font);
+  font-size: 0.9em;
+  overflow-wrap: anywhere;
+}
+
+h1 {
+  font-family: var(--display-font);
+  font-size: 1.6rem;
+  letter-spacing: 0.015em;
+  margin: 0 0 0.75rem;
+}
+
+h2 {
+  font-family: var(--display-font);
+  font-size: 1.15rem;
+  letter-spacing: 0.01em;
+  margin: 0 0 0.5rem;
+}
+
+.muted {
+  color: var(--muted);
+}
+
+.small {
+  font-size: 0.875rem;
+}
+
+.grow {
+  flex: 1;
+  min-width: 0;
+}
+
+.hidden {
+  display: none !important;
+}
+
+/* --- layout ------------------------------------------------------------------ */
+
+.topbar {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  gap: 1rem;
+  flex-wrap: wrap;
+  padding: 0.75rem 16px;
+  background: linear-gradient(180deg, var(--surface), #0b070a);
+  border-bottom: 1px solid var(--border);
+  box-shadow: 0 1px 0 var(--accent-wash);
+}
+
+.brand {
+  color: var(--text);
+  font-family: var(--display-font);
+  font-size: 1.1rem;
+  font-weight: 600;
+  letter-spacing: 0.04em;
+  text-decoration: none;
+}
+
+.topbar nav {
+  display: flex;
+  align-items: center;
+  gap: 0.5rem;
+  flex-wrap: wrap;
+}
+
+main {
+  margin: 0 auto;
+  padding: 1.5rem 16px 3rem;
+}
+
+main.wide {
+  max-width: 960px;
+}
+
+main.narrow {
+  max-width: 440px;
+  padding-top: 3rem;
+}
+
+main.full {
+  max-width: 1400px;
+}
+
+.card,
+.panel {
+  position: relative;
+  background: var(--surface);
+  border: 1px solid var(--border);
+  border-top: 1px solid var(--border-strong);
+  border-radius: var(--radius);
+  padding: 1.25rem;
+  box-shadow: 0 16px 32px -20px rgba(0, 0, 0, 0.8);
+}
+
+.panel {
+  margin: 1rem 0;
+}
+
+/* --- forms ------------------------------------------------------------------- */
+
+.stack {
+  display: flex;
+  flex-direction: column;
+  gap: 0.85rem;
+}
+
+.grid2 {
+  display: grid;
+  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+  gap: 0.85rem;
+}
+
+.field {
+  display: flex;
+  flex-direction: column;
+  gap: 0.3rem;
+}
+
+.field > span,
+.field > legend {
+  font-weight: 550;
+  font-size: 0.9rem;
+}
+
+input[type="text"],
+input[type="password"],
+input[type="email"],
+input[type="url"],
+select,
+textarea {
+  width: 100%;
+  min-width: 0;
+  padding: 0.55rem 0.7rem;
+  border: 1px solid var(--border);
+  border-radius: 8px;
+  background: var(--surface-2);
+  color: var(--text);
+  font: inherit;
+}
+
+textarea {
+  resize: vertical;
+  font-family: var(--mono-font);
+  font-size: 0.875rem;
+  line-height: 1.5;
+  tab-size: 2;
+}
+
+input:disabled,
+input[readonly] {
+  opacity: 0.7;
+}
+
+:focus-visible {
+  outline: 2px solid var(--focus);
+  outline-offset: 2px;
+  box-shadow: 0 0 0 5px var(--focus-glow);
+  border-radius: 4px;
+}
+
+fieldset {
+  border: 1px solid var(--border);
+  border-radius: 8px;
+  padding: 0.75rem;
+  margin: 0;
+}
+
+legend {
+  padding: 0 0.3rem;
+}
+
+.check,
+.field-check {
+  display: flex;
+  align-items: flex-start;
+  gap: 0.5rem;
+  flex-direction: row;
+}
+
+.check input {
+  margin-top: 0.3rem;
+}
+
+button,
+.btn {
+  display: inline-flex;
+  align-items: center;
+  justify-content: center;
+  gap: 0.4rem;
+  padding: 0.55rem 1rem;
+  border: 1px solid var(--border);
+  border-radius: 8px;
+  background: var(--surface-2);
+  color: var(--text);
+  font: inherit;
+  font-weight: 550;
+  text-decoration: none;
+  transition: border-color 0.15s ease, box-shadow 0.15s ease, color 0.15s ease;
+}
+
+button:hover:not(:disabled),
+.btn:hover:not([aria-disabled="true"]) {
+  border-color: var(--accent-strong);
+  color: var(--text);
+}
+
+button:disabled,
+.btn[aria-disabled="true"] {
+  opacity: 0.55;
+}
+
+button.primary,
+.btn.primary {
+  background: linear-gradient(180deg, var(--accent-strong), var(--accent) 85%);
+  border-color: var(--border-strong);
+  color: var(--accent-text);
+}
+
+button.primary:hover:not(:disabled),
+.btn.primary:hover {
+  border-color: var(--focus);
+  box-shadow: 0 0 0 3px var(--focus-glow);
+  color: var(--accent-text);
+}
+
+button.danger,
+.btn.danger {
+  color: var(--danger);
+}
+
+button.danger:hover:not(:disabled) {
+  border-color: var(--danger);
+}
+
+button.small,
+.btn.small {
+  padding: 0.3rem 0.65rem;
+  font-size: 0.85rem;
+}
+
+form.inline {
+  display: inline;
+}
+
+.buttons {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 0.5rem;
+  align-items: center;
+}
+
+/* --- accent swatches ----------------------------------------------------------- */
+
+.swatches {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 0.5rem;
+  margin-top: 0.4rem;
+}
+
+.swatch {
+  display: inline-flex;
+  align-items: center;
+  gap: 0.45rem;
+  padding: 0.3rem 0.7rem 0.3rem 0.45rem;
+  border: 1px solid var(--border);
+  border-radius: 999px;
+  background: var(--surface-2);
+  font-size: 0.85rem;
+  color: var(--muted);
+  transition: border-color 0.15s ease, color 0.15s ease;
+}
+
+.swatch:hover {
+  border-color: var(--accent-strong);
+  color: var(--text);
+}
+
+/* The radio itself is the accessible control; the dot is what you see. */
+.swatch input[type="radio"] {
+  position: absolute;
+  opacity: 0;
+  width: 0;
+  height: 0;
+}
+
+.swatch:has(input:checked) {
+  border-color: var(--focus);
+  color: var(--text);
+  box-shadow: 0 0 0 2px var(--focus-glow);
+}
+
+.swatch:has(input:focus-visible) {
+  outline: 2px solid var(--focus);
+  outline-offset: 2px;
+}
+
+.swatch-dot {
+  width: 1.1rem;
+  height: 1.1rem;
+  border-radius: 50%;
+  border: 1px solid rgba(255, 255, 255, 0.22);
+  background: var(--swatch, transparent);
+  flex-shrink: 0;
+}
+
+.swatch-none .swatch-dot {
+  background:
+    linear-gradient(135deg, transparent 46%, var(--muted) 46%, var(--muted) 54%, transparent 54%),
+    #1a1016;
+}
+
+.swatch-crimson { --swatch: #9c1f34; }
+.swatch-rose { --swatch: #c2456b; }
+.swatch-violet { --swatch: #7b4bc4; }
+.swatch-indigo { --swatch: #4257b2; }
+.swatch-teal { --swatch: #1f8a7a; }
+.swatch-moss { --swatch: #4f8a3d; }
+.swatch-amber { --swatch: #b07d1e; }
+.swatch-ember { --swatch: #c2562a; }
+
+.swatch-custom input[type="color"] {
+  width: 1.6rem;
+  height: 1.3rem;
+  padding: 0;
+  border: 1px solid var(--border);
+  border-radius: 4px;
+  background: none;
+}
+
+/* --- notices, badges, rows ------------------------------------------------------ */
+
+.notice {
+  padding: 0.65rem 0.85rem;
+  border: 1px solid var(--border);
+  border-radius: 8px;
+  background: var(--surface-2);
+  margin: 0.75rem 0;
+}
+
+.notice.ok {
+  border-color: var(--ok);
+  background: var(--ok-bg);
+}
+
+.notice.error {
+  border-color: var(--danger);
+  background: var(--danger-bg);
+}
+
+.badge {
+  display: inline-block;
+  padding: 0.05rem 0.5rem;
+  border: 1px solid var(--border);
+  border-radius: 999px;
+  font-size: 0.78rem;
+  color: var(--muted);
+  white-space: nowrap;
+}
+
+.badge.danger {
+  color: var(--danger);
+  border-color: var(--danger);
+}
+
+.rows {
+  list-style: none;
+  margin: 0.5rem 0 0.75rem;
+  padding: 0;
+}
+
+.rows > li {
+  display: flex;
+  align-items: center;
+  gap: 0.75rem;
+  padding: 0.65rem 0;
+  border-bottom: 1px solid var(--border);
+}
+
+.rows > li:last-child {
+  border-bottom: 0;
+}
+
+.paste-link {
+  font-family: var(--display-font);
+  font-size: 1.05rem;
+  text-decoration: none;
+}
+
+.paste-link:hover {
+  text-decoration: underline;
+}
+
+.paste-meta {
+  display: flex;
+  flex-wrap: wrap;
+  align-items: center;
+  gap: 0.4rem;
+  margin: 0.2rem 0 0;
+}
+
+.pager {
+  display: flex;
+  align-items: center;
+  gap: 0.75rem;
+  margin-top: 1rem;
+}
+
+/* --- a paste -------------------------------------------------------------------- */
+
+.paste {
+  display: flex;
+  flex-direction: column;
+  gap: 0.75rem;
+}
+
+.paste-head {
+  display: flex;
+  align-items: flex-start;
+  justify-content: space-between;
+  gap: 1rem;
+  flex-wrap: wrap;
+}
+
+.paste-head h1 {
+  margin: 0;
+  overflow-wrap: anywhere;
+}
+
+.paste-actions {
+  flex-shrink: 0;
+}
+
+.jpml-note {
+  margin: 0;
+}
+
+/* The code surface takes its background from the chosen highlight theme (Shiki
+ * puts it on the <pre>), and the frame around it from the page accent. */
+.code {
+  position: relative;
+  border: 1px solid var(--border);
+  border-top: 1px solid var(--border-strong);
+  border-radius: var(--radius);
+  overflow: hidden;
+  box-shadow: 0 16px 32px -20px rgba(0, 0, 0, 0.8);
+}
+
+.code pre.shiki {
+  margin: 0;
+  padding: 1rem 0;
+  overflow-x: auto;
+  font-family: var(--mono-font);
+  font-size: 0.875rem;
+  line-height: 1.55;
+  tab-size: 2;
+}
+
+.code pre.sh-plain {
+  background: var(--surface);
+  color: var(--text);
+}
+
+.code pre.shiki code {
+  display: block;
+  width: max-content;
+  min-width: 100%;
+  font-size: inherit;
+  counter-reset: line;
+}
+
+.code .line {
+  display: inline-block;
+  width: 100%;
+  padding: 0 1rem;
+  scroll-margin-top: 4rem;
+}
+
+/* Line numbers are a counter rather than markup, so selecting the code and
+ * copying it never picks them up. */
+.code.numbered pre.shiki code {
+  counter-reset: line;
+}
+
+.code.numbered .line {
+  padding-left: 4.2rem;
+}
+
+.code.numbered .line::before {
+  counter-increment: line;
+  content: counter(line);
+  position: absolute;
+  left: 0;
+  width: 3.4rem;
+  padding-right: 0.8rem;
+  text-align: right;
+  color: var(--muted);
+  opacity: 0.55;
+  user-select: none;
+  -webkit-user-select: none;
+}
+
+.code.numbered .line {
+  position: relative;
+}
+
+.code .line:target,
+.code .line.lit {
+  background: var(--focus-glow);
+  box-shadow: inset 3px 0 0 var(--focus);
+}
+
+.code .line:target::before,
+.code .line.lit::before {
+  opacity: 1;
+  color: var(--focus);
+}
+
+/* A light highlight theme brings its own pale background with it, so the
+ * gutter and the frame move with it rather than staying dark against it. */
+.code.light {
+  border-color: rgba(0, 0, 0, 0.18);
+  color-scheme: light;
+}
+
+.code.light .line::before {
+  color: #2a1a20;
+  opacity: 0.4;
+}
+
+.code.light .line:target,
+.code.light .line.lit {
+  background: rgba(0, 0, 0, 0.07);
+}
+
+::selection {
+  background: var(--accent);
+  color: var(--accent-text);
+}
+
+@media (max-width: 640px) {
+  .paste-head {
+    flex-direction: column;
+  }
+
+  .code.numbered .line {
+    padding-left: 3.2rem;
+  }
+
+  .code.numbered .line::before {
+    width: 2.6rem;
+    padding-right: 0.6rem;
+  }
+}
+
+@media (prefers-reduced-motion: reduce) {
+  * {
+    transition: none !important;
+  }
+}
diff --git a/scripts/sync-jpml-grammar.ts b/scripts/sync-jpml-grammar.ts
new file mode 100644
index 0000000..aaca381
--- /dev/null
+++ b/scripts/sync-jpml-grammar.ts
@@ -0,0 +1,40 @@
+/* scripts/sync-jpml-grammar.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/**
+ * Copies the JPML TextMate grammar out of the jpml-vscode checkout, so the
+ * highlighting here matches the editor rather than drifting from it.
+ *
+ *   bun run sync:jpml [path/to/jpml-vscode]
+ */
+
+import { resolve } from "node:path";
+
+const DESTINATION = resolve(import.meta.dir, "..", "syntaxes", "jpml.tmLanguage.json");
+
+const candidates = [
+  process.argv[2],
+  resolve(import.meta.dir, "..", "..", "jpml-vscode"),
+].filter((path): path is string => Boolean(path));
+
+for (const root of candidates) {
+  const source = Bun.file(resolve(root, "syntaxes", "jpml.tmLanguage.json"));
+  if (!(await source.exists())) continue;
+
+  const text = await source.text();
+  // Parse before writing: a grammar that isn't valid JSON would take the
+  // server down at its next start, and this script is the last chance to say so.
+  JSON.parse(text);
+
+  await Bun.write(DESTINATION, text);
+  console.log(`Copied ${resolve(root, "syntaxes", "jpml.tmLanguage.json")}\n     -> ${DESTINATION}`);
+  process.exit(0);
+}
+
+console.error(
+  "Couldn't find jpml-vscode. Pass its path:\n  bun run sync:jpml ../jpml-vscode",
+);
+process.exit(1);
diff --git a/src/auth/oidc.ts b/src/auth/oidc.ts
new file mode 100644
index 0000000..56fb8d6
--- /dev/null
+++ b/src/auth/oidc.ts
@@ -0,0 +1,171 @@
+/* src/auth/oidc.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose";
+import { config, redirectUri } from "../env";
+
+interface Discovery {
+  issuer: string;
+  authorization_endpoint: string;
+  token_endpoint: string;
+  userinfo_endpoint: string;
+  jwks_uri: string;
+  end_session_endpoint?: string;
+}
+
+let cached: { at: number; doc: Discovery } | null = null;
+let jwks: ReturnType<typeof createRemoteJWKSet> | null = null;
+
+/**
+ * The auth server's OpenID configuration. Cached for an hour so a paste view
+ * never waits on it, and re-fetched after that so key and endpoint changes
+ * land without a restart.
+ */
+export async function discover(): Promise<Discovery> {
+  if (cached && Date.now() - cached.at < 3_600_000) return cached.doc;
+
+  const url = `${config.issuer}/.well-known/openid-configuration`;
+  const res = await fetch(url, { headers: { accept: "application/json" } });
+  if (!res.ok) throw new Error(`Discovery failed: ${url} returned ${res.status}`);
+  const doc = (await res.json()) as Discovery;
+
+  // A provider that answers for a different issuer than we configured is either
+  // misconfigured or not the server we meant to trust.
+  if (doc.issuer !== config.issuer) {
+    throw new Error(`Discovery issuer mismatch: expected ${config.issuer}, got ${doc.issuer}`);
+  }
+
+  cached = { at: Date.now(), doc };
+  jwks ??= createRemoteJWKSet(new URL(doc.jwks_uri));
+  return doc;
+}
+
+export interface AuthorizeRequest {
+  url: string;
+  state: string;
+  verifier: string;
+  nonce: string;
+}
+
+export async function authorizeUrl(state: string, challenge: string, nonce: string): Promise<string> {
+  const doc = await discover();
+  const url = new URL(doc.authorization_endpoint);
+  url.searchParams.set("response_type", "code");
+  url.searchParams.set("client_id", config.clientId);
+  url.searchParams.set("redirect_uri", redirectUri);
+  url.searchParams.set("scope", "openid profile");
+  url.searchParams.set("state", state);
+  url.searchParams.set("nonce", nonce);
+  url.searchParams.set("code_challenge", challenge);
+  url.searchParams.set("code_challenge_method", "S256");
+  return url.toString();
+}
+
+interface TokenResponse {
+  access_token: string;
+  id_token: string;
+  token_type: string;
+  expires_in: number;
+}
+
+export interface Identity {
+  /** The OIDC subject: stable for this user at this auth server. */
+  id: string;
+  username: string;
+  name: string | null;
+  picture: string | null;
+}
+
+/**
+ * Swaps the authorization code for tokens and verifies the id_token against
+ * the auth server's published keys.
+ */
+export async function exchangeCode(code: string, verifier: string, nonce: string): Promise<Identity> {
+  const doc = await discover();
+
+  const body = new URLSearchParams({
+    grant_type: "authorization_code",
+    code,
+    redirect_uri: redirectUri,
+    client_id: config.clientId,
+    code_verifier: verifier,
+  });
+
+  const headers: Record<string, string> = {
+    "content-type": "application/x-www-form-urlencoded",
+    accept: "application/json",
+  };
+  // Confidential clients authenticate with Basic; public ones rely on PKCE alone.
+  if (config.clientSecret) {
+    const credentials = `${encodeURIComponent(config.clientId)}:${encodeURIComponent(config.clientSecret)}`;
+    headers.authorization = `Basic ${btoa(credentials)}`;
+  }
+
+  const res = await fetch(doc.token_endpoint, { method: "POST", headers, body });
+  if (!res.ok) {
+    const detail = await res.text();
+    throw new Error(`Token exchange failed (${res.status}): ${detail.slice(0, 200)}`);
+  }
+  const tokens = (await res.json()) as TokenResponse;
+
+  const { payload } = await jwtVerify(tokens.id_token, jwks!, {
+    issuer: config.issuer,
+    audience: config.clientId,
+  });
+
+  if (typeof payload.sub !== "string" || !payload.sub) throw new Error("The id_token has no subject.");
+  if (payload.nonce !== nonce) throw new Error("The id_token nonce doesn't match this sign-in.");
+
+  return identityFrom(payload, await fetchUserinfo(doc, tokens.access_token, payload.sub));
+}
+
+/**
+ * The id_token carries profile claims already; userinfo is a best-effort
+ * top-up, so a failure there must not break an otherwise valid sign-in.
+ */
+async function fetchUserinfo(doc: Discovery, accessToken: string, sub: string): Promise<JWTPayload | null> {
+  try {
+    const res = await fetch(doc.userinfo_endpoint, {
+      headers: { authorization: `Bearer ${accessToken}`, accept: "application/json" },
+    });
+    if (!res.ok) return null;
+    const info = (await res.json()) as JWTPayload;
+    // A userinfo response for somebody else is a mix-up, not extra detail.
+    return info.sub === sub ? info : null;
+  } catch {
+    return null;
+  }
+}
+
+function text(...candidates: unknown[]): string | null {
+  for (const candidate of candidates) {
+    if (typeof candidate === "string" && candidate.trim()) return candidate.trim().slice(0, 200);
+  }
+  return null;
+}
+
+function identityFrom(idToken: JWTPayload, userinfo: JWTPayload | null): Identity {
+  const claims = { ...idToken, ...(userinfo ?? {}) };
+  const sub = idToken.sub!;
+  const picture = text(claims.picture);
+  return {
+    id: sub,
+    username: text(claims.preferred_username, claims.name) ?? sub,
+    name: text(claims.name),
+    // Rendered as an <img src>, so only https URLs are kept.
+    picture: picture && picture.startsWith("https://") ? picture : null,
+  };
+}
+
+/** Where to send the browser to end the session at the auth server too. */
+export async function endSessionUrl(): Promise<string | null> {
+  const doc = await discover();
+  if (!doc.end_session_endpoint) return null;
+  const url = new URL(doc.end_session_endpoint);
+  url.searchParams.set("client_id", config.clientId);
+  url.searchParams.set("post_logout_redirect_uri", `${config.origin}/`);
+  return url.toString();
+}
diff --git a/src/auth/session.ts b/src/auth/session.ts
new file mode 100644
index 0000000..5c3092f
--- /dev/null
+++ b/src/auth/session.ts
@@ -0,0 +1,77 @@
+/* src/auth/session.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { deleteCookie, getCookie, setCookie } from "hono/cookie";
+import { TTL, isSecure, now, type AppContext, type CurrentUser } from "../env";
+import { randomToken, sha256Hex, timingSafeEqualStr } from "../lib/crypto";
+import { createSession, deleteSession, getSession, getUser } from "../db";
+
+const COOKIE = "paste_session";
+
+/**
+ * Only the hash of the cookie value is stored, so a copy of the database
+ * doesn't hand anyone a working session.
+ */
+export async function startSession(c: AppContext, userId: string): Promise<void> {
+  const token = randomToken(32);
+  const expiresAt = now() + TTL.session;
+  createSession(await sha256Hex(token), userId, randomToken(16), expiresAt);
+
+  setCookie(c, COOKIE, token, {
+    httpOnly: true,
+    secure: isSecure(),
+    sameSite: "Lax",
+    path: "/",
+    maxAge: TTL.session,
+  });
+}
+
+export async function endCurrentSession(c: AppContext): Promise<void> {
+  const session = c.get("session");
+  if (session) deleteSession(session.idHash);
+  deleteCookie(c, COOKIE, { path: "/", secure: isSecure() });
+}
+
+/** Middleware: puts the signed-in user (or null) on the context for every route. */
+export async function loadSession(c: AppContext): Promise<void> {
+  c.set("session", null);
+  c.set("user", null);
+
+  const token = getCookie(c, COOKIE);
+  if (!token) return;
+
+  const row = getSession(await sha256Hex(token));
+  if (!row) {
+    deleteCookie(c, COOKIE, { path: "/", secure: isSecure() });
+    return;
+  }
+
+  const user = getUser(row.user_id);
+  if (!user) {
+    deleteSession(row.id_hash);
+    return;
+  }
+
+  c.set("session", {
+    idHash: row.id_hash,
+    userId: row.user_id,
+    csrf: row.csrf,
+    expiresAt: row.expires_at,
+  });
+  c.set("user", {
+    id: user.id,
+    username: user.username,
+    name: user.name,
+    picture: user.picture,
+  } satisfies CurrentUser);
+}
+
+/** Second CSRF layer, behind the Origin check in the request pipeline. */
+export function csrfOk(c: AppContext, submitted: string | undefined): boolean {
+  const session = c.get("session");
+  if (!session || !submitted) return false;
+  return timingSafeEqualStr(submitted, session.csrf);
+}
diff --git a/src/db.ts b/src/db.ts
new file mode 100644
index 0000000..50fb353
--- /dev/null
+++ b/src/db.ts
@@ -0,0 +1,300 @@
+/* src/db.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { Database } from "bun:sqlite";
+import { dirname } from "node:path";
+import { mkdirSync } from "node:fs";
+import { config, now } from "./env";
+
+mkdirSync(dirname(config.databaseFile), { recursive: true });
+
+export const db = new Database(config.databaseFile, { create: true, strict: true });
+
+// WAL lets readers (every paste view) run while a write is in flight, which is
+// the whole access pattern of a pastebin.
+db.exec("PRAGMA journal_mode = WAL");
+db.exec("PRAGMA foreign_keys = ON");
+db.exec("PRAGMA busy_timeout = 5000");
+db.exec("PRAGMA synchronous = NORMAL");
+
+db.exec(`
+  CREATE TABLE IF NOT EXISTS users (
+    id         TEXT PRIMARY KEY,
+    username   TEXT NOT NULL,
+    name       TEXT,
+    picture    TEXT,
+    created_at INTEGER NOT NULL,
+    updated_at INTEGER NOT NULL
+  );
+
+  CREATE TABLE IF NOT EXISTS sessions (
+    id_hash    TEXT PRIMARY KEY,
+    user_id    TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+    csrf       TEXT NOT NULL,
+    created_at INTEGER NOT NULL,
+    expires_at INTEGER NOT NULL
+  );
+  CREATE INDEX IF NOT EXISTS sessions_expires ON sessions(expires_at);
+
+  -- Sign-ins that have been sent to the auth server but not yet come back.
+  CREATE TABLE IF NOT EXISTS logins (
+    state_hash TEXT PRIMARY KEY,
+    verifier   TEXT NOT NULL,
+    nonce      TEXT NOT NULL,
+    return_to  TEXT NOT NULL,
+    expires_at INTEGER NOT NULL
+  );
+  CREATE INDEX IF NOT EXISTS logins_expires ON logins(expires_at);
+
+  CREATE TABLE IF NOT EXISTS pastes (
+    slug       TEXT PRIMARY KEY,
+    author_id  TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+    title      TEXT,
+    body       TEXT NOT NULL,
+    language   TEXT NOT NULL,
+    theme      TEXT NOT NULL,
+    accent     TEXT,
+    unlisted   INTEGER NOT NULL DEFAULT 0,
+    created_at INTEGER NOT NULL,
+    updated_at INTEGER NOT NULL,
+    expires_at INTEGER
+  );
+  CREATE INDEX IF NOT EXISTS pastes_listing ON pastes(unlisted, created_at DESC);
+  CREATE INDEX IF NOT EXISTS pastes_author ON pastes(author_id, created_at DESC);
+  CREATE INDEX IF NOT EXISTS pastes_expires ON pastes(expires_at);
+`);
+
+export interface UserRow {
+  id: string;
+  username: string;
+  name: string | null;
+  picture: string | null;
+  created_at: number;
+  updated_at: number;
+}
+
+export interface PasteRow {
+  slug: string;
+  author_id: string;
+  title: string | null;
+  body: string;
+  language: string;
+  theme: string;
+  accent: string | null;
+  unlisted: number;
+  created_at: number;
+  updated_at: number;
+  expires_at: number | null;
+}
+
+/** A paste row joined with the author's display details. */
+export interface PasteWithAuthor extends PasteRow {
+  author_username: string;
+  author_name: string | null;
+}
+
+/** Mirrors the claims from the last sign-in; the auth server stays the source of truth. */
+export function upsertUser(user: {
+  id: string;
+  username: string;
+  name: string | null;
+  picture: string | null;
+}): void {
+  const ts = now();
+  db.query(
+    `INSERT INTO users (id, username, name, picture, created_at, updated_at)
+     VALUES (?, ?, ?, ?, ?, ?)
+     ON CONFLICT(id) DO UPDATE SET
+       username = excluded.username,
+       name = excluded.name,
+       picture = excluded.picture,
+       updated_at = excluded.updated_at`,
+  ).run(user.id, user.username, user.name, user.picture, ts, ts);
+}
+
+export function getUser(id: string): UserRow | null {
+  return db.query<UserRow, [string]>("SELECT * FROM users WHERE id = ?").get(id);
+}
+
+// --- sessions -----------------------------------------------------------------------
+
+export interface SessionRow {
+  id_hash: string;
+  user_id: string;
+  csrf: string;
+  created_at: number;
+  expires_at: number;
+}
+
+export function createSession(idHash: string, userId: string, csrf: string, expiresAt: number): void {
+  db.query("INSERT INTO sessions (id_hash, user_id, csrf, created_at, expires_at) VALUES (?, ?, ?, ?, ?)").run(
+    idHash,
+    userId,
+    csrf,
+    now(),
+    expiresAt,
+  );
+}
+
+export function getSession(idHash: string): SessionRow | null {
+  return db
+    .query<SessionRow, [string, number]>("SELECT * FROM sessions WHERE id_hash = ? AND expires_at > ?")
+    .get(idHash, now());
+}
+
+export function deleteSession(idHash: string): void {
+  db.query("DELETE FROM sessions WHERE id_hash = ?").run(idHash);
+}
+
+// --- in-flight sign-ins --------------------------------------------------------------
+
+export interface LoginRow {
+  state_hash: string;
+  verifier: string;
+  nonce: string;
+  return_to: string;
+  expires_at: number;
+}
+
+export function createLogin(
+  stateHash: string,
+  verifier: string,
+  nonce: string,
+  returnTo: string,
+  expiresAt: number,
+): void {
+  db.query(
+    "INSERT INTO logins (state_hash, verifier, nonce, return_to, expires_at) VALUES (?, ?, ?, ?, ?)",
+  ).run(stateHash, verifier, nonce, returnTo, expiresAt);
+}
+
+/** Single-use: redeeming a state removes it, so a replayed callback finds nothing. */
+export function takeLogin(stateHash: string): LoginRow | null {
+  const row = db.query<LoginRow, [string]>("DELETE FROM logins WHERE state_hash = ? RETURNING *").get(stateHash);
+  return row && row.expires_at > now() ? row : null;
+}
+
+// --- pastes ---------------------------------------------------------------------------
+
+export interface PasteInput {
+  slug: string;
+  authorId: string;
+  title: string | null;
+  body: string;
+  language: string;
+  theme: string;
+  accent: string | null;
+  unlisted: boolean;
+  expiresAt: number | null;
+}
+
+export function slugTaken(slug: string): boolean {
+  return db.query<{ slug: string }, [string]>("SELECT slug FROM pastes WHERE slug = ?").get(slug) !== null;
+}
+
+export function createPaste(input: PasteInput): void {
+  const ts = now();
+  db.query(
+    `INSERT INTO pastes (slug, author_id, title, body, language, theme, accent, unlisted, created_at, updated_at, expires_at)
+     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+  ).run(
+    input.slug,
+    input.authorId,
+    input.title,
+    input.body,
+    input.language,
+    input.theme,
+    input.accent,
+    input.unlisted ? 1 : 0,
+    ts,
+    ts,
+    input.expiresAt,
+  );
+}
+
+export function updatePaste(slug: string, input: Omit<PasteInput, "slug" | "authorId">): void {
+  db.query(
+    `UPDATE pastes SET title = ?, body = ?, language = ?, theme = ?, accent = ?, unlisted = ?, updated_at = ?, expires_at = ?
+     WHERE slug = ?`,
+  ).run(
+    input.title,
+    input.body,
+    input.language,
+    input.theme,
+    input.accent,
+    input.unlisted ? 1 : 0,
+    now(),
+    input.expiresAt,
+    slug,
+  );
+}
+
+const LIVE = "(p.expires_at IS NULL OR p.expires_at > ?)";
+
+const WITH_AUTHOR = `
+  SELECT p.*, u.username AS author_username, u.name AS author_name
+  FROM pastes p JOIN users u ON u.id = p.author_id`;
+
+export function getPaste(slug: string): PasteWithAuthor | null {
+  return db.query<PasteWithAuthor, [string, number]>(`${WITH_AUTHOR} WHERE p.slug = ? AND ${LIVE}`).get(slug, now());
+}
+
+export function deletePaste(slug: string): void {
+  db.query("DELETE FROM pastes WHERE slug = ?").run(slug);
+}
+
+/** Public index: listed, unexpired pastes, newest first. */
+export function listPastes(limit: number, offset: number): PasteWithAuthor[] {
+  return db
+    .query<PasteWithAuthor, [number, number, number]>(
+      `${WITH_AUTHOR} WHERE p.unlisted = 0 AND ${LIVE} ORDER BY p.created_at DESC, p.rowid DESC LIMIT ? OFFSET ?`,
+    )
+    .all(now(), limit, offset);
+}
+
+export function countPastes(): number {
+  return (
+    db
+      .query<{ n: number }, [number]>(`SELECT count(*) AS n FROM pastes p WHERE p.unlisted = 0 AND ${LIVE}`)
+      .get(now())?.n ?? 0
+  );
+}
+
+/** One author's pastes, including their unlisted ones. */
+export function listPastesByAuthor(authorId: string, limit: number, offset: number): PasteWithAuthor[] {
+  return db
+    .query<PasteWithAuthor, [string, number, number, number]>(
+      `${WITH_AUTHOR} WHERE p.author_id = ? AND ${LIVE} ORDER BY p.created_at DESC, p.rowid DESC LIMIT ? OFFSET ?`,
+    )
+    .all(authorId, now(), limit, offset);
+}
+
+export function countPastesByAuthor(authorId: string): number {
+  return (
+    db
+      .query<{ n: number }, [string, number]>(`SELECT count(*) AS n FROM pastes p WHERE p.author_id = ? AND ${LIVE}`)
+      .get(authorId, now())?.n ?? 0
+  );
+}
+
+/** How many pastes an author has made recently — the create rate limit's input. */
+export function countRecentByAuthor(authorId: string, since: number): number {
+  return (
+    db
+      .query<{ n: number }, [string, number]>(
+        "SELECT count(*) AS n FROM pastes WHERE author_id = ? AND created_at > ?",
+      )
+      .get(authorId, since)?.n ?? 0
+  );
+}
+
+/** Drops what has aged out. Expired pastes are already invisible to every query above. */
+export function sweepExpired(): void {
+  const ts = now();
+  db.query("DELETE FROM pastes WHERE expires_at IS NOT NULL AND expires_at <= ?").run(ts);
+  db.query("DELETE FROM sessions WHERE expires_at <= ?").run(ts);
+  db.query("DELETE FROM logins WHERE expires_at <= ?").run(ts);
+}
diff --git a/src/env.ts b/src/env.ts
new file mode 100644
index 0000000..19a2b9e
--- /dev/null
+++ b/src/env.ts
@@ -0,0 +1,100 @@
+/* src/env.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import type { Context } from "hono";
+
+function required(name: string): string {
+  const value = process.env[name]?.trim();
+  if (!value) {
+    throw new Error(`${name} is not set. Copy .env.example to .env and fill it in.`);
+  }
+  return value;
+}
+
+function optional(name: string, fallback: string): string {
+  return process.env[name]?.trim() || fallback;
+}
+
+function integer(name: string, fallback: number): number {
+  const raw = process.env[name]?.trim();
+  if (!raw) return fallback;
+  const value = Number(raw);
+  if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive number.`);
+  return Math.floor(value);
+}
+
+export interface Config {
+  /** Public origin of this pastebin, e.g. https://paste.doughmination.gay. */
+  origin: string;
+  siteName: string;
+  port: number;
+  host: string;
+  databaseFile: string;
+  /** OIDC issuer: the auth-server's public origin. */
+  issuer: string;
+  clientId: string;
+  /** Empty for a public (PKCE-only) client. */
+  clientSecret: string;
+  /** Largest paste body accepted, in bytes of UTF-8. */
+  maxBodyBytes: number;
+  /** Bodies larger than this are served without syntax highlighting. */
+  maxHighlightBytes: number;
+}
+
+export const config: Config = {
+  origin: required("ORIGIN").replace(/\/+$/, ""),
+  siteName: optional("SITE_NAME", "Doughmination Paste"),
+  port: integer("PORT", 3000),
+  host: optional("HOST", "0.0.0.0"),
+  databaseFile: optional("DATABASE_FILE", "data/pastebin.db"),
+  issuer: required("OIDC_ISSUER").replace(/\/+$/, ""),
+  clientId: required("OIDC_CLIENT_ID"),
+  clientSecret: optional("OIDC_CLIENT_SECRET", ""),
+  maxBodyBytes: integer("MAX_BODY_BYTES", 512 * 1024),
+  maxHighlightBytes: integer("MAX_HIGHLIGHT_BYTES", 192 * 1024),
+};
+
+/** The redirect URI registered with the auth server for this client. */
+export const redirectUri = `${config.origin}/auth/callback`;
+
+export function isSecure(): boolean {
+  return new URL(config.origin).protocol === "https:";
+}
+
+export interface SessionInfo {
+  idHash: string;
+  userId: string;
+  csrf: string;
+  expiresAt: number;
+}
+
+export interface CurrentUser {
+  id: string;
+  username: string;
+  name: string | null;
+  picture: string | null;
+}
+
+export type AppEnv = {
+  Variables: {
+    session: SessionInfo | null;
+    user: CurrentUser | null;
+    /** Per-response nonce for the one <style> block the layout emits. */
+    nonce: string;
+  };
+};
+
+export type AppContext = Context<AppEnv>;
+
+export const TTL = {
+  session: 60 * 60 * 24 * 14,
+  /** How long a half-finished sign-in may sit at the auth server. */
+  pendingLogin: 60 * 10,
+} as const;
+
+export function now(): number {
+  return Math.floor(Date.now() / 1000);
+}
diff --git a/src/highlight.ts b/src/highlight.ts
new file mode 100644
index 0000000..301a106
--- /dev/null
+++ b/src/highlight.ts
@@ -0,0 +1,286 @@
+/* src/highlight.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { createHighlighter, type Highlighter, type LanguageRegistration } from "shiki";
+import { config } from "./env";
+import { doughminationDark, doughminationLight } from "./themes";
+import jpmlGrammar from "../syntaxes/jpml.tmLanguage.json" with { type: "json" };
+
+/**
+ * The grammar file is copied verbatim from jpml-vscode so the two stay in
+ * sync; only the registration metadata Shiki needs is added here. Its patterns
+ * use Oniguruma inline flags, so this module keeps Shiki's default WASM engine
+ * rather than the JavaScript RegExp one.
+ */
+const jpml = {
+  ...(jpmlGrammar as unknown as LanguageRegistration),
+  name: "jpml",
+  displayName: "JPML",
+  aliases: ["jp"],
+} satisfies LanguageRegistration;
+
+export interface LanguageOption {
+  id: string;
+  label: string;
+}
+
+/**
+ * Languages offered in the composer. `text` and `jpml` lead because they are
+ * this site's defaults; the rest are alphabetical.
+ */
+export const LANGUAGES: LanguageOption[] = [
+  { id: "text", label: "Plain text" },
+  { id: "jpml", label: "JPML (.jp)" },
+  { id: "bash", label: "Bash / shell" },
+  { id: "c", label: "C" },
+  { id: "cpp", label: "C++" },
+  { id: "csharp", label: "C#" },
+  { id: "css", label: "CSS" },
+  { id: "diff", label: "Diff / patch" },
+  { id: "docker", label: "Dockerfile" },
+  { id: "elixir", label: "Elixir" },
+  { id: "go", label: "Go" },
+  { id: "haskell", label: "Haskell" },
+  { id: "html", label: "HTML" },
+  { id: "ini", label: "INI" },
+  { id: "java", label: "Java" },
+  { id: "javascript", label: "JavaScript" },
+  { id: "json", label: "JSON" },
+  { id: "kotlin", label: "Kotlin" },
+  { id: "lua", label: "Lua" },
+  { id: "markdown", label: "Markdown" },
+  { id: "nix", label: "Nix" },
+  { id: "php", label: "PHP" },
+  { id: "powershell", label: "PowerShell" },
+  { id: "python", label: "Python" },
+  { id: "ruby", label: "Ruby" },
+  { id: "rust", label: "Rust" },
+  { id: "scss", label: "SCSS" },
+  { id: "sql", label: "SQL" },
+  { id: "svelte", label: "Svelte" },
+  { id: "swift", label: "Swift" },
+  { id: "toml", label: "TOML" },
+  { id: "tsx", label: "TSX / JSX" },
+  { id: "typescript", label: "TypeScript" },
+  { id: "vue", label: "Vue" },
+  { id: "xml", label: "XML" },
+  { id: "yaml", label: "YAML" },
+  { id: "zig", label: "Zig" },
+];
+
+const LANGUAGE_IDS = new Set(LANGUAGES.map((l) => l.id));
+
+export function isLanguage(id: string): boolean {
+  return LANGUAGE_IDS.has(id);
+}
+
+export function languageLabel(id: string): string {
+  return LANGUAGES.find((l) => l.id === id)?.label ?? id;
+}
+
+/** File extension used when a paste is downloaded. */
+const EXTENSIONS: Record<string, string> = {
+  text: "txt",
+  jpml: "jp",
+  bash: "sh",
+  csharp: "cs",
+  docker: "Dockerfile",
+  elixir: "ex",
+  haskell: "hs",
+  javascript: "js",
+  markdown: "md",
+  powershell: "ps1",
+  python: "py",
+  ruby: "rb",
+  rust: "rs",
+  typescript: "ts",
+  yaml: "yml",
+};
+
+export function extensionFor(language: string): string {
+  return EXTENSIONS[language] ?? language;
+}
+
+export interface ThemeOption {
+  id: string;
+  label: string;
+  /** Themes built for a light page get a light paste surface. */
+  light: boolean;
+}
+
+export const THEMES: ThemeOption[] = [
+  { id: "doughmination-dark", label: "Doughmination", light: false },
+  { id: "doughmination-light", label: "Doughmination Light", light: true },
+  { id: "catppuccin-mocha", label: "Catppuccin Mocha", light: false },
+  { id: "dracula", label: "Dracula", light: false },
+  { id: "github-dark", label: "GitHub Dark", light: false },
+  { id: "nord", label: "Nord", light: false },
+  { id: "tokyo-night", label: "Tokyo Night", light: false },
+  { id: "vitesse-dark", label: "Vitesse Dark", light: false },
+  { id: "github-light", label: "GitHub Light", light: true },
+  { id: "vitesse-light", label: "Vitesse Light", light: true },
+];
+
+export const DEFAULT_THEME = "doughmination-dark";
+
+const THEME_IDS = new Set(THEMES.map((t) => t.id));
+
+export function isTheme(id: string): boolean {
+  return THEME_IDS.has(id);
+}
+
+export function themeIsLight(id: string): boolean {
+  return THEMES.find((t) => t.id === id)?.light ?? false;
+}
+
+let highlighterPromise: Promise<Highlighter> | null = null;
+
+/**
+ * One highlighter for the process. Themes load up front (there are ten and
+ * they are small); grammars load the first time a paste asks for them, so
+ * start-up doesn't pay for languages nobody has used.
+ */
+function highlighter(): Promise<Highlighter> {
+  highlighterPromise ??= createHighlighter({
+    themes: [doughminationDark, doughminationLight, ...THEMES.map((t) => t.id).filter((id) => !id.startsWith("doughmination"))],
+    langs: [jpml],
+  });
+  return highlighterPromise;
+}
+
+/** Loads the grammars used most, so the first paste view isn't the one that waits. */
+export async function warmUp(): Promise<void> {
+  const shiki = await highlighter();
+  await shiki.loadLanguage("json", "javascript", "typescript", "python", "bash", "markdown");
+}
+
+const loaded = new Set<string>(["jpml", "text"]);
+
+async function ensureLanguage(shiki: Highlighter, language: string): Promise<boolean> {
+  if (loaded.has(language)) return true;
+  try {
+    await shiki.loadLanguage(language as Parameters<Highlighter["loadLanguage"]>[0]);
+    loaded.add(language);
+    return true;
+  } catch (err) {
+    console.error(`[highlight] could not load grammar "${language}":`, err);
+    return false;
+  }
+}
+
+export interface Rendered {
+  /** `<pre class="shiki">…` with one `<span class="line" id="Ln">` per line. */
+  html: string;
+  /** Rules for the classes in `html`, for the page's single nonced <style>. */
+  css: string;
+  lines: number;
+  /** False when the body was too big, or its grammar failed to load. */
+  highlighted: boolean;
+}
+
+function escapeHtml(text: string): string {
+  return text
+    .replace(/&/g, "&amp;")
+    .replace(/</g, "&lt;")
+    .replace(/>/g, "&gt;")
+    .replace(/"/g, "&quot;");
+}
+
+/** Plain, unhighlighted fallback in the same shape the highlighted path returns. */
+function plain(body: string): Rendered {
+  const lines = body.split("\n");
+  const rows = lines
+    .map((line, i) => `<span class="line" id="L${i + 1}">${escapeHtml(line) || "\n"}</span>`)
+    .join("\n");
+  return {
+    html: `<pre class="shiki sh-plain"><code>${rows}</code></pre>`,
+    css: "",
+    lines: lines.length,
+    highlighted: false,
+  };
+}
+
+/**
+ * Moves Shiki's inline `style="…"` attributes onto generated classes.
+ *
+ * Inline style attributes can't be covered by a CSP nonce, so keeping them
+ * would mean allowing `style-src 'unsafe-inline'` site-wide — a bad trade on a
+ * site whose whole job is displaying text other people wrote. Every `style="`
+ * in this string is Shiki's own: paste content reaches here already escaped,
+ * so a quote in the body is `&quot;` and can't close an attribute.
+ */
+function externaliseStyles(html: string, prefix: string): { html: string; css: string } {
+  const classes = new Map<string, string>();
+
+  const out = html.replace(/ style="([^"]*)"/g, (_match, style: string) => {
+    let name = classes.get(style);
+    if (!name) {
+      name = `${prefix}${classes.size}`;
+      classes.set(style, name);
+    }
+    return ` class="${name}"`;
+  });
+
+  // Shiki puts style on <pre>, <code> and token spans; <pre> and the line spans
+  // already carry classes, so merge rather than replace on those two.
+  const merged = out
+    .replace(/<pre class="([^"]*)"([^>]*?)class="([^"]*)"/g, '<pre class="$1 $3"$2')
+    .replace(/<span class="line"([^>]*?) class="([^"]*)"/g, '<span class="line $2"$1')
+    .replace(/<(pre|span|code)((?:[^>"]|"[^"]*")*?)  +/g, "<$1$2 ");
+
+  const css = Array.from(classes, ([style, name]) => `.${name}{${style}}`).join("");
+  return { html: merged, css };
+}
+
+const MAX_LINES_NUMBERED = 20_000;
+
+/**
+ * Renders one paste. Bodies past `MAX_HIGHLIGHT_BYTES` skip the tokenizer:
+ * highlighting megabytes of text is slow enough to hold the event loop.
+ */
+export async function render(body: string, language: string, theme: string): Promise<Rendered> {
+  if (Buffer.byteLength(body, "utf8") > config.maxHighlightBytes) return plain(body);
+  if (language === "text") return plain(body);
+
+  const shiki = await highlighter();
+  if (!(await ensureLanguage(shiki, language))) return plain(body);
+
+  let lines = 0;
+  let html: string;
+  try {
+    html = shiki.codeToHtml(body, {
+      lang: language,
+      theme,
+      transformers: [
+        {
+          name: "line-anchors",
+          line(node, line) {
+            // Anchors so #L12 (and the copy-link control) can address a line.
+            node.properties.id = `L${line}`;
+            lines = line;
+          },
+        },
+      ],
+    });
+  } catch (err) {
+    console.error("[highlight] render failed:", err);
+    return plain(body);
+  }
+
+  // Classes are namespaced per render so two pastes on one page could never
+  // collide; in practice a page shows one paste.
+  const { html: classed, css } = externaliseStyles(html, "sh");
+  return {
+    html: classed,
+    css,
+    lines: lines || body.split("\n").length,
+    highlighted: true,
+  };
+}
+
+export function shouldNumber(lines: number): boolean {
+  return lines <= MAX_LINES_NUMBERED;
+}
diff --git a/src/index.ts b/src/index.ts
new file mode 100644
index 0000000..85ddd4c
--- /dev/null
+++ b/src/index.ts
@@ -0,0 +1,107 @@
+/* src/index.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { Hono } from "hono";
+import { serveStatic } from "hono/bun";
+import { config, isSecure, type AppEnv } from "./env";
+import { sweepExpired } from "./db";
+import { loadSession } from "./auth/session";
+import { randomToken } from "./lib/crypto";
+import { warmUp } from "./highlight";
+import { auth } from "./routes/auth";
+import { pastes } from "./routes/pastes";
+import { message } from "./views/layout";
+
+const app = new Hono<AppEnv>();
+
+const ORIGIN = new URL(config.origin).origin;
+
+app.use("*", async (c, next) => {
+  // One nonce per response, for the single <style> block the layout emits.
+  c.set("nonce", randomToken(16));
+
+  // CSRF, layer one: browsers label every cross-site request with Origin or
+  // Sec-Fetch-Site, so state-changing requests from elsewhere never reach a
+  // handler. Session-bound forms additionally carry a CSRF token.
+  const method = c.req.method;
+  if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS") {
+    const sentOrigin = c.req.header("origin");
+    const site = c.req.header("sec-fetch-site");
+    if (sentOrigin ? sentOrigin !== ORIGIN : site && site !== "same-origin" && site !== "none") {
+      return c.text("Cross-site request refused.", 403);
+    }
+  }
+
+  await loadSession(c);
+  await next();
+
+  const h = c.res.headers;
+  // Raw and download responses set their own, stricter policy.
+  if (!h.has("Content-Security-Policy")) {
+    h.set(
+      "Content-Security-Policy",
+      `default-src 'none'; script-src 'self'; style-src 'self' 'nonce-${c.get("nonce")}'; ` +
+        "img-src 'self' https: data:; connect-src 'self'; form-action 'self'; " +
+        "base-uri 'none'; frame-ancestors 'none'",
+    );
+  }
+  h.set("X-Frame-Options", "DENY");
+  h.set("X-Content-Type-Options", "nosniff");
+  h.set("Referrer-Policy", "same-origin");
+  h.set("Cross-Origin-Opener-Policy", "same-origin");
+  if (isSecure()) h.set("Strict-Transport-Security", "max-age=63072000; includeSubDomains");
+  if (!h.has("Cache-Control")) h.set("Cache-Control", "no-store");
+});
+
+app.use(
+  "/static/*",
+  serveStatic({
+    root: "./public",
+    onFound: (_path, c) => {
+      c.header("Cache-Control", "public, max-age=3600");
+    },
+  }),
+);
+
+app.get("/favicon.ico", (c) => c.redirect("/static/favicon.svg", 301));
+
+app.get("/robots.txt", (c) => {
+  c.header("Content-Type", "text/plain; charset=utf-8");
+  c.header("Cache-Control", "public, max-age=3600");
+  return c.body("User-agent: *\nDisallow: /new\nDisallow: /mine\nDisallow: /auth/\n");
+});
+
+app.get("/health", (c) => c.json({ ok: true }));
+
+app.route("/", auth);
+app.route("/", pastes);
+
+app.notFound((c) => message(c, "Not found", "There's nothing at that address.", 404));
+
+app.onError((err, c) => {
+  console.error("[error]", c.req.method, new URL(c.req.url).pathname, err);
+  return c.text("Something went wrong on our side. Please try again.", 500);
+});
+
+// Expired pastes are already invisible to every query; this is what actually
+// reclaims the space, alongside spent sessions and abandoned sign-ins.
+sweepExpired();
+setInterval(sweepExpired, 60 * 60 * 1000).unref();
+
+// Pull in the most-used grammars now so the first paste view isn't the request
+// that pays for them.
+warmUp().catch((err) => console.error("[highlight] warm-up failed:", err));
+
+console.log(`${config.siteName} listening on http://${config.host}:${config.port} (public origin ${config.origin})`);
+
+export default {
+  port: config.port,
+  hostname: config.host,
+  // Generated slugs are short, but a title or body is not: allow a request
+  // body comfortably past the configured paste limit for form overhead.
+  maxRequestBodySize: config.maxBodyBytes + 1024 * 1024,
+  fetch: app.fetch,
+};
diff --git a/src/jpml.ts b/src/jpml.ts
new file mode 100644
index 0000000..80b5d56
--- /dev/null
+++ b/src/jpml.ts
@@ -0,0 +1,43 @@
+/* src/jpml.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { JPDecodeError, loads } from "jpml-lang/core";
+
+/**
+ * Pastes tagged `jpml` are run through the real parser, so the page can say
+ * where a document breaks instead of leaving a reader to guess from the
+ * highlighting. This is advisory only: a broken `.jp` file is still a
+ * perfectly good thing to paste, usually the reason for pasting it.
+ */
+
+export interface JpmlCheck {
+  ok: boolean;
+  /** Parser message with no location prefix, e.g. `expected ':' after key`. */
+  message?: string;
+  line?: number;
+  col?: number;
+}
+
+/** Documents past this size are skipped: the check is a nicety, not worth the stall. */
+const MAX_CHECK_BYTES = 256 * 1024;
+
+export function check(body: string): JpmlCheck | null {
+  if (Buffer.byteLength(body, "utf8") > MAX_CHECK_BYTES) return null;
+
+  try {
+    // Duplicate keys are an error in the parser's default mode, which matches
+    // what the VS Code extension reports out of the box.
+    loads(body);
+    return { ok: true };
+  } catch (err) {
+    if (err instanceof JPDecodeError) {
+      return { ok: false, message: err.rawMessage, line: err.line, col: err.col };
+    }
+    // Anything else is a bug here, not in the pasted document.
+    console.error("[jpml] unexpected check failure:", err);
+    return null;
+  }
+}
diff --git a/src/lib/colour.ts b/src/lib/colour.ts
new file mode 100644
index 0000000..f4db235
--- /dev/null
+++ b/src/lib/colour.ts
@@ -0,0 +1,157 @@
+/* src/lib/colour.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/**
+ * A paste's accent is stored as one hex colour. The rest of the tints the
+ * stylesheet needs — hover, focus ring, borders, glow — are derived from it
+ * here, so an author picks a single colour and the whole page stays coherent
+ * instead of drifting away from the site's look.
+ */
+
+export interface AccentPreset {
+  id: string;
+  label: string;
+  hex: string;
+}
+
+/** The site's own crimson first; the rest are picked to stay legible on #07050a. */
+export const ACCENT_PRESETS: AccentPreset[] = [
+  { id: "crimson", label: "Crimson", hex: "#9c1f34" },
+  { id: "rose", label: "Rose", hex: "#c2456b" },
+  { id: "violet", label: "Violet", hex: "#7b4bc4" },
+  { id: "indigo", label: "Indigo", hex: "#4257b2" },
+  { id: "teal", label: "Teal", hex: "#1f8a7a" },
+  { id: "moss", label: "Moss", hex: "#4f8a3d" },
+  { id: "amber", label: "Amber", hex: "#b07d1e" },
+  { id: "ember", label: "Ember", hex: "#c2562a" },
+];
+
+const HEX = /^#[0-9a-f]{6}$/;
+
+/** Accepts `#abc` and `#aabbcc`, in any case, and returns the long lowercase form. */
+export function normaliseHex(input: string | undefined): string | null {
+  const value = (input ?? "").trim().toLowerCase();
+  if (!value) return null;
+  const withHash = value.startsWith("#") ? value : `#${value}`;
+  const expanded = /^#[0-9a-f]{3}$/.test(withHash)
+    ? `#${withHash[1]}${withHash[1]}${withHash[2]}${withHash[2]}${withHash[3]}${withHash[3]}`
+    : withHash;
+  return HEX.test(expanded) ? expanded : null;
+}
+
+interface Hsl {
+  h: number;
+  s: number;
+  l: number;
+}
+
+function toRgb(hex: string): [number, number, number] {
+  return [
+    parseInt(hex.slice(1, 3), 16),
+    parseInt(hex.slice(3, 5), 16),
+    parseInt(hex.slice(5, 7), 16),
+  ];
+}
+
+function toHsl(hex: string): Hsl {
+  const [r255, g255, b255] = toRgb(hex);
+  const r = r255 / 255;
+  const g = g255 / 255;
+  const b = b255 / 255;
+  const max = Math.max(r, g, b);
+  const min = Math.min(r, g, b);
+  const l = (max + min) / 2;
+  const d = max - min;
+
+  if (d === 0) return { h: 0, s: 0, l };
+
+  const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+  let h: number;
+  if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
+  else if (max === g) h = ((b - r) / d + 2) / 6;
+  else h = ((r - g) / d + 4) / 6;
+  return { h, s, l };
+}
+
+function hueToChannel(p: number, q: number, tRaw: number): number {
+  let t = tRaw;
+  if (t < 0) t += 1;
+  if (t > 1) t -= 1;
+  if (t < 1 / 6) return p + (q - p) * 6 * t;
+  if (t < 1 / 2) return q;
+  if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
+  return p;
+}
+
+function toHex({ h, s, l }: Hsl): string {
+  let r: number;
+  let g: number;
+  let b: number;
+  if (s === 0) {
+    r = g = b = l;
+  } else {
+    const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+    const p = 2 * l - q;
+    r = hueToChannel(p, q, h + 1 / 3);
+    g = hueToChannel(p, q, h);
+    b = hueToChannel(p, q, h - 1 / 3);
+  }
+  const channel = (v: number) =>
+    Math.round(Math.min(1, Math.max(0, v)) * 255)
+      .toString(16)
+      .padStart(2, "0");
+  return `#${channel(r)}${channel(g)}${channel(b)}`;
+}
+
+function clamp(value: number, min = 0, max = 1): number {
+  return Math.min(max, Math.max(min, value));
+}
+
+function shift(hsl: Hsl, dl: number, ds = 0): string {
+  return toHex({ h: hsl.h, s: clamp(hsl.s + ds), l: clamp(hsl.l + dl) });
+}
+
+function rgba(hex: string, alpha: number): string {
+  const [r, g, b] = toRgb(hex);
+  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
+}
+
+/** Mixes `hex` toward the page background, for borders that read as tinted, not coloured. */
+function towardBackground(hex: string, amount: number): string {
+  const [r, g, b] = toRgb(hex);
+  const [br, bg, bb] = toRgb("#07050a");
+  const mix = (a: number, back: number) => Math.round(back + (a - back) * amount);
+  const channel = (v: number) => v.toString(16).padStart(2, "0");
+  return `#${channel(mix(r, br))}${channel(mix(g, bg))}${channel(mix(b, bb))}`;
+}
+
+/**
+ * The CSS custom properties that re-tint a page. Names match the ones
+ * `style.css` defines on `:root`, so setting them on an element overrides the
+ * site default for that subtree and nothing else.
+ */
+export function accentVars(hex: string): string {
+  const hsl = toHsl(hex);
+
+  // A very dark or very desaturated pick would make links and buttons vanish,
+  // so the derived tints are floored into a usable band.
+  const base = toHex({ h: hsl.h, s: clamp(hsl.s, 0.25), l: clamp(hsl.l, 0.24, 0.62) });
+  const baseHsl = toHsl(base);
+
+  const strong = shift(baseHsl, 0.08, 0.04);
+  const focus = shift(baseHsl, 0.16, 0.06);
+
+  return [
+    `--accent:${base}`,
+    `--accent-strong:${strong}`,
+    `--focus:${focus}`,
+    `--focus-glow:${rgba(focus, 0.35)}`,
+    `--border:${towardBackground(base, 0.34)}`,
+    `--border-strong:${towardBackground(base, 0.62)}`,
+    `--accent-wash:${rgba(base, 0.16)}`,
+    `--accent-wash-soft:${rgba(base, 0.1)}`,
+  ].join(";");
+}
diff --git a/src/lib/crypto.ts b/src/lib/crypto.ts
new file mode 100644
index 0000000..bc3a171
--- /dev/null
+++ b/src/lib/crypto.ts
@@ -0,0 +1,55 @@
+/* src/lib/crypto.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/** URL-safe base64 without padding — the encoding PKCE and JWTs use. */
+export function b64url(bytes: ArrayBuffer | Uint8Array): string {
+  const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
+  let binary = "";
+  for (const byte of view) binary += String.fromCharCode(byte);
+  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+export function randomToken(bytes = 32): string {
+  return b64url(crypto.getRandomValues(new Uint8Array(bytes)));
+}
+
+const ALPHABET = "abcdefghijkmnopqrstuvwxyz23456789";
+
+/** Short, lowercase, unambiguous id for pastes that don't name their own slug. */
+export function randomSlug(length = 8): string {
+  const picks = crypto.getRandomValues(new Uint8Array(length));
+  let out = "";
+  for (const pick of picks) out += ALPHABET[pick % ALPHABET.length];
+  return out;
+}
+
+export async function sha256(input: string): Promise<ArrayBuffer> {
+  return crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
+}
+
+export async function sha256Hex(input: string): Promise<string> {
+  const digest = new Uint8Array(await sha256(input));
+  return Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+/** Constant-time string compare, so a mismatch leaks nothing through timing. */
+export function timingSafeEqualStr(a: string, b: string): boolean {
+  if (a.length !== b.length) return false;
+  let diff = 0;
+  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
+  return diff === 0;
+}
+
+export interface Pkce {
+  verifier: string;
+  challenge: string;
+}
+
+/** RFC 7636 S256: the verifier stays here, only its hash reaches the auth server. */
+export async function pkce(): Promise<Pkce> {
+  const verifier = randomToken(32);
+  return { verifier, challenge: b64url(await sha256(verifier)) };
+}
diff --git a/src/lib/http.ts b/src/lib/http.ts
new file mode 100644
index 0000000..1711883
--- /dev/null
+++ b/src/lib/http.ts
@@ -0,0 +1,32 @@
+/* src/lib/http.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import type { AppContext } from "../env";
+
+/** Parsed form body with every value coerced to a string (files dropped). */
+export async function form(c: AppContext): Promise<Record<string, string>> {
+  const body = await c.req.parseBody({ all: true });
+  const out: Record<string, string> = {};
+  for (const [key, value] of Object.entries(body)) {
+    const first = Array.isArray(value) ? value[0] : value;
+    if (typeof first === "string") out[key] = first;
+  }
+  return out;
+}
+
+/** Only same-site paths: "/x" yes, "//host", "/\host" and absolute URLs no. */
+export function safeReturn(raw: unknown, fallback = "/"): string {
+  if (typeof raw !== "string" || !raw.startsWith("/")) return fallback;
+  if (raw.startsWith("//") || raw.startsWith("/\\")) return fallback;
+  if (/[\x00-\x20]/.test(raw)) return fallback;
+  return raw.length > 2048 ? fallback : raw;
+}
+
+export function clientIp(c: AppContext): string {
+  const forwarded = c.req.header("x-forwarded-for");
+  if (forwarded) return forwarded.split(",")[0]!.trim();
+  return c.req.header("cf-connecting-ip") ?? "unknown";
+}
diff --git a/src/lib/validate.ts b/src/lib/validate.ts
new file mode 100644
index 0000000..42791ba
--- /dev/null
+++ b/src/lib/validate.ts
@@ -0,0 +1,96 @@
+/* src/lib/validate.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { now } from "../env";
+
+// Slugs are the whole URL after the origin, so they stay lowercase and boring:
+// 3–64 characters, letters, digits, dashes and underscores, no leading or
+// trailing punctuation.
+const SLUG = /^[a-z0-9](?:[a-z0-9_-]{1,62}[a-z0-9])?$/;
+
+/**
+ * Paths the app serves itself. A paste may not take one of these, or it would
+ * shadow a real page — `/new` must stay the composer.
+ */
+export const RESERVED_SLUGS = new Set([
+  "new",
+  "auth",
+  "login",
+  "logout",
+  "raw",
+  "dl",
+  "static",
+  "mine",
+  "about",
+  "api",
+  "edit",
+  "delete",
+  "favicon.ico",
+  "robots.txt",
+  "health",
+  "u",
+  "p",
+]);
+
+export function normaliseSlug(input: string | undefined): string {
+  return (input ?? "").trim().toLowerCase();
+}
+
+export function slugProblem(slug: string): string | null {
+  if (!SLUG.test(slug)) {
+    return "Slugs are 3–64 lowercase letters, digits, dashes or underscores, starting and ending with a letter or digit.";
+  }
+  if (RESERVED_SLUGS.has(slug)) return `"${slug}" is reserved for the site itself. Pick another.`;
+  return null;
+}
+
+export function cleanText(input: string | undefined, max: number): string | null {
+  const value = (input ?? "").trim();
+  if (!value) return null;
+  return value.slice(0, max);
+}
+
+/**
+ * Normalises line endings and strips a trailing newline. Browsers send CRLF
+ * from a textarea regardless of what was typed, and a stray blank final line
+ * would show up as a numbered line in every paste.
+ */
+export function normaliseBody(input: string | undefined): string {
+  return (input ?? "").replace(/\r\n?/g, "\n").replace(/\n+$/, "");
+}
+
+export interface ExpiryOption {
+  id: string;
+  label: string;
+  /** Seconds from now, or null for "keep forever". */
+  seconds: number | null;
+}
+
+export const EXPIRY_OPTIONS: ExpiryOption[] = [
+  { id: "never", label: "Never", seconds: null },
+  { id: "1h", label: "1 hour", seconds: 60 * 60 },
+  { id: "1d", label: "1 day", seconds: 60 * 60 * 24 },
+  { id: "1w", label: "1 week", seconds: 60 * 60 * 24 * 7 },
+  { id: "1m", label: "30 days", seconds: 60 * 60 * 24 * 30 },
+  { id: "1y", label: "1 year", seconds: 60 * 60 * 24 * 365 },
+];
+
+export function expiryProblem(id: string): string | null {
+  return EXPIRY_OPTIONS.some((o) => o.id === id) ? null : "That isn't one of the expiry choices.";
+}
+
+export function expiresAtFrom(id: string): number | null {
+  const option = EXPIRY_OPTIONS.find((o) => o.id === id);
+  return option?.seconds == null ? null : now() + option.seconds;
+}
+
+/** Turns a stored timestamp back into the option a form should preselect. */
+export function expiryIdFrom(expiresAt: number | null): string {
+  if (expiresAt === null) return "never";
+  const remaining = expiresAt - now();
+  const match = EXPIRY_OPTIONS.filter((o) => o.seconds !== null).find((o) => o.seconds! >= remaining);
+  return match?.id ?? "1y";
+}
diff --git a/src/routes/auth.tsx b/src/routes/auth.tsx
new file mode 100644
index 0000000..2adb1f3
--- /dev/null
+++ b/src/routes/auth.tsx
@@ -0,0 +1,104 @@
+/* src/routes/auth.tsx
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { Hono } from "hono";
+import { TTL, now, type AppEnv } from "../env";
+import { createLogin, takeLogin, upsertUser } from "../db";
+import { authorizeUrl, endSessionUrl, exchangeCode } from "../auth/oidc";
+import { csrfOk, endCurrentSession, startSession } from "../auth/session";
+import { pkce, randomToken, sha256Hex } from "../lib/crypto";
+import { form, safeReturn } from "../lib/http";
+import { message } from "../views/layout";
+
+export const auth = new Hono<AppEnv>();
+
+/**
+ * Starts the OpenID Connect code flow against the Doughmination auth server.
+ * The state, PKCE verifier and nonce live in this app's database rather than
+ * in a cookie, so a reply that doesn't match a sign-in we started is rejected
+ * without trusting anything the browser carried back.
+ */
+auth.get("/auth/login", async (c) => {
+  if (c.get("user")) return c.redirect(safeReturn(c.req.query("return_to")));
+
+  const state = randomToken(24);
+  const nonce = randomToken(24);
+  const { verifier, challenge } = await pkce();
+  const returnTo = safeReturn(c.req.query("return_to"));
+
+  createLogin(await sha256Hex(state), verifier, nonce, returnTo, now() + TTL.pendingLogin);
+
+  try {
+    return c.redirect(await authorizeUrl(state, challenge, nonce));
+  } catch (err) {
+    console.error("[auth] could not reach the auth server:", err);
+    return message(
+      c,
+      "Sign-in is unavailable",
+      "The authentication server didn't answer. Pastes are still readable; try signing in again in a moment.",
+      502,
+    );
+  }
+});
+
+auth.get("/auth/callback", async (c) => {
+  const query = c.req.query();
+
+  // The auth server reports a refusal (e.g. the account isn't in an allowed
+  // group) on the redirect rather than at the token endpoint.
+  if (query.error) {
+    const detail = query.error === "access_denied" ? "Your account isn't allowed to use this pastebin." : query.error;
+    return message(c, "Sign-in refused", detail, 403);
+  }
+
+  if (!query.code || !query.state) {
+    return message(c, "Incomplete sign-in", "That sign-in reply was missing its code or state.", 400);
+  }
+
+  const login = takeLogin(await sha256Hex(query.state));
+  if (!login) {
+    return message(
+      c,
+      "That sign-in expired",
+      "Sign-ins are good for ten minutes and can only be used once. Start again from the sign-in button.",
+      400,
+    );
+  }
+
+  let identity;
+  try {
+    identity = await exchangeCode(query.code, login.verifier, login.nonce);
+  } catch (err) {
+    console.error("[auth] code exchange failed:", err);
+    return message(c, "Sign-in failed", "The authentication server wouldn't confirm that sign-in.", 502);
+  }
+
+  upsertUser(identity);
+  await startSession(c, identity.id);
+
+  const separator = login.return_to.includes("?") ? "&" : "?";
+  return c.redirect(`${login.return_to}${separator}m=signed-in`);
+});
+
+auth.post("/auth/logout", async (c) => {
+  const body = await form(c);
+  if (!csrfOk(c, body._csrf)) return c.text("That form expired. Go back and try again.", 403);
+
+  await endCurrentSession(c);
+
+  // Ending the session here leaves the auth server's own session alone, so
+  // offer to close that too rather than deciding for the user.
+  const single = body.everywhere === "1";
+  if (single) {
+    try {
+      const url = await endSessionUrl();
+      if (url) return c.redirect(url);
+    } catch (err) {
+      console.error("[auth] end-session lookup failed:", err);
+    }
+  }
+  return c.redirect("/?m=signed-out");
+});
diff --git a/src/routes/pastes.tsx b/src/routes/pastes.tsx
new file mode 100644
index 0000000..7b126b5
--- /dev/null
+++ b/src/routes/pastes.tsx
@@ -0,0 +1,416 @@
+/* src/routes/pastes.tsx
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { Hono } from "hono";
+import { config, now, type AppContext, type AppEnv } from "../env";
+import {
+  countPastes,
+  countPastesByAuthor,
+  countRecentByAuthor,
+  createPaste,
+  deletePaste,
+  getPaste,
+  listPastes,
+  listPastesByAuthor,
+  slugTaken,
+  updatePaste,
+  type PasteWithAuthor,
+} from "../db";
+import { csrfOk } from "../auth/session";
+import { randomSlug } from "../lib/crypto";
+import { form } from "../lib/http";
+import { ACCENT_PRESETS, accentVars, normaliseHex } from "../lib/colour";
+import {
+  cleanText,
+  expiresAtFrom,
+  expiryIdFrom,
+  expiryProblem,
+  normaliseBody,
+  normaliseSlug,
+  slugProblem,
+} from "../lib/validate";
+import {
+  DEFAULT_THEME,
+  extensionFor,
+  isLanguage,
+  isTheme,
+  render as highlight,
+  shouldNumber,
+  themeIsLight,
+} from "../highlight";
+import { check as checkJpml } from "../jpml";
+import { message, render } from "../views/layout";
+import { Composer, PasteRows, PasteView, type ComposerValues } from "../views/pastes";
+import { Flash, Pager } from "../views/ui";
+
+export const pastes = new Hono<AppEnv>();
+
+const PER_PAGE = 25;
+
+/** Pastes one account may publish per hour, so a stuck script can't fill the disk. */
+const HOURLY_LIMIT = 60;
+
+function pageNumber(c: AppContext): number {
+  const raw = Number(c.req.query("page") ?? "1");
+  return Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : 1;
+}
+
+// --- listings -------------------------------------------------------------------------
+
+pastes.get("/", (c) => {
+  const page = pageNumber(c);
+  const total = countPastes();
+  const rows = listPastes(PER_PAGE, (page - 1) * PER_PAGE);
+
+  return render(
+    c,
+    { title: "Recent pastes", description: `Public pastes on ${config.siteName}.` },
+    <>
+      <Flash code={c.req.query("m")} />
+      <div class="card">
+        <h1>Recent pastes</h1>
+        <p class="muted">
+          Anyone can read what's here. {c.get("user") ? "Publish one from the New paste button." : "Sign in to publish one."}
+        </p>
+        <PasteRows pastes={rows} empty="Nothing published yet." />
+        <Pager path="/" page={page} total={total} perPage={PER_PAGE} />
+      </div>
+    </>,
+  );
+});
+
+pastes.get("/mine", async (c) => {
+  const user = c.get("user");
+  if (!user) return c.redirect("/auth/login?return_to=%2Fmine");
+
+  const page = pageNumber(c);
+  const total = countPastesByAuthor(user.id);
+  const rows = listPastesByAuthor(user.id, PER_PAGE, (page - 1) * PER_PAGE);
+
+  return render(
+    c,
+    { title: "Your pastes", noindex: true },
+    <>
+      <Flash code={c.req.query("m")} />
+      <div class="card">
+        <h1>Your pastes</h1>
+        <p class="muted">Everything you've published, unlisted ones included.</p>
+        <PasteRows pastes={rows} showAuthor={false} empty="You haven't published anything yet." />
+        <Pager path="/mine" page={page} total={total} perPage={PER_PAGE} />
+      </div>
+    </>,
+  );
+});
+
+// --- composing -------------------------------------------------------------------------
+
+function blankValues(): ComposerValues {
+  return {
+    title: "",
+    slug: "",
+    body: "",
+    language: "text",
+    theme: DEFAULT_THEME,
+    accentChoice: "none",
+    accentCustom: "#9c1f34",
+    expiry: "never",
+    unlisted: false,
+  };
+}
+
+/** Works out which accent control an existing paste's stored colour came from. */
+function valuesFrom(paste: PasteWithAuthor): ComposerValues {
+  const preset = paste.accent ? ACCENT_PRESETS.find((p) => p.hex === paste.accent) : undefined;
+  return {
+    title: paste.title ?? "",
+    slug: paste.slug,
+    body: paste.body,
+    language: paste.language,
+    theme: paste.theme,
+    accentChoice: paste.accent === null ? "none" : (preset?.id ?? "custom"),
+    accentCustom: paste.accent ?? "#9c1f34",
+    expiry: expiryIdFrom(paste.expires_at),
+    unlisted: paste.unlisted === 1,
+  };
+}
+
+interface Parsed {
+  values: ComposerValues;
+  error: string | null;
+  /** Filled in only when `error` is null. */
+  accent: string | null;
+  expiresAt: number | null;
+}
+
+/**
+ * Reads the composer form back into validated fields. Everything the user
+ * typed survives on the returned `values` so a rejected submission can be
+ * re-rendered without losing the paste.
+ */
+function parseComposer(body: Record<string, string>): Parsed {
+  const accentChoice = body.accent_choice ?? "none";
+  const accentCustom = normaliseHex(body.accent_custom) ?? "#9c1f34";
+
+  const values: ComposerValues = {
+    title: (body.title ?? "").trim().slice(0, 200),
+    slug: normaliseSlug(body.slug),
+    body: normaliseBody(body.body),
+    language: body.language ?? "text",
+    theme: body.theme ?? DEFAULT_THEME,
+    accentChoice,
+    accentCustom,
+    expiry: body.expiry ?? "never",
+    unlisted: body.unlisted === "1",
+  };
+
+  const fail = (error: string): Parsed => ({ values, error, accent: null, expiresAt: null });
+
+  if (!values.body) return fail("A paste needs some content.");
+  const size = Buffer.byteLength(values.body, "utf8");
+  if (size > config.maxBodyBytes) {
+    return fail(`That paste is ${Math.round(size / 1024)} KB; the limit is ${Math.round(config.maxBodyBytes / 1024)} KB.`);
+  }
+
+  if (!isLanguage(values.language)) return fail("That isn't one of the languages on offer.");
+  if (!isTheme(values.theme)) return fail("That isn't one of the highlight themes on offer.");
+
+  const expiryFault = expiryProblem(values.expiry);
+  if (expiryFault) return fail(expiryFault);
+
+  let accent: string | null = null;
+  if (accentChoice === "custom") {
+    const hex = normaliseHex(body.accent_custom);
+    if (!hex) return fail("That accent colour isn't a valid hex colour.");
+    accent = hex;
+  } else if (accentChoice !== "none") {
+    const preset = ACCENT_PRESETS.find((p) => p.id === accentChoice);
+    if (!preset) return fail("That isn't one of the accent colours on offer.");
+    accent = preset.hex;
+  }
+
+  return { values, error: null, accent, expiresAt: expiresAtFrom(values.expiry) };
+}
+
+pastes.get("/new", async (c) => {
+  const user = c.get("user");
+  if (!user) return c.redirect("/auth/login?return_to=%2Fnew&m=sign-in-needed");
+
+  return render(
+    c,
+    { title: "New paste", page: "composer", noindex: true },
+    <div class="card">
+      <h1>New paste</h1>
+      <Composer values={blankValues()} csrf={c.get("session")!.csrf} maxBytes={config.maxBodyBytes} />
+    </div>,
+  );
+});
+
+pastes.post("/new", async (c) => {
+  const user = c.get("user");
+  if (!user) return message(c, "Sign in first", "Only signed-in accounts can publish pastes.", 401);
+
+  const body = await form(c);
+  if (!csrfOk(c, body._csrf)) return c.text("That form expired. Go back and try again.", 403);
+
+  if (countRecentByAuthor(user.id, now() - 3600) >= HOURLY_LIMIT) {
+    return message(c, "Slow down", `That's ${HOURLY_LIMIT} pastes in an hour. Try again later.`, 429);
+  }
+
+  const parsed = parseComposer(body);
+  const reject = (error: string) =>
+    render(
+      c,
+      { title: "New paste", page: "composer", status: 400, noindex: true },
+      <div class="card">
+        <h1>New paste</h1>
+        <Composer values={parsed.values} csrf={c.get("session")!.csrf} error={error} maxBytes={config.maxBodyBytes} />
+      </div>,
+    );
+
+  if (parsed.error) return reject(parsed.error);
+
+  let slug: string;
+  if (parsed.values.slug) {
+    slug = parsed.values.slug;
+    const fault = slugProblem(slug);
+    if (fault) return reject(fault);
+    if (slugTaken(slug)) return reject(`The slug "${slug}" is already taken.`);
+  } else {
+    const generated = freeSlug();
+    if (!generated) return message(c, "Couldn't allocate an address", "Please try publishing again.", 503);
+    slug = generated;
+  }
+
+  createPaste({
+    slug,
+    authorId: user.id,
+    title: cleanText(parsed.values.title, 200),
+    body: parsed.values.body,
+    language: parsed.values.language,
+    theme: parsed.values.theme,
+    accent: parsed.accent,
+    unlisted: parsed.values.unlisted,
+    expiresAt: parsed.expiresAt,
+  });
+
+  return c.redirect(`/${slug}?m=paste-created`);
+});
+
+/** Generated slugs collide vanishingly rarely; a few tries removes the doubt. */
+function freeSlug(): string | null {
+  for (let attempt = 0; attempt < 8; attempt++) {
+    const slug = randomSlug(attempt < 5 ? 8 : 12);
+    if (!slugTaken(slug)) return slug;
+  }
+  return null;
+}
+
+// --- reading -----------------------------------------------------------------------------
+
+pastes.get("/raw/:slug", (c) => {
+  const paste = getPaste(c.req.param("slug"));
+  if (!paste) return c.text("Not found", 404);
+
+  c.header("Content-Type", "text/plain; charset=utf-8");
+  c.header("X-Content-Type-Options", "nosniff");
+  // A paste is arbitrary text from another account, so it is never allowed to
+  // execute as a document on this origin.
+  c.header("Content-Disposition", "inline");
+  c.header("Content-Security-Policy", "default-src 'none'; sandbox");
+  return c.body(paste.body);
+});
+
+pastes.get("/dl/:slug", (c) => {
+  const paste = getPaste(c.req.param("slug"));
+  if (!paste) return c.text("Not found", 404);
+
+  const name = `${paste.slug}.${extensionFor(paste.language)}`;
+  c.header("Content-Type", "application/octet-stream");
+  c.header("X-Content-Type-Options", "nosniff");
+  c.header("Content-Disposition", `attachment; filename="${name.replace(/[^\w.-]/g, "_")}"`);
+  return c.body(paste.body);
+});
+
+pastes.get("/:slug", async (c) => {
+  const paste = getPaste(c.req.param("slug"));
+  if (!paste) {
+    return message(c, "No such paste", "It may have expired, been deleted, or never existed.", 404);
+  }
+
+  const user = c.get("user");
+  const rendered = await highlight(paste.body, paste.language, paste.theme);
+  const jpml = paste.language === "jpml" ? checkJpml(paste.body) : null;
+
+  return render(
+    c,
+    {
+      title: paste.title ?? paste.slug,
+      page: "paste",
+      full: true,
+      css: rendered.css,
+      accentVars: paste.accent ? accentVars(paste.accent) : undefined,
+      noindex: paste.unlisted === 1,
+      description: paste.title ?? `A paste by ${paste.author_username}.`,
+    },
+    <>
+      <Flash code={c.req.query("m")} />
+      <PasteView
+        paste={paste}
+        html={rendered.html}
+        lines={rendered.lines}
+        numbered={shouldNumber(rendered.lines)}
+        highlighted={rendered.highlighted}
+        light={themeIsLight(paste.theme)}
+        jpml={jpml}
+        isOwner={user?.id === paste.author_id}
+        csrf={c.get("session")?.csrf ?? ""}
+        size={Buffer.byteLength(paste.body, "utf8")}
+      />
+    </>,
+  );
+});
+
+// --- editing -------------------------------------------------------------------------------
+
+/** Resolves a paste the signed-in account is allowed to change. */
+async function ownPaste(c: AppContext): Promise<PasteWithAuthor | Response> {
+  const user = c.get("user");
+  const paste = getPaste(c.req.param("slug") ?? "");
+  if (!paste) return message(c, "No such paste", "It may have expired, been deleted, or never existed.", 404);
+  if (!user) return message(c, "Sign in first", "Only the author can change a paste.", 401);
+  if (paste.author_id !== user.id) return message(c, "Not yours", "Only the author can change this paste.", 403);
+  return paste;
+}
+
+pastes.get("/:slug/edit", async (c) => {
+  const found = await ownPaste(c);
+  if (found instanceof Response) return found;
+
+  return render(
+    c,
+    { title: `Edit ${found.slug}`, page: "composer", noindex: true },
+    <div class="card">
+      <h1>Edit paste</h1>
+      <Composer
+        values={valuesFrom(found)}
+        csrf={c.get("session")!.csrf}
+        editing={found.slug}
+        maxBytes={config.maxBodyBytes}
+      />
+    </div>,
+  );
+});
+
+pastes.post("/:slug/edit", async (c) => {
+  const found = await ownPaste(c);
+  if (found instanceof Response) return found;
+
+  const body = await form(c);
+  if (!csrfOk(c, body._csrf)) return c.text("That form expired. Go back and try again.", 403);
+
+  const parsed = parseComposer(body);
+  if (parsed.error) {
+    // The slug isn't editable, so keep showing the real one.
+    parsed.values.slug = found.slug;
+    return render(
+      c,
+      { title: `Edit ${found.slug}`, page: "composer", status: 400, noindex: true },
+      <div class="card">
+        <h1>Edit paste</h1>
+        <Composer
+          values={parsed.values}
+          csrf={c.get("session")!.csrf}
+          editing={found.slug}
+          error={parsed.error}
+          maxBytes={config.maxBodyBytes}
+        />
+      </div>,
+    );
+  }
+
+  updatePaste(found.slug, {
+    title: cleanText(parsed.values.title, 200),
+    body: parsed.values.body,
+    language: parsed.values.language,
+    theme: parsed.values.theme,
+    accent: parsed.accent,
+    unlisted: parsed.values.unlisted,
+    expiresAt: parsed.expiresAt,
+  });
+
+  return c.redirect(`/${found.slug}?m=paste-updated`);
+});
+
+pastes.post("/:slug/delete", async (c) => {
+  const found = await ownPaste(c);
+  if (found instanceof Response) return found;
+
+  const body = await form(c);
+  if (!csrfOk(c, body._csrf)) return c.text("That form expired. Go back and try again.", 403);
+
+  deletePaste(found.slug);
+  return c.redirect("/mine?m=paste-deleted");
+});
diff --git a/src/themes.ts b/src/themes.ts
new file mode 100644
index 0000000..98858c0
--- /dev/null
+++ b/src/themes.ts
@@ -0,0 +1,147 @@
+/* src/themes.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import type { ThemeRegistration } from "shiki";
+
+/**
+ * Two house themes built on the Doughmination palette, so a paste sitting in
+ * the page doesn't look like it was pasted in from somewhere else.
+ *
+ * Hue assignments are shared by both: crimson for keywords and JPML section
+ * headers, rose for keys and properties, green for strings, blue for numbers,
+ * violet for language constants, warm gold for functions.
+ */
+
+interface Hues {
+  fg: string;
+  bg: string;
+  comment: string;
+  keyword: string;
+  property: string;
+  string: string;
+  number: string;
+  constant: string;
+  func: string;
+  type: string;
+  punctuation: string;
+  invalid: string;
+  selection: string;
+}
+
+function build(name: string, type: "dark" | "light", h: Hues): ThemeRegistration {
+  return {
+    name,
+    type,
+    colors: {
+      "editor.background": h.bg,
+      "editor.foreground": h.fg,
+      "editor.selectionBackground": h.selection,
+    },
+    settings: [
+      { settings: { background: h.bg, foreground: h.fg } },
+
+      { scope: ["comment", "punctuation.definition.comment"], settings: { foreground: h.comment, fontStyle: "italic" } },
+
+      {
+        scope: [
+          "keyword",
+          "storage",
+          "storage.type",
+          "keyword.control",
+          "keyword.operator.expression",
+          "keyword.operator.new",
+          "variable.language",
+          "entity.name.tag",
+          "markup.heading",
+        ],
+        settings: { foreground: h.keyword },
+      },
+
+      // JPML: a [section] header is the document's spine, so it gets the
+      // strongest colour in the theme and the only bold weight.
+      { scope: ["entity.name.section", "entity.name.section.jpml"], settings: { foreground: h.keyword, fontStyle: "bold" } },
+      { scope: ["punctuation.definition.section"], settings: { foreground: h.keyword } },
+
+      {
+        scope: [
+          "support.type.property-name",
+          "variable.other.property",
+          "meta.object-literal.key",
+          "entity.name.tag.yaml",
+          "support.type.property-name.toml",
+        ],
+        settings: { foreground: h.property },
+      },
+
+      {
+        scope: ["string", "string.quoted", "string.unquoted", "markup.inserted", "meta.embedded.line"],
+        settings: { foreground: h.string },
+      },
+      { scope: ["constant.character.escape", "string.regexp"], settings: { foreground: h.func } },
+      { scope: ["invalid", "invalid.illegal"], settings: { foreground: h.invalid, fontStyle: "underline" } },
+
+      { scope: ["constant.numeric", "constant.other.unit"], settings: { foreground: h.number } },
+      {
+        scope: ["constant.language", "constant.language.boolean", "constant.language.null", "constant.other"],
+        settings: { foreground: h.constant },
+      },
+
+      {
+        scope: ["entity.name.function", "support.function", "meta.function-call.generic"],
+        settings: { foreground: h.func },
+      },
+      {
+        scope: ["entity.name.type", "entity.name.class", "support.class", "support.type", "entity.other.inherited-class"],
+        settings: { foreground: h.type },
+      },
+
+      { scope: ["variable", "variable.other", "meta.definition.variable.name"], settings: { foreground: h.fg } },
+      { scope: ["variable.parameter", "entity.name.variable.parameter"], settings: { foreground: h.type } },
+
+      {
+        scope: ["punctuation", "meta.brace", "keyword.operator", "punctuation.separator", "punctuation.terminator"],
+        settings: { foreground: h.punctuation },
+      },
+
+      { scope: ["markup.deleted"], settings: { foreground: h.invalid } },
+      { scope: ["markup.bold"], settings: { fontStyle: "bold" } },
+      { scope: ["markup.italic"], settings: { fontStyle: "italic" } },
+      { scope: ["markup.underline.link"], settings: { foreground: h.number, fontStyle: "underline" } },
+    ],
+  };
+}
+
+export const doughminationDark = build("doughmination-dark", "dark", {
+  fg: "#ece3e6",
+  bg: "#0c070c",
+  comment: "#7a636b",
+  keyword: "#e23a52",
+  property: "#f5a9b8",
+  string: "#7fc49a",
+  number: "#5bcefa",
+  constant: "#c8a2ff",
+  func: "#ffd39b",
+  type: "#e8b4c4",
+  punctuation: "#9c848c",
+  invalid: "#ff4d5e",
+  selection: "#3a1420",
+});
+
+export const doughminationLight = build("doughmination-light", "light", {
+  fg: "#2a1a20",
+  bg: "#fdf6f8",
+  comment: "#8a7078",
+  keyword: "#9c1f34",
+  property: "#b03a58",
+  string: "#3f7d55",
+  number: "#1d6f9e",
+  constant: "#6b3fb0",
+  func: "#94661a",
+  type: "#8a4460",
+  punctuation: "#7a656c",
+  invalid: "#c0192c",
+  selection: "#f6dde3",
+});
diff --git a/src/views/layout.tsx b/src/views/layout.tsx
new file mode 100644
index 0000000..c975edb
--- /dev/null
+++ b/src/views/layout.tsx
@@ -0,0 +1,115 @@
+/* src/views/layout.tsx
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { raw } from "hono/html";
+import type { Child } from "hono/jsx";
+import type { ContentfulStatusCode } from "hono/utils/http-status";
+import { config, type AppContext } from "../env";
+
+export interface PageOptions {
+  title: string;
+  /** Picks the behaviour in /static/app.js. */
+  page?: string;
+  /** Centered card layout for short pages. */
+  narrow?: boolean;
+  /** Full-bleed layout for reading code. */
+  full?: boolean;
+  status?: ContentfulStatusCode;
+  /** Extra CSS for this response only, emitted under the page's CSP nonce. */
+  css?: string;
+  /** Accent overrides from a paste, applied to <body>. */
+  accentVars?: string;
+  description?: string;
+  /** Set on paste pages so a stale copy is never served after an edit. */
+  noindex?: boolean;
+}
+
+export async function render(c: AppContext, opts: PageOptions, body: Child): Promise<Response> {
+  const user = c.get("user");
+  const session = c.get("session");
+  const nonce = c.get("nonce");
+
+  const layout = opts.full ? "full" : opts.narrow ? "narrow" : "wide";
+
+  // Shiki's token colours and a paste's accent both arrive as CSS text. They
+  // go in one nonced <style> rather than on inline style attributes, which a
+  // nonce cannot cover — see highlight.ts.
+  const sheet = [opts.accentVars ? `body{${opts.accentVars}}` : "", opts.css ?? ""].filter(Boolean).join("\n");
+
+  const html = (
+    <html lang="en">
+      <head>
+        <meta charset="utf-8" />
+        <meta name="viewport" content="width=device-width, initial-scale=1" />
+        <meta name="color-scheme" content="dark" />
+        {opts.noindex && <meta name="robots" content="noindex" />}
+        <title>{`${opts.title} · ${config.siteName}`}</title>
+        {opts.description && <meta name="description" content={opts.description} />}
+        <link rel="icon" type="image/svg+xml" href="/static/favicon.svg" />
+        <link rel="stylesheet" href="/static/style.css" />
+        <script src="/static/app.js" defer></script>
+        {sheet && raw(`<style nonce="${nonce}">${sheet}</style>`)}
+      </head>
+      <body data-page={opts.page ?? ""} data-csrf={session?.csrf ?? ""}>
+        <header class="topbar">
+          <a class="brand" href="/">
+            {config.siteName}
+          </a>
+          <nav>
+            <a class="btn small" href="/">
+              Recent
+            </a>
+            {user ? (
+              <>
+                <a class="btn small" href="/mine">
+                  Mine
+                </a>
+                <a class="btn small primary" href="/new">
+                  New paste
+                </a>
+                <form method="post" action="/auth/logout" class="inline">
+                  <input type="hidden" name="_csrf" value={session?.csrf ?? ""} />
+                  <button type="submit" class="small" title={`Signed in as ${user.username}`}>
+                    Sign out
+                  </button>
+                </form>
+              </>
+            ) : (
+              <a class="btn small primary" href={`/auth/login?return_to=${encodeURIComponent(currentPath(c))}`}>
+                Sign in
+              </a>
+            )}
+          </nav>
+        </header>
+        <main class={layout}>{body}</main>
+      </body>
+    </html>
+  );
+
+  return c.html(`<!doctype html>${await html}`, opts.status ?? 200);
+}
+
+function currentPath(c: AppContext): string {
+  const url = new URL(c.req.url);
+  return url.pathname + url.search;
+}
+
+/** Small standalone page for 404s and refusals. */
+export function message(c: AppContext, title: string, text: string, status: ContentfulStatusCode = 400) {
+  return render(
+    c,
+    { title, narrow: true, status },
+    <div class="card">
+      <h1>{title}</h1>
+      <p class="muted">{text}</p>
+      <p>
+        <a class="btn" href="/">
+          Back to recent pastes
+        </a>
+      </p>
+    </div>,
+  );
+}
diff --git a/src/views/pastes.tsx b/src/views/pastes.tsx
new file mode 100644
index 0000000..651b02c
--- /dev/null
+++ b/src/views/pastes.tsx
@@ -0,0 +1,325 @@
+/* src/views/pastes.tsx
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { raw } from "hono/html";
+import type { PasteWithAuthor } from "../db";
+import { LANGUAGES, THEMES, languageLabel } from "../highlight";
+import { ACCENT_PRESETS } from "../lib/colour";
+import { EXPIRY_OPTIONS } from "../lib/validate";
+import type { JpmlCheck } from "../jpml";
+import { Csrf, ErrorNote, bytes, date, relative } from "./ui";
+
+export interface ComposerValues {
+  title: string;
+  slug: string;
+  body: string;
+  language: string;
+  theme: string;
+  accentChoice: string;
+  accentCustom: string;
+  expiry: string;
+  unlisted: boolean;
+}
+
+export interface ComposerProps {
+  values: ComposerValues;
+  csrf: string;
+  error?: string | null;
+  /** Present when editing: the slug is already spent and can't move. */
+  editing?: string;
+  maxBytes: number;
+}
+
+export function Composer(props: ComposerProps) {
+  const { values, editing } = props;
+  const action = editing ? `/${editing}/edit` : "/new";
+
+  return (
+    <form method="post" action={action} class="composer stack" data-max-bytes={String(props.maxBytes)}>
+      <Csrf token={props.csrf} />
+      <ErrorNote error={props.error} />
+
+      <div class="grid2">
+        <label class="field">
+          <span>Title</span>
+          <input type="text" name="title" value={values.title} maxlength={200} placeholder="Optional" autofocus />
+        </label>
+
+        <label class="field">
+          <span>Slug</span>
+          {editing ? (
+            <input type="text" value={editing} readonly disabled />
+          ) : (
+            <input
+              type="text"
+              name="slug"
+              value={values.slug}
+              maxlength={64}
+              placeholder="Optional — a short one is generated"
+              pattern="[A-Za-z0-9_-]{3,64}"
+              autocapitalize="off"
+              autocorrect="off"
+              spellcheck={false}
+            />
+          )}
+          <small class="muted">
+            {editing ? "A paste keeps its address for good." : "Becomes the address: /your-slug"}
+          </small>
+        </label>
+      </div>
+
+      <label class="field">
+        <span>Content</span>
+        <textarea
+          name="body"
+          rows={22}
+          required
+          spellcheck={false}
+          autocapitalize="off"
+          autocorrect="off"
+          placeholder="Paste away."
+        >
+          {values.body}
+        </textarea>
+        <small class="muted">
+          <span data-counter>0 B</span> of {bytes(props.maxBytes)}
+        </small>
+      </label>
+
+      <div class="grid2">
+        <label class="field">
+          <span>Language</span>
+          <select name="language">
+            {LANGUAGES.map((lang) => (
+              <option value={lang.id} selected={lang.id === values.language}>
+                {lang.label}
+              </option>
+            ))}
+          </select>
+        </label>
+
+        <label class="field">
+          <span>Highlight theme</span>
+          <select name="theme">
+            {THEMES.map((theme) => (
+              <option value={theme.id} selected={theme.id === values.theme}>
+                {theme.label}
+              </option>
+            ))}
+          </select>
+        </label>
+      </div>
+
+      <fieldset class="field">
+        <legend>Accent colour</legend>
+        <p class="muted small">Re-tints this paste's page. Everything else keeps the site's own colours.</p>
+        <div class="swatches">
+          <label class={`swatch swatch-none${values.accentChoice === "none" ? " on" : ""}`} title="Site default">
+            <input type="radio" name="accent_choice" value="none" checked={values.accentChoice === "none"} />
+            <span class="swatch-dot" aria-hidden="true" />
+            <span class="swatch-label">Default</span>
+          </label>
+
+          {ACCENT_PRESETS.map((preset) => (
+            <label
+              class={`swatch swatch-${preset.id}${values.accentChoice === preset.id ? " on" : ""}`}
+              title={preset.label}
+            >
+              <input type="radio" name="accent_choice" value={preset.id} checked={values.accentChoice === preset.id} />
+              <span class="swatch-dot" aria-hidden="true" />
+              <span class="swatch-label">{preset.label}</span>
+            </label>
+          ))}
+
+          <label class={`swatch swatch-custom${values.accentChoice === "custom" ? " on" : ""}`} title="Custom colour">
+            <input type="radio" name="accent_choice" value="custom" checked={values.accentChoice === "custom"} />
+            <input
+              type="color"
+              name="accent_custom"
+              value={values.accentCustom || "#9c1f34"}
+              aria-label="Custom accent colour"
+            />
+            <span class="swatch-label">Custom</span>
+          </label>
+        </div>
+      </fieldset>
+
+      <div class="grid2">
+        <label class="field">
+          <span>Expires</span>
+          <select name="expiry">
+            {EXPIRY_OPTIONS.map((option) => (
+              <option value={option.id} selected={option.id === values.expiry}>
+                {option.label}
+              </option>
+            ))}
+          </select>
+        </label>
+
+        <label class="check field-check">
+          <input type="checkbox" name="unlisted" value="1" checked={values.unlisted} />
+          <span>
+            Unlisted
+            <small class="muted"> — reachable by link, kept off the front page.</small>
+          </span>
+        </label>
+      </div>
+
+      <div class="buttons">
+        <button type="submit" class="primary">
+          {editing ? "Save changes" : "Publish paste"}
+        </button>
+        <a class="btn" href={editing ? `/${editing}` : "/"}>
+          Cancel
+        </a>
+      </div>
+    </form>
+  );
+}
+
+export interface PasteViewProps {
+  paste: PasteWithAuthor;
+  html: string;
+  lines: number;
+  numbered: boolean;
+  highlighted: boolean;
+  /** The chosen theme is built for a light page, so the frame follows it. */
+  light: boolean;
+  jpml: JpmlCheck | null;
+  isOwner: boolean;
+  csrf: string;
+  size: number;
+  flash?: string | undefined;
+}
+
+export function PasteView(props: PasteViewProps) {
+  const { paste } = props;
+  const title = paste.title ?? paste.slug;
+  const author = paste.author_name ?? paste.author_username;
+
+  return (
+    <article class="paste">
+      <header class="paste-head">
+        <div class="grow">
+          <h1>{title}</h1>
+          <p class="muted small paste-meta">
+            <span>
+              by <strong>{author}</strong>
+            </span>
+            <span aria-hidden="true">·</span>
+            <span title={date(paste.created_at)}>{relative(paste.created_at)}</span>
+            {paste.updated_at !== paste.created_at && (
+              <>
+                <span aria-hidden="true">·</span>
+                <span title={date(paste.updated_at)}>edited {relative(paste.updated_at)}</span>
+              </>
+            )}
+            <span aria-hidden="true">·</span>
+            <span>{languageLabel(paste.language)}</span>
+            <span aria-hidden="true">·</span>
+            <span>
+              {props.lines} {props.lines === 1 ? "line" : "lines"}, {bytes(props.size)}
+            </span>
+            {paste.unlisted === 1 && <span class="badge">unlisted</span>}
+            {paste.expires_at !== null && (
+              <span class="badge danger" title={date(paste.expires_at)}>
+                expires {relative(paste.expires_at)}
+              </span>
+            )}
+          </p>
+        </div>
+
+        <div class="buttons paste-actions">
+          <button type="button" class="small" data-copy-body title="Copy the paste to the clipboard">
+            Copy
+          </button>
+          <a class="btn small" href={`/raw/${paste.slug}`}>
+            Raw
+          </a>
+          <a class="btn small" href={`/dl/${paste.slug}`}>
+            Download
+          </a>
+          {props.isOwner && (
+            <>
+              <a class="btn small" href={`/${paste.slug}/edit`}>
+                Edit
+              </a>
+              <form method="post" action={`/${paste.slug}/delete`} class="inline" data-confirm-delete>
+                <Csrf token={props.csrf} />
+                <button type="submit" class="small danger">
+                  Delete
+                </button>
+              </form>
+            </>
+          )}
+        </div>
+      </header>
+
+      {props.jpml && !props.jpml.ok && (
+        <p class="notice error jpml-note" role="status">
+          <strong>JPML:</strong> {props.jpml.message}{" "}
+          {props.jpml.line !== undefined && (
+            <>
+              at <a href={`#L${props.jpml.line}`}>line {props.jpml.line}</a>
+              {props.jpml.col !== undefined && `, column ${props.jpml.col}`}
+            </>
+          )}
+        </p>
+      )}
+      {props.jpml?.ok && (
+        <p class="notice ok jpml-note" role="status">
+          <strong>JPML:</strong> this document parses cleanly.
+        </p>
+      )}
+
+      {!props.highlighted && paste.language !== "text" && (
+        <p class="notice jpml-note">
+          Too large to highlight — showing it as plain text.
+        </p>
+      )}
+
+      <div
+        class={`code${props.numbered ? " numbered" : ""}${props.light && props.highlighted ? " light" : ""}`}
+        data-lines={String(props.lines)}
+      >
+        {raw(props.html)}
+      </div>
+    </article>
+  );
+}
+
+export function PasteRows(props: { pastes: PasteWithAuthor[]; showAuthor?: boolean; empty: string }) {
+  if (props.pastes.length === 0) return <p class="muted">{props.empty}</p>;
+
+  return (
+    <ul class="rows paste-rows">
+      {props.pastes.map((paste) => (
+        <li>
+          <div class="grow">
+            <a class="paste-link" href={`/${paste.slug}`}>
+              {paste.title ?? paste.slug}
+            </a>
+            <p class="muted small paste-meta">
+              <code>/{paste.slug}</code>
+              <span aria-hidden="true">·</span>
+              <span>{languageLabel(paste.language)}</span>
+              {props.showAuthor !== false && (
+                <>
+                  <span aria-hidden="true">·</span>
+                  <span>{paste.author_name ?? paste.author_username}</span>
+                </>
+              )}
+              <span aria-hidden="true">·</span>
+              <span title={date(paste.created_at)}>{relative(paste.created_at)}</span>
+              {paste.unlisted === 1 && <span class="badge">unlisted</span>}
+              {paste.expires_at !== null && <span class="badge danger">expiring</span>}
+            </p>
+          </div>
+        </li>
+      ))}
+    </ul>
+  );
+}
diff --git a/src/views/ui.tsx b/src/views/ui.tsx
new file mode 100644
index 0000000..42ee019
--- /dev/null
+++ b/src/views/ui.tsx
@@ -0,0 +1,103 @@
+/* src/views/ui.tsx
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import type { Child } from "hono/jsx";
+
+// Flash messages travel as a fixed code in `?m=`, never as free text, so a
+// crafted link can't put words in this site's mouth.
+const MESSAGES: Record<string, string> = {
+  "signed-in": "You're signed in.",
+  "signed-out": "You're signed out.",
+  "paste-created": "Paste published.",
+  "paste-updated": "Paste updated.",
+  "paste-deleted": "Paste deleted.",
+  "sign-in-needed": "Sign in to publish a paste.",
+};
+
+export function Flash(props: { code?: string | undefined }) {
+  const text = props.code ? MESSAGES[props.code] : undefined;
+  return text ? <p class="notice ok">{text}</p> : null;
+}
+
+export function ErrorNote(props: { error?: string | null | undefined }) {
+  return props.error ? (
+    <p class="notice error" role="alert">
+      {props.error}
+    </p>
+  ) : null;
+}
+
+export function Csrf(props: { token: string }) {
+  return <input type="hidden" name="_csrf" value={props.token} />;
+}
+
+export function Section(props: { title: string; children?: Child; id?: string; description?: string }) {
+  return (
+    <section class="panel" id={props.id}>
+      <h2>{props.title}</h2>
+      {props.description && <p class="muted">{props.description}</p>}
+      {props.children}
+    </section>
+  );
+}
+
+export function date(ts: number | null | undefined): string {
+  if (!ts) return "never";
+  return new Date(ts * 1000).toISOString().slice(0, 16).replace("T", " ") + " UTC";
+}
+
+export function relative(ts: number | null | undefined): string {
+  if (!ts) return "never";
+  const diff = Math.floor(Date.now() / 1000) - ts;
+  const future = diff < 0;
+  const abs = Math.abs(diff);
+  const unit =
+    abs < 60 ? [abs, "second"] :
+    abs < 3600 ? [Math.floor(abs / 60), "minute"] :
+    abs < 86400 ? [Math.floor(abs / 3600), "hour"] :
+    [Math.floor(abs / 86400), "day"];
+  const [n, word] = unit as [number, string];
+  const text = `${n} ${word}${n === 1 ? "" : "s"}`;
+  return future ? `in ${text}` : `${text} ago`;
+}
+
+export function bytes(count: number): string {
+  if (count < 1024) return `${count} B`;
+  if (count < 1024 * 1024) return `${(count / 1024).toFixed(count < 10240 ? 1 : 0)} KB`;
+  return `${(count / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+/** Links to the next and previous page of a listing, when there is one. */
+export function Pager(props: { path: string; page: number; total: number; perPage: number }) {
+  const pages = Math.max(1, Math.ceil(props.total / props.perPage));
+  if (pages <= 1) return null;
+  const link = (page: number) => (page <= 1 ? props.path : `${props.path}?page=${page}`);
+  return (
+    <nav class="pager">
+      {props.page > 1 ? (
+        <a class="btn small" href={link(props.page - 1)}>
+          Newer
+        </a>
+      ) : (
+        <span class="btn small" aria-disabled="true">
+          Newer
+        </span>
+      )}
+      <span class="muted small">
+        Page {props.page} of {pages}
+      </span>
+      {props.page < pages ? (
+        <a class="btn small" href={link(props.page + 1)}>
+          Older
+        </a>
+      ) : (
+        <span class="btn small" aria-disabled="true">
+          Older
+        </span>
+      )}
+    </nav>
+  );
+}
diff --git a/syntaxes/jpml.tmLanguage.json b/syntaxes/jpml.tmLanguage.json
new file mode 100644
index 0000000..add4ee1
--- /dev/null
+++ b/syntaxes/jpml.tmLanguage.json
@@ -0,0 +1,178 @@
+{
+  "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
+  "name": "JPML",
+  "scopeName": "source.jpml",
+  "fileTypes": ["jp"],
+  "patterns": [
+    { "include": "#comment" },
+    { "include": "#section" },
+    { "include": "#entry" }
+  ],
+  "repository": {
+    "comment": {
+      "match": "(#).*$",
+      "name": "comment.line.number-sign.jpml",
+      "captures": {
+        "1": { "name": "punctuation.definition.comment.jpml" }
+      }
+    },
+
+    "section": {
+      "comment": "A [header] opens a section. Only reachable at the top level: inside a value, '[' is an array.",
+      "name": "meta.section.jpml",
+      "begin": "^\\s*(\\[)",
+      "beginCaptures": {
+        "1": { "name": "punctuation.definition.section.begin.jpml" }
+      },
+      "end": "(\\])|(?=\\s*(?:#|$))",
+      "endCaptures": {
+        "1": { "name": "punctuation.definition.section.end.jpml" }
+      },
+      "patterns": [
+        {
+          "match": "\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'",
+          "name": "entity.name.section.jpml string.quoted.jpml"
+        },
+        {
+          "match": "\\.",
+          "name": "punctuation.separator.section.jpml"
+        },
+        {
+          "match": "[^.\\]\"'#\\r\\n]+",
+          "name": "entity.name.section.jpml"
+        }
+      ]
+    },
+
+    "entry": {
+      "comment": "key: value. The value must start on the key's line, and ends at a comma, a closing bracket or the end of the line.",
+      "name": "meta.entry.jpml",
+      "begin": "(\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|[^\\s:,{}\\[\\]\"'#][^:,{}\\[\\]\"'#\\r\\n]*?)\\s*(:)",
+      "beginCaptures": {
+        "1": { "name": "support.type.property-name.jpml" },
+        "2": { "name": "punctuation.separator.key-value.jpml" }
+      },
+      "end": "(?=\\s*(?:[,}\\]]|$))",
+      "patterns": [
+        { "include": "#value" }
+      ]
+    },
+
+    "value": {
+      "patterns": [
+        { "include": "#comment" },
+        { "include": "#object" },
+        { "include": "#array" },
+        { "include": "#string-double" },
+        { "include": "#string-single" },
+        { "include": "#number" },
+        { "include": "#boolean" },
+        { "include": "#null" },
+        { "include": "#bare" }
+      ]
+    },
+
+    "object": {
+      "name": "meta.structure.dictionary.jpml",
+      "begin": "\\{",
+      "beginCaptures": {
+        "0": { "name": "punctuation.definition.dictionary.begin.jpml" }
+      },
+      "end": "\\}",
+      "endCaptures": {
+        "0": { "name": "punctuation.definition.dictionary.end.jpml" }
+      },
+      "patterns": [
+        { "include": "#comment" },
+        { "include": "#entry" },
+        {
+          "match": ",",
+          "name": "punctuation.separator.dictionary.jpml"
+        }
+      ]
+    },
+
+    "array": {
+      "name": "meta.structure.array.jpml",
+      "begin": "\\[",
+      "beginCaptures": {
+        "0": { "name": "punctuation.definition.array.begin.jpml" }
+      },
+      "end": "\\]",
+      "endCaptures": {
+        "0": { "name": "punctuation.definition.array.end.jpml" }
+      },
+      "patterns": [
+        {
+          "match": ",",
+          "name": "punctuation.separator.array.jpml"
+        },
+        { "include": "#value" }
+      ]
+    },
+
+    "string-double": {
+      "name": "string.quoted.double.jpml",
+      "begin": "\"",
+      "beginCaptures": {
+        "0": { "name": "punctuation.definition.string.begin.jpml" }
+      },
+      "end": "(\")|(?<![\\\\\\n])$",
+      "endCaptures": {
+        "1": { "name": "punctuation.definition.string.end.jpml" }
+      },
+      "patterns": [
+        { "include": "#escape" }
+      ]
+    },
+
+    "string-single": {
+      "name": "string.quoted.single.jpml",
+      "begin": "'",
+      "beginCaptures": {
+        "0": { "name": "punctuation.definition.string.begin.jpml" }
+      },
+      "end": "(')|(?<![\\\\\\n])$",
+      "endCaptures": {
+        "1": { "name": "punctuation.definition.string.end.jpml" }
+      },
+      "patterns": [
+        { "include": "#escape" }
+      ]
+    },
+
+    "escape": {
+      "patterns": [
+        {
+          "match": "\\\\(?:[\"'\\\\/0abefnrtv]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|$)",
+          "name": "constant.character.escape.jpml"
+        },
+        {
+          "match": "\\\\.",
+          "name": "invalid.illegal.unrecognized-string-escape.jpml"
+        }
+      ]
+    },
+
+    "number": {
+      "match": "(?i)[+-]?(?:0x(?:_?[0-9a-f])+|0o(?:_?[0-7])+|0b(?:_?[01])+|(?:\\d+(?:_\\d+)*(?:\\.(?:\\d+(?:_\\d+)*)?)?|\\.\\d+(?:_\\d+)*)(?:e[+-]?\\d+(?:_\\d+)*)?|inf(?:inity)?|nan)(?=\\s*(?:[,}\\]#]|$))",
+      "name": "constant.numeric.jpml"
+    },
+
+    "boolean": {
+      "match": "(?i)(?:true|false)(?=\\s*(?:[,}\\]#]|$))",
+      "name": "constant.language.boolean.jpml"
+    },
+
+    "null": {
+      "match": "(?i)(?:null|none|nil)(?=\\s*(?:[,}\\]#]|$))",
+      "name": "constant.language.null.jpml"
+    },
+
+    "bare": {
+      "comment": "An unquoted string runs to the next comma, closing bracket, comment or line end.",
+      "match": "[^\\s,{}\\[\\]#\"'][^,}\\]#\\r\\n]*?(?=\\s*(?:[,}\\]#]|$))",
+      "name": "string.unquoted.jpml"
+    }
+  }
+}
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..dab5dd9
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,34 @@
+{
+  "compilerOptions": {
+    // Environment setup & latest features
+    "lib": ["ESNext", "DOM"],
+    "target": "ESNext",
+    "module": "Preserve",
+    "moduleDetection": "force",
+    "jsx": "react-jsx",
+    "jsxImportSource": "hono/jsx",
+    "allowJs": true,
+    "types": ["bun"],
+    "resolveJsonModule": true,
+
+    // Bundler mode
+    "moduleResolution": "bundler",
+    "allowImportingTsExtensions": true,
+    "verbatimModuleSyntax": true,
+    "noEmit": true,
+
+    // Best practices
+    "strict": true,
+    "skipLibCheck": true,
+    "noFallthroughCasesInSwitch": true,
+    "noUncheckedIndexedAccess": true,
+    "noImplicitOverride": true,
+
+    // Some stricter flags (disabled by default)
+    "noUnusedLocals": false,
+    "noUnusedParameters": false,
+    "noPropertyAccessFromIndexSignature": false
+  },
+  "include": ["src/**/*", "public/static/*.js"],
+  "exclude": ["node_modules"]
+}