Dough Git

commit

buns

commit
0b20658eb8076ba20eea6d9892d458b84c245a7f
author
Clove Twilight <[email protected]>
date
2026-09-16 11:46

diff --git a/.dev.vars.example b/.dev.vars.example
new file mode 100644
index 0000000..5df94cb
--- /dev/null
+++ b/.dev.vars.example
@@ -0,0 +1,15 @@
+# Copy to .dev.vars for `wrangler dev`. In production set these with
+# `wrangler secret put <NAME>` instead.
+
+# Local issuer. Passkeys are bound to this origin's hostname.
+ISSUER=http://localhost:8787
+
+# Encrypts signing keys and TOTP secrets at rest in D1. Changing it makes every
+# stored signing key and TOTP secret unreadable.
+# Generate with: openssl rand -base64 32
+KEY_ENCRYPTION_KEY=
+
+# Required to create the first admin at /setup. /setup closes for good once any
+# user exists, so this can be deleted afterwards.
+# Generate with: openssl rand -hex 24
+SETUP_TOKEN=
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..793fd80
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,45 @@
+# dependencies (bun install)
+node_modules
+
+# 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
+
+# wrangler
+.wrangler
+.dev.vars
+.dev.vars.*
+!.dev.vars.example
+
+# caches
+.eslintcache
+.cache
+*.tsbuildinfo
+
+# IntelliJ based IDEs
+.idea
+
+# Finder (MacOS) folder config
+.DS_Store
+
+# wrangler
+.wrangler
+.dev.vars
+!.dev.vars.example
diff --git a/bun.lock b/bun.lock
new file mode 100644
index 0000000..cda58e8
--- /dev/null
+++ b/bun.lock
@@ -0,0 +1,301 @@
+{
+  "lockfileVersion": 2,
+  "configVersion": 1,
+  "workspaces": {
+    "": {
+      "name": "auth-server",
+      "dependencies": {
+        "@simplewebauthn/server": "^14.0.2",
+        "hono": "^4.13.8",
+        "jose": "^6.2.12",
+        "uqr": "^0.1.3",
+      },
+      "devDependencies": {
+        "@cloudflare/workers-types": "^5.20260916.1",
+        "typescript": "^7.0.2",
+        "wrangler": "^4.132.0",
+      },
+    },
+  },
+  "packages": {
+    "@cloudflare/kv-asset-handler": ["@cloudflare/[email protected]", "", {}, "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg=="],
+
+    "@cloudflare/unenv-preset": ["@cloudflare/[email protected]", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw=="],
+
+    "@cloudflare/workerd-darwin-64": ["@cloudflare/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-EFjNxN4l5caJoHADhchROvO52EFFt+zmJvFZRmwX6UU9pE53BAbF94wRBhbpylv5Ethsd1TdJNwYuUPgZYbETg=="],
+
+    "@cloudflare/workerd-darwin-arm64": ["@cloudflare/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Xm2jbLw8M/o5YkuI5VsHCVU4rgnzr3ROl+Awk7FCBJ3mtLJNuxPtJNB/zZI+/t+3QtgsSPnmTisS5Gq6/KLQ/A=="],
+
+    "@cloudflare/workerd-linux-64": ["@cloudflare/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-hkQp+PWBp7U6uDMd6hqUf4lfErPV79jolLaK6j4U50HrHC4jqWxESPemkxEk8H7p9jTKkZ9I9Z0nA5DLAE0J6g=="],
+
+    "@cloudflare/workerd-linux-arm64": ["@cloudflare/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-3yi8/irVGNQbuYTSmLXcEGupk4Js42jU3kyAx88MDbwGQUa34VbucKcNwHwfhqwEUNaIrn8ohlOEcNJChQl0Og=="],
+
+    "@cloudflare/workerd-windows-64": ["@cloudflare/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+FQ3o/grK2tQy6dw3AqSOYWsYROZqxCQKBqSHQVcXvr2x2QetCT64OrvAAJ0hpQAokREFwQyzsNmMiZbAdW0zw=="],
+
+    "@cloudflare/workers-types": ["@cloudflare/[email protected]", "", {}, "sha512-BR2oaseRZZ5q8uToQpAA/6hYNc1+jcKB5OIfK+PkZPkbS7OICVKvRS+WpKgbyTQ7yl6colb3pIHwQRgszfFd5g=="],
+
+    "@cspotcode/source-map-support": ["@cspotcode/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="],
+
+    "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
+
+    "@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ=="],
+
+    "@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ=="],
+
+    "@esbuild/android-arm64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg=="],
+
+    "@esbuild/android-x64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "x64" }, "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng=="],
+
+    "@esbuild/darwin-arm64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q=="],
+
+    "@esbuild/darwin-x64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ=="],
+
+    "@esbuild/freebsd-arm64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw=="],
+
+    "@esbuild/freebsd-x64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ=="],
+
+    "@esbuild/linux-arm": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ=="],
+
+    "@esbuild/linux-arm64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g=="],
+
+    "@esbuild/linux-ia32": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ia32" }, "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w=="],
+
+    "@esbuild/linux-loong64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg=="],
+
+    "@esbuild/linux-mips64el": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ=="],
+
+    "@esbuild/linux-ppc64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ=="],
+
+    "@esbuild/linux-riscv64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ=="],
+
+    "@esbuild/linux-s390x": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag=="],
+
+    "@esbuild/linux-x64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA=="],
+
+    "@esbuild/netbsd-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw=="],
+
+    "@esbuild/netbsd-x64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg=="],
+
+    "@esbuild/openbsd-arm64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q=="],
+
+    "@esbuild/openbsd-x64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw=="],
+
+    "@esbuild/openharmony-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg=="],
+
+    "@esbuild/sunos-x64": ["@esbuild/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ=="],
+
+    "@esbuild/win32-arm64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA=="],
+
+    "@esbuild/win32-ia32": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg=="],
+
+    "@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A=="],
+
+    "@hexagon/base64": ["@hexagon/[email protected]", "", {}, "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw=="],
+
+    "@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
+
+    "@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.3" }, "os": "darwin", "cpu": "arm64" }, "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA=="],
+
+    "@img/sharp-darwin-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.3" }, "os": "darwin", "cpu": "x64" }, "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw=="],
+
+    "@img/sharp-freebsd-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "os": "freebsd" }, "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA=="],
+
+    "@img/sharp-libvips-darwin-arm64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg=="],
+
+    "@img/sharp-libvips-darwin-x64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw=="],
+
+    "@img/sharp-libvips-linux-arm": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA=="],
+
+    "@img/sharp-libvips-linux-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A=="],
+
+    "@img/sharp-libvips-linux-ppc64": ["@img/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w=="],
+
+    "@img/sharp-libvips-linux-riscv64": ["@img/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ=="],
+
+    "@img/sharp-libvips-linux-s390x": ["@img/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q=="],
+
+    "@img/sharp-libvips-linux-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA=="],
+
+    "@img/sharp-libvips-linuxmusl-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw=="],
+
+    "@img/sharp-libvips-linuxmusl-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw=="],
+
+    "@img/sharp-linux-arm": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.3" }, "os": "linux", "cpu": "arm" }, "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A=="],
+
+    "@img/sharp-linux-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64" }, "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ=="],
+
+    "@img/sharp-linux-ppc64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.3" }, "os": "linux", "cpu": "ppc64" }, "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ=="],
+
+    "@img/sharp-linux-riscv64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.3" }, "os": "linux", "cpu": "none" }, "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA=="],
+
+    "@img/sharp-linux-s390x": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.3" }, "os": "linux", "cpu": "s390x" }, "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ=="],
+
+    "@img/sharp-linux-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.3" }, "os": "linux", "cpu": "x64" }, "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA=="],
+
+    "@img/sharp-linuxmusl-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64" }, "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA=="],
+
+    "@img/sharp-linuxmusl-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.3" }, "os": "linux", "cpu": "x64" }, "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg=="],
+
+    "@img/sharp-wasm32": ["@img/[email protected]", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="],
+
+    "@img/sharp-webcontainers-wasm32": ["@img/[email protected]", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "cpu": "none" }, "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA=="],
+
+    "@img/sharp-win32-arm64": ["@img/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw=="],
+
+    "@img/sharp-win32-ia32": ["@img/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw=="],
+
+    "@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg=="],
+
+    "@jridgewell/resolve-uri": ["@jridgewell/[email protected]", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
+
+    "@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="],
+
+    "@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="],
+
+    "@levischuck/tiny-cbor": ["@levischuck/[email protected]", "", {}, "sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow=="],
+
+    "@peculiar/asn1-android": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-SYHm4SoWSI0nRCoos6jpGusIqhPH9bbGBqv7ohlZ+H6BunrDzzQPk2ePgDuEUzV82OdvbLgtW4twUDwhU9P3YQ=="],
+
+    "@peculiar/asn1-asym-key": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-pkcs8": "^2.9.4", "@peculiar/asn1-schema": "^2.9.4", "@peculiar/asn1-x509": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-s7SJfjcXlR3MYMngDTeMLCy3VjGaIxeEy905CQ0j09pDbeYhNBvBGA7r7cAvCZYkVFo9kVg9RAki0K2iUz7SGQ=="],
+
+    "@peculiar/asn1-cms": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.4", "@peculiar/asn1-x509": "^2.9.4", "@peculiar/asn1-x509-attr": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-cben7oxmQsUGZqotus7yt0srYdncOT6RNWcTQ77T2RFOXejYVYkXadrfePdRcrVpO9K95IRLKKglG2k38jKXuw=="],
+
+    "@peculiar/asn1-csr": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.4", "@peculiar/asn1-x509": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-xd4YN4vpRjkDAQWVfZZkeu12IEND7DOpkqaHSIHxZl1uggUNa9Ju0QxY2jHvDAS9pP0zhRBytg8ifsnGo3V0jw=="],
+
+    "@peculiar/asn1-ecc": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.4", "@peculiar/asn1-x509": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-JJXefFshRAuVAjWQo/39bkg1ywc1VaiO44S8RRC+Ykvf/u2KDmYffoDb0ZBPCR5uJy4AGKQhl8mX+Q8ShcWaXQ=="],
+
+    "@peculiar/asn1-pfx": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-cms": "^2.9.4", "@peculiar/asn1-pkcs8": "^2.9.4", "@peculiar/asn1-rsa": "^2.9.4", "@peculiar/asn1-schema": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-khuGzHTzNzk4GDlIBEILyIs6Lce0yn0ZBdoI9v93kmNncfZRhD+AQ5ODFqdhvoE8cMJF/JMTQ8yA+t1D14kqCw=="],
+
+    "@peculiar/asn1-pkcs8": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.4", "@peculiar/asn1-x509": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-duRdotlUx9eDZe6QrQpQKl61RbWykCHBCkKayP8V8XdEFwlKHZ8qGGDMyS6Pye7OX7nLFttTTpRkJeet78ckwQ=="],
+
+    "@peculiar/asn1-pkcs9": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-cms": "^2.9.4", "@peculiar/asn1-pfx": "^2.9.4", "@peculiar/asn1-pkcs8": "^2.9.4", "@peculiar/asn1-schema": "^2.9.4", "@peculiar/asn1-x509": "^2.9.4", "@peculiar/asn1-x509-attr": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-kaL4cNxBpdQE2dKlyZBqz4ygCrwffO+8wfoxTEqM1Z8RadvCeELBRzcv0dzM8aY9azHMwODO5nxU65zXmhToOQ=="],
+
+    "@peculiar/asn1-rsa": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.4", "@peculiar/asn1-x509": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-pZ96eD1PptovcWQ/GSmuNFXd/7EQJNlKfDaNCyE2rx3W0v6QFelkzquVqRSRyyDXXCYD69ZXJDzZ8GhIiQzKoA=="],
+
+    "@peculiar/asn1-schema": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-GjzePcT9Iw8NzeOPf73iNS9xM+TBhd/FilAfP+RQGkTMQJTVWtytN3JHJACCjf/ABNau5S7mS3g+DcuxmRgYEg=="],
+
+    "@peculiar/asn1-x509": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.4", "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-CxhBo/RdEbMMob7T31ZdQjGuoyRFLVwrDzTn25bihzBasRg9kRm/0IxIPvhgQtcK/9dNcO1XQL2fuPugwELL0Q=="],
+
+    "@peculiar/asn1-x509-attr": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-schema": "^2.9.4", "@peculiar/asn1-x509": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-ehQXbpQaQYycgu8OrvigwSPTFfVRcu0ECNYCWw+yzBp02Lw5paRqzzhUpfOgO2K38+WfFZuEz/0RPtam5g0OMg=="],
+
+    "@peculiar/asn1-x509-post-quantum": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-asym-key": "^2.9.4", "@peculiar/asn1-schema": "^2.9.4", "@peculiar/asn1-x509": "^2.9.4", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-GD0k7BY3dsEIeai7C7bVRPddj/PzZu+sTawRPRxdHKbdy1f9b58WQyk0eFJdr28GShyLVTU8poyi4+bTAZfEtQ=="],
+
+    "@peculiar/utils": ["@peculiar/[email protected]", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ=="],
+
+    "@peculiar/x509": ["@peculiar/[email protected]", "", { "dependencies": { "@peculiar/asn1-cms": "^2.9.4", "@peculiar/asn1-csr": "^2.9.4", "@peculiar/asn1-ecc": "^2.9.4", "@peculiar/asn1-pkcs9": "^2.9.4", "@peculiar/asn1-rsa": "^2.9.4", "@peculiar/asn1-schema": "^2.9.4", "@peculiar/asn1-x509": "^2.9.4", "@peculiar/asn1-x509-post-quantum": "^2.9.4", "pvtsutils": "^1.3.6", "tslib": "^2.8.1", "tsyringe": "^4.10.0" } }, "sha512-IYbg1R03CSQGWwl24kGyqrdVtixNSbRaDvBg1r5wyYjTP+VwPQkka1BzTgU5+vxiuwqg04OxdvdJ1xYYFIdUSA=="],
+
+    "@poppinss/colors": ["@poppinss/[email protected]", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="],
+
+    "@poppinss/dumper": ["@poppinss/[email protected]", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="],
+
+    "@poppinss/exception": ["@poppinss/[email protected]", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="],
+
+    "@simplewebauthn/server": ["@simplewebauthn/[email protected]", "", { "dependencies": { "@hexagon/base64": "^1.1.27", "@levischuck/tiny-cbor": "^0.2.2", "@peculiar/asn1-android": "^2.6.0", "@peculiar/asn1-ecc": "^2.6.1", "@peculiar/asn1-rsa": "^2.6.1", "@peculiar/asn1-schema": "^2.6.0", "@peculiar/asn1-x509": "^2.6.1", "@peculiar/asn1-x509-post-quantum": "^2.9.4", "@peculiar/x509": "^2.1.0", "reflect-metadata": "^0.2.2" } }, "sha512-g+m/xv9/8FRWsDY22CwsTYRzt3WwS9fJrR3P7eY3Ti01FXH5FQ36Xn55v6D+5tb6VajlqOj4hywP/Vxsb6a3Sg=="],
+
+    "@sindresorhus/is": ["@sindresorhus/[email protected]", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="],
+
+    "@speed-highlight/core": ["@speed-highlight/[email protected]", "", {}, "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw=="],
+
+    "@typescript/typescript-aix-ppc64": ["@typescript/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="],
+
+    "@typescript/typescript-darwin-arm64": ["@typescript/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="],
+
+    "@typescript/typescript-darwin-x64": ["@typescript/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="],
+
+    "@typescript/typescript-freebsd-arm64": ["@typescript/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="],
+
+    "@typescript/typescript-freebsd-x64": ["@typescript/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="],
+
+    "@typescript/typescript-linux-arm": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="],
+
+    "@typescript/typescript-linux-arm64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="],
+
+    "@typescript/typescript-linux-loong64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="],
+
+    "@typescript/typescript-linux-mips64el": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="],
+
+    "@typescript/typescript-linux-ppc64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="],
+
+    "@typescript/typescript-linux-riscv64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="],
+
+    "@typescript/typescript-linux-s390x": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="],
+
+    "@typescript/typescript-linux-x64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="],
+
+    "@typescript/typescript-netbsd-arm64": ["@typescript/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="],
+
+    "@typescript/typescript-netbsd-x64": ["@typescript/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="],
+
+    "@typescript/typescript-openbsd-arm64": ["@typescript/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="],
+
+    "@typescript/typescript-openbsd-x64": ["@typescript/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="],
+
+    "@typescript/typescript-sunos-x64": ["@typescript/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="],
+
+    "@typescript/typescript-win32-arm64": ["@typescript/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],
+
+    "@typescript/typescript-win32-x64": ["@typescript/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],
+
+    "asn1js": ["[email protected]", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.1.5", "tslib": "^2.8.1" } }, "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg=="],
+
+    "blake3-wasm": ["[email protected]", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="],
+
+    "cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],
+
+    "detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
+
+    "error-stack-parser-es": ["[email protected]", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="],
+
+    "esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.1", "@esbuild/android-arm": "0.28.1", "@esbuild/android-arm64": "0.28.1", "@esbuild/android-x64": "0.28.1", "@esbuild/darwin-arm64": "0.28.1", "@esbuild/darwin-x64": "0.28.1", "@esbuild/freebsd-arm64": "0.28.1", "@esbuild/freebsd-x64": "0.28.1", "@esbuild/linux-arm": "0.28.1", "@esbuild/linux-arm64": "0.28.1", "@esbuild/linux-ia32": "0.28.1", "@esbuild/linux-loong64": "0.28.1", "@esbuild/linux-mips64el": "0.28.1", "@esbuild/linux-ppc64": "0.28.1", "@esbuild/linux-riscv64": "0.28.1", "@esbuild/linux-s390x": "0.28.1", "@esbuild/linux-x64": "0.28.1", "@esbuild/netbsd-arm64": "0.28.1", "@esbuild/netbsd-x64": "0.28.1", "@esbuild/openbsd-arm64": "0.28.1", "@esbuild/openbsd-x64": "0.28.1", "@esbuild/openharmony-arm64": "0.28.1", "@esbuild/sunos-x64": "0.28.1", "@esbuild/win32-arm64": "0.28.1", "@esbuild/win32-ia32": "0.28.1", "@esbuild/win32-x64": "0.28.1" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw=="],
+
+    "fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
+
+    "hono": ["[email protected]", "", {}, "sha512-/Gng7NfoykZl2pjukW5Z6+8Yxm3BPRf86GTbQnt0SbySkvax4fyL4H3HhY1cCpBGmiW9XDRFzRV+CXK2W8QudQ=="],
+
+    "jose": ["[email protected]", "", {}, "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw=="],
+
+    "kleur": ["[email protected]", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="],
+
+    "miniflare": ["[email protected]", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.4", "undici": "7.29.0", "workerd": "1.20260915.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-ApLsq9X2jbpkLAPXx89afGvuNxAFzd1rUK+nzfBSLu+34YWc2Q2YlgH6f3kSEEQYZ2gAlC5Q5IP6tDNNg/1KqQ=="],
+
+    "path-to-regexp": ["[email protected]", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="],
+
+    "pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
+
+    "pvtsutils": ["[email protected]", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg=="],
+
+    "pvutils": ["[email protected]", "", {}, "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg=="],
+
+    "reflect-metadata": ["[email protected]", "", {}, "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="],
+
+    "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
+
+    "sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.4", "@img/sharp-darwin-x64": "0.35.4", "@img/sharp-freebsd-wasm32": "0.35.4", "@img/sharp-libvips-darwin-arm64": "1.3.3", "@img/sharp-libvips-darwin-x64": "1.3.3", "@img/sharp-libvips-linux-arm": "1.3.3", "@img/sharp-libvips-linux-arm64": "1.3.3", "@img/sharp-libvips-linux-ppc64": "1.3.3", "@img/sharp-libvips-linux-riscv64": "1.3.3", "@img/sharp-libvips-linux-s390x": "1.3.3", "@img/sharp-libvips-linux-x64": "1.3.3", "@img/sharp-libvips-linuxmusl-arm64": "1.3.3", "@img/sharp-libvips-linuxmusl-x64": "1.3.3", "@img/sharp-linux-arm": "0.35.4", "@img/sharp-linux-arm64": "0.35.4", "@img/sharp-linux-ppc64": "0.35.4", "@img/sharp-linux-riscv64": "0.35.4", "@img/sharp-linux-s390x": "0.35.4", "@img/sharp-linux-x64": "0.35.4", "@img/sharp-linuxmusl-arm64": "0.35.4", "@img/sharp-linuxmusl-x64": "0.35.4", "@img/sharp-webcontainers-wasm32": "0.35.4", "@img/sharp-win32-arm64": "0.35.4", "@img/sharp-win32-ia32": "0.35.4", "@img/sharp-win32-x64": "0.35.4" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA=="],
+
+    "supports-color": ["[email protected]", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="],
+
+    "tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+    "tsyringe": ["[email protected]", "", { "dependencies": { "tslib": "^1.9.3" } }, "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw=="],
+
+    "typescript": ["[email protected]", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="],
+
+    "undici": ["[email protected]", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
+
+    "unenv": ["[email protected]", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="],
+
+    "uqr": ["[email protected]", "", {}, "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA=="],
+
+    "workerd": ["[email protected]", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260915.1", "@cloudflare/workerd-darwin-arm64": "1.20260915.1", "@cloudflare/workerd-linux-64": "1.20260915.1", "@cloudflare/workerd-linux-arm64": "1.20260915.1", "@cloudflare/workerd-windows-64": "1.20260915.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-9Nqh22lW/ondXnMkFTbn65MHZLdsE2izJ9sFIVdqAufQTEVWnUkcpp7T5JtLr4ASN/VuxlTVZ5xgYntyo+d4ag=="],
+
+    "wrangler": ["[email protected]", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.5.0", "@cloudflare/unenv-preset": "2.16.1", "blake3-wasm": "2.1.5", "esbuild": "0.28.1", "miniflare": "5.20260915.0-alpha", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260915.1" }, "optionalDependencies": { "fsevents": "2.3.3" }, "peerDependencies": { "@cloudflare/workers-types": "^5.20260915.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js", "cf-wrangler": "bin/cf-wrangler.js" } }, "sha512-61HD7Unw3g7h9zSQoqldzfL3MEbCKUVfwtlMgfSQtjYwMjBD8z83K/EXnYGv75R5hczx3grFfjYH+tdmJm5PHg=="],
+
+    "ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="],
+
+    "youch": ["[email protected]", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@poppinss/dumper": "^0.6.4", "@speed-highlight/core": "^1.2.7", "cookie": "^1.0.2", "youch-core": "^0.3.3" } }, "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ=="],
+
+    "youch-core": ["[email protected]", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="],
+
+    "tsyringe/tslib": ["[email protected]", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="],
+  }
+}
diff --git a/migrations/0001_init.sql b/migrations/0001_init.sql
new file mode 100644
index 0000000..bae842e
--- /dev/null
+++ b/migrations/0001_init.sql
@@ -0,0 +1,164 @@
+-- migrations/0001_init.sql
+-- Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+-- Licensed under the DASL-1.2 Licence.
+--
+-- Timestamps are unix seconds. Every secret that is only ever compared
+-- (session ids, codes, refresh tokens, login links, client secrets) is stored
+-- as a SHA-256 hex digest, never in plaintext.
+
+CREATE TABLE users (
+  id              TEXT PRIMARY KEY,               -- the OIDC `sub`
+  username        TEXT NOT NULL UNIQUE COLLATE NOCASE,
+  name            TEXT,
+  email           TEXT,
+  email_verified  INTEGER NOT NULL DEFAULT 0,
+  picture         TEXT,
+  password_hash   TEXT,
+  totp_secret     TEXT,                           -- encrypted, set once confirmed
+  totp_pending    TEXT,                           -- encrypted, awaiting first code
+  totp_last_step  INTEGER NOT NULL DEFAULT 0,     -- replay guard
+  disabled        INTEGER NOT NULL DEFAULT 0,
+  created_at      INTEGER NOT NULL,
+  updated_at      INTEGER NOT NULL,
+  last_login_at   INTEGER
+);
+
+CREATE TABLE groups (
+  name        TEXT PRIMARY KEY,
+  description TEXT NOT NULL DEFAULT '',
+  created_at  INTEGER NOT NULL
+);
+
+CREATE TABLE user_groups (
+  user_id    TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  group_name TEXT NOT NULL REFERENCES groups (name) ON DELETE CASCADE,
+  PRIMARY KEY (user_id, group_name)
+);
+
+CREATE INDEX user_groups_group ON user_groups (group_name);
+
+CREATE TABLE passkeys (
+  id           TEXT PRIMARY KEY,                  -- credential id, base64url
+  user_id      TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  public_key   TEXT NOT NULL,                     -- COSE key, base64url
+  counter      INTEGER NOT NULL DEFAULT 0,
+  transports   TEXT NOT NULL DEFAULT '[]',
+  device_type  TEXT NOT NULL,
+  backed_up    INTEGER NOT NULL DEFAULT 0,
+  name         TEXT NOT NULL,
+  created_at   INTEGER NOT NULL,
+  last_used_at INTEGER
+);
+
+CREATE INDEX passkeys_user ON passkeys (user_id);
+
+CREATE TABLE sessions (
+  id_hash      TEXT PRIMARY KEY,
+  user_id      TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  csrf         TEXT NOT NULL,
+  auth_time    INTEGER NOT NULL,
+  amr          TEXT NOT NULL,                     -- JSON array
+  ip           TEXT,
+  user_agent   TEXT,
+  created_at   INTEGER NOT NULL,
+  last_seen_at INTEGER NOT NULL,
+  expires_at   INTEGER NOT NULL
+);
+
+CREATE INDEX sessions_user ON sessions (user_id);
+CREATE INDEX sessions_expiry ON sessions (expires_at);
+
+-- Half-finished password logins waiting on a TOTP code.
+CREATE TABLE pending_logins (
+  id_hash    TEXT PRIMARY KEY,
+  user_id    TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  return_to  TEXT NOT NULL,
+  attempts   INTEGER NOT NULL DEFAULT 0,
+  expires_at INTEGER NOT NULL
+);
+
+CREATE TABLE webauthn_challenges (
+  id         TEXT PRIMARY KEY,
+  challenge  TEXT NOT NULL,
+  purpose    TEXT NOT NULL,                       -- 'login' | 'register'
+  user_id    TEXT REFERENCES users (id) ON DELETE CASCADE,
+  expires_at INTEGER NOT NULL
+);
+
+CREATE TABLE login_links (
+  token_hash TEXT PRIMARY KEY,
+  user_id    TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  created_by TEXT,
+  created_at INTEGER NOT NULL,
+  expires_at INTEGER NOT NULL
+);
+
+CREATE INDEX login_links_user ON login_links (user_id);
+
+CREATE TABLE clients (
+  id                        TEXT PRIMARY KEY,
+  name                      TEXT NOT NULL,
+  secret_hash               TEXT,                 -- NULL = public client (PKCE)
+  redirect_uris             TEXT NOT NULL,        -- JSON array
+  post_logout_redirect_uris TEXT NOT NULL,        -- JSON array
+  allowed_groups            TEXT NOT NULL,        -- JSON array, empty = everyone
+  created_at                INTEGER NOT NULL,
+  updated_at                INTEGER NOT NULL
+);
+
+CREATE TABLE auth_codes (
+  code_hash             TEXT PRIMARY KEY,
+  client_id             TEXT NOT NULL REFERENCES clients (id) ON DELETE CASCADE,
+  user_id               TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  redirect_uri          TEXT NOT NULL,
+  scope                 TEXT NOT NULL,
+  nonce                 TEXT,
+  code_challenge        TEXT,
+  auth_time             INTEGER NOT NULL,
+  amr                   TEXT NOT NULL,
+  expires_at            INTEGER NOT NULL
+);
+
+CREATE TABLE refresh_tokens (
+  token_hash TEXT PRIMARY KEY,
+  family_id  TEXT NOT NULL,
+  client_id  TEXT NOT NULL REFERENCES clients (id) ON DELETE CASCADE,
+  user_id    TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  scope      TEXT NOT NULL,
+  auth_time  INTEGER NOT NULL,
+  amr        TEXT NOT NULL,
+  created_at INTEGER NOT NULL,
+  expires_at INTEGER NOT NULL,
+  used_at    INTEGER,
+  revoked_at INTEGER
+);
+
+CREATE INDEX refresh_tokens_family ON refresh_tokens (family_id);
+CREATE INDEX refresh_tokens_user ON refresh_tokens (user_id);
+
+CREATE TABLE signing_keys (
+  kid         TEXT PRIMARY KEY,
+  alg         TEXT NOT NULL,
+  private_jwk TEXT NOT NULL,                      -- encrypted
+  public_jwk  TEXT NOT NULL,
+  created_at  INTEGER NOT NULL,
+  retired_at  INTEGER                             -- NULL = signing with it
+);
+
+CREATE TABLE rate_limits (
+  key          TEXT PRIMARY KEY,
+  count        INTEGER NOT NULL,
+  window_start INTEGER NOT NULL
+);
+
+CREATE TABLE audit_log (
+  id       INTEGER PRIMARY KEY AUTOINCREMENT,
+  at       INTEGER NOT NULL,
+  actor_id TEXT,
+  action   TEXT NOT NULL,
+  target   TEXT,
+  ip       TEXT,
+  detail   TEXT
+);
+
+CREATE INDEX audit_log_at ON audit_log (at);
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..6ead48a
--- /dev/null
+++ b/package.json
@@ -0,0 +1,26 @@
+{
+  "name": "auth-server",
+  "version": "0.1.0",
+  "description": "Doughmination single sign-on: an OpenID Connect provider with passkeys, passwords and TOTP, running on Cloudflare Workers + D1.",
+  "type": "module",
+  "private": true,
+  "scripts": {
+    "dev": "wrangler dev",
+    "deploy": "wrangler deploy",
+    "db:migrate:local": "wrangler d1 migrations apply auth-server --local",
+    "db:migrate:remote": "wrangler d1 migrations apply auth-server --remote",
+    "cf-typegen": "wrangler types --env-interface Env",
+    "typecheck": "tsc --noEmit"
+  },
+  "dependencies": {
+    "@simplewebauthn/server": "^14.0.2",
+    "hono": "^4.13.8",
+    "jose": "^6.2.12",
+    "uqr": "^0.1.3"
+  },
+  "devDependencies": {
+    "@cloudflare/workers-types": "^5.20260916.1",
+    "typescript": "^7.0.2",
+    "wrangler": "^4.132.0"
+  }
+}
diff --git a/public/_headers b/public/_headers
new file mode 100644
index 0000000..7766872
--- /dev/null
+++ b/public/_headers
@@ -0,0 +1,3 @@
+/static/*
+  X-Content-Type-Options: nosniff
+  Cache-Control: public, max-age=3600
diff --git a/public/static/app.js b/public/static/app.js
new file mode 100644
index 0000000..c4c3b30
--- /dev/null
+++ b/public/static/app.js
@@ -0,0 +1,224 @@
+/* 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.
+ */
+
+"use strict";
+
+// --- base64url <-> ArrayBuffer, for browsers without the WebAuthn JSON helpers --
+
+function toBuffer(b64url) {
+  const b64 = b64url.replace(/-/g, "+").replace(/_/g, "/");
+  const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
+  const out = new Uint8Array(bin.length);
+  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
+  return out.buffer;
+}
+
+function toB64url(buffer) {
+  if (!buffer) return undefined;
+  const bytes = new Uint8Array(buffer);
+  let bin = "";
+  for (const b of bytes) bin += String.fromCharCode(b);
+  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+function creationOptions(json) {
+  if (PublicKeyCredential.parseCreationOptionsFromJSON) {
+    return PublicKeyCredential.parseCreationOptionsFromJSON(json);
+  }
+  return {
+    ...json,
+    challenge: toBuffer(json.challenge),
+    user: { ...json.user, id: toBuffer(json.user.id) },
+    excludeCredentials: (json.excludeCredentials || []).map((c) => ({ ...c, id: toBuffer(c.id) })),
+  };
+}
+
+function requestOptions(json) {
+  if (PublicKeyCredential.parseRequestOptionsFromJSON) {
+    return PublicKeyCredential.parseRequestOptionsFromJSON(json);
+  }
+  return {
+    ...json,
+    challenge: toBuffer(json.challenge),
+    allowCredentials: (json.allowCredentials || []).map((c) => ({ ...c, id: toBuffer(c.id) })),
+  };
+}
+
+function credentialJSON(cred) {
+  try {
+    if (typeof cred.toJSON === "function") return cred.toJSON();
+  } catch {
+    // Some password managers return objects whose toJSON throws; build it by hand.
+  }
+  const r = cred.response;
+  const response = { clientDataJSON: toB64url(r.clientDataJSON) };
+  if (r.attestationObject) {
+    response.attestationObject = toB64url(r.attestationObject);
+    response.transports = typeof r.getTransports === "function" ? r.getTransports() : [];
+  } else {
+    response.authenticatorData = toB64url(r.authenticatorData);
+    response.signature = toB64url(r.signature);
+    response.userHandle = toB64url(r.userHandle);
+  }
+  return {
+    id: cred.id,
+    rawId: toB64url(cred.rawId),
+    type: cred.type,
+    authenticatorAttachment: cred.authenticatorAttachment || undefined,
+    clientExtensionResults: cred.getClientExtensionResults(),
+    response,
+  };
+}
+
+async function postJSON(url, body) {
+  const headers = { "Content-Type": "application/json" };
+  const csrf = document.body.dataset.csrf;
+  if (csrf) headers["X-CSRF-Token"] = csrf;
+  const res = await fetch(url, { method: "POST", headers, body: JSON.stringify(body || {}), credentials: "same-origin" });
+  let data = {};
+  try {
+    data = await res.json();
+  } catch {
+    // non-JSON error page
+  }
+  if (res.status === 401 && data.reauth) {
+    window.location.href = data.reauth;
+    throw new Error("redirecting");
+  }
+  if (!res.ok) throw new Error(data.error || "Something went wrong. Please try again.");
+  return data;
+}
+
+function showError(message) {
+  const el = document.getElementById("passkey-error");
+  if (!el) return;
+  el.textContent = message;
+  el.classList.toggle("hidden", !message);
+}
+
+function webauthnMessage(err) {
+  if (!err) return "Something went wrong. Please try again.";
+  if (err.name === "NotAllowedError" || err.name === "AbortError") return "";
+  if (err.name === "InvalidStateError") return "That passkey is already registered to your account.";
+  if (err.name === "SecurityError") return "Passkeys can't be used on this address.";
+  return err.message || "Something went wrong. Please try again.";
+}
+
+// --- sign in ---------------------------------------------------------------------
+
+function initLogin() {
+  const root = document.getElementById("login");
+  const button = document.getElementById("passkey-signin");
+  if (!root || !button) return;
+
+  if (!window.PublicKeyCredential) {
+    button.disabled = true;
+    button.textContent = "Passkeys aren't supported in this browser";
+    return;
+  }
+
+  const returnTo = root.dataset.return || "/account";
+  let conditional = null;
+
+  async function signIn(mediation) {
+    const { id, options } = await postJSON("/login/passkey/options");
+    const request = { publicKey: requestOptions(options) };
+    if (mediation === "conditional") {
+      conditional = new AbortController();
+      request.mediation = "conditional";
+      request.signal = conditional.signal;
+    }
+    const cred = await navigator.credentials.get(request);
+    if (!cred) return;
+    showError("");
+    const result = await postJSON("/login/passkey/verify", { id, response: credentialJSON(cred), return: returnTo });
+    window.location.href = result.redirect;
+  }
+
+  button.addEventListener("click", async () => {
+    if (conditional) conditional.abort();
+    button.disabled = true;
+    try {
+      await signIn("modal");
+    } catch (err) {
+      showError(webauthnMessage(err));
+    } finally {
+      button.disabled = false;
+      startConditional();
+    }
+  });
+
+  // Offer saved passkeys straight from the username field's autofill.
+  async function startConditional() {
+    if (!PublicKeyCredential.isConditionalMediationAvailable) return;
+    if (!(await PublicKeyCredential.isConditionalMediationAvailable())) return;
+    try {
+      await signIn("conditional");
+    } catch (err) {
+      if (err && err.name !== "AbortError") showError(webauthnMessage(err));
+    }
+  }
+  startConditional();
+}
+
+// --- account -----------------------------------------------------------------------
+
+function initAccount() {
+  const formEl = document.getElementById("passkey-add");
+  if (!formEl) return;
+  const button = formEl.querySelector("button");
+
+  if (!window.PublicKeyCredential) {
+    button.disabled = true;
+    button.textContent = "Passkeys aren't supported in this browser";
+    return;
+  }
+
+  formEl.addEventListener("submit", async (ev) => {
+    ev.preventDefault();
+    showError("");
+    button.disabled = true;
+    try {
+      const name = formEl.querySelector('input[name="name"]').value.trim();
+      const { id, options } = await postJSON("/account/passkeys/options");
+      const cred = await navigator.credentials.create({ publicKey: creationOptions(options) });
+      if (!cred) return;
+      const result = await postJSON("/account/passkeys/verify", { id, response: credentialJSON(cred), name });
+      window.location.href = result.redirect;
+    } catch (err) {
+      showError(webauthnMessage(err));
+    } finally {
+      button.disabled = false;
+    }
+  });
+}
+
+// --- shared --------------------------------------------------------------------------
+
+document.addEventListener("submit", (ev) => {
+  const message = ev.target.dataset && ev.target.dataset.confirm;
+  if (message && !window.confirm(message)) ev.preventDefault();
+});
+
+document.addEventListener("click", async (ev) => {
+  const button = ev.target.closest && ev.target.closest("[data-copy]");
+  if (!button) return;
+  try {
+    await navigator.clipboard.writeText(button.dataset.copy);
+    const label = button.textContent;
+    button.textContent = "Copied";
+    setTimeout(() => (button.textContent = label), 1500);
+  } catch {
+    const input = button.parentElement.querySelector("input");
+    if (input) input.select();
+  }
+});
+
+document.addEventListener("DOMContentLoaded", () => {
+  const page = document.body.dataset.page;
+  if (page === "login") initLogin();
+  if (page === "account") initAccount();
+});
diff --git a/public/static/style.css b/public/static/style.css
new file mode 100644
index 0000000..15c7f9a
--- /dev/null
+++ b/public/static/style.css
@@ -0,0 +1,493 @@
+/* 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.
+ */
+
+:root {
+  --bg: #060d18;
+  --surface: #0d1a2c;
+  --surface-2: #13243b;
+  --border: #22375a;
+  --text: #e6edf7;
+  --muted: #8ea2bf;
+  --accent: #8ab4ff;
+  --accent-text: #06101f;
+  --ok: #5fd39a;
+  --ok-bg: rgba(95, 211, 154, 0.12);
+  --danger: #ff7a8a;
+  --danger-bg: rgba(255, 122, 138, 0.12);
+  --focus: #b9d2ff;
+  --radius: 10px;
+  color-scheme: dark;
+}
+
+@media (prefers-color-scheme: light) {
+  :root {
+    --bg: #f4f6fb;
+    --surface: #ffffff;
+    --surface-2: #eef2f9;
+    --border: #d4dcea;
+    --text: #0f1a2b;
+    --muted: #5a6b85;
+    --accent: #2456c9;
+    --accent-text: #ffffff;
+    --ok: #16794a;
+    --ok-bg: rgba(22, 121, 74, 0.1);
+    --danger: #c02a3d;
+    --danger-bg: rgba(192, 42, 61, 0.08);
+    --focus: #2456c9;
+    color-scheme: light;
+  }
+}
+
+*,
+*::before,
+*::after {
+  box-sizing: border-box;
+}
+
+html {
+  -webkit-text-size-adjust: 100%;
+}
+
+body {
+  margin: 0;
+  background: var(--bg);
+  color: var(--text);
+  font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+}
+
+a {
+  color: var(--accent);
+}
+
+code {
+  font-family: ui-monospace, "Cascadia Code", Menlo, monospace;
+  font-size: 0.9em;
+  overflow-wrap: anywhere;
+}
+
+h1 {
+  font-size: 1.5rem;
+  margin: 0 0 0.75rem;
+}
+
+h2 {
+  font-size: 1.1rem;
+  margin: 0 0 0.5rem;
+}
+
+.muted {
+  color: var(--muted);
+}
+
+.small {
+  font-size: 0.875rem;
+}
+
+.hidden {
+  display: none !important;
+}
+
+/* --- layout ------------------------------------------------------------------ */
+
+.topbar {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  gap: 1rem;
+  flex-wrap: wrap;
+  padding: 0.75rem 16px;
+  border-bottom: 1px solid var(--border);
+  background: var(--surface);
+}
+
+.brand {
+  color: var(--text);
+  font-weight: 650;
+  text-decoration: none;
+}
+
+.topbar nav {
+  display: flex;
+  align-items: center;
+  gap: 1rem;
+}
+
+main {
+  margin: 0 auto;
+  padding: 1.5rem 16px 3rem;
+}
+
+main.wide {
+  max-width: 960px;
+}
+
+main.narrow {
+  max-width: 440px;
+  padding-top: 3rem;
+}
+
+.card,
+.panel {
+  background: var(--surface);
+  border: 1px solid var(--border);
+  border-radius: var(--radius);
+  padding: 1.25rem;
+}
+
+.panel {
+  margin: 1rem 0;
+}
+
+.tabs {
+  display: flex;
+  gap: 0.25rem;
+  overflow-x: auto;
+  margin-bottom: 1rem;
+  border-bottom: 1px solid var(--border);
+}
+
+.tabs a {
+  padding: 0.5rem 0.75rem;
+  color: var(--muted);
+  text-decoration: none;
+  white-space: nowrap;
+  border-bottom: 2px solid transparent;
+}
+
+.tabs a.active {
+  color: var(--text);
+  border-bottom-color: var(--accent);
+}
+
+/* --- 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 {
+  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: ui-monospace, "Cascadia Code", Menlo, monospace;
+  font-size: 0.875rem;
+}
+
+input:disabled {
+  opacity: 0.7;
+}
+
+:focus-visible {
+  outline: 2px solid var(--focus);
+  outline-offset: 2px;
+}
+
+fieldset {
+  border: 1px solid var(--border);
+  border-radius: 8px;
+  padding: 0.75rem;
+  margin: 0;
+}
+
+legend {
+  padding: 0 0.3rem;
+  font-weight: 550;
+  font-size: 0.9rem;
+}
+
+.checks {
+  display: flex;
+  flex-direction: column;
+  gap: 0.4rem;
+}
+
+.check {
+  display: flex;
+  align-items: flex-start;
+  gap: 0.5rem;
+}
+
+.check input {
+  margin-top: 0.3rem;
+}
+
+button {
+  padding: 0.55rem 1rem;
+  border: 1px solid var(--border);
+  border-radius: 8px;
+  background: var(--surface-2);
+  color: var(--text);
+  font: inherit;
+  font-weight: 550;
+  cursor: pointer;
+}
+
+button:hover:not(:disabled) {
+  border-color: var(--accent);
+}
+
+button:disabled {
+  opacity: 0.55;
+  cursor: not-allowed;
+}
+
+button.primary {
+  background: var(--accent);
+  border-color: var(--accent);
+  color: var(--accent-text);
+}
+
+button.danger {
+  color: var(--danger);
+}
+
+button.small {
+  padding: 0.3rem 0.65rem;
+  font-size: 0.85rem;
+}
+
+button.wide {
+  width: 100%;
+}
+
+button.link {
+  padding: 0;
+  border: 0;
+  background: none;
+  color: var(--accent);
+  font-weight: inherit;
+  text-decoration: underline;
+}
+
+form.inline {
+  display: inline;
+}
+
+.inline-edit {
+  display: flex;
+  flex-wrap: wrap;
+  align-items: center;
+  gap: 0.5rem;
+  margin: 0.5rem 0;
+}
+
+.inline-edit input[type="text"] {
+  flex: 1 1 12rem;
+  width: auto;
+}
+
+.buttons {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 0.5rem;
+}
+
+.divider {
+  display: flex;
+  align-items: center;
+  gap: 0.75rem;
+  margin: 1.25rem 0;
+  color: var(--muted);
+  font-size: 0.85rem;
+}
+
+.divider::before,
+.divider::after {
+  content: "";
+  flex: 1;
+  border-top: 1px solid var(--border);
+}
+
+details summary {
+  cursor: pointer;
+  color: var(--muted);
+  margin: 0.25rem 0;
+}
+
+details[open] summary {
+  margin-bottom: 0.75rem;
+}
+
+/* --- content ------------------------------------------------------------------ */
+
+.notice {
+  padding: 0.65rem 0.85rem;
+  border: 1px solid var(--border);
+  border-radius: 8px;
+  background: var(--surface-2);
+  margin: 0.75rem 0;
+}
+
+.notice p {
+  margin: 0.25rem 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;
+  margin: 0.1rem 0.3rem 0.1rem 0;
+  padding: 0.05rem 0.5rem;
+  border: 1px solid var(--border);
+  border-radius: 999px;
+  font-size: 0.78rem;
+  color: var(--muted);
+  white-space: nowrap;
+}
+
+.badge.ok {
+  color: var(--ok);
+  border-color: var(--ok);
+}
+
+.badge.danger {
+  color: var(--danger);
+  border-color: var(--danger);
+  margin-left: 0.4rem;
+}
+
+.rows {
+  list-style: none;
+  margin: 0 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;
+}
+
+.grow {
+  flex: 1;
+  min-width: 0;
+}
+
+.table-wrap {
+  overflow-x: auto;
+}
+
+table {
+  width: 100%;
+  border-collapse: collapse;
+}
+
+th,
+td {
+  padding: 0.55rem 0.5rem;
+  border-bottom: 1px solid var(--border);
+  text-align: left;
+  vertical-align: top;
+}
+
+th {
+  color: var(--muted);
+  font-weight: 550;
+  font-size: 0.85rem;
+}
+
+table.compact td {
+  font-size: 0.875rem;
+}
+
+.kv {
+  display: grid;
+  grid-template-columns: max-content 1fr;
+  gap: 0.4rem 1rem;
+  margin: 0;
+}
+
+.kv dt {
+  color: var(--muted);
+}
+
+.kv dd {
+  margin: 0;
+  min-width: 0;
+}
+
+.copyrow {
+  display: flex;
+  gap: 0.5rem;
+}
+
+.copyrow input {
+  flex: 1;
+  font-family: ui-monospace, "Cascadia Code", Menlo, monospace;
+}
+
+.qr {
+  display: block;
+  margin: 1rem auto;
+  background: #fff;
+  border-radius: 8px;
+}
+
+.secret code {
+  font-size: 1.05rem;
+  letter-spacing: 0.05em;
+}
+
+@media (max-width: 560px) {
+  .rows > li {
+    flex-wrap: wrap;
+  }
+
+  .kv {
+    grid-template-columns: 1fr;
+  }
+
+  .kv dd {
+    margin-bottom: 0.5rem;
+  }
+}
diff --git a/src/data/cleanup.ts b/src/data/cleanup.ts
new file mode 100644
index 0000000..bc6aca9
--- /dev/null
+++ b/src/data/cleanup.ts
@@ -0,0 +1,32 @@
+/* src/data/cleanup.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 { TTL, now, type Env } from "../env";
+
+const AUDIT_RETENTION = 60 * 60 * 24 * 180;
+const RATE_LIMIT_RETENTION = 60 * 60 * 24;
+
+/** Run from the cron trigger. Everything here is already unusable; this only reclaims space. */
+export async function sweepExpired(env: Env): Promise<void> {
+  const ts = now();
+  const results = await env.DB.batch([
+    env.DB.prepare("DELETE FROM sessions WHERE expires_at <= ?").bind(ts),
+    env.DB.prepare("DELETE FROM pending_logins WHERE expires_at <= ?").bind(ts),
+    env.DB.prepare("DELETE FROM webauthn_challenges WHERE expires_at <= ?").bind(ts),
+    env.DB.prepare("DELETE FROM login_links WHERE expires_at <= ?").bind(ts),
+    env.DB.prepare("DELETE FROM auth_codes WHERE expires_at <= ?").bind(ts),
+    // Revoked or used refresh tokens are kept until they expire anyway, so reuse
+    // of an old token can still be recognised and its family shut down.
+    env.DB.prepare("DELETE FROM refresh_tokens WHERE expires_at <= ?").bind(ts),
+    env.DB.prepare("DELETE FROM signing_keys WHERE retired_at IS NOT NULL AND retired_at <= ?").bind(
+      ts - TTL.retiredKey,
+    ),
+    env.DB.prepare("DELETE FROM rate_limits WHERE window_start <= ?").bind(ts - RATE_LIMIT_RETENTION),
+    env.DB.prepare("DELETE FROM audit_log WHERE at <= ?").bind(ts - AUDIT_RETENTION),
+  ]);
+  const removed = results.reduce((sum, r) => sum + (r.meta.changes ?? 0), 0);
+  console.log(`[cleanup] removed ${removed} expired rows`);
+}
diff --git a/src/data/clients.ts b/src/data/clients.ts
new file mode 100644
index 0000000..99c5f9e
--- /dev/null
+++ b/src/data/clients.ts
@@ -0,0 +1,143 @@
+/* src/data/clients.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, type Env } from "../env";
+import { randomToken, sha256Hex, timingSafeEqualStr } from "../lib/crypto";
+
+interface ClientRow {
+  id: string;
+  name: string;
+  secret_hash: string | null;
+  redirect_uris: string;
+  post_logout_redirect_uris: string;
+  allowed_groups: string;
+  created_at: number;
+  updated_at: number;
+}
+
+export interface Client {
+  id: string;
+  name: string;
+  secretHash: string | null;
+  isPublic: boolean;
+  redirectUris: string[];
+  postLogoutRedirectUris: string[];
+  allowedGroups: string[];
+  createdAt: number;
+  updatedAt: number;
+}
+
+function toClient(row: ClientRow): Client {
+  return {
+    id: row.id,
+    name: row.name,
+    secretHash: row.secret_hash,
+    isPublic: row.secret_hash === null,
+    redirectUris: JSON.parse(row.redirect_uris) as string[],
+    postLogoutRedirectUris: JSON.parse(row.post_logout_redirect_uris) as string[],
+    allowedGroups: JSON.parse(row.allowed_groups) as string[],
+    createdAt: row.created_at,
+    updatedAt: row.updated_at,
+  };
+}
+
+export async function getClient(env: Env, id: string): Promise<Client | null> {
+  const row = await env.DB.prepare("SELECT * FROM clients WHERE id = ?").bind(id).first<ClientRow>();
+  return row ? toClient(row) : null;
+}
+
+export async function listClients(env: Env): Promise<Client[]> {
+  const { results } = await env.DB.prepare("SELECT * FROM clients ORDER BY name").all<ClientRow>();
+  return results.map(toClient);
+}
+
+export interface ClientInput {
+  name: string;
+  redirectUris: string[];
+  postLogoutRedirectUris: string[];
+  allowedGroups: string[];
+}
+
+function newSecret(): string {
+  return `dsso_${randomToken(32)}`;
+}
+
+/** Returns the plaintext secret for confidential clients — shown exactly once. */
+export async function createClient(
+  env: Env,
+  id: string,
+  confidential: boolean,
+  input: ClientInput,
+): Promise<{ ok: true; secret: string | null } | { ok: false; error: string }> {
+  const secret = confidential ? newSecret() : null;
+  const ts = now();
+  try {
+    await env.DB.prepare(
+      `INSERT INTO clients (id, name, secret_hash, redirect_uris, post_logout_redirect_uris, allowed_groups, created_at, updated_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+      .bind(
+        id,
+        input.name,
+        secret ? await sha256Hex(secret) : null,
+        JSON.stringify(input.redirectUris),
+        JSON.stringify(input.postLogoutRedirectUris),
+        JSON.stringify(input.allowedGroups),
+        ts,
+        ts,
+      )
+      .run();
+    return { ok: true, secret };
+  } catch (err) {
+    if (String(err).includes("UNIQUE")) return { ok: false, error: "That client id is already in use." };
+    throw err;
+  }
+}
+
+export async function updateClient(env: Env, id: string, input: ClientInput): Promise<void> {
+  await env.DB.prepare(
+    `UPDATE clients SET name = ?, redirect_uris = ?, post_logout_redirect_uris = ?, allowed_groups = ?, updated_at = ?
+     WHERE id = ?`,
+  )
+    .bind(
+      input.name,
+      JSON.stringify(input.redirectUris),
+      JSON.stringify(input.postLogoutRedirectUris),
+      JSON.stringify(input.allowedGroups),
+      now(),
+      id,
+    )
+    .run();
+}
+
+/** Issues a new secret (making a public client confidential if need be). */
+export async function rotateClientSecret(env: Env, id: string): Promise<string> {
+  const secret = newSecret();
+  await env.DB.prepare("UPDATE clients SET secret_hash = ?, updated_at = ? WHERE id = ?")
+    .bind(await sha256Hex(secret), now(), id)
+    .run();
+  return secret;
+}
+
+export async function makeClientPublic(env: Env, id: string): Promise<void> {
+  await env.DB.prepare("UPDATE clients SET secret_hash = NULL, updated_at = ? WHERE id = ?")
+    .bind(now(), id)
+    .run();
+}
+
+export async function deleteClient(env: Env, id: string): Promise<void> {
+  await env.DB.prepare("DELETE FROM clients WHERE id = ?").bind(id).run();
+}
+
+export async function verifyClientSecret(client: Client, secret: string): Promise<boolean> {
+  if (!client.secretHash) return false;
+  return timingSafeEqualStr(await sha256Hex(secret), client.secretHash);
+}
+
+/** Empty allow-list = every account may use the client. */
+export function clientAllows(client: Client, groups: string[]): boolean {
+  return client.allowedGroups.length === 0 || client.allowedGroups.some((g) => groups.includes(g));
+}
diff --git a/src/data/groups.ts b/src/data/groups.ts
new file mode 100644
index 0000000..8d78a27
--- /dev/null
+++ b/src/data/groups.ts
@@ -0,0 +1,39 @@
+/* src/data/groups.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, type Env } from "../env";
+
+export interface GroupRow {
+  name: string;
+  description: string;
+  created_at: number;
+  member_count: number;
+}
+
+export async function listGroups(env: Env): Promise<GroupRow[]> {
+  const { results } = await env.DB.prepare(
+    `SELECT g.*, (SELECT COUNT(*) FROM user_groups ug WHERE ug.group_name = g.name) AS member_count
+     FROM groups g ORDER BY g.name`,
+  ).all<GroupRow>();
+  return results;
+}
+
+export async function createGroup(env: Env, name: string, description: string): Promise<boolean> {
+  const result = await env.DB.prepare(
+    "INSERT OR IGNORE INTO groups (name, description, created_at) VALUES (?, ?, ?)",
+  )
+    .bind(name, description, now())
+    .run();
+  return result.meta.changes === 1;
+}
+
+export async function updateGroup(env: Env, name: string, description: string): Promise<void> {
+  await env.DB.prepare("UPDATE groups SET description = ? WHERE name = ?").bind(description, name).run();
+}
+
+export async function deleteGroup(env: Env, name: string): Promise<void> {
+  await env.DB.prepare("DELETE FROM groups WHERE name = ?").bind(name).run();
+}
diff --git a/src/data/keys.ts b/src/data/keys.ts
new file mode 100644
index 0000000..506311a
--- /dev/null
+++ b/src/data/keys.ts
@@ -0,0 +1,135 @@
+/* src/data/keys.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 {
+  calculateJwkThumbprint,
+  createLocalJWKSet,
+  exportJWK,
+  generateKeyPair,
+  importJWK,
+  type JSONWebKeySet,
+  type JWK,
+} from "jose";
+import { TTL, now, type Env } from "../env";
+import { decrypt, encrypt } from "../lib/crypto";
+
+export const ALG = "RS256";
+
+interface KeyRow {
+  kid: string;
+  alg: string;
+  private_jwk: string;
+  public_jwk: string;
+  created_at: number;
+  retired_at: number | null;
+}
+
+export interface SigningKey {
+  kid: string;
+  key: CryptoKey;
+}
+
+// Per-isolate caches. The active-key lookup is re-checked every minute so a
+// rotation made through another isolate is picked up quickly.
+const privateKeys = new Map<string, Promise<CryptoKey>>();
+let active: { kid: string; checkedAt: number } | null = null;
+let jwks: { set: JSONWebKeySet; checkedAt: number } | null = null;
+
+async function createKey(env: Env): Promise<KeyRow> {
+  const { privateKey, publicKey } = await generateKeyPair(ALG, { modulusLength: 2048, extractable: true });
+  const publicJwk = await exportJWK(publicKey);
+  const kid = await calculateJwkThumbprint(publicJwk);
+  const row: KeyRow = {
+    kid,
+    alg: ALG,
+    private_jwk: await encrypt(env.KEY_ENCRYPTION_KEY, JSON.stringify(await exportJWK(privateKey))),
+    public_jwk: JSON.stringify({ ...publicJwk, kid, alg: ALG, use: "sig" }),
+    created_at: now(),
+    retired_at: null,
+  };
+  await env.DB.prepare(
+    "INSERT INTO signing_keys (kid, alg, private_jwk, public_jwk, created_at) VALUES (?, ?, ?, ?, ?)",
+  )
+    .bind(row.kid, row.alg, row.private_jwk, row.public_jwk, row.created_at)
+    .run();
+  return row;
+}
+
+function loadPrivate(env: Env, row: Pick<KeyRow, "kid" | "private_jwk">): Promise<CryptoKey> {
+  let key = privateKeys.get(row.kid);
+  if (!key) {
+    key = decrypt(env.KEY_ENCRYPTION_KEY, row.private_jwk).then(
+      async (json) => (await importJWK(JSON.parse(json) as JWK, ALG)) as CryptoKey,
+    );
+    key.catch(() => privateKeys.delete(row.kid));
+    privateKeys.set(row.kid, key);
+  }
+  return key;
+}
+
+export async function signingKey(env: Env): Promise<SigningKey> {
+  const ts = Date.now();
+  if (active && ts - active.checkedAt < 60_000) {
+    const cached = privateKeys.get(active.kid);
+    if (cached) return { kid: active.kid, key: await cached };
+  }
+
+  let row = await env.DB.prepare(
+    "SELECT kid, private_jwk FROM signing_keys WHERE retired_at IS NULL ORDER BY created_at DESC LIMIT 1",
+  ).first<Pick<KeyRow, "kid" | "private_jwk">>();
+  // First run: nothing to sign with yet, so make a key.
+  if (!row) row = await createKey(env);
+
+  active = { kid: row.kid, checkedAt: ts };
+  return { kid: row.kid, key: await loadPrivate(env, row) };
+}
+
+export async function publicJwks(env: Env): Promise<JSONWebKeySet> {
+  const ts = Date.now();
+  if (jwks && ts - jwks.checkedAt < 60_000) return jwks.set;
+
+  const { results } = await env.DB.prepare(
+    "SELECT public_jwk FROM signing_keys WHERE retired_at IS NULL OR retired_at > ? ORDER BY created_at DESC",
+  )
+    .bind(now() - TTL.retiredKey)
+    .all<{ public_jwk: string }>();
+  const set = { keys: results.map((r) => JSON.parse(r.public_jwk) as JWK) };
+  // Don't cache an empty set: the first token signed would otherwise fail to
+  // verify in this isolate for a minute.
+  if (set.keys.length) jwks = { set, checkedAt: ts };
+  return set;
+}
+
+export function resetJwksCache(): void {
+  jwks = null;
+}
+
+export async function verificationKeys(env: Env) {
+  return createLocalJWKSet(await publicJwks(env));
+}
+
+export interface KeyListing {
+  kid: string;
+  alg: string;
+  created_at: number;
+  retired_at: number | null;
+}
+
+export async function listKeys(env: Env): Promise<KeyListing[]> {
+  const { results } = await env.DB.prepare(
+    "SELECT kid, alg, created_at, retired_at FROM signing_keys ORDER BY created_at DESC",
+  ).all<KeyListing>();
+  return results;
+}
+
+/** Retires every current key and starts signing with a fresh one. */
+export async function rotateKeys(env: Env): Promise<string> {
+  await env.DB.prepare("UPDATE signing_keys SET retired_at = ? WHERE retired_at IS NULL").bind(now()).run();
+  const row = await createKey(env);
+  active = null;
+  jwks = null;
+  return row.kid;
+}
diff --git a/src/data/links.ts b/src/data/links.ts
new file mode 100644
index 0000000..bafcaee
--- /dev/null
+++ b/src/data/links.ts
@@ -0,0 +1,72 @@
+/* src/data/links.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 { issuer, now, type Env } from "../env";
+import { randomToken, sha256Hex } from "../lib/crypto";
+
+/**
+ * One-time sign-in links, issued by an admin to bootstrap a new account or
+ * recover one that lost its passkeys. Returns the full URL, shown once.
+ */
+export async function createLoginLink(
+  env: Env,
+  userId: string,
+  createdBy: string,
+  ttlSeconds: number,
+): Promise<{ url: string; expiresAt: number }> {
+  const token = randomToken(32);
+  const ts = now();
+  const expiresAt = ts + ttlSeconds;
+  await env.DB.batch([
+    // Only the newest link for an account stays valid.
+    env.DB.prepare("DELETE FROM login_links WHERE user_id = ?").bind(userId),
+    env.DB.prepare(
+      "INSERT INTO login_links (token_hash, user_id, created_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?)",
+    ).bind(await sha256Hex(token), userId, createdBy, ts, expiresAt),
+  ]);
+  return { url: `${issuer(env)}/login/link/${token}`, expiresAt };
+}
+
+export interface LinkTarget {
+  user_id: string;
+  username: string;
+  name: string | null;
+}
+
+/** Looks a link up without using it (the confirmation page). */
+export async function peekLoginLink(env: Env, token: string): Promise<LinkTarget | null> {
+  return env.DB.prepare(
+    `SELECT l.user_id, u.username, u.name FROM login_links l JOIN users u ON u.id = l.user_id
+     WHERE l.token_hash = ? AND l.expires_at > ? AND u.disabled = 0`,
+  )
+    .bind(await sha256Hex(token), now())
+    .first<LinkTarget>();
+}
+
+/** Uses a link up. Returns the account it signs in to, or null. */
+export async function consumeLoginLink(env: Env, token: string): Promise<string | null> {
+  const row = await env.DB.prepare(
+    "DELETE FROM login_links WHERE token_hash = ? RETURNING user_id, expires_at",
+  )
+    .bind(await sha256Hex(token))
+    .first<{ user_id: string; expires_at: number }>();
+  if (!row || row.expires_at <= now()) return null;
+  const user = await env.DB.prepare("SELECT disabled FROM users WHERE id = ?")
+    .bind(row.user_id)
+    .first<{ disabled: number }>();
+  return user && !user.disabled ? row.user_id : null;
+}
+
+export async function hasOpenLoginLink(env: Env, userId: string): Promise<number | null> {
+  const row = await env.DB.prepare("SELECT expires_at FROM login_links WHERE user_id = ? AND expires_at > ?")
+    .bind(userId, now())
+    .first<{ expires_at: number }>();
+  return row?.expires_at ?? null;
+}
+
+export async function revokeLoginLinks(env: Env, userId: string): Promise<void> {
+  await env.DB.prepare("DELETE FROM login_links WHERE user_id = ?").bind(userId).run();
+}
diff --git a/src/data/passkeys.ts b/src/data/passkeys.ts
new file mode 100644
index 0000000..f9adda3
--- /dev/null
+++ b/src/data/passkeys.ts
@@ -0,0 +1,240 @@
+/* src/data/passkeys.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 {
+  generateAuthenticationOptions,
+  generateRegistrationOptions,
+  verifyAuthenticationResponse,
+  verifyRegistrationResponse,
+  type AuthenticationResponseJSON,
+  type PublicKeyCredentialCreationOptionsJSON,
+  type PublicKeyCredentialRequestOptionsJSON,
+  type RegistrationResponseJSON,
+} from "@simplewebauthn/server";
+import { TTL, issuerOrigin, now, rpId, siteName, type Env } from "../env";
+import { b64url, fromB64url, fromUtf8, randomToken, utf8 } from "../lib/crypto";
+import type { UserRow } from "./users";
+
+export interface PasskeyRow {
+  id: string;
+  user_id: string;
+  public_key: string;
+  counter: number;
+  transports: string;
+  device_type: string;
+  backed_up: number;
+  name: string;
+  created_at: number;
+  last_used_at: number | null;
+}
+
+export async function listPasskeys(env: Env, userId: string): Promise<PasskeyRow[]> {
+  const { results } = await env.DB.prepare(
+    "SELECT * FROM passkeys WHERE user_id = ? ORDER BY created_at",
+  )
+    .bind(userId)
+    .all<PasskeyRow>();
+  return results;
+}
+
+export async function countPasskeys(env: Env, userId: string): Promise<number> {
+  const row = await env.DB.prepare("SELECT COUNT(*) AS n FROM passkeys WHERE user_id = ?")
+    .bind(userId)
+    .first<{ n: number }>();
+  return row?.n ?? 0;
+}
+
+export async function renamePasskey(env: Env, userId: string, id: string, name: string): Promise<void> {
+  await env.DB.prepare("UPDATE passkeys SET name = ? WHERE id = ? AND user_id = ?").bind(name, id, userId).run();
+}
+
+export async function deletePasskey(env: Env, userId: string, id: string): Promise<void> {
+  await env.DB.prepare("DELETE FROM passkeys WHERE id = ? AND user_id = ?").bind(id, userId).run();
+}
+
+async function saveChallenge(
+  env: Env,
+  challenge: string,
+  purpose: "login" | "register",
+  userId: string | null,
+): Promise<string> {
+  const id = randomToken(18);
+  await env.DB.prepare(
+    "INSERT INTO webauthn_challenges (id, challenge, purpose, user_id, expires_at) VALUES (?, ?, ?, ?, ?)",
+  )
+    .bind(id, challenge, purpose, userId, now() + TTL.challenge)
+    .run();
+  return id;
+}
+
+/** Single use: the row is deleted as it is read. */
+async function takeChallenge(
+  env: Env,
+  id: string,
+  purpose: "login" | "register",
+  userId: string | null,
+): Promise<string | null> {
+  const row = await env.DB.prepare(
+    "DELETE FROM webauthn_challenges WHERE id = ? RETURNING challenge, purpose, user_id, expires_at",
+  )
+    .bind(id)
+    .first<{ challenge: string; purpose: string; user_id: string | null; expires_at: number }>();
+  if (!row || row.purpose !== purpose || row.user_id !== userId || row.expires_at <= now()) return null;
+  return row.challenge;
+}
+
+// --- registration --------------------------------------------------------------
+
+export async function registrationOptions(
+  env: Env,
+  user: UserRow,
+): Promise<{ id: string; options: PublicKeyCredentialCreationOptionsJSON }> {
+  const existing = await listPasskeys(env, user.id);
+  const options = await generateRegistrationOptions({
+    rpName: siteName(env),
+    rpID: rpId(env),
+    userName: user.username,
+    userDisplayName: user.name ?? user.username,
+    userID: utf8(user.id),
+    attestationType: "none",
+    excludeCredentials: existing.map((p) => ({
+      id: p.id,
+      transports: JSON.parse(p.transports) as string[],
+    })),
+    authenticatorSelection: { residentKey: "required", userVerification: "required" },
+  });
+  const id = await saveChallenge(env, options.challenge, "register", user.id);
+  return { id, options };
+}
+
+export type RegisterResult = { ok: true; passkey: PasskeyRow } | { ok: false; error: string };
+
+export async function finishRegistration(
+  env: Env,
+  user: UserRow,
+  challengeId: string,
+  response: RegistrationResponseJSON,
+  name: string,
+): Promise<RegisterResult> {
+  const challenge = await takeChallenge(env, challengeId, "register", user.id);
+  if (!challenge) return { ok: false, error: "That request expired. Please try again." };
+
+  let verification;
+  try {
+    verification = await verifyRegistrationResponse({
+      response,
+      expectedChallenge: challenge,
+      expectedOrigin: issuerOrigin(env),
+      expectedRPID: rpId(env),
+      requireUserVerification: true,
+    });
+  } catch (err) {
+    console.warn("[passkeys] registration rejected", err);
+    return { ok: false, error: "Your device's response couldn't be verified." };
+  }
+  if (!verification.verified) return { ok: false, error: "Your device's response couldn't be verified." };
+
+  const info = verification.registrationInfo;
+  const row: PasskeyRow = {
+    id: info.credential.id,
+    user_id: user.id,
+    public_key: b64url(info.credential.publicKey),
+    counter: info.credential.counter,
+    transports: JSON.stringify(info.credential.transports ?? []),
+    device_type: info.credentialDeviceType,
+    backed_up: info.credentialBackedUp ? 1 : 0,
+    name,
+    created_at: now(),
+    last_used_at: null,
+  };
+  try {
+    await env.DB.prepare(
+      `INSERT INTO passkeys (id, user_id, public_key, counter, transports, device_type, backed_up, name, created_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+      .bind(row.id, row.user_id, row.public_key, row.counter, row.transports, row.device_type, row.backed_up, row.name, row.created_at)
+      .run();
+  } catch (err) {
+    if (String(err).includes("UNIQUE")) return { ok: false, error: "That passkey is already registered." };
+    throw err;
+  }
+  return { ok: true, passkey: row };
+}
+
+// --- authentication ------------------------------------------------------------
+
+export async function authenticationOptions(
+  env: Env,
+): Promise<{ id: string; options: PublicKeyCredentialRequestOptionsJSON }> {
+  // No allowCredentials: passkeys are discoverable, so the browser offers
+  // whichever ones it holds for this site and the username never has to be typed.
+  const options = await generateAuthenticationOptions({
+    rpID: rpId(env),
+    userVerification: "required",
+  });
+  const id = await saveChallenge(env, options.challenge, "login", null);
+  return { id, options };
+}
+
+export type AuthResult = { ok: true; userId: string; amr: string[] } | { ok: false; error: string };
+
+export async function finishAuthentication(
+  env: Env,
+  challengeId: string,
+  response: AuthenticationResponseJSON,
+): Promise<AuthResult> {
+  const failure = { ok: false, error: "That passkey couldn't be used to sign in." } as const;
+
+  const challenge = await takeChallenge(env, challengeId, "login", null);
+  if (!challenge) return { ok: false, error: "That sign-in attempt expired. Please try again." };
+
+  const passkey = await env.DB.prepare("SELECT * FROM passkeys WHERE id = ?")
+    .bind(String(response?.id ?? ""))
+    .first<PasskeyRow>();
+  if (!passkey) return { ok: false, error: "This passkey isn't registered here. It may have been removed." };
+
+  const handle = response.response?.userHandle;
+  if (handle) {
+    try {
+      if (fromUtf8(fromB64url(handle)) !== passkey.user_id) return failure;
+    } catch {
+      return failure;
+    }
+  }
+
+  let verification;
+  try {
+    verification = await verifyAuthenticationResponse({
+      response,
+      expectedChallenge: challenge,
+      expectedOrigin: issuerOrigin(env),
+      expectedRPID: rpId(env),
+      credential: {
+        id: passkey.id,
+        publicKey: fromB64url(passkey.public_key),
+        counter: passkey.counter,
+        transports: JSON.parse(passkey.transports) as string[],
+      },
+      requireUserVerification: true,
+    });
+  } catch (err) {
+    console.warn("[passkeys] authentication rejected", err);
+    return failure;
+  }
+  if (!verification.verified) return failure;
+
+  const info = verification.authenticationInfo;
+  await env.DB.prepare(
+    "UPDATE passkeys SET counter = ?, backed_up = ?, last_used_at = ? WHERE id = ?",
+  )
+    .bind(info.newCounter, info.credentialBackedUp ? 1 : 0, now(), passkey.id)
+    .run();
+
+  // RFC 8176: synced passkeys are software keys, device-bound ones hardware.
+  // User verification was required, so either way it was multi-factor.
+  const kind = info.credentialDeviceType === "multiDevice" ? "swk" : "hwk";
+  return { ok: true, userId: passkey.user_id, amr: [kind, "user", "mfa"] };
+}
diff --git a/src/data/sessions.ts b/src/data/sessions.ts
new file mode 100644
index 0000000..99feba8
--- /dev/null
+++ b/src/data/sessions.ts
@@ -0,0 +1,217 @@
+/* src/data/sessions.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 { getCookie, setCookie, deleteCookie } from "hono/cookie";
+import { ADMIN_GROUP, TTL, isSecure, now, type AppContext, type CurrentUser, type Env, type SessionInfo } from "../env";
+import { randomToken, sha256Hex } from "../lib/crypto";
+import { clientIp, userAgent } from "../lib/http";
+import { groupsFor, markLogin } from "./users";
+
+function cookieName(env: Env, base: string): string {
+  // __Host- pins the cookie to this exact origin: Secure, Path=/, no Domain.
+  return isSecure(env) ? `__Host-${base}` : base;
+}
+
+export const sessionCookie = (env: Env) => cookieName(env, "sso_session");
+export const pendingCookie = (env: Env) => cookieName(env, "sso_pending");
+
+export function writeCookie(c: AppContext, name: string, value: string, maxAge: number): void {
+  setCookie(c, name, value, {
+    httpOnly: true,
+    secure: isSecure(c.env),
+    sameSite: "Lax",
+    path: "/",
+    maxAge,
+  });
+}
+
+export function clearCookie(c: AppContext, name: string): void {
+  deleteCookie(c, name, { path: "/", secure: isSecure(c.env) });
+}
+
+export async function startSession(c: AppContext, userId: string, amr: string[]): Promise<void> {
+  // Drop whatever session this browser already had so ids never get reused
+  // across a re-authentication.
+  await endSession(c);
+
+  const token = randomToken(32);
+  const ts = now();
+  await c.env.DB.prepare(
+    `INSERT INTO sessions (id_hash, user_id, csrf, auth_time, amr, ip, user_agent, created_at, last_seen_at, expires_at)
+     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+  )
+    .bind(
+      await sha256Hex(token),
+      userId,
+      randomToken(24),
+      ts,
+      JSON.stringify(amr),
+      clientIp(c),
+      userAgent(c),
+      ts,
+      ts,
+      ts + TTL.session,
+    )
+    .run();
+  await markLogin(c.env, userId);
+  writeCookie(c, sessionCookie(c.env), token, TTL.session);
+}
+
+export async function endSession(c: AppContext): Promise<void> {
+  const token = getCookie(c, sessionCookie(c.env));
+  if (token) {
+    await c.env.DB.prepare("DELETE FROM sessions WHERE id_hash = ?").bind(await sha256Hex(token)).run();
+  }
+  clearCookie(c, sessionCookie(c.env));
+  c.set("session", null);
+  c.set("user", null);
+}
+
+interface SessionJoin {
+  id_hash: string;
+  user_id: string;
+  csrf: string;
+  auth_time: number;
+  amr: string;
+  last_seen_at: number;
+  expires_at: number;
+  username: string;
+  name: string | null;
+  email: string | null;
+  picture: string | null;
+  disabled: number;
+}
+
+/** Resolves the session cookie into c.var.session / c.var.user. */
+export async function loadSession(c: AppContext): Promise<void> {
+  c.set("session", null);
+  c.set("user", null);
+
+  const token = getCookie(c, sessionCookie(c.env));
+  if (!token) return;
+
+  const idHash = await sha256Hex(token);
+  const row = await c.env.DB.prepare(
+    `SELECT s.*, u.username, u.name, u.email, u.picture, u.disabled
+     FROM sessions s JOIN users u ON u.id = s.user_id
+     WHERE s.id_hash = ?`,
+  )
+    .bind(idHash)
+    .first<SessionJoin>();
+
+  const ts = now();
+  if (!row || row.expires_at <= ts || row.disabled) {
+    if (row) await c.env.DB.prepare("DELETE FROM sessions WHERE id_hash = ?").bind(idHash).run();
+    clearCookie(c, sessionCookie(c.env));
+    return;
+  }
+
+  if (ts - row.last_seen_at > 300) {
+    await c.env.DB.prepare("UPDATE sessions SET last_seen_at = ?, ip = ? WHERE id_hash = ?")
+      .bind(ts, clientIp(c), idHash)
+      .run();
+  }
+
+  const groups = await groupsFor(c.env, row.user_id);
+  const session: SessionInfo = {
+    idHash,
+    userId: row.user_id,
+    csrf: row.csrf,
+    authTime: row.auth_time,
+    amr: JSON.parse(row.amr) as string[],
+  };
+  const user: CurrentUser = {
+    id: row.user_id,
+    username: row.username,
+    name: row.name,
+    email: row.email,
+    picture: row.picture,
+    groups,
+    isAdmin: groups.includes(ADMIN_GROUP),
+  };
+  c.set("session", session);
+  c.set("user", user);
+}
+
+export interface SessionListing {
+  id_hash: string;
+  ip: string | null;
+  user_agent: string | null;
+  created_at: number;
+  last_seen_at: number;
+  amr: string;
+}
+
+export async function listSessions(env: Env, userId: string): Promise<SessionListing[]> {
+  const { results } = await env.DB.prepare(
+    `SELECT id_hash, ip, user_agent, created_at, last_seen_at, amr FROM sessions
+     WHERE user_id = ? AND expires_at > ? ORDER BY last_seen_at DESC`,
+  )
+    .bind(userId, now())
+    .all<SessionListing>();
+  return results;
+}
+
+export async function revokeSession(env: Env, userId: string, idHash: string): Promise<void> {
+  await env.DB.prepare("DELETE FROM sessions WHERE user_id = ? AND id_hash = ?").bind(userId, idHash).run();
+}
+
+export async function revokeOtherSessions(env: Env, userId: string, keepIdHash: string): Promise<void> {
+  await env.DB.prepare("DELETE FROM sessions WHERE user_id = ? AND id_hash != ?").bind(userId, keepIdHash).run();
+}
+
+// --- pending password logins (waiting on TOTP) --------------------------------
+
+export async function startPendingLogin(c: AppContext, userId: string, returnTo: string): Promise<void> {
+  const token = randomToken(32);
+  await c.env.DB.prepare(
+    "INSERT INTO pending_logins (id_hash, user_id, return_to, expires_at) VALUES (?, ?, ?, ?)",
+  )
+    .bind(await sha256Hex(token), userId, returnTo, now() + TTL.pendingLogin)
+    .run();
+  writeCookie(c, pendingCookie(c.env), token, TTL.pendingLogin);
+}
+
+export interface PendingLogin {
+  id_hash: string;
+  user_id: string;
+  return_to: string;
+  attempts: number;
+}
+
+export async function peekPendingLogin(c: AppContext): Promise<PendingLogin | null> {
+  const token = getCookie(c, pendingCookie(c.env));
+  if (!token) return null;
+  return c.env.DB.prepare(
+    "SELECT id_hash, user_id, return_to, attempts FROM pending_logins WHERE id_hash = ? AND expires_at > ?",
+  )
+    .bind(await sha256Hex(token), now())
+    .first<PendingLogin>();
+}
+
+/** Counts a code attempt; returns the pending login only while attempts remain. */
+export async function spendPendingAttempt(c: AppContext, maxAttempts: number): Promise<PendingLogin | null> {
+  const token = getCookie(c, pendingCookie(c.env));
+  if (!token) return null;
+  const row = await c.env.DB.prepare(
+    `UPDATE pending_logins SET attempts = attempts + 1
+     WHERE id_hash = ? AND expires_at > ?
+     RETURNING id_hash, user_id, return_to, attempts`,
+  )
+    .bind(await sha256Hex(token), now())
+    .first<PendingLogin>();
+  if (!row) return null;
+  if (row.attempts > maxAttempts) {
+    await finishPendingLogin(c, row.id_hash);
+    return null;
+  }
+  return row;
+}
+
+export async function finishPendingLogin(c: AppContext, idHash: string): Promise<void> {
+  await c.env.DB.prepare("DELETE FROM pending_logins WHERE id_hash = ?").bind(idHash).run();
+  clearCookie(c, pendingCookie(c.env));
+}
diff --git a/src/data/users.ts b/src/data/users.ts
new file mode 100644
index 0000000..fea0b6f
--- /dev/null
+++ b/src/data/users.ts
@@ -0,0 +1,246 @@
+/* src/data/users.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 { ADMIN_GROUP, now, type Env } from "../env";
+
+export interface UserRow {
+  id: string;
+  username: string;
+  name: string | null;
+  email: string | null;
+  email_verified: number;
+  picture: string | null;
+  password_hash: string | null;
+  totp_secret: string | null;
+  totp_pending: string | null;
+  totp_last_step: number;
+  disabled: number;
+  created_at: number;
+  updated_at: number;
+  last_login_at: number | null;
+}
+
+export interface UserSummary extends UserRow {
+  groups: string[];
+  passkey_count: number;
+}
+
+export async function getUser(env: Env, id: string): Promise<UserRow | null> {
+  return env.DB.prepare("SELECT * FROM users WHERE id = ?").bind(id).first<UserRow>();
+}
+
+export async function getUserByUsername(env: Env, username: string): Promise<UserRow | null> {
+  return env.DB.prepare("SELECT * FROM users WHERE username = ?").bind(username).first<UserRow>();
+}
+
+export async function countUsers(env: Env): Promise<number> {
+  const row = await env.DB.prepare("SELECT COUNT(*) AS n FROM users").first<{ n: number }>();
+  return row?.n ?? 0;
+}
+
+export async function groupsFor(env: Env, userId: string): Promise<string[]> {
+  const { results } = await env.DB.prepare(
+    "SELECT group_name FROM user_groups WHERE user_id = ? ORDER BY group_name",
+  )
+    .bind(userId)
+    .all<{ group_name: string }>();
+  return results.map((r) => r.group_name);
+}
+
+export async function listUsers(env: Env): Promise<UserSummary[]> {
+  const { results } = await env.DB.prepare(
+    `SELECT u.*,
+       (SELECT COUNT(*) FROM passkeys p WHERE p.user_id = u.id) AS passkey_count,
+       (SELECT json_group_array(group_name) FROM
+          (SELECT group_name FROM user_groups g WHERE g.user_id = u.id ORDER BY group_name)
+       ) AS groups_json
+     FROM users u ORDER BY u.username`,
+  ).all<UserRow & { passkey_count: number; groups_json: string }>();
+  return results.map(({ groups_json, ...row }) => ({
+    ...row,
+    groups: JSON.parse(groups_json) as string[],
+  }));
+}
+
+export interface NewUser {
+  id?: string;
+  username: string;
+  name: string | null;
+  email: string | null;
+  emailVerified: boolean;
+}
+
+export type CreateResult = { ok: true; id: string } | { ok: false; error: string };
+
+export async function createUser(env: Env, input: NewUser): Promise<CreateResult> {
+  const id = input.id || crypto.randomUUID();
+  const ts = now();
+  try {
+    await env.DB.prepare(
+      `INSERT INTO users (id, username, name, email, email_verified, created_at, updated_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?)`,
+    )
+      .bind(id, input.username, input.name, input.email, input.emailVerified ? 1 : 0, ts, ts)
+      .run();
+    return { ok: true, id };
+  } catch (err) {
+    if (String(err).includes("UNIQUE")) {
+      return { ok: false, error: "That username or subject id is already taken." };
+    }
+    throw err;
+  }
+}
+
+/**
+ * Creates the very first account as an admin. The insert only happens while
+ * the users table is empty, so two racing /setup submissions can't both win.
+ */
+export async function createFirstAdmin(env: Env, input: NewUser): Promise<string | null> {
+  const id = crypto.randomUUID();
+  const ts = now();
+  const [inserted] = await env.DB.batch([
+    env.DB.prepare(
+      `INSERT INTO users (id, username, name, email, email_verified, created_at, updated_at)
+       SELECT ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM users)`,
+    ).bind(id, input.username, input.name, input.email, input.emailVerified ? 1 : 0, ts, ts),
+    env.DB.prepare(
+      "INSERT OR IGNORE INTO groups (name, description, created_at) VALUES (?, ?, ?)",
+    ).bind(ADMIN_GROUP, "Can manage users, groups and applications on this server.", ts),
+    env.DB.prepare(
+      "INSERT OR IGNORE INTO user_groups (user_id, group_name) SELECT id, ? FROM users WHERE id = ?",
+    ).bind(ADMIN_GROUP, id),
+  ]);
+  return inserted?.meta.changes === 1 ? id : null;
+}
+
+export interface ProfileUpdate {
+  name: string | null;
+  email: string | null;
+  picture: string | null;
+}
+
+export async function updateProfile(env: Env, user: UserRow, update: ProfileUpdate): Promise<void> {
+  // Changing the address un-verifies it; keeping it keeps whatever it was.
+  const verified = update.email !== null && update.email === user.email ? user.email_verified : 0;
+  await env.DB.prepare(
+    "UPDATE users SET name = ?, email = ?, email_verified = ?, picture = ?, updated_at = ? WHERE id = ?",
+  )
+    .bind(update.name, update.email, verified, update.picture, now(), user.id)
+    .run();
+}
+
+export async function adminUpdateUser(
+  env: Env,
+  id: string,
+  update: ProfileUpdate & { username: string; emailVerified: boolean },
+): Promise<string | null> {
+  try {
+    await env.DB.prepare(
+      `UPDATE users SET username = ?, name = ?, email = ?, email_verified = ?, picture = ?, updated_at = ?
+       WHERE id = ?`,
+    )
+      .bind(
+        update.username,
+        update.name,
+        update.email,
+        update.email && update.emailVerified ? 1 : 0,
+        update.picture,
+        now(),
+        id,
+      )
+      .run();
+    return null;
+  } catch (err) {
+    if (String(err).includes("UNIQUE")) return "That username is already taken.";
+    throw err;
+  }
+}
+
+export async function setPasswordHash(env: Env, id: string, hash: string | null): Promise<void> {
+  // Without a password there is nothing for TOTP to protect, so it goes too.
+  const sql =
+    hash === null
+      ? "UPDATE users SET password_hash = NULL, totp_secret = NULL, totp_pending = NULL, updated_at = ? WHERE id = ?"
+      : "UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?";
+  const stmt = env.DB.prepare(sql);
+  await (hash === null ? stmt.bind(now(), id) : stmt.bind(hash, now(), id)).run();
+}
+
+export async function setTotpPending(env: Env, id: string, sealed: string | null): Promise<void> {
+  await env.DB.prepare("UPDATE users SET totp_pending = ?, updated_at = ? WHERE id = ?")
+    .bind(sealed, now(), id)
+    .run();
+}
+
+export async function enableTotp(env: Env, id: string, sealed: string, step: number): Promise<void> {
+  await env.DB.prepare(
+    "UPDATE users SET totp_secret = ?, totp_pending = NULL, totp_last_step = ?, updated_at = ? WHERE id = ?",
+  )
+    .bind(sealed, step, now(), id)
+    .run();
+}
+
+export async function disableTotp(env: Env, id: string): Promise<void> {
+  await env.DB.prepare(
+    "UPDATE users SET totp_secret = NULL, totp_pending = NULL, updated_at = ? WHERE id = ?",
+  )
+    .bind(now(), id)
+    .run();
+}
+
+/**
+ * Records `step` as used. Returns false if it (or a later step) was already
+ * used, i.e. the code is a replay.
+ */
+export async function claimTotpStep(env: Env, id: string, step: number): Promise<boolean> {
+  const result = await env.DB.prepare(
+    "UPDATE users SET totp_last_step = ? WHERE id = ? AND totp_last_step < ?",
+  )
+    .bind(step, id, step)
+    .run();
+  return result.meta.changes === 1;
+}
+
+export async function markLogin(env: Env, id: string): Promise<void> {
+  await env.DB.prepare("UPDATE users SET last_login_at = ? WHERE id = ?").bind(now(), id).run();
+}
+
+export async function setDisabled(env: Env, id: string, disabled: boolean): Promise<void> {
+  const stmts = [
+    env.DB.prepare("UPDATE users SET disabled = ?, updated_at = ? WHERE id = ?").bind(
+      disabled ? 1 : 0,
+      now(),
+      id,
+    ),
+  ];
+  if (disabled) stmts.push(...revokeAllStatements(env, id));
+  await env.DB.batch(stmts);
+}
+
+export function revokeAllStatements(env: Env, userId: string): D1PreparedStatement[] {
+  return [
+    env.DB.prepare("DELETE FROM sessions WHERE user_id = ?").bind(userId),
+    env.DB.prepare("DELETE FROM pending_logins WHERE user_id = ?").bind(userId),
+    env.DB.prepare(
+      "UPDATE refresh_tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL",
+    ).bind(now(), userId),
+  ];
+}
+
+export async function deleteUser(env: Env, id: string): Promise<void> {
+  await env.DB.prepare("DELETE FROM users WHERE id = ?").bind(id).run();
+}
+
+export async function setUserGroups(env: Env, userId: string, groups: string[]): Promise<void> {
+  await env.DB.batch([
+    env.DB.prepare("DELETE FROM user_groups WHERE user_id = ?").bind(userId),
+    ...groups.map((g) =>
+      env.DB.prepare(
+        "INSERT OR IGNORE INTO user_groups (user_id, group_name) SELECT ?, name FROM groups WHERE name = ?",
+      ).bind(userId, g),
+    ),
+  ]);
+}
diff --git a/src/env.ts b/src/env.ts
new file mode 100644
index 0000000..35de4b7
--- /dev/null
+++ b/src/env.ts
@@ -0,0 +1,85 @@
+/* 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";
+
+export interface Env {
+  DB: D1Database;
+  ISSUER: string;
+  SITE_NAME: string;
+  KEY_ENCRYPTION_KEY: string;
+  SETUP_TOKEN?: string;
+}
+
+export interface SessionInfo {
+  idHash: string;
+  userId: string;
+  csrf: string;
+  authTime: number;
+  amr: string[];
+}
+
+export interface CurrentUser {
+  id: string;
+  username: string;
+  name: string | null;
+  email: string | null;
+  picture: string | null;
+  groups: string[];
+  isAdmin: boolean;
+}
+
+export type AppEnv = {
+  Bindings: Env;
+  Variables: {
+    session: SessionInfo | null;
+    user: CurrentUser | null;
+  };
+};
+
+export type AppContext = Context<AppEnv>;
+
+/** Members of this group can use /admin. */
+export const ADMIN_GROUP = "auth-admin";
+
+export const TTL = {
+  session: 60 * 60 * 24 * 14,
+  pendingLogin: 60 * 10,
+  challenge: 60 * 5,
+  authCode: 60,
+  accessToken: 60 * 60,
+  idToken: 60 * 60,
+  refreshToken: 60 * 60 * 24 * 30,
+  /** Changing sign-in methods or using /admin needs a sign-in this recent. */
+  recentAuth: 60 * 30,
+  /** Retired signing keys stay in the JWKS this long so issued tokens verify. */
+  retiredKey: 60 * 60 * 24 * 2,
+} as const;
+
+export function issuer(env: Env): string {
+  return env.ISSUER.replace(/\/+$/, "");
+}
+
+export function issuerOrigin(env: Env): string {
+  return new URL(issuer(env)).origin;
+}
+
+/** WebAuthn relying party id: the issuer's hostname. */
+export function rpId(env: Env): string {
+  return new URL(issuer(env)).hostname;
+}
+
+export function isSecure(env: Env): boolean {
+  return new URL(issuer(env)).protocol === "https:";
+}
+
+export function siteName(env: Env): string {
+  return env.SITE_NAME || "Sign in";
+}
+
+export function now(): number {
+  return Math.floor(Date.now() / 1000);
+}
diff --git a/src/lib/audit.ts b/src/lib/audit.ts
new file mode 100644
index 0000000..e49b19e
--- /dev/null
+++ b/src/lib/audit.ts
@@ -0,0 +1,48 @@
+/* src/lib/audit.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, type AppContext } from "../env";
+import { clientIp } from "./http";
+
+export interface AuditEntry {
+  id: number;
+  at: number;
+  actor_id: string | null;
+  actor_username: string | null;
+  action: string;
+  target: string | null;
+  ip: string | null;
+  detail: string | null;
+}
+
+export async function audit(
+  c: AppContext,
+  action: string,
+  opts: { actor?: string | null; target?: string | null; detail?: string | null } = {},
+): Promise<void> {
+  const actor = opts.actor === undefined ? (c.get("user")?.id ?? null) : opts.actor;
+  try {
+    await c.env.DB.prepare(
+      "INSERT INTO audit_log (at, actor_id, action, target, ip, detail) VALUES (?, ?, ?, ?, ?, ?)",
+    )
+      .bind(now(), actor, action, opts.target ?? null, clientIp(c), opts.detail ?? null)
+      .run();
+  } catch (err) {
+    // Never let a logging failure break a sign-in.
+    console.error("[audit] write failed", action, err);
+  }
+}
+
+export async function recentAudit(c: AppContext, limit = 200): Promise<AuditEntry[]> {
+  const { results } = await c.env.DB.prepare(
+    `SELECT a.*, u.username AS actor_username
+     FROM audit_log a LEFT JOIN users u ON u.id = a.actor_id
+     ORDER BY a.id DESC LIMIT ?`,
+  )
+    .bind(limit)
+    .all<AuditEntry>();
+  return results;
+}
diff --git a/src/lib/crypto.ts b/src/lib/crypto.ts
new file mode 100644
index 0000000..fb9fb06
--- /dev/null
+++ b/src/lib/crypto.ts
@@ -0,0 +1,95 @@
+/* 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.
+ */
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+export function b64url(bytes: Uint8Array | ArrayBuffer): string {
+  const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
+  let binary = "";
+  for (const b of view) binary += String.fromCharCode(b);
+  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+export function fromB64url(input: string): Uint8Array<ArrayBuffer> {
+  const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
+  const padded = b64 + "=".repeat((4 - (b64.length % 4)) % 4);
+  const binary = atob(padded);
+  const out = new Uint8Array(binary.length);
+  for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
+  return out;
+}
+
+export function utf8(input: string): Uint8Array<ArrayBuffer> {
+  return new Uint8Array(encoder.encode(input));
+}
+
+export function fromUtf8(input: Uint8Array): string {
+  return decoder.decode(input);
+}
+
+export function randomBytes(length: number): Uint8Array<ArrayBuffer> {
+  return crypto.getRandomValues(new Uint8Array(length));
+}
+
+/** A URL-safe random secret. 32 bytes = 256 bits. */
+export function randomToken(bytes = 32): string {
+  return b64url(randomBytes(bytes));
+}
+
+export async function sha256(input: string | Uint8Array<ArrayBuffer>): Promise<Uint8Array<ArrayBuffer>> {
+  const data = typeof input === "string" ? utf8(input) : input;
+  return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
+}
+
+export async function sha256Hex(input: string): Promise<string> {
+  return [...(await sha256(input))].map((b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+export function timingSafeEqual(a: Uint8Array<ArrayBuffer>, b: Uint8Array<ArrayBuffer>): boolean {
+  if (a.byteLength !== b.byteLength) return false;
+  return crypto.subtle.timingSafeEqual(a, b);
+}
+
+export function timingSafeEqualStr(a: string, b: string): boolean {
+  return timingSafeEqual(utf8(a), utf8(b));
+}
+
+// --- encryption at rest ------------------------------------------------------
+// AES-256-GCM, keyed off KEY_ENCRYPTION_KEY. Stored as `v1.<iv>.<ciphertext>`.
+
+const aesKeys = new Map<string, Promise<CryptoKey>>();
+
+function aesKey(secret: string): Promise<CryptoKey> {
+  if (!secret || secret.length < 32) {
+    throw new Error("KEY_ENCRYPTION_KEY is missing or shorter than 32 characters");
+  }
+  let key = aesKeys.get(secret);
+  if (!key) {
+    key = sha256(secret).then((raw) =>
+      crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]),
+    );
+    aesKeys.set(secret, key);
+  }
+  return key;
+}
+
+export async function encrypt(secret: string, plaintext: string): Promise<string> {
+  const iv = randomBytes(12);
+  const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await aesKey(secret), utf8(plaintext));
+  return `v1.${b64url(iv)}.${b64url(ct)}`;
+}
+
+export async function decrypt(secret: string, sealed: string): Promise<string> {
+  const [version, iv, ct] = sealed.split(".");
+  if (version !== "v1" || !iv || !ct) throw new Error("unrecognised ciphertext");
+  const pt = await crypto.subtle.decrypt(
+    { name: "AES-GCM", iv: fromB64url(iv) },
+    await aesKey(secret),
+    fromB64url(ct),
+  );
+  return fromUtf8(new Uint8Array(pt));
+}
diff --git a/src/lib/guards.tsx b/src/lib/guards.tsx
new file mode 100644
index 0000000..a8c4742
--- /dev/null
+++ b/src/lib/guards.tsx
@@ -0,0 +1,100 @@
+/* src/lib/guards.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 { createMiddleware } from "hono/factory";
+import { TTL, issuerOrigin, now, type AppContext, type AppEnv } from "../env";
+import { timingSafeEqualStr } from "./crypto";
+import { form, safeReturn } from "./http";
+import { render } from "../views/layout";
+
+function wantsJson(c: AppContext): boolean {
+  return (c.req.header("content-type") ?? "").includes("application/json");
+}
+
+function loginUrl(returnTo: string, reauth = false): string {
+  const params = new URLSearchParams({ return: returnTo });
+  if (reauth) params.set("reauth", "1");
+  return `/login?${params}`;
+}
+
+/** Where to come back to after signing in: the page, or for a POST, the page it came from. */
+function returnTarget(c: AppContext, fallback: string): string {
+  if (c.req.method === "GET") {
+    const url = new URL(c.req.url);
+    return url.pathname + url.search;
+  }
+  // Referrer-Policy is same-origin, so a Referer here is one of our own pages.
+  try {
+    const referer = new URL(c.req.header("referer") ?? "");
+    if (referer.origin === issuerOrigin(c.env)) return safeReturn(referer.pathname + referer.search, fallback);
+  } catch {
+    // no usable referer
+  }
+  return fallback;
+}
+
+export const requireUser = createMiddleware<AppEnv>(async (c, next) => {
+  if (!c.get("user")) {
+    if (wantsJson(c)) return c.json({ error: "Your session ended. Sign in again." }, 401);
+    return c.redirect(loginUrl(returnTarget(c, "/account")));
+  }
+  await next();
+});
+
+export const requireAdmin = createMiddleware<AppEnv>(async (c, next) => {
+  if (!c.get("user")?.isAdmin) {
+    return render(
+      c,
+      { title: "Not allowed", narrow: true, status: 403 },
+      <div class="card">
+        <h1>Admins only</h1>
+        <p class="muted">Your account isn't in the admin group for this server.</p>
+        <p>
+          <a href="/account">Back to your account</a>
+        </p>
+      </div>,
+    );
+  }
+  await next();
+});
+
+/**
+ * Every state-changing request from a signed-in page carries the session's
+ * CSRF token, either as a `_csrf` form field or an `x-csrf-token` header.
+ */
+export const requireCsrf = createMiddleware<AppEnv>(async (c, next) => {
+  if (c.req.method === "POST") {
+    const session = c.get("session");
+    const sent = wantsJson(c) ? c.req.header("x-csrf-token") : (await form(c))._csrf;
+    if (!session || !sent || !timingSafeEqualStr(sent, session.csrf)) {
+      if (wantsJson(c)) return c.json({ error: "This page is out of date. Reload and try again." }, 403);
+      return c.text("This form is out of date. Go back, reload the page and try again.", 403);
+    }
+  }
+  await next();
+});
+
+/**
+ * Changing how an account signs in (or anything in /admin) needs a recent
+ * sign-in, so a session lifted from an unlocked machine can't be used to lock
+ * the owner out.
+ */
+export function recentAuthRedirect(c: AppContext, returnTo: string): Response | null {
+  const session = c.get("session");
+  if (session && now() - session.authTime <= TTL.recentAuth) return null;
+  const url = loginUrl(returnTarget(c, returnTo), true);
+  if (wantsJson(c)) return c.json({ error: "Please confirm it's you.", reauth: url }, 401);
+  return c.redirect(url);
+}
+
+export const requireRecentAuthForPosts = (returnTo: string) =>
+  createMiddleware<AppEnv>(async (c, next) => {
+    if (c.req.method === "POST") {
+      const redirect = recentAuthRedirect(c, returnTo);
+      if (redirect) return redirect;
+    }
+    await next();
+  });
diff --git a/src/lib/http.ts b/src/lib/http.ts
new file mode 100644
index 0000000..89d1ad3
Binary files /dev/null and b/src/lib/http.ts differ
diff --git a/src/lib/password.ts b/src/lib/password.ts
new file mode 100644
index 0000000..cee58db
--- /dev/null
+++ b/src/lib/password.ts
@@ -0,0 +1,64 @@
+/* src/lib/password.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 { b64url, fromB64url, randomBytes, timingSafeEqual, utf8 } from "./crypto";
+
+// Sized for the Workers free plan's 10ms CPU budget per request (100k, the
+// Workers maximum, costs ~10ms on its own). The count is stored with each hash
+// and older hashes are upgraded on sign-in, so this can be raised to 100_000
+// after moving to a paid plan.
+const ITERATIONS = 40_000;
+const SCHEME = "pbkdf2-sha256";
+
+export const PASSWORD_MIN = 10;
+export const PASSWORD_MAX = 512;
+
+async function derive(password: string, salt: Uint8Array<ArrayBuffer>, iterations: number) {
+  const key = await crypto.subtle.importKey("raw", utf8(password), "PBKDF2", false, ["deriveBits"]);
+  const bits = await crypto.subtle.deriveBits(
+    { name: "PBKDF2", hash: "SHA-256", salt, iterations },
+    key,
+    256,
+  );
+  return new Uint8Array(bits);
+}
+
+export async function hashPassword(password: string): Promise<string> {
+  const salt = randomBytes(16);
+  const hash = await derive(password, salt, ITERATIONS);
+  return `${SCHEME}$${ITERATIONS}$${b64url(salt)}$${b64url(hash)}`;
+}
+
+export async function verifyPassword(password: string, stored: string): Promise<boolean> {
+  const [scheme, iter, salt, hash] = stored.split("$");
+  const iterations = Number(iter);
+  if (scheme !== SCHEME || !salt || !hash || !Number.isInteger(iterations) || iterations < 1) {
+    return false;
+  }
+  const actual = await derive(password, fromB64url(salt), iterations);
+  return timingSafeEqual(actual, fromB64url(hash));
+}
+
+/** True when a hash was made with fewer iterations than we use now. */
+export function needsRehash(stored: string): boolean {
+  return Number(stored.split("$")[1]) < ITERATIONS;
+}
+
+// Burned on unknown usernames so response timing doesn't reveal which exist.
+const DUMMY = `${SCHEME}$${ITERATIONS}$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`;
+
+export async function burnPasswordCheck(password: string): Promise<void> {
+  await verifyPassword(password, DUMMY);
+}
+
+export function passwordProblem(password: string, username: string): string | null {
+  if (password.length < PASSWORD_MIN) return `Passwords need at least ${PASSWORD_MIN} characters.`;
+  if (password.length > PASSWORD_MAX) return `Passwords can be at most ${PASSWORD_MAX} characters.`;
+  if (password.toLowerCase().includes(username.toLowerCase())) {
+    return "Passwords can't contain your username.";
+  }
+  return null;
+}
diff --git a/src/lib/ratelimit.ts b/src/lib/ratelimit.ts
new file mode 100644
index 0000000..1b7cc28
--- /dev/null
+++ b/src/lib/ratelimit.ts
@@ -0,0 +1,36 @@
+/* src/lib/ratelimit.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, type Env } from "../env";
+
+/**
+ * Counts one attempt against `key` in a fixed window and reports whether it is
+ * still within `limit`. The upsert is a single statement, so parallel requests
+ * can't slip past the limit together.
+ */
+export async function attempt(
+  env: Env,
+  key: string,
+  limit: number,
+  windowSeconds: number,
+): Promise<boolean> {
+  const ts = now();
+  const stale = ts - windowSeconds;
+  const row = await env.DB.prepare(
+    `INSERT INTO rate_limits (key, count, window_start) VALUES (?1, 1, ?2)
+     ON CONFLICT (key) DO UPDATE SET
+       count        = CASE WHEN window_start <= ?3 THEN 1 ELSE count + 1 END,
+       window_start = CASE WHEN window_start <= ?3 THEN ?2 ELSE window_start END
+     RETURNING count`,
+  )
+    .bind(key, ts, stale)
+    .first<{ count: number }>();
+  return (row?.count ?? 1) <= limit;
+}
+
+export async function clearAttempts(env: Env, key: string): Promise<void> {
+  await env.DB.prepare("DELETE FROM rate_limits WHERE key = ?").bind(key).run();
+}
diff --git a/src/lib/totp.ts b/src/lib/totp.ts
new file mode 100644
index 0000000..4357c73
--- /dev/null
+++ b/src/lib/totp.ts
@@ -0,0 +1,104 @@
+/* src/lib/totp.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 { randomBytes } from "./crypto";
+
+// RFC 6238: SHA-1, 6 digits, 30 second steps — what every authenticator app
+// supports without asking.
+const STEP = 30;
+const DIGITS = 6;
+const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
+
+export function base32Encode(bytes: Uint8Array): string {
+  let bits = 0;
+  let value = 0;
+  let out = "";
+  for (const byte of bytes) {
+    value = (value << 8) | byte;
+    bits += 8;
+    while (bits >= 5) {
+      out += ALPHABET[(value >>> (bits - 5)) & 31];
+      bits -= 5;
+    }
+  }
+  if (bits > 0) out += ALPHABET[(value << (5 - bits)) & 31];
+  return out;
+}
+
+export function base32Decode(input: string): Uint8Array<ArrayBuffer> {
+  const clean = input.toUpperCase().replace(/[\s=]/g, "");
+  const out: number[] = [];
+  let bits = 0;
+  let value = 0;
+  for (const char of clean) {
+    const idx = ALPHABET.indexOf(char);
+    if (idx === -1) throw new Error("invalid base32");
+    value = (value << 5) | idx;
+    bits += 5;
+    if (bits >= 8) {
+      out.push((value >>> (bits - 8)) & 255);
+      bits -= 8;
+    }
+  }
+  return new Uint8Array(out);
+}
+
+export function generateTotpSecret(): string {
+  return base32Encode(randomBytes(20));
+}
+
+async function codeAt(key: CryptoKey, step: number): Promise<string> {
+  const counter = new Uint8Array(8);
+  new DataView(counter.buffer).setBigUint64(0, BigInt(step));
+  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, counter));
+  const offset = mac[mac.length - 1]! & 0x0f;
+  const binary =
+    ((mac[offset]! & 0x7f) << 24) |
+    (mac[offset + 1]! << 16) |
+    (mac[offset + 2]! << 8) |
+    mac[offset + 3]!;
+  return String(binary % 10 ** DIGITS).padStart(DIGITS, "0");
+}
+
+/**
+ * Checks `code` against the current step and one either side for clock drift.
+ * Returns the matching step, which callers must persist and refuse to accept
+ * again (or anything before it) so a code can't be replayed.
+ */
+export async function verifyTotp(
+  secret: string,
+  code: string,
+  lastStep: number,
+): Promise<number | null> {
+  const digits = code.replace(/\s/g, "");
+  if (!/^\d{6}$/.test(digits)) return null;
+
+  const key = await crypto.subtle.importKey(
+    "raw",
+    base32Decode(secret),
+    { name: "HMAC", hash: "SHA-1" },
+    false,
+    ["sign"],
+  );
+  const current = Math.floor(Date.now() / 1000 / STEP);
+  for (const step of [current - 1, current, current + 1]) {
+    if (step <= lastStep) continue;
+    if ((await codeAt(key, step)) === digits) return step;
+  }
+  return null;
+}
+
+export function otpauthUri(secret: string, issuerName: string, account: string): string {
+  const label = encodeURIComponent(`${issuerName}:${account}`);
+  const params = new URLSearchParams({
+    secret,
+    issuer: issuerName,
+    algorithm: "SHA1",
+    digits: String(DIGITS),
+    period: String(STEP),
+  });
+  return `otpauth://totp/${label}?${params}`;
+}
diff --git a/src/lib/validate.ts b/src/lib/validate.ts
new file mode 100644
index 0000000..74a8650
--- /dev/null
+++ b/src/lib/validate.ts
@@ -0,0 +1,89 @@
+/* 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.
+ */
+
+// Lowercase, 1–32 chars, no leading/trailing punctuation. Apps use usernames
+// as mailbox names and URL slugs, so they stay boring on purpose.
+const USERNAME = /^[a-z0-9](?:[a-z0-9._-]{0,30}[a-z0-9])?$/;
+
+// Must fit a 64 byte WebAuthn user handle.
+const SUBJECT = /^[A-Za-z0-9._:@-]{1,64}$/;
+
+const GROUP = /^[a-z0-9][a-z0-9_-]{0,63}$/;
+
+const CLIENT_ID = /^[A-Za-z0-9._-]{3,128}$/;
+
+const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+export function normaliseUsername(input: string | undefined): string {
+  return (input ?? "").trim().toLowerCase();
+}
+
+export function usernameProblem(username: string): string | null {
+  return USERNAME.test(username)
+    ? null
+    : "Usernames are 1–32 lowercase letters, digits, dots, dashes or underscores, starting and ending with a letter or digit.";
+}
+
+export function subjectProblem(subject: string): string | null {
+  return SUBJECT.test(subject)
+    ? null
+    : "Subject ids are 1–64 letters, digits or . _ : @ - characters.";
+}
+
+export function groupProblem(name: string): string | null {
+  return GROUP.test(name)
+    ? null
+    : "Group names are 1–64 lowercase letters, digits, dashes or underscores.";
+}
+
+export function clientIdProblem(id: string): string | null {
+  return CLIENT_ID.test(id)
+    ? null
+    : "Client ids are 3–128 letters, digits, dots, dashes or underscores.";
+}
+
+export function cleanText(input: string | undefined, max: number): string | null {
+  const value = (input ?? "").trim();
+  if (!value) return null;
+  return value.slice(0, max);
+}
+
+export function emailProblem(email: string | null): string | null {
+  if (email === null) return null;
+  return email.length <= 254 && EMAIL.test(email) ? null : "That email address doesn't look right.";
+}
+
+export function pictureProblem(url: string | null): string | null {
+  if (url === null) return null;
+  try {
+    const parsed = new URL(url);
+    if (parsed.protocol !== "https:") return "Picture URLs must use https.";
+    return url.length <= 2048 ? null : "That picture URL is too long.";
+  } catch {
+    return "That picture URL isn't a valid URL.";
+  }
+}
+
+function isLoopback(hostname: string): boolean {
+  return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
+}
+
+/**
+ * Redirect URIs are matched exactly, so validation only has to make sure they
+ * are absolute, have no fragment, and use https (plain http only for loopback).
+ */
+export function redirectUriProblem(uri: string): string | null {
+  let parsed: URL;
+  try {
+    parsed = new URL(uri);
+  } catch {
+    return `"${uri}" isn't an absolute URL.`;
+  }
+  if (parsed.hash || uri.includes("#")) return `"${uri}" can't contain a fragment.`;
+  if (parsed.protocol === "https:") return null;
+  if (parsed.protocol === "http:" && isLoopback(parsed.hostname)) return null;
+  return `"${uri}" must use https (http is only allowed for localhost).`;
+}
diff --git a/src/main.ts b/src/main.ts
new file mode 100644
index 0000000..51f88d6
--- /dev/null
+++ b/src/main.ts
@@ -0,0 +1,85 @@
+/* src/main.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 { isSecure, issuerOrigin, type AppEnv, type Env } from "./env";
+import { loadSession } from "./data/sessions";
+import { sweepExpired } from "./data/cleanup";
+import { oidc } from "./oidc/endpoints";
+import { login } from "./routes/login";
+import { setup } from "./routes/setup";
+import { account } from "./routes/account";
+import { admin } from "./routes/admin";
+
+const app = new Hono<AppEnv>();
+
+// Protocol endpoints that other sites legitimately POST to. They don't act on
+// the browser's session cookie (or, for /end-session, confirm first).
+const CROSS_ORIGIN_POSTS = new Set(["/token", "/revoke", "/userinfo", "/end-session", "/authorize"]);
+
+app.use("*", async (c, next) => {
+  const url = new URL(c.req.url);
+  const origin = issuerOrigin(c.env);
+
+  // Passkeys and cookies are bound to the issuer's hostname, so anything
+  // arriving on another host (e.g. the workers.dev URL) is sent there.
+  if (url.origin !== origin) {
+    if (c.req.method === "GET" || c.req.method === "HEAD") {
+      return c.redirect(origin + url.pathname + url.search, 308);
+    }
+    return c.text("Use " + origin, 421);
+  }
+
+  // CSRF, layer one: browsers label every cross-site request with Origin or
+  // Sec-Fetch-Site, so state-changing requests from elsewhere are refused.
+  // Session-bound forms additionally carry a CSRF token (lib/guards).
+  const safe = c.req.method === "GET" || c.req.method === "HEAD" || c.req.method === "OPTIONS";
+  if (!safe && !CROSS_ORIGIN_POSTS.has(url.pathname)) {
+    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;
+  h.set(
+    "Content-Security-Policy",
+    "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' https: data:; connect-src '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("Permissions-Policy", "publickey-credentials-get=(self), publickey-credentials-create=(self)");
+  h.set("Cross-Origin-Opener-Policy", "same-origin");
+  if (isSecure(c.env)) h.set("Strict-Transport-Security", "max-age=63072000; includeSubDomains");
+  if (!h.has("Cache-Control")) h.set("Cache-Control", "no-store");
+});
+
+app.get("/", (c) => c.redirect(c.get("user") ? "/account" : "/login"));
+
+app.route("/", oidc);
+app.route("/", login);
+app.route("/", setup);
+app.route("/", account);
+app.route("/", admin);
+
+app.notFound((c) => c.text("Not found", 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);
+});
+
+export default {
+  fetch: app.fetch,
+  async scheduled(_event: ScheduledController, env: Env, ctx: ExecutionContext) {
+    ctx.waitUntil(sweepExpired(env));
+  },
+} satisfies ExportedHandler<Env>;
diff --git a/src/oidc/endpoints.tsx b/src/oidc/endpoints.tsx
new file mode 100644
index 0000000..31dc057
--- /dev/null
+++ b/src/oidc/endpoints.tsx
@@ -0,0 +1,542 @@
+/* src/oidc/endpoints.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 { cors } from "hono/cors";
+import { TTL, issuer, now, type AppContext, type AppEnv } from "../env";
+import { audit } from "../lib/audit";
+import { b64url, randomToken, sha256, sha256Hex, timingSafeEqualStr } from "../lib/crypto";
+import { form } from "../lib/http";
+import { clientAllows, getClient, verifyClientSecret, type Client } from "../data/clients";
+import { publicJwks } from "../data/keys";
+import { endSession } from "../data/sessions";
+import { getUser, groupsFor } from "../data/users";
+import { render } from "../views/layout";
+import { Csrf } from "../views/ui";
+import {
+  SUPPORTED_CLAIMS,
+  SUPPORTED_SCOPES,
+  issueTokens,
+  parseScope,
+  userClaims,
+  verifyAccessToken,
+  verifyIdTokenHint,
+} from "./tokens";
+
+export const oidc = new Hono<AppEnv>();
+
+// Machine-to-machine endpoints are called from other origins (including SPAs),
+// carry no cookies, and so are safe to open to any origin.
+const openCors = cors({
+  origin: "*",
+  allowMethods: ["GET", "POST", "OPTIONS"],
+  allowHeaders: ["Authorization", "Content-Type"],
+  maxAge: 86400,
+});
+for (const path of ["/.well-known/*", "/token", "/userinfo", "/revoke"]) {
+  oidc.use(path, openCors);
+}
+
+// --- discovery ----------------------------------------------------------------------
+
+oidc.get("/.well-known/openid-configuration", (c) => {
+  const iss = issuer(c.env);
+  c.header("Cache-Control", "public, max-age=300");
+  return c.json({
+    issuer: iss,
+    authorization_endpoint: `${iss}/authorize`,
+    token_endpoint: `${iss}/token`,
+    userinfo_endpoint: `${iss}/userinfo`,
+    jwks_uri: `${iss}/.well-known/jwks.json`,
+    end_session_endpoint: `${iss}/end-session`,
+    revocation_endpoint: `${iss}/revoke`,
+    scopes_supported: SUPPORTED_SCOPES,
+    claims_supported: SUPPORTED_CLAIMS,
+    response_types_supported: ["code"],
+    response_modes_supported: ["query"],
+    grant_types_supported: ["authorization_code", "refresh_token"],
+    subject_types_supported: ["public"],
+    id_token_signing_alg_values_supported: ["RS256"],
+    token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"],
+    revocation_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"],
+    code_challenge_methods_supported: ["S256"],
+    prompt_values_supported: ["none", "login"],
+    authorization_response_iss_parameter_supported: true,
+    claims_parameter_supported: false,
+    request_parameter_supported: false,
+    request_uri_parameter_supported: false,
+  });
+});
+
+oidc.get("/.well-known/jwks.json", async (c) => {
+  c.header("Cache-Control", "public, max-age=300");
+  return c.json(await publicJwks(c.env));
+});
+
+// --- authorize ------------------------------------------------------------------------
+
+function errorPage(c: AppContext, title: string, text: string, status: 400 | 403 = 400) {
+  return render(
+    c,
+    { title, narrow: true, status },
+    <div class="card">
+      <h1>{title}</h1>
+      <p class="muted">{text}</p>
+    </div>,
+  );
+}
+
+async function authorizeParams(c: AppContext): Promise<Record<string, string>> {
+  if (c.req.method === "POST") return form(c);
+  const out: Record<string, string> = {};
+  for (const [k, v] of new URL(c.req.url).searchParams) if (!(k in out)) out[k] = v;
+  return out;
+}
+
+async function authorize(c: AppContext) {
+  const params = await authorizeParams(c);
+  const iss = issuer(c.env);
+
+  // Until client and redirect_uri are both trusted, errors can only be shown
+  // here: redirecting to an unverified URI would make this an open redirector.
+  if (!params.client_id || !params.redirect_uri) {
+    return errorPage(c, "Incomplete sign-in request", "The app didn't say who it is or where to send you back to.");
+  }
+  const client = await getClient(c.env, params.client_id);
+  if (!client) {
+    return errorPage(c, "Unknown application", "The app that sent you here isn't registered with this server.");
+  }
+  if (!client.redirectUris.includes(params.redirect_uri)) {
+    return errorPage(c, "Unregistered redirect", `${client.name} asked to send you somewhere it isn't allowed to.`);
+  }
+
+  const back = (values: Record<string, string>) => {
+    const url = new URL(params.redirect_uri!);
+    for (const [k, v] of Object.entries(values)) url.searchParams.set(k, v);
+    if (params.state !== undefined) url.searchParams.set("state", params.state);
+    url.searchParams.set("iss", iss);
+    return c.redirect(url.toString());
+  };
+  const fail = (error: string, description: string) => back({ error, error_description: description });
+
+  if (params.request || params.request_uri) {
+    return fail(params.request ? "request_not_supported" : "request_uri_not_supported", "Request objects aren't supported.");
+  }
+  if (params.response_type !== "code") return fail("unsupported_response_type", "Only response_type=code is supported.");
+  if (params.response_mode && params.response_mode !== "query") {
+    return fail("invalid_request", "Only response_mode=query is supported.");
+  }
+
+  const scopes = parseScope(params.scope);
+  if (!scopes.includes("openid")) return fail("invalid_scope", "The openid scope is required.");
+
+  const challenge = params.code_challenge;
+  if (challenge) {
+    if (params.code_challenge_method !== "S256") return fail("invalid_request", "code_challenge_method must be S256.");
+    if (!/^[A-Za-z0-9_-]{43}$/.test(challenge)) return fail("invalid_request", "Malformed code_challenge.");
+  } else if (client.isPublic) {
+    return fail("invalid_request", "Public clients must use PKCE (S256).");
+  }
+  if (params.nonce && params.nonce.length > 512) return fail("invalid_request", "nonce is too long.");
+
+  const prompts = (params.prompt ?? "").split(" ").filter(Boolean);
+  if (prompts.includes("none") && prompts.length > 1) {
+    return fail("invalid_request", "prompt=none can't be combined with other values.");
+  }
+  let maxAge: number | null = null;
+  if (params.max_age !== undefined) {
+    maxAge = Number(params.max_age);
+    if (!Number.isInteger(maxAge) || maxAge < 0) return fail("invalid_request", "max_age must be a non-negative integer.");
+  }
+
+  // `_fresh` is added by us when bouncing through /login: a session that
+  // authenticated at or after that moment satisfies prompt=login / max_age.
+  const session = c.get("session");
+  const fresh = Number(params._fresh) || 0;
+  let needLogin = !session;
+  if (session && !(fresh && session.authTime >= fresh)) {
+    if (prompts.includes("login")) needLogin = true;
+    if (maxAge !== null && now() - session.authTime > maxAge) needLogin = true;
+  }
+
+  if (needLogin) {
+    if (prompts.includes("none")) return fail("login_required", "The user isn't signed in.");
+    const again = new URLSearchParams(params);
+    again.set("_fresh", String(now()));
+    const loginParams = new URLSearchParams({ return: `/authorize?${again}` });
+    if (session) loginParams.set("reauth", "1");
+    return c.redirect(`/login?${loginParams}`);
+  }
+
+  const user = await getUser(c.env, session!.userId);
+  if (!user || user.disabled) {
+    await endSession(c);
+    return fail("login_required", "The user isn't signed in.");
+  }
+
+  if (!clientAllows(client, await groupsFor(c.env, user.id))) {
+    await audit(c, "oidc.access_denied", { target: client.id });
+    if (prompts.includes("none")) return fail("access_denied", "This account isn't allowed to use this application.");
+    const denied = new URL(params.redirect_uri);
+    denied.searchParams.set("error", "access_denied");
+    if (params.state !== undefined) denied.searchParams.set("state", params.state);
+    denied.searchParams.set("iss", iss);
+    return render(
+      c,
+      { title: "No access", narrow: true, status: 403 },
+      <div class="card">
+        <h1>No access to {client.name}</h1>
+        <p class="muted">
+          You're signed in as <strong>@{user.username}</strong>, which isn't allowed to use {client.name}. If you think it should be, ask an admin.
+        </p>
+        <form method="post" action="/logout" class="stack">
+          <Csrf token={session!.csrf} />
+          <button type="submit" class="wide">Sign in as someone else</button>
+        </form>
+        <p class="small">
+          <a href={denied.toString()}>Back to {client.name}</a>
+        </p>
+      </div>,
+    );
+  }
+
+  const code = randomToken(32);
+  await c.env.DB.prepare(
+    `INSERT INTO auth_codes (code_hash, client_id, user_id, redirect_uri, scope, nonce, code_challenge, auth_time, amr, expires_at)
+     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+  )
+    .bind(
+      await sha256Hex(code),
+      client.id,
+      user.id,
+      params.redirect_uri,
+      scopes.join(" "),
+      params.nonce ?? null,
+      challenge ?? null,
+      session!.authTime,
+      JSON.stringify(session!.amr),
+      now() + TTL.authCode,
+    )
+    .run();
+
+  return back({ code });
+}
+
+oidc.get("/authorize", authorize);
+oidc.post("/authorize", authorize);
+
+// --- token --------------------------------------------------------------------------
+
+function tokenError(c: AppContext, error: string, description: string, status: 400 | 401 = 400) {
+  c.header("Cache-Control", "no-store");
+  if (status === 401) c.header("WWW-Authenticate", 'Basic realm="token"');
+  return c.json({ error, error_description: description }, status);
+}
+
+type ClientAuth = { ok: true; client: Client } | { ok: false; response: Response };
+
+/** RFC 6749 §2.3: client_secret_basic, client_secret_post, or none for public clients. */
+async function authenticateClient(c: AppContext, body: Record<string, string>): Promise<ClientAuth> {
+  const failed = (description: string, status: 400 | 401 = 401): ClientAuth => ({
+    ok: false,
+    response: tokenError(c, status === 401 ? "invalid_client" : "invalid_request", description, status),
+  });
+
+  let clientId = body.client_id;
+  let secret: string | undefined;
+  const header = c.req.header("authorization");
+
+  if (header?.startsWith("Basic ")) {
+    if (body.client_secret) return failed("Use only one client authentication method.", 400);
+    let decoded: string;
+    try {
+      decoded = atob(header.slice(6).trim());
+    } catch {
+      return failed("Malformed Basic credentials.");
+    }
+    const idx = decoded.indexOf(":");
+    if (idx === -1) return failed("Malformed Basic credentials.");
+    const formDecode = (v: string) => decodeURIComponent(v.replace(/\+/g, " "));
+    try {
+      const basicId = formDecode(decoded.slice(0, idx));
+      if (clientId && clientId !== basicId) return failed("client_id doesn't match the credentials.", 400);
+      clientId = basicId;
+      secret = formDecode(decoded.slice(idx + 1));
+    } catch {
+      return failed("Malformed Basic credentials.");
+    }
+  } else if (body.client_secret !== undefined) {
+    secret = body.client_secret;
+  }
+
+  if (!clientId) return failed("Client authentication is required.");
+  const client = await getClient(c.env, clientId);
+  if (!client) return failed("Unknown client.");
+
+  if (client.isPublic) {
+    if (secret) return failed("Public clients don't use a secret.");
+    return { ok: true, client };
+  }
+  if (!secret || !(await verifyClientSecret(client, secret))) return failed("Client authentication failed.");
+  return { ok: true, client };
+}
+
+oidc.post("/token", async (c) => {
+  const body = await form(c);
+  const auth = await authenticateClient(c, body);
+  if (!auth.ok) return auth.response;
+  const { client } = auth;
+
+  c.header("Cache-Control", "no-store");
+  c.header("Pragma", "no-cache");
+
+  if (body.grant_type === "authorization_code") {
+    if (!body.code || !body.redirect_uri) return tokenError(c, "invalid_request", "code and redirect_uri are required.");
+
+    // DELETE … RETURNING makes the code single-use even under concurrent redemption.
+    const row = await c.env.DB.prepare("DELETE FROM auth_codes WHERE code_hash = ? RETURNING *")
+      .bind(await sha256Hex(body.code))
+      .first<{
+        client_id: string;
+        user_id: string;
+        redirect_uri: string;
+        scope: string;
+        nonce: string | null;
+        code_challenge: string | null;
+        auth_time: number;
+        amr: string;
+        expires_at: number;
+      }>();
+    if (!row || row.expires_at <= now() || row.client_id !== client.id || row.redirect_uri !== body.redirect_uri) {
+      return tokenError(c, "invalid_grant", "The authorization code is invalid or expired.");
+    }
+
+    if (row.code_challenge) {
+      const verifier = body.code_verifier ?? "";
+      if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) return tokenError(c, "invalid_grant", "code_verifier is missing or malformed.");
+      if (!timingSafeEqualStr(b64url(await sha256(verifier)), row.code_challenge)) {
+        return tokenError(c, "invalid_grant", "code_verifier doesn't match.");
+      }
+    } else if (body.code_verifier) {
+      return tokenError(c, "invalid_grant", "No code_challenge was sent for this code.");
+    }
+
+    const user = await getUser(c.env, row.user_id);
+    if (!user || user.disabled || !clientAllows(client, await groupsFor(c.env, user.id))) {
+      return tokenError(c, "invalid_grant", "The account can no longer use this application.");
+    }
+
+    const scopes = row.scope.split(" ");
+    const tokens = await issueTokens(
+      c.env,
+      { clientId: client.id, user, scopes, authTime: row.auth_time, amr: JSON.parse(row.amr) as string[], nonce: row.nonce },
+      { familyId: randomToken(16) },
+    );
+    await audit(c, "oidc.token_issued", { actor: user.id, target: client.id });
+    return c.json(tokens);
+  }
+
+  if (body.grant_type === "refresh_token") {
+    if (!body.refresh_token) return tokenError(c, "invalid_request", "refresh_token is required.");
+    const hash = await sha256Hex(body.refresh_token);
+    const row = await c.env.DB.prepare("SELECT * FROM refresh_tokens WHERE token_hash = ?")
+      .bind(hash)
+      .first<{
+        family_id: string;
+        client_id: string;
+        user_id: string;
+        scope: string;
+        auth_time: number;
+        amr: string;
+        expires_at: number;
+        used_at: number | null;
+        revoked_at: number | null;
+      }>();
+    const invalid = () => tokenError(c, "invalid_grant", "The refresh token is invalid, expired or revoked.");
+    if (!row || row.client_id !== client.id || row.revoked_at || row.expires_at <= now()) return invalid();
+
+    // Rotation: each refresh token works once. Seeing one again means it was
+    // copied, so the whole family is shut down.
+    const claimed = await c.env.DB.prepare(
+      "UPDATE refresh_tokens SET used_at = ? WHERE token_hash = ? AND used_at IS NULL",
+    )
+      .bind(now(), hash)
+      .run();
+    if (claimed.meta.changes !== 1) {
+      await c.env.DB.prepare("UPDATE refresh_tokens SET revoked_at = ? WHERE family_id = ? AND revoked_at IS NULL")
+        .bind(now(), row.family_id)
+        .run();
+      await audit(c, "oidc.refresh_reuse", { actor: row.user_id, target: client.id });
+      return invalid();
+    }
+
+    const granted = row.scope.split(" ");
+    let scopes = granted;
+    if (body.scope) {
+      scopes = parseScope(body.scope);
+      if (!scopes.includes("openid") || scopes.some((s) => !granted.includes(s))) {
+        return tokenError(c, "invalid_scope", "Requested scope exceeds the original grant.");
+      }
+    }
+
+    const user = await getUser(c.env, row.user_id);
+    if (!user || user.disabled || !clientAllows(client, await groupsFor(c.env, user.id))) return invalid();
+
+    const tokens = await issueTokens(
+      c.env,
+      { clientId: client.id, user, scopes, authTime: row.auth_time, amr: JSON.parse(row.amr) as string[] },
+      { familyId: row.family_id },
+    );
+    return c.json(tokens);
+  }
+
+  return tokenError(c, "unsupported_grant_type", "Supported grants: authorization_code, refresh_token.");
+});
+
+// --- userinfo -------------------------------------------------------------------------
+
+async function userinfo(c: AppContext) {
+  const header = c.req.header("authorization");
+  let token = header?.startsWith("Bearer ") ? header.slice(7).trim() : undefined;
+  if (!token && c.req.method === "POST") token = (await form(c)).access_token;
+
+  const reject = (error: string) => {
+    c.header("WWW-Authenticate", `Bearer error="${error}"`);
+    return c.json({ error }, 401);
+  };
+  if (!token) return reject("invalid_request");
+
+  const claims = await verifyAccessToken(c.env, token);
+  if (!claims || !claims.scopes.includes("openid")) return reject("invalid_token");
+
+  const [user, client] = await Promise.all([getUser(c.env, claims.sub), getClient(c.env, claims.clientId)]);
+  if (!user || user.disabled || !client) return reject("invalid_token");
+
+  c.header("Cache-Control", "no-store");
+  return c.json(await userClaims(c.env, user, claims.scopes));
+}
+
+oidc.get("/userinfo", userinfo);
+oidc.post("/userinfo", userinfo);
+
+// --- revocation (RFC 7009) ------------------------------------------------------------
+
+oidc.post("/revoke", async (c) => {
+  const body = await form(c);
+  const auth = await authenticateClient(c, body);
+  if (!auth.ok) return auth.response;
+
+  // Access tokens are short-lived JWTs and can't be recalled; per the RFC an
+  // unknown or unsupported token still gets a 200.
+  if (body.token) {
+    const row = await c.env.DB.prepare("SELECT family_id, client_id FROM refresh_tokens WHERE token_hash = ?")
+      .bind(await sha256Hex(body.token))
+      .first<{ family_id: string; client_id: string }>();
+    if (row && row.client_id === auth.client.id) {
+      await c.env.DB.prepare("UPDATE refresh_tokens SET revoked_at = ? WHERE family_id = ? AND revoked_at IS NULL")
+        .bind(now(), row.family_id)
+        .run();
+    }
+  }
+  return c.body(null, 200);
+});
+
+// --- RP-initiated logout ------------------------------------------------------------
+
+type LogoutTarget = { ok: true; client: Client | null; returnTo: string | null } | { ok: false; response: Promise<Response> };
+
+/** Validates client_id / post_logout_redirect_uri exactly against the registration. */
+async function logoutTarget(c: AppContext, clientId: string | undefined, uri: string | undefined, state: string | undefined): Promise<LogoutTarget> {
+  const client = clientId ? await getClient(c.env, clientId) : null;
+  if (!uri) return { ok: true, client, returnTo: null };
+  if (!client || !client.postLogoutRedirectUris.includes(uri)) {
+    return {
+      ok: false,
+      response: errorPage(c, "Sign-out failed", "The app asked to send you somewhere it isn't allowed to after signing out."),
+    };
+  }
+  const url = new URL(uri);
+  if (state) url.searchParams.set("state", state);
+  return { ok: true, client, returnTo: url.toString() };
+}
+
+async function endSessionRequest(c: AppContext) {
+  const params = c.req.method === "POST" ? await form(c) : Object.fromEntries(new URL(c.req.url).searchParams);
+
+  const hint = params.id_token_hint ? await verifyIdTokenHint(c.env, params.id_token_hint) : null;
+  if (params.id_token_hint && !hint) {
+    return errorPage(c, "Sign-out failed", "The app sent a sign-out request this server couldn't verify.");
+  }
+
+  let clientId = params.client_id;
+  if (hint) {
+    if (clientId && !hint.aud.includes(clientId)) {
+      return errorPage(c, "Sign-out failed", "The sign-out request doesn't match the app that sent it.");
+    }
+    clientId ??= hint.aud[0];
+  }
+
+  const target = await logoutTarget(c, clientId, params.post_logout_redirect_uri, params.state);
+  if (!target.ok) return target.response;
+  const { client, returnTo } = target;
+
+  const session = c.get("session");
+  const user = c.get("user");
+  // A logout request without proof it came from the app is just a link anyone
+  // could send, so it gets a confirmation step instead of acting straight away.
+  if (session && user && !(hint && hint.sub === user.id)) {
+    return render(
+      c,
+      { title: "Sign out", narrow: true },
+      <div class="card">
+        <h1>Sign out?</h1>
+        <p class="muted">
+          {client ? `${client.name} wants to sign you out` : "Sign out"} of @{user.username} on this server.
+        </p>
+        <form method="post" action="/end-session/confirm" class="stack">
+          <Csrf token={session.csrf} />
+          <input type="hidden" name="client_id" value={clientId ?? ""} />
+          <input type="hidden" name="post_logout_redirect_uri" value={params.post_logout_redirect_uri ?? ""} />
+          <input type="hidden" name="state" value={params.state ?? ""} />
+          <button type="submit" class="primary wide">Sign out</button>
+        </form>
+        {returnTo && (
+          <p class="small">
+            <a href={returnTo}>Stay signed in and go back</a>
+          </p>
+        )}
+      </div>,
+    );
+  }
+
+  if (session) {
+    await audit(c, "logout.rp", { target: client?.id ?? null });
+    await endSession(c);
+  }
+  return c.redirect(returnTo ?? "/login?m=signed-out");
+}
+
+oidc.get("/end-session", endSessionRequest);
+oidc.post("/end-session", endSessionRequest);
+
+oidc.post("/end-session/confirm", async (c) => {
+  const session = c.get("session");
+  const body = await form(c);
+  if (session) {
+    if (!body._csrf || !timingSafeEqualStr(body._csrf, session.csrf)) {
+      return c.text("This form is out of date. Go back, reload the page and try again.", 403);
+    }
+  }
+
+  const target = await logoutTarget(c, body.client_id || undefined, body.post_logout_redirect_uri || undefined, body.state || undefined);
+  if (!target.ok) return target.response;
+
+  if (session) {
+    await audit(c, "logout.rp", { target: target.client?.id ?? null });
+    await endSession(c);
+  }
+  return c.redirect(target.returnTo ?? "/login?m=signed-out");
+});
diff --git a/src/oidc/tokens.ts b/src/oidc/tokens.ts
new file mode 100644
index 0000000..1e9c9f1
--- /dev/null
+++ b/src/oidc/tokens.ts
@@ -0,0 +1,202 @@
+/* src/oidc/tokens.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 { SignJWT, compactVerify, errors, jwtVerify, type JWTPayload } from "jose";
+import { TTL, issuer, now, type Env } from "../env";
+import { b64url, randomToken, sha256, sha256Hex } from "../lib/crypto";
+import { ALG, resetJwksCache, signingKey, verificationKeys } from "../data/keys";
+import { groupsFor, type UserRow } from "../data/users";
+
+export const SUPPORTED_SCOPES = ["openid", "profile", "email", "groups", "offline_access"] as const;
+
+export const SUPPORTED_CLAIMS = [
+  "sub",
+  "iss",
+  "aud",
+  "exp",
+  "iat",
+  "auth_time",
+  "nonce",
+  "amr",
+  "at_hash",
+  "name",
+  "preferred_username",
+  "picture",
+  "updated_at",
+  "email",
+  "email_verified",
+  "groups",
+];
+
+/** Keeps the scopes we know, in a stable order, without duplicates. */
+export function parseScope(raw: string | undefined): string[] {
+  const asked = new Set((raw ?? "").split(" ").filter(Boolean));
+  return SUPPORTED_SCOPES.filter((s) => asked.has(s));
+}
+
+export async function userClaims(env: Env, user: UserRow, scopes: string[]): Promise<Record<string, unknown>> {
+  const claims: Record<string, unknown> = { sub: user.id };
+  if (scopes.includes("profile")) {
+    claims.name = user.name ?? user.username;
+    claims.preferred_username = user.username;
+    if (user.picture) claims.picture = user.picture;
+    claims.updated_at = user.updated_at;
+  }
+  if (scopes.includes("email") && user.email) {
+    claims.email = user.email;
+    claims.email_verified = user.email_verified === 1;
+  }
+  if (scopes.includes("groups")) {
+    claims.groups = await groupsFor(env, user.id);
+  }
+  return claims;
+}
+
+export interface Grant {
+  clientId: string;
+  user: UserRow;
+  scopes: string[];
+  authTime: number;
+  amr: string[];
+  nonce?: string | null;
+}
+
+export interface TokenResponse {
+  access_token: string;
+  token_type: "Bearer";
+  expires_in: number;
+  id_token: string;
+  scope: string;
+  refresh_token?: string;
+}
+
+async function atHash(accessToken: string): Promise<string> {
+  const digest = await sha256(accessToken);
+  return b64url(digest.slice(0, digest.length / 2));
+}
+
+export async function issueTokens(
+  env: Env,
+  grant: Grant,
+  refresh: { familyId: string } | null,
+): Promise<TokenResponse> {
+  const { kid, key } = await signingKey(env);
+  const iss = issuer(env);
+  const iat = now();
+
+  const accessToken = await new SignJWT({
+    client_id: grant.clientId,
+    scope: grant.scopes.join(" "),
+  })
+    .setProtectedHeader({ alg: ALG, kid, typ: "at+jwt" })
+    .setIssuer(iss)
+    .setSubject(grant.user.id)
+    .setAudience(grant.clientId)
+    .setJti(randomToken(16))
+    .setIssuedAt(iat)
+    .setExpirationTime(iat + TTL.accessToken)
+    .sign(key);
+
+  const idClaims: JWTPayload = {
+    ...(await userClaims(env, grant.user, grant.scopes)),
+    auth_time: grant.authTime,
+    amr: grant.amr,
+    at_hash: await atHash(accessToken),
+  };
+  if (grant.nonce) idClaims.nonce = grant.nonce;
+
+  const idToken = await new SignJWT(idClaims)
+    .setProtectedHeader({ alg: ALG, kid, typ: "JWT" })
+    .setIssuer(iss)
+    .setSubject(grant.user.id)
+    .setAudience(grant.clientId)
+    .setIssuedAt(iat)
+    .setExpirationTime(iat + TTL.idToken)
+    .sign(key);
+
+  const response: TokenResponse = {
+    access_token: accessToken,
+    token_type: "Bearer",
+    expires_in: TTL.accessToken,
+    id_token: idToken,
+    scope: grant.scopes.join(" "),
+  };
+
+  if (refresh && grant.scopes.includes("offline_access")) {
+    const token = `dssr_${randomToken(32)}`;
+    await env.DB.prepare(
+      `INSERT INTO refresh_tokens (token_hash, family_id, client_id, user_id, scope, auth_time, amr, created_at, expires_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+      .bind(
+        await sha256Hex(token),
+        refresh.familyId,
+        grant.clientId,
+        grant.user.id,
+        grant.scopes.join(" "),
+        grant.authTime,
+        JSON.stringify(grant.amr),
+        iat,
+        iat + TTL.refreshToken,
+      )
+      .run();
+    response.refresh_token = token;
+  }
+
+  return response;
+}
+
+/**
+ * Verifies a token we signed. A key rotated in another isolate may not be in
+ * this isolate's cached JWKS yet, so a missing key triggers one refetch.
+ */
+async function withKeys<T>(env: Env, fn: (keys: Awaited<ReturnType<typeof verificationKeys>>) => Promise<T>): Promise<T> {
+  try {
+    return await fn(await verificationKeys(env));
+  } catch (err) {
+    if (!(err instanceof errors.JWKSNoMatchingKey)) throw err;
+    resetJwksCache();
+    return fn(await verificationKeys(env));
+  }
+}
+
+export interface AccessTokenClaims {
+  sub: string;
+  clientId: string;
+  scopes: string[];
+}
+
+export async function verifyAccessToken(env: Env, token: string): Promise<AccessTokenClaims | null> {
+  try {
+    const { payload } = await withKeys(env, (keys) =>
+      jwtVerify(token, keys, { issuer: issuer(env), typ: "at+jwt", algorithms: [ALG] }),
+    );
+    if (typeof payload.sub !== "string" || typeof payload.client_id !== "string") return null;
+    return {
+      sub: payload.sub,
+      clientId: payload.client_id,
+      scopes: typeof payload.scope === "string" ? payload.scope.split(" ") : [],
+    };
+  } catch {
+    return null;
+  }
+}
+
+/**
+ * id_token_hint for logout: the signature and issuer must check out, but an
+ * expired token is still a perfectly good hint.
+ */
+export async function verifyIdTokenHint(env: Env, token: string): Promise<{ sub: string; aud: string[] } | null> {
+  try {
+    const { payload } = await withKeys(env, (keys) => compactVerify(token, keys, { algorithms: [ALG] }));
+    const claims = JSON.parse(new TextDecoder().decode(payload)) as JWTPayload;
+    if (claims.iss !== issuer(env) || typeof claims.sub !== "string") return null;
+    const aud = Array.isArray(claims.aud) ? claims.aud : claims.aud ? [claims.aud] : [];
+    return { sub: claims.sub, aud };
+  } catch {
+    return null;
+  }
+}
diff --git a/src/routes/account.tsx b/src/routes/account.tsx
new file mode 100644
index 0000000..4498af8
--- /dev/null
+++ b/src/routes/account.tsx
@@ -0,0 +1,431 @@
+/* src/routes/account.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 { renderSVG } from "uqr";
+import type { RegistrationResponseJSON } from "@simplewebauthn/server";
+import { TTL, now, siteName, type AppContext, type AppEnv } from "../env";
+import { audit } from "../lib/audit";
+import { decrypt, encrypt } from "../lib/crypto";
+import { form, readJson } from "../lib/http";
+import { recentAuthRedirect, requireCsrf, requireUser } from "../lib/guards";
+import { hashPassword, passwordProblem, PASSWORD_MIN } from "../lib/password";
+import { generateTotpSecret, otpauthUri, verifyTotp } from "../lib/totp";
+import { cleanText, emailProblem, pictureProblem } from "../lib/validate";
+import {
+  countPasskeys,
+  deletePasskey,
+  finishRegistration,
+  listPasskeys,
+  registrationOptions,
+  renamePasskey,
+} from "../data/passkeys";
+import { endSession, listSessions, revokeOtherSessions, revokeSession } from "../data/sessions";
+import {
+  claimTotpStep,
+  disableTotp,
+  enableTotp,
+  getUser,
+  setPasswordHash,
+  setTotpPending,
+  updateProfile,
+  type UserRow,
+} from "../data/users";
+import { render } from "../views/layout";
+import { Csrf, ErrorNote, Field, Flash, Section, date, describeAgent, relative } from "../views/ui";
+
+export const account = new Hono<AppEnv>();
+
+account.use("/account", requireUser);
+account.use("/account/*", requireUser, requireCsrf);
+
+async function me(c: AppContext): Promise<UserRow> {
+  const user = await getUser(c.env, c.get("user")!.id);
+  if (!user) throw new Error("session user vanished");
+  return user;
+}
+
+function amrLabel(amr: string): string {
+  const list = JSON.parse(amr) as string[];
+  if (list.includes("swk") || list.includes("hwk")) return "passkey";
+  if (list.includes("otp") && list.includes("pwd")) return "password + code";
+  if (list.includes("pwd")) return "password";
+  if (list.includes("link")) return "sign-in link";
+  if (list.includes("setup")) return "setup";
+  return "unknown";
+}
+
+async function accountPage(c: AppContext, opts: { error?: string; status?: 400 } = {}) {
+  const user = await me(c);
+  const session = c.get("session")!;
+  const [passkeys, sessions] = await Promise.all([listPasskeys(c.env, user.id), listSessions(c.env, user.id)]);
+  const csrf = session.csrf;
+  const stale = now() - session.authTime > TTL.recentAuth;
+
+  return render(
+    c,
+    { title: "Your account", page: "account", status: opts.status },
+    <>
+      <h1>Hi, {user.name ?? user.username}</h1>
+      <Flash code={c.req.query("m")} />
+      <ErrorNote error={opts.error} />
+      <p class="notice error hidden" id="passkey-error" role="alert"></p>
+      {stale && (
+        <p class="notice">
+          You signed in {relative(session.authTime)}. Changing how you sign in will ask you to confirm it's you first.
+        </p>
+      )}
+
+      <Section title="Profile" description="Shared with the apps you sign in to.">
+        <form method="post" action="/account/profile" class="stack">
+          <Csrf token={csrf} />
+          <label class="field">
+            <span>Username</span>
+            <input type="text" value={user.username} disabled />
+            <small class="muted">Only an admin can change this.</small>
+          </label>
+          <Field label="Display name" name="name" value={user.name} autocomplete="name" maxlength={100} />
+          <Field
+            label="Email"
+            name="email"
+            type="email"
+            value={user.email}
+            autocomplete="email"
+            maxlength={254}
+            hint={user.email ? (user.email_verified ? "Verified." : "Not verified.") : undefined}
+          />
+          <Field label="Picture URL" name="picture" type="url" value={user.picture} maxlength={2048} placeholder="https://…" />
+          <div>
+            <button type="submit">Save profile</button>
+          </div>
+        </form>
+      </Section>
+
+      <Section title="Passkeys" description="The quickest and safest way to sign in: your device unlocks with a fingerprint, face or PIN.">
+        {passkeys.length === 0 ? (
+          <p class="muted">No passkeys yet.</p>
+        ) : (
+          <ul class="rows">
+            {passkeys.map((p) => (
+              <li>
+                <div class="grow">
+                  <form method="post" action={`/account/passkeys/${encodeURIComponent(p.id)}/rename`} class="inline-edit">
+                    <Csrf token={csrf} />
+                    <input type="text" name="name" value={p.name} maxlength={60} aria-label="Passkey name" required />
+                    <button type="submit" class="small">Rename</button>
+                  </form>
+                  <small class="muted">
+                    {p.device_type === "multiDevice" ? "Synced" : "This device only"} · added {date(p.created_at)} · last used{" "}
+                    {relative(p.last_used_at)}
+                  </small>
+                </div>
+                <form
+                  method="post"
+                  action={`/account/passkeys/${encodeURIComponent(p.id)}/delete`}
+                  data-confirm={`Remove the passkey "${p.name}"?`}
+                >
+                  <Csrf token={csrf} />
+                  <button type="submit" class="danger small">Remove</button>
+                </form>
+              </li>
+            ))}
+          </ul>
+        )}
+        <form id="passkey-add" class="inline-edit">
+          <input type="text" name="name" placeholder="Name, e.g. Phone" maxlength={60} aria-label="New passkey name" />
+          <button type="submit" class="primary">Add a passkey</button>
+        </form>
+      </Section>
+
+      <Section title="Password">
+        <p class="muted">
+          {user.password_hash
+            ? "You can sign in with a password."
+            : "No password set. Add one as a fallback for devices without your passkeys."}
+        </p>
+        <form method="post" action="/account/password" class="stack">
+          <Csrf token={csrf} />
+          <input type="text" name="username" value={user.username} autocomplete="username" hidden />
+          <Field
+            label={user.password_hash ? "New password" : "Password"}
+            name="password"
+            type="password"
+            required
+            autocomplete="new-password"
+            maxlength={512}
+            hint={`At least ${PASSWORD_MIN} characters. A long phrase beats a short tricky one.`}
+          />
+          <Field label="Confirm password" name="confirm" type="password" required autocomplete="new-password" maxlength={512} />
+          <div>
+            <button type="submit">{user.password_hash ? "Change password" : "Set password"}</button>
+          </div>
+        </form>
+        {user.password_hash && (
+          <form method="post" action="/account/password/remove" data-confirm="Remove your password? You'll only be able to sign in with a passkey.">
+            <Csrf token={csrf} />
+            <button type="submit" class="danger small" disabled={passkeys.length === 0}>
+              Remove password
+            </button>
+            {passkeys.length === 0 && <small class="muted"> Add a passkey first.</small>}
+          </form>
+        )}
+      </Section>
+
+      <Section title="Two-factor codes" description="Asks for a code from an authenticator app after your password. Passkey sign-ins don't need it.">
+        {!user.password_hash ? (
+          <p class="muted">Set a password first.</p>
+        ) : user.totp_secret ? (
+          <form method="post" action="/account/totp/disable" class="inline-edit">
+            <Csrf token={csrf} />
+            <span class="badge ok">On</span>
+            <input
+              type="text"
+              name="code"
+              placeholder="Current code"
+              inputmode="numeric"
+              autocomplete="one-time-code"
+              maxlength={7}
+              required
+              aria-label="Current code"
+            />
+            <button type="submit" class="danger">Turn off</button>
+          </form>
+        ) : (
+          <form method="post" action="/account/totp/start">
+            <Csrf token={csrf} />
+            <button type="submit">Set up an authenticator app</button>
+          </form>
+        )}
+      </Section>
+
+      <Section title="Sessions" description="Browsers signed in to this server. Apps you've signed in to keep their own sessions.">
+        <ul class="rows">
+          {sessions.map((s) => (
+            <li>
+              <div class="grow">
+                <strong>{describeAgent(s.user_agent)}</strong>
+                {s.id_hash === session.idHash && <span class="badge">This browser</span>}
+                <br />
+                <small class="muted">
+                  {s.ip ?? "unknown IP"} · via {amrLabel(s.amr)} · signed in {date(s.created_at)} · active {relative(s.last_seen_at)}
+                </small>
+              </div>
+              <form method="post" action={`/account/sessions/${s.id_hash}/revoke`}>
+                <Csrf token={csrf} />
+                <button type="submit" class="small">Sign out</button>
+              </form>
+            </li>
+          ))}
+        </ul>
+        {sessions.length > 1 && (
+          <form method="post" action="/account/sessions/revoke-others">
+            <Csrf token={csrf} />
+            <button type="submit" class="danger small">Sign out everywhere else</button>
+          </form>
+        )}
+      </Section>
+    </>,
+  );
+}
+
+account.get("/account", (c) => accountPage(c));
+
+account.post("/account/profile", async (c) => {
+  const body = await form(c);
+  const update = {
+    name: cleanText(body.name, 100),
+    email: cleanText(body.email, 254),
+    picture: cleanText(body.picture, 2048),
+  };
+  const problem = emailProblem(update.email) ?? pictureProblem(update.picture);
+  if (problem) return accountPage(c, { error: problem, status: 400 });
+
+  await updateProfile(c.env, await me(c), update);
+  await audit(c, "account.profile");
+  return c.redirect("/account?m=profile-saved");
+});
+
+// --- passkeys --------------------------------------------------------------------
+
+account.post("/account/passkeys/options", async (c) => {
+  const reauth = recentAuthRedirect(c, "/account");
+  if (reauth) return reauth;
+  return c.json(await registrationOptions(c.env, await me(c)));
+});
+
+account.post("/account/passkeys/verify", async (c) => {
+  const reauth = recentAuthRedirect(c, "/account");
+  if (reauth) return reauth;
+
+  const body = await readJson<{ id?: string; response?: RegistrationResponseJSON; name?: string }>(c);
+  if (!body?.id || !body.response) return c.json({ error: "Malformed request." }, 400);
+
+  const name = cleanText(body.name, 60) ?? "Passkey";
+  const result = await finishRegistration(c.env, await me(c), body.id, body.response, name);
+  if (!result.ok) return c.json({ error: result.error }, 400);
+
+  await audit(c, "account.passkey_added", { detail: name });
+  return c.json({ redirect: "/account?m=passkey-added" });
+});
+
+account.post("/account/passkeys/:id/rename", async (c) => {
+  const body = await form(c);
+  const name = cleanText(body.name, 60);
+  if (!name) return accountPage(c, { error: "Passkeys need a name.", status: 400 });
+  await renamePasskey(c.env, c.get("user")!.id, c.req.param("id"), name);
+  return c.redirect("/account?m=passkey-renamed");
+});
+
+account.post("/account/passkeys/:id/delete", async (c) => {
+  const reauth = recentAuthRedirect(c, "/account");
+  if (reauth) return reauth;
+
+  const user = await me(c);
+  if (!user.password_hash && (await countPasskeys(c.env, user.id)) <= 1) {
+    return accountPage(c, {
+      error: "That's your only way to sign in. Add another passkey or a password before removing it.",
+      status: 400,
+    });
+  }
+  await deletePasskey(c.env, user.id, c.req.param("id"));
+  await audit(c, "account.passkey_removed");
+  return c.redirect("/account?m=passkey-removed");
+});
+
+// --- password ------------------------------------------------------------------
+
+account.post("/account/password", async (c) => {
+  const reauth = recentAuthRedirect(c, "/account");
+  if (reauth) return reauth;
+
+  const user = await me(c);
+  const body = await form(c);
+  const password = body.password ?? "";
+  const problem =
+    passwordProblem(password, user.username) ??
+    (password !== body.confirm ? "The two passwords don't match." : null);
+  if (problem) return accountPage(c, { error: problem, status: 400 });
+
+  await setPasswordHash(c.env, user.id, await hashPassword(password));
+  await revokeOtherSessions(c.env, user.id, c.get("session")!.idHash);
+  await audit(c, "account.password_set");
+  return c.redirect("/account?m=password-set");
+});
+
+account.post("/account/password/remove", async (c) => {
+  const reauth = recentAuthRedirect(c, "/account");
+  if (reauth) return reauth;
+
+  const user = await me(c);
+  if ((await countPasskeys(c.env, user.id)) === 0) {
+    return accountPage(c, { error: "Add a passkey before removing your password.", status: 400 });
+  }
+  await setPasswordHash(c.env, user.id, null);
+  await audit(c, "account.password_removed");
+  return c.redirect("/account?m=password-removed");
+});
+
+// --- TOTP ----------------------------------------------------------------------
+
+account.post("/account/totp/start", async (c) => {
+  const reauth = recentAuthRedirect(c, "/account");
+  if (reauth) return reauth;
+
+  const user = await me(c);
+  if (!user.password_hash) return c.redirect("/account");
+  if (user.totp_secret) return c.redirect("/account");
+  await setTotpPending(c.env, user.id, await encrypt(c.env.KEY_ENCRYPTION_KEY, generateTotpSecret()));
+  return c.redirect("/account/totp");
+});
+
+async function totpSetupPage(c: AppContext, error?: string) {
+  const user = await me(c);
+  if (!user.totp_pending || user.totp_secret) return c.redirect("/account");
+
+  const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_pending);
+  const uri = otpauthUri(secret, siteName(c.env), user.username);
+  const svg = renderSVG(uri, { border: 2 });
+  const qr = `data:image/svg+xml,${encodeURIComponent(svg)}`;
+
+  return render(
+    c,
+    { title: "Set up two-factor codes", narrow: true, status: error ? 400 : 200 },
+    <div class="card">
+      <h1>Scan this code</h1>
+      <p class="muted">Use any authenticator app (1Password, Aegis, Google Authenticator…), then enter the code it shows.</p>
+      <ErrorNote error={error} />
+      <img class="qr" src={qr} alt="QR code for your authenticator app" width="220" height="220" />
+      <details>
+        <summary>Can't scan it?</summary>
+        <p>Enter this key instead:</p>
+        <p class="secret">
+          <code>{secret.match(/.{1,4}/g)?.join(" ")}</code>
+        </p>
+      </details>
+      <form method="post" action="/account/totp/confirm" class="stack">
+        <Csrf token={c.get("session")!.csrf} />
+        <Field label="Code" name="code" required inputmode="numeric" autocomplete="one-time-code" maxlength={7} autofocus />
+        <button type="submit" class="primary wide">Turn on</button>
+      </form>
+      <p class="small">
+        <a href="/account">Cancel</a>
+      </p>
+    </div>,
+  );
+}
+
+account.get("/account/totp", (c) => totpSetupPage(c));
+
+account.post("/account/totp/confirm", async (c) => {
+  const reauth = recentAuthRedirect(c, "/account");
+  if (reauth) return reauth;
+
+  const user = await me(c);
+  if (!user.totp_pending) return c.redirect("/account");
+
+  const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_pending);
+  const step = await verifyTotp(secret, (await form(c)).code ?? "", 0);
+  if (step === null) return totpSetupPage(c, "That code didn't match. Check your device's clock and try the next one.");
+
+  await enableTotp(c.env, user.id, user.totp_pending, step);
+  await audit(c, "account.totp_enabled");
+  return c.redirect("/account?m=totp-enabled");
+});
+
+account.post("/account/totp/disable", async (c) => {
+  const reauth = recentAuthRedirect(c, "/account");
+  if (reauth) return reauth;
+
+  const user = await me(c);
+  if (!user.totp_secret) return c.redirect("/account");
+
+  const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_secret);
+  const step = await verifyTotp(secret, (await form(c)).code ?? "", user.totp_last_step);
+  if (step === null || !(await claimTotpStep(c.env, user.id, step))) {
+    return accountPage(c, { error: "That code didn't work, so two-factor codes are still on.", status: 400 });
+  }
+  await disableTotp(c.env, user.id);
+  await audit(c, "account.totp_disabled");
+  return c.redirect("/account?m=totp-disabled");
+});
+
+// --- sessions ------------------------------------------------------------------
+
+account.post("/account/sessions/revoke-others", async (c) => {
+  await revokeOtherSessions(c.env, c.get("user")!.id, c.get("session")!.idHash);
+  await audit(c, "account.sessions_revoked");
+  return c.redirect("/account?m=sessions-revoked");
+});
+
+account.post("/account/sessions/:id/revoke", async (c) => {
+  const id = c.req.param("id");
+  if (id === c.get("session")!.idHash) {
+    await endSession(c);
+    return c.redirect("/login?m=signed-out");
+  }
+  await revokeSession(c.env, c.get("user")!.id, id);
+  return c.redirect("/account?m=session-revoked");
+});
diff --git a/src/routes/admin.tsx b/src/routes/admin.tsx
new file mode 100644
index 0000000..e164297
--- /dev/null
+++ b/src/routes/admin.tsx
@@ -0,0 +1,958 @@
+/* src/routes/admin.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 type { Child } from "hono/jsx";
+import { ADMIN_GROUP, issuer, type AppContext, type AppEnv } from "../env";
+import { audit, recentAudit } from "../lib/audit";
+import { form, formAll, lines } from "../lib/http";
+import { requireAdmin, requireCsrf, requireRecentAuthForPosts, requireUser } from "../lib/guards";
+import {
+  cleanText,
+  clientIdProblem,
+  emailProblem,
+  groupProblem,
+  normaliseUsername,
+  pictureProblem,
+  redirectUriProblem,
+  subjectProblem,
+  usernameProblem,
+} from "../lib/validate";
+import {
+  createClient,
+  deleteClient,
+  getClient,
+  listClients,
+  makeClientPublic,
+  rotateClientSecret,
+  updateClient,
+  type Client,
+  type ClientInput,
+} from "../data/clients";
+import { createGroup, deleteGroup, listGroups, updateGroup, type GroupRow } from "../data/groups";
+import { listKeys, rotateKeys } from "../data/keys";
+import { createLoginLink, hasOpenLoginLink, revokeLoginLinks } from "../data/links";
+import { deletePasskey, listPasskeys } from "../data/passkeys";
+import { listSessions } from "../data/sessions";
+import {
+  adminUpdateUser,
+  createUser,
+  deleteUser,
+  disableTotp,
+  getUser,
+  groupsFor,
+  listUsers,
+  revokeAllStatements,
+  setDisabled,
+  setPasswordHash,
+  setUserGroups,
+} from "../data/users";
+import { render } from "../views/layout";
+import { Csrf, ErrorNote, Field, Flash, Section, date, relative } from "../views/ui";
+
+export const admin = new Hono<AppEnv>();
+
+admin.use("/admin", requireUser, requireAdmin);
+admin.use("/admin/*", requireUser, requireAdmin, requireCsrf, requireRecentAuthForPosts("/admin"));
+
+admin.get("/admin", (c) => c.redirect("/admin/users"));
+
+const TABS = [
+  ["/admin/users", "Users"],
+  ["/admin/groups", "Groups"],
+  ["/admin/clients", "Applications"],
+  ["/admin/keys", "Signing keys"],
+  ["/admin/audit", "Audit log"],
+] as const;
+
+function adminPage(
+  c: AppContext,
+  opts: { title: string; tab: string; error?: string | null; status?: 400 | 404 },
+  body: Child,
+) {
+  return render(
+    c,
+    { title: opts.title, page: "admin", status: opts.status },
+    <>
+      <nav class="tabs">
+        {TABS.map(([href, label]) => (
+          <a href={href} class={opts.tab === href ? "active" : undefined}>
+            {label}
+          </a>
+        ))}
+      </nav>
+      <Flash code={c.req.query("m")} />
+      <ErrorNote error={opts.error} />
+      {body}
+    </>,
+  );
+}
+
+function csrf(c: AppContext): string {
+  return c.get("session")!.csrf;
+}
+
+function GroupChecks(props: { groups: GroupRow[]; selected: string[]; name?: string }) {
+  if (props.groups.length === 0) return <p class="muted">No groups yet.</p>;
+  return (
+    <div class="checks">
+      {props.groups.map((g) => (
+        <label class="check">
+          <input type="checkbox" name={props.name ?? "groups"} value={g.name} checked={props.selected.includes(g.name)} />
+          <span>
+            {g.name}
+            {g.description && <small class="muted"> — {g.description}</small>}
+          </span>
+        </label>
+      ))}
+    </div>
+  );
+}
+
+function notFound(c: AppContext, what: string) {
+  return adminPage(
+    c,
+    { title: "Not found", tab: "", status: 404 },
+    <p>
+      That {what} doesn't exist. <a href="/admin">Back</a>
+    </p>,
+  );
+}
+
+// --- users -----------------------------------------------------------------------
+
+async function usersPage(c: AppContext, error?: string, values: Record<string, string> = {}, chosen: string[] = []) {
+  const [users, groups] = await Promise.all([listUsers(c.env), listGroups(c.env)]);
+  return adminPage(
+    c,
+    { title: "Users", tab: "/admin/users", error, status: error ? 400 : undefined },
+    <>
+      <Section title={`Users (${users.length})`}>
+        <div class="table-wrap">
+          <table>
+            <thead>
+              <tr>
+                <th>User</th>
+                <th>Groups</th>
+                <th>Sign-in methods</th>
+                <th>Last sign-in</th>
+              </tr>
+            </thead>
+            <tbody>
+              {users.map((u) => (
+                <tr>
+                  <td>
+                    <a href={`/admin/users/${encodeURIComponent(u.id)}`}>
+                      <strong>{u.name ?? u.username}</strong>
+                    </a>
+                    <br />
+                    <small class="muted">@{u.username}</small>
+                    {u.disabled ? <span class="badge danger">disabled</span> : null}
+                  </td>
+                  <td>{u.groups.length ? u.groups.map((g) => <span class="badge">{g}</span>) : <span class="muted">—</span>}</td>
+                  <td>
+                    {u.passkey_count > 0 && <span class="badge">{u.passkey_count} passkey{u.passkey_count === 1 ? "" : "s"}</span>}
+                    {u.password_hash && <span class="badge">password{u.totp_secret ? " + 2FA" : ""}</span>}
+                    {!u.passkey_count && !u.password_hash && <span class="muted">none</span>}
+                  </td>
+                  <td>{relative(u.last_login_at)}</td>
+                </tr>
+              ))}
+            </tbody>
+          </table>
+        </div>
+      </Section>
+
+      <Section title="Add a user" description="They'll need a sign-in link from their page to set up a passkey or password.">
+        <form method="post" action="/admin/users" class="stack">
+          <Csrf token={csrf(c)} />
+          <div class="grid2">
+            <Field label="Username" name="username" value={values.username} required maxlength={32} autocomplete="off" />
+            <Field label="Display name" name="name" value={values.name} maxlength={100} autocomplete="off" />
+            <Field label="Email" name="email" type="email" value={values.email} maxlength={254} autocomplete="off" />
+            <label class="check">
+              <input type="checkbox" name="email_verified" value="1" checked={values.email_verified === "1"} />
+              <span>Email is verified</span>
+            </label>
+          </div>
+          <fieldset>
+            <legend>Groups</legend>
+            <GroupChecks groups={groups} selected={chosen} />
+          </fieldset>
+          <details>
+            <summary>Advanced</summary>
+            <Field
+              label="Subject id"
+              name="subject"
+              value={values.subject}
+              maxlength={64}
+              autocomplete="off"
+              hint="The permanent `sub` apps see. Leave blank for a random UUID. Set it to carry an account over from another identity provider without apps treating it as a new person."
+            />
+          </details>
+          <div>
+            <button type="submit" class="primary">Create user</button>
+          </div>
+        </form>
+      </Section>
+    </>,
+  );
+}
+
+admin.get("/admin/users", (c) => usersPage(c));
+
+admin.post("/admin/users", async (c) => {
+  const body = await form(c);
+  const groups = await formAll(c, "groups");
+  const username = normaliseUsername(body.username);
+  const email = cleanText(body.email, 254);
+  const subject = cleanText(body.subject, 64);
+  const problem =
+    usernameProblem(username) ?? emailProblem(email) ?? (subject ? subjectProblem(subject) : null);
+  if (problem) return usersPage(c, problem, body, groups);
+
+  const result = await createUser(c.env, {
+    id: subject ?? undefined,
+    username,
+    name: cleanText(body.name, 100),
+    email,
+    emailVerified: body.email_verified === "1",
+  });
+  if (!result.ok) return usersPage(c, result.error, body, groups);
+
+  await setUserGroups(c.env, result.id, groups);
+  await audit(c, "admin.user_created", { target: username, detail: groups.join(",") });
+  return c.redirect(`/admin/users/${encodeURIComponent(result.id)}?m=user-created`);
+});
+
+async function userPage(
+  c: AppContext,
+  id: string,
+  opts: { error?: string; link?: { url: string; expiresAt: number } } = {},
+) {
+  const user = await getUser(c.env, id);
+  if (!user) return notFound(c, "user");
+
+  const [groups, allGroups, passkeys, sessions, openLink] = await Promise.all([
+    groupsFor(c.env, id),
+    listGroups(c.env),
+    listPasskeys(c.env, id),
+    listSessions(c.env, id),
+    hasOpenLoginLink(c.env, id),
+  ]);
+  const base = `/admin/users/${encodeURIComponent(id)}`;
+  const token = csrf(c);
+  const self = c.get("user")!.id === id;
+
+  return adminPage(
+    c,
+    { title: `@${user.username}`, tab: "/admin/users", error: opts.error, status: opts.error ? 400 : undefined },
+    <>
+      <p>
+        <a href="/admin/users">← All users</a>
+      </p>
+      <h1>
+        {user.name ?? user.username} <small class="muted">@{user.username}</small>
+        {user.disabled ? <span class="badge danger">disabled</span> : null}
+      </h1>
+      <p class="muted">
+        Subject <code>{user.id}</code> · created {date(user.created_at)} · last sign-in {relative(user.last_login_at)}
+      </p>
+
+      {opts.link && (
+        <div class="notice ok">
+          <p>
+            <strong>Sign-in link</strong> — send this to @{user.username}. It works once and expires{" "}
+            {relative(opts.link.expiresAt)}. It won't be shown again.
+          </p>
+          <p class="copyrow">
+            <input type="text" readonly value={opts.link.url} aria-label="Sign-in link" />
+            <button type="button" data-copy={opts.link.url}>Copy</button>
+          </p>
+        </div>
+      )}
+
+      <Section title="Profile">
+        <form method="post" action={`${base}/profile`} class="stack">
+          <Csrf token={token} />
+          <div class="grid2">
+            <Field label="Username" name="username" value={user.username} required maxlength={32} autocomplete="off" hint="Apps may use this as a mailbox or URL; changing it can break things there." />
+            <Field label="Display name" name="name" value={user.name} maxlength={100} autocomplete="off" />
+            <Field label="Email" name="email" type="email" value={user.email} maxlength={254} autocomplete="off" />
+            <Field label="Picture URL" name="picture" type="url" value={user.picture} maxlength={2048} autocomplete="off" />
+            <label class="check">
+              <input type="checkbox" name="email_verified" value="1" checked={user.email_verified === 1} />
+              <span>Email is verified</span>
+            </label>
+          </div>
+          <div>
+            <button type="submit">Save profile</button>
+          </div>
+        </form>
+      </Section>
+
+      <Section title="Groups" description="Sent to apps in the `groups` claim, and used to limit who can open each application.">
+        <form method="post" action={`${base}/groups`} class="stack">
+          <Csrf token={token} />
+          <GroupChecks groups={allGroups} selected={groups} />
+          <div>
+            <button type="submit">Save groups</button>
+          </div>
+        </form>
+      </Section>
+
+      <Section title="Sign-in link" description="A one-time link that signs this person in so they can add a passkey or password. Use it for new accounts and lost devices.">
+        {openLink && (
+          <form method="post" action={`${base}/link/revoke`} class="inline-edit">
+            <Csrf token={token} />
+            <span>An unused link expires {relative(openLink)}.</span>
+            <button type="submit" class="small">Revoke it</button>
+          </form>
+        )}
+        <form method="post" action={`${base}/link`} class="inline-edit">
+          <Csrf token={token} />
+          <label>
+            Valid for{" "}
+            <select name="ttl">
+              <option value="900">15 minutes</option>
+              <option value="3600" selected>1 hour</option>
+              <option value="86400">1 day</option>
+              <option value="604800">7 days</option>
+            </select>
+          </label>
+          <button type="submit" class="primary">{openLink ? "Replace link" : "Create link"}</button>
+        </form>
+      </Section>
+
+      <Section title="Sign-in methods">
+        <ul class="rows">
+          {passkeys.map((p) => (
+            <li>
+              <div class="grow">
+                <strong>Passkey: {p.name}</strong>
+                <br />
+                <small class="muted">added {date(p.created_at)} · last used {relative(p.last_used_at)}</small>
+              </div>
+              <form method="post" action={`${base}/passkeys/${encodeURIComponent(p.id)}/delete`} data-confirm={`Remove the passkey "${p.name}"?`}>
+                <Csrf token={token} />
+                <button type="submit" class="danger small">Remove</button>
+              </form>
+            </li>
+          ))}
+          {user.password_hash && (
+            <li>
+              <div class="grow">
+                <strong>Password</strong>
+              </div>
+              <form method="post" action={`${base}/password/remove`} data-confirm="Remove this password (and any two-factor setup)?">
+                <Csrf token={token} />
+                <button type="submit" class="danger small">Remove</button>
+              </form>
+            </li>
+          )}
+          {user.totp_secret && (
+            <li>
+              <div class="grow">
+                <strong>Two-factor codes</strong>
+              </div>
+              <form method="post" action={`${base}/totp/reset`} data-confirm="Turn off two-factor codes for this account?">
+                <Csrf token={token} />
+                <button type="submit" class="danger small">Turn off</button>
+              </form>
+            </li>
+          )}
+          {!passkeys.length && !user.password_hash && <li class="muted">None. Send a sign-in link so they can add one.</li>}
+        </ul>
+      </Section>
+
+      <Section title="Access">
+        <p class="muted">
+          {sessions.length} active browser session{sessions.length === 1 ? "" : "s"} on this server.
+        </p>
+        <div class="buttons">
+          <form method="post" action={`${base}/signout`} data-confirm="Sign this account out of every browser and application?">
+            <Csrf token={token} />
+            <button type="submit">Sign out everywhere</button>
+          </form>
+          {!self &&
+            (user.disabled ? (
+              <form method="post" action={`${base}/enable`}>
+                <Csrf token={token} />
+                <button type="submit">Enable account</button>
+              </form>
+            ) : (
+              <form method="post" action={`${base}/disable`} data-confirm="Disable this account? They'll be signed out everywhere.">
+                <Csrf token={token} />
+                <button type="submit" class="danger">Disable account</button>
+              </form>
+            ))}
+        </div>
+      </Section>
+
+      {!self && (
+        <Section title="Delete account" description="Permanent. Apps keep whatever they stored about this person; a new account will get a new subject id.">
+          <form method="post" action={`${base}/delete`} class="inline-edit">
+            <Csrf token={token} />
+            <input type="text" name="confirm" placeholder={`Type ${user.username} to confirm`} required autocomplete="off" aria-label="Confirm username" />
+            <button type="submit" class="danger">Delete</button>
+          </form>
+        </Section>
+      )}
+    </>,
+  );
+}
+
+admin.get("/admin/users/:id", (c) => userPage(c, c.req.param("id")));
+
+admin.post("/admin/users/:id/profile", async (c) => {
+  const id = c.req.param("id");
+  const body = await form(c);
+  const update = {
+    username: normaliseUsername(body.username),
+    name: cleanText(body.name, 100),
+    email: cleanText(body.email, 254),
+    picture: cleanText(body.picture, 2048),
+    emailVerified: body.email_verified === "1",
+  };
+  const problem = usernameProblem(update.username) ?? emailProblem(update.email) ?? pictureProblem(update.picture);
+  if (problem) return userPage(c, id, { error: problem });
+
+  const error = await adminUpdateUser(c.env, id, update);
+  if (error) return userPage(c, id, { error });
+  await audit(c, "admin.user_updated", { target: id });
+  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=user-saved`);
+});
+
+admin.post("/admin/users/:id/groups", async (c) => {
+  const id = c.req.param("id");
+  const groups = await formAll(c, "groups");
+  if (id === c.get("user")!.id && !groups.includes(ADMIN_GROUP)) {
+    return userPage(c, id, { error: `You can't remove yourself from ${ADMIN_GROUP}. Ask another admin.` });
+  }
+  await setUserGroups(c.env, id, groups);
+  await audit(c, "admin.user_groups", { target: id, detail: groups.join(",") });
+  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=groups-saved`);
+});
+
+const LINK_TTLS = new Set([900, 3600, 86400, 604800]);
+
+admin.post("/admin/users/:id/link", async (c) => {
+  const id = c.req.param("id");
+  const user = await getUser(c.env, id);
+  if (!user) return notFound(c, "user");
+  if (user.disabled) return userPage(c, id, { error: "Enable the account before sending a sign-in link." });
+
+  const ttl = Number((await form(c)).ttl);
+  const link = await createLoginLink(c.env, id, c.get("user")!.id, LINK_TTLS.has(ttl) ? ttl : 3600);
+  await audit(c, "admin.link_created", { target: id, detail: `ttl=${ttl}` });
+  return userPage(c, id, { link });
+});
+
+admin.post("/admin/users/:id/link/revoke", async (c) => {
+  const id = c.req.param("id");
+  await revokeLoginLinks(c.env, id);
+  await audit(c, "admin.link_revoked", { target: id });
+  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=link-revoked`);
+});
+
+admin.post("/admin/users/:id/passkeys/:pid/delete", async (c) => {
+  const id = c.req.param("id");
+  await deletePasskey(c.env, id, c.req.param("pid"));
+  await audit(c, "admin.passkey_removed", { target: id });
+  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=credential-removed`);
+});
+
+admin.post("/admin/users/:id/password/remove", async (c) => {
+  const id = c.req.param("id");
+  await setPasswordHash(c.env, id, null);
+  await audit(c, "admin.password_removed", { target: id });
+  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=credential-removed`);
+});
+
+admin.post("/admin/users/:id/totp/reset", async (c) => {
+  const id = c.req.param("id");
+  await disableTotp(c.env, id);
+  await audit(c, "admin.totp_reset", { target: id });
+  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=credential-removed`);
+});
+
+admin.post("/admin/users/:id/signout", async (c) => {
+  const id = c.req.param("id");
+  await c.env.DB.batch(revokeAllStatements(c.env, id));
+  await audit(c, "admin.user_signed_out", { target: id });
+  if (id === c.get("user")!.id) return c.redirect("/login?m=signed-out");
+  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=user-signed-out`);
+});
+
+admin.post("/admin/users/:id/disable", async (c) => {
+  const id = c.req.param("id");
+  if (id === c.get("user")!.id) return userPage(c, id, { error: "You can't disable your own account." });
+  await setDisabled(c.env, id, true);
+  await revokeLoginLinks(c.env, id);
+  await audit(c, "admin.user_disabled", { target: id });
+  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=user-disabled`);
+});
+
+admin.post("/admin/users/:id/enable", async (c) => {
+  const id = c.req.param("id");
+  await setDisabled(c.env, id, false);
+  await audit(c, "admin.user_enabled", { target: id });
+  return c.redirect(`/admin/users/${encodeURIComponent(id)}?m=user-enabled`);
+});
+
+admin.post("/admin/users/:id/delete", async (c) => {
+  const id = c.req.param("id");
+  const user = await getUser(c.env, id);
+  if (!user) return notFound(c, "user");
+  if (id === c.get("user")!.id) return userPage(c, id, { error: "You can't delete your own account." });
+  if (normaliseUsername((await form(c)).confirm) !== user.username) {
+    return userPage(c, id, { error: "Type the username exactly to delete the account." });
+  }
+  await deleteUser(c.env, id);
+  await audit(c, "admin.user_deleted", { target: `${user.username} (${id})` });
+  return c.redirect("/admin/users?m=user-deleted");
+});
+
+// --- groups ----------------------------------------------------------------------
+
+async function groupsPage(c: AppContext, error?: string) {
+  const groups = await listGroups(c.env);
+  const token = csrf(c);
+  return adminPage(
+    c,
+    { title: "Groups", tab: "/admin/groups", error, status: error ? 400 : undefined },
+    <>
+      <Section title="Groups" description="Apps receive group names in the `groups` claim. Name them after what they allow, e.g. system-owner or inbox-admin.">
+        <ul class="rows">
+          {groups.map((g) => (
+            <li>
+              <div class="grow">
+                <strong>{g.name}</strong> <small class="muted">{g.member_count} member{g.member_count === 1 ? "" : "s"}</small>
+                <form method="post" action={`/admin/groups/${encodeURIComponent(g.name)}`} class="inline-edit">
+                  <Csrf token={token} />
+                  <input type="text" name="description" value={g.description} maxlength={200} placeholder="Description" aria-label={`Description of ${g.name}`} />
+                  <button type="submit" class="small">Save</button>
+                </form>
+              </div>
+              {g.name !== ADMIN_GROUP && (
+                <form method="post" action={`/admin/groups/${encodeURIComponent(g.name)}/delete`} data-confirm={`Delete the group "${g.name}"? Members lose it immediately.`}>
+                  <Csrf token={token} />
+                  <button type="submit" class="danger small">Delete</button>
+                </form>
+              )}
+            </li>
+          ))}
+        </ul>
+      </Section>
+      <Section title="New group">
+        <form method="post" action="/admin/groups" class="stack">
+          <Csrf token={token} />
+          <div class="grid2">
+            <Field label="Name" name="name" required maxlength={64} autocomplete="off" />
+            <Field label="Description" name="description" maxlength={200} autocomplete="off" />
+          </div>
+          <div>
+            <button type="submit" class="primary">Create group</button>
+          </div>
+        </form>
+      </Section>
+    </>,
+  );
+}
+
+admin.get("/admin/groups", (c) => groupsPage(c));
+
+admin.post("/admin/groups", async (c) => {
+  const body = await form(c);
+  const name = (body.name ?? "").trim().toLowerCase();
+  const problem = groupProblem(name);
+  if (problem) return groupsPage(c, problem);
+  if (!(await createGroup(c.env, name, cleanText(body.description, 200) ?? ""))) {
+    return groupsPage(c, "A group with that name already exists.");
+  }
+  await audit(c, "admin.group_created", { target: name });
+  return c.redirect("/admin/groups?m=group-created");
+});
+
+admin.post("/admin/groups/:name", async (c) => {
+  const body = await form(c);
+  await updateGroup(c.env, c.req.param("name"), cleanText(body.description, 200) ?? "");
+  return c.redirect("/admin/groups?m=group-saved");
+});
+
+admin.post("/admin/groups/:name/delete", async (c) => {
+  const name = c.req.param("name");
+  if (name === ADMIN_GROUP) return groupsPage(c, `${ADMIN_GROUP} can't be deleted.`);
+  await deleteGroup(c.env, name);
+  await audit(c, "admin.group_deleted", { target: name });
+  return c.redirect("/admin/groups?m=group-deleted");
+});
+
+// --- clients -----------------------------------------------------------------------
+
+interface ClientForm {
+  input: ClientInput;
+  raw: Record<string, string>;
+}
+
+async function readClientForm(c: AppContext): Promise<ClientForm | { error: string; raw: Record<string, string>; groups: string[] }> {
+  const raw = await form(c);
+  const chosen = await formAll(c, "allowed_groups");
+  const known = new Set((await listGroups(c.env)).map((g) => g.name));
+  const name = cleanText(raw.name, 100);
+  const redirectUris = lines(raw.redirect_uris);
+  const postLogoutRedirectUris = lines(raw.post_logout_redirect_uris);
+
+  const fail = (error: string) => ({ error, raw, groups: chosen });
+  if (!name) return fail("Applications need a name.");
+  if (redirectUris.length === 0) return fail("Add at least one redirect URI.");
+  if (redirectUris.length + postLogoutRedirectUris.length > 40) return fail("That's too many URIs.");
+  for (const uri of [...redirectUris, ...postLogoutRedirectUris]) {
+    const problem = redirectUriProblem(uri);
+    if (problem) return fail(problem);
+  }
+  return {
+    raw,
+    input: {
+      name,
+      redirectUris: [...new Set(redirectUris)],
+      postLogoutRedirectUris: [...new Set(postLogoutRedirectUris)],
+      allowedGroups: chosen.filter((g) => known.has(g)),
+    },
+  };
+}
+
+function ClientFields(props: { groups: GroupRow[]; name?: string; redirects?: string; postLogout?: string; allowed: string[] }) {
+  return (
+    <>
+      <Field label="Name" name="name" value={props.name} required maxlength={100} autocomplete="off" hint="Shown to people when they're asked to sign in." />
+      <label class="field">
+        <span>Redirect URIs</span>
+        <textarea name="redirect_uris" rows={3} required placeholder="https://app.example.com/auth/callback">
+          {props.redirects ?? ""}
+        </textarea>
+        <small class="muted">One per line, matched exactly.</small>
+      </label>
+      <label class="field">
+        <span>Post-logout redirect URIs</span>
+        <textarea name="post_logout_redirect_uris" rows={2} placeholder="https://app.example.com/">
+          {props.postLogout ?? ""}
+        </textarea>
+        <small class="muted">Optional. Where the app may send people after signing out here.</small>
+      </label>
+      <fieldset>
+        <legend>Who can use it</legend>
+        <p class="muted small">Leave everything unticked to allow every account.</p>
+        <GroupChecks groups={props.groups} selected={props.allowed} name="allowed_groups" />
+      </fieldset>
+    </>
+  );
+}
+
+async function clientsPage(c: AppContext, error?: string, raw: Record<string, string> = {}, allowed: string[] = []) {
+  const [clients, groups] = await Promise.all([listClients(c.env), listGroups(c.env)]);
+  return adminPage(
+    c,
+    { title: "Applications", tab: "/admin/clients", error, status: error ? 400 : undefined },
+    <>
+      <Section title="Applications" description="Each app that signs people in through this server is an OpenID Connect client.">
+        {clients.length === 0 ? (
+          <p class="muted">No applications yet.</p>
+        ) : (
+          <div class="table-wrap">
+            <table>
+              <thead>
+                <tr>
+                  <th>Name</th>
+                  <th>Client id</th>
+                  <th>Type</th>
+                  <th>Allowed</th>
+                </tr>
+              </thead>
+              <tbody>
+                {clients.map((cl) => (
+                  <tr>
+                    <td>
+                      <a href={`/admin/clients/${encodeURIComponent(cl.id)}`}>
+                        <strong>{cl.name}</strong>
+                      </a>
+                    </td>
+                    <td>
+                      <code>{cl.id}</code>
+                    </td>
+                    <td>{cl.isPublic ? "public (PKCE)" : "confidential"}</td>
+                    <td>{cl.allowedGroups.length ? cl.allowedGroups.map((g) => <span class="badge">{g}</span>) : "everyone"}</td>
+                  </tr>
+                ))}
+              </tbody>
+            </table>
+          </div>
+        )}
+      </Section>
+
+      <Section title="Add an application">
+        <form method="post" action="/admin/clients" class="stack">
+          <Csrf token={csrf(c)} />
+          <ClientFields groups={groups} name={raw.name} redirects={raw.redirect_uris} postLogout={raw.post_logout_redirect_uris} allowed={allowed} />
+          <fieldset>
+            <legend>Type</legend>
+            <label class="check">
+              <input type="radio" name="type" value="confidential" checked={raw.type !== "public"} />
+              <span>
+                Confidential <small class="muted">— has a server that can keep a client secret (dough-git, inbox).</small>
+              </span>
+            </label>
+            <label class="check">
+              <input type="radio" name="type" value="public" checked={raw.type === "public"} />
+              <span>
+                Public <small class="muted">— runs entirely in the browser or on a device; uses PKCE and no secret.</small>
+              </span>
+            </label>
+          </fieldset>
+          <details>
+            <summary>Advanced</summary>
+            <Field
+              label="Client id"
+              name="client_id"
+              value={raw.client_id}
+              maxlength={128}
+              autocomplete="off"
+              hint="Leave blank for a random id. Set it to keep an app's existing client id when moving it over from another provider."
+            />
+          </details>
+          <div>
+            <button type="submit" class="primary">Create application</button>
+          </div>
+        </form>
+      </Section>
+    </>,
+  );
+}
+
+admin.get("/admin/clients", (c) => clientsPage(c));
+
+admin.post("/admin/clients", async (c) => {
+  const parsed = await readClientForm(c);
+  if ("error" in parsed) return clientsPage(c, parsed.error, parsed.raw, parsed.groups);
+
+  const id = cleanText(parsed.raw.client_id, 128) ?? crypto.randomUUID();
+  const idProblem = clientIdProblem(id);
+  if (idProblem) return clientsPage(c, idProblem, parsed.raw, parsed.input.allowedGroups);
+
+  const result = await createClient(c.env, id, parsed.raw.type !== "public", parsed.input);
+  if (!result.ok) return clientsPage(c, result.error, parsed.raw, parsed.input.allowedGroups);
+
+  await audit(c, "admin.client_created", { target: id });
+  return clientPage(c, id, { secret: result.secret });
+});
+
+function Integration(props: { c: AppContext; client: Client }) {
+  const iss = issuer(props.c.env);
+  const rows: [string, string][] = [
+    ["Issuer", iss],
+    ["Discovery", `${iss}/.well-known/openid-configuration`],
+    ["Client id", props.client.id],
+    ["Token auth", props.client.isPublic ? "none (PKCE)" : "client_secret_basic or client_secret_post"],
+    ["Scopes", "openid profile email groups (+ offline_access for refresh tokens)"],
+  ];
+  return (
+    <dl class="kv">
+      {rows.map(([k, v]) => (
+        <>
+          <dt>{k}</dt>
+          <dd>
+            <code>{v}</code>
+          </dd>
+        </>
+      ))}
+    </dl>
+  );
+}
+
+async function clientPage(c: AppContext, id: string, opts: { error?: string; secret?: string | null } = {}) {
+  const client = await getClient(c.env, id);
+  if (!client) return notFound(c, "application");
+  const groups = await listGroups(c.env);
+  const base = `/admin/clients/${encodeURIComponent(id)}`;
+  const token = csrf(c);
+
+  return adminPage(
+    c,
+    { title: client.name, tab: "/admin/clients", error: opts.error, status: opts.error ? 400 : undefined },
+    <>
+      <p>
+        <a href="/admin/clients">← All applications</a>
+      </p>
+      <h1>{client.name}</h1>
+
+      {opts.secret && (
+        <div class="notice ok">
+          <p>
+            <strong>Client secret</strong> — copy it into the app's configuration now. It won't be shown again.
+          </p>
+          <p class="copyrow">
+            <input type="text" readonly value={opts.secret} aria-label="Client secret" />
+            <button type="button" data-copy={opts.secret}>Copy</button>
+          </p>
+        </div>
+      )}
+
+      <Section title="Connecting the app">
+        <Integration c={c} client={client} />
+      </Section>
+
+      <Section title="Settings">
+        <form method="post" action={base} class="stack">
+          <Csrf token={token} />
+          <ClientFields
+            groups={groups}
+            name={client.name}
+            redirects={client.redirectUris.join("\n")}
+            postLogout={client.postLogoutRedirectUris.join("\n")}
+            allowed={client.allowedGroups}
+          />
+          <div>
+            <button type="submit">Save</button>
+          </div>
+        </form>
+      </Section>
+
+      <Section title="Client secret">
+        <p class="muted">
+          {client.isPublic
+            ? "This is a public client: it has no secret and must use PKCE."
+            : "Rotating the secret breaks the app until it's given the new one."}
+        </p>
+        <div class="buttons">
+          <form method="post" action={`${base}/secret`} data-confirm={client.isPublic ? "Give this app a secret and make it confidential?" : "Replace the secret? The old one stops working immediately."}>
+            <Csrf token={token} />
+            <button type="submit">{client.isPublic ? "Create a secret" : "Rotate secret"}</button>
+          </form>
+          {!client.isPublic && (
+            <form method="post" action={`${base}/public`} data-confirm="Remove the secret and make this a public PKCE client?">
+              <Csrf token={token} />
+              <button type="submit" class="danger">Make public</button>
+            </form>
+          )}
+        </div>
+      </Section>
+
+      <Section title="Delete application" description="Its refresh tokens stop working immediately; issued access tokens are refused by /userinfo.">
+        <form method="post" action={`${base}/delete`} data-confirm={`Delete ${client.name}? People won't be able to sign in to it.`}>
+          <Csrf token={token} />
+          <button type="submit" class="danger">Delete</button>
+        </form>
+      </Section>
+    </>,
+  );
+}
+
+admin.get("/admin/clients/:id", (c) => clientPage(c, c.req.param("id")));
+
+admin.post("/admin/clients/:id", async (c) => {
+  const id = c.req.param("id");
+  if (!(await getClient(c.env, id))) return notFound(c, "application");
+  const parsed = await readClientForm(c);
+  if ("error" in parsed) return clientPage(c, id, { error: parsed.error });
+  await updateClient(c.env, id, parsed.input);
+  await audit(c, "admin.client_updated", { target: id });
+  return c.redirect(`/admin/clients/${encodeURIComponent(id)}?m=client-saved`);
+});
+
+admin.post("/admin/clients/:id/secret", async (c) => {
+  const id = c.req.param("id");
+  if (!(await getClient(c.env, id))) return notFound(c, "application");
+  const secret = await rotateClientSecret(c.env, id);
+  await audit(c, "admin.client_secret_rotated", { target: id });
+  return clientPage(c, id, { secret });
+});
+
+admin.post("/admin/clients/:id/public", async (c) => {
+  const id = c.req.param("id");
+  await makeClientPublic(c.env, id);
+  await audit(c, "admin.client_made_public", { target: id });
+  return c.redirect(`/admin/clients/${encodeURIComponent(id)}?m=client-public`);
+});
+
+admin.post("/admin/clients/:id/delete", async (c) => {
+  const id = c.req.param("id");
+  await deleteClient(c.env, id);
+  await audit(c, "admin.client_deleted", { target: id });
+  return c.redirect("/admin/clients?m=client-deleted");
+});
+
+// --- keys + audit ------------------------------------------------------------------
+
+admin.get("/admin/keys", async (c) => {
+  const keys = await listKeys(c.env);
+  return adminPage(
+    c,
+    { title: "Signing keys", tab: "/admin/keys" },
+    <Section title="Signing keys" description="Tokens are signed with the newest active key. Apps pick up new keys from the JWKS automatically. A key is created on first use.">
+      <ul class="rows">
+        {keys.map((k) => (
+          <li>
+            <div class="grow">
+              <code>{k.kid}</code> <span class={`badge ${k.retired_at ? "" : "ok"}`}>{k.retired_at ? "retired" : "active"}</span>
+              <br />
+              <small class="muted">
+                {k.alg} · created {date(k.created_at)}
+                {k.retired_at ? ` · retired ${date(k.retired_at)}` : ""}
+              </small>
+            </div>
+          </li>
+        ))}
+      </ul>
+      <form method="post" action="/admin/keys/rotate" data-confirm="Rotate the signing key?">
+        <Csrf token={csrf(c)} />
+        <button type="submit">Rotate now</button>
+      </form>
+    </Section>,
+  );
+});
+
+admin.post("/admin/keys/rotate", async (c) => {
+  const kid = await rotateKeys(c.env);
+  await audit(c, "admin.keys_rotated", { target: kid });
+  return c.redirect("/admin/keys?m=keys-rotated");
+});
+
+admin.get("/admin/audit", async (c) => {
+  const entries = await recentAudit(c);
+  return adminPage(
+    c,
+    { title: "Audit log", tab: "/admin/audit" },
+    <Section title="Recent activity" description="The latest 200 events. Kept for 180 days.">
+      <div class="table-wrap">
+        <table class="compact">
+          <thead>
+            <tr>
+              <th>When</th>
+              <th>Who</th>
+              <th>What</th>
+              <th>Target</th>
+              <th>IP</th>
+            </tr>
+          </thead>
+          <tbody>
+            {entries.map((e) => (
+              <tr>
+                <td title={date(e.at)}>{relative(e.at)}</td>
+                <td>{e.actor_username ? `@${e.actor_username}` : <span class="muted">—</span>}</td>
+                <td>
+                  <code>{e.action}</code>
+                  {e.detail && <small class="muted"> {e.detail}</small>}
+                </td>
+                <td>{e.target ?? ""}</td>
+                <td>{e.ip ?? ""}</td>
+              </tr>
+            ))}
+          </tbody>
+        </table>
+      </div>
+    </Section>,
+  );
+});
diff --git a/src/routes/login.tsx b/src/routes/login.tsx
new file mode 100644
index 0000000..bba64f8
--- /dev/null
+++ b/src/routes/login.tsx
@@ -0,0 +1,302 @@
+/* src/routes/login.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 type { AuthenticationResponseJSON } from "@simplewebauthn/server";
+import type { AppContext, AppEnv } from "../env";
+import { audit } from "../lib/audit";
+import { decrypt, timingSafeEqualStr } from "../lib/crypto";
+import { clientIp, form, readJson, safeReturn } from "../lib/http";
+import { burnPasswordCheck, hashPassword, needsRehash, verifyPassword } from "../lib/password";
+import { attempt, clearAttempts } from "../lib/ratelimit";
+import { verifyTotp } from "../lib/totp";
+import { normaliseUsername } from "../lib/validate";
+import { authenticationOptions, finishAuthentication } from "../data/passkeys";
+import { consumeLoginLink, peekLoginLink } from "../data/links";
+import {
+  endSession,
+  finishPendingLogin,
+  peekPendingLogin,
+  spendPendingAttempt,
+  startPendingLogin,
+  startSession,
+} from "../data/sessions";
+import { claimTotpStep, countUsers, getUser, getUserByUsername, setPasswordHash } from "../data/users";
+import { render } from "../views/layout";
+import { ErrorNote, Field, Flash } from "../views/ui";
+
+const WINDOW = 15 * 60;
+const USER_LIMIT = 10;
+const IP_LIMIT = 50;
+const TOTP_ATTEMPTS = 5;
+const GENERIC_FAILURE = "That username and password don't match.";
+
+export const login = new Hono<AppEnv>();
+
+interface LoginPageOptions {
+  returnTo: string;
+  reauth: boolean;
+  username?: string;
+  error?: string;
+  message?: string;
+  status?: 401 | 429;
+}
+
+function loginPage(c: AppContext, opts: LoginPageOptions) {
+  const user = c.get("user");
+  const username = opts.username ?? (opts.reauth ? user?.username : undefined);
+  return render(
+    c,
+    { title: "Sign in", page: "login", narrow: true, status: opts.status },
+    <div class="card" id="login" data-return={opts.returnTo}>
+      <h1>{opts.reauth ? "Confirm it's you" : "Sign in"}</h1>
+      {opts.reauth && (
+        <p class="muted">This needs a fresh sign-in. It only takes a moment.</p>
+      )}
+      <Flash code={opts.message} />
+      <ErrorNote error={opts.error} />
+      <p class="notice error hidden" id="passkey-error" role="alert"></p>
+
+      <button type="button" class="primary wide" id="passkey-signin">
+        Sign in with a passkey
+      </button>
+
+      <div class="divider">
+        <span>or use a password</span>
+      </div>
+
+      <form method="post" action="/login/password" class="stack">
+        <input type="hidden" name="return" value={opts.returnTo} />
+        {opts.reauth && <input type="hidden" name="reauth" value="1" />}
+        <Field
+          label="Username"
+          name="username"
+          value={username}
+          required
+          autocomplete="username webauthn"
+          autofocus={!username}
+          maxlength={64}
+        />
+        <Field
+          label="Password"
+          name="password"
+          type="password"
+          required
+          autocomplete="current-password"
+          autofocus={Boolean(username)}
+          maxlength={512}
+        />
+        <button type="submit" class="wide">
+          Sign in
+        </button>
+      </form>
+    </div>,
+  );
+}
+
+login.get("/login", async (c) => {
+  const returnTo = safeReturn(c.req.query("return"));
+  const reauth = c.req.query("reauth") === "1";
+  if (c.get("user") && !reauth) return c.redirect(returnTo);
+  if ((await countUsers(c.env)) === 0) return c.redirect("/setup");
+  return loginPage(c, { returnTo, reauth, message: c.req.query("m") });
+});
+
+login.post("/login/password", async (c) => {
+  const body = await form(c);
+  const returnTo = safeReturn(body.return);
+  const reauth = body.reauth === "1";
+  const username = normaliseUsername(body.username).slice(0, 64);
+  const password = (body.password ?? "").slice(0, 512);
+
+  const ipOk = await attempt(c.env, `login-ip:${clientIp(c)}`, IP_LIMIT, WINDOW);
+  const userOk = await attempt(c.env, `login-user:${username}`, USER_LIMIT, WINDOW);
+  if (!ipOk || !userOk) {
+    await audit(c, "login.rate_limited", { actor: null, target: username });
+    return loginPage(c, {
+      returnTo,
+      reauth,
+      username,
+      status: 429,
+      error: "Too many sign-in attempts. Wait a few minutes and try again.",
+    });
+  }
+
+  const user = username ? await getUserByUsername(c.env, username) : null;
+  if (!user || !user.password_hash || user.disabled) {
+    await burnPasswordCheck(password);
+    await audit(c, "login.failed", { actor: null, target: username, detail: "password" });
+    return loginPage(c, { returnTo, reauth, username, status: 401, error: GENERIC_FAILURE });
+  }
+
+  if (!(await verifyPassword(password, user.password_hash))) {
+    await audit(c, "login.failed", { actor: user.id, target: user.username, detail: "password" });
+    return loginPage(c, { returnTo, reauth, username, status: 401, error: GENERIC_FAILURE });
+  }
+
+  await clearAttempts(c.env, `login-user:${username}`);
+  if (needsRehash(user.password_hash)) {
+    await setPasswordHash(c.env, user.id, await hashPassword(password));
+  }
+
+  if (user.totp_secret) {
+    await startPendingLogin(c, user.id, returnTo);
+    return c.redirect("/login/totp");
+  }
+
+  await startSession(c, user.id, ["pwd"]);
+  await audit(c, "login.password", { actor: user.id, target: user.username });
+  return c.redirect(returnTo);
+});
+
+function totpPage(c: AppContext, error?: string) {
+  return render(
+    c,
+    { title: "Two-factor code", narrow: true, status: error ? 401 : 200 },
+    <div class="card">
+      <h1>Enter your code</h1>
+      <p class="muted">Open your authenticator app and enter the 6-digit code for this account.</p>
+      <ErrorNote error={error} />
+      <form method="post" action="/login/totp" class="stack">
+        <Field
+          label="Code"
+          name="code"
+          required
+          autocomplete="one-time-code"
+          inputmode="numeric"
+          pattern="[0-9 ]{6,7}"
+          maxlength={7}
+          autofocus
+        />
+        <button type="submit" class="primary wide">
+          Continue
+        </button>
+      </form>
+      <p class="muted small">
+        <a href="/login">Start over</a>
+      </p>
+    </div>,
+  );
+}
+
+login.get("/login/totp", async (c) => {
+  if (!(await peekPendingLogin(c))) return c.redirect("/login");
+  return totpPage(c);
+});
+
+login.post("/login/totp", async (c) => {
+  const body = await form(c);
+  const pending = await spendPendingAttempt(c, TOTP_ATTEMPTS);
+  if (!pending) return c.redirect("/login");
+
+  const user = await getUser(c.env, pending.user_id);
+  if (!user || user.disabled || !user.totp_secret) {
+    await finishPendingLogin(c, pending.id_hash);
+    return c.redirect("/login");
+  }
+
+  const secret = await decrypt(c.env.KEY_ENCRYPTION_KEY, user.totp_secret);
+  const step = await verifyTotp(secret, body.code ?? "", user.totp_last_step);
+  if (step === null || !(await claimTotpStep(c.env, user.id, step))) {
+    await audit(c, "login.failed", { actor: user.id, target: user.username, detail: "totp" });
+    const left = TOTP_ATTEMPTS - pending.attempts;
+    if (left <= 0) {
+      await finishPendingLogin(c, pending.id_hash);
+      return c.redirect("/login");
+    }
+    return totpPage(c, `That code didn't work. ${left} ${left === 1 ? "try" : "tries"} left.`);
+  }
+
+  await finishPendingLogin(c, pending.id_hash);
+  await startSession(c, user.id, ["pwd", "otp", "mfa"]);
+  await audit(c, "login.password_totp", { actor: user.id, target: user.username });
+  return c.redirect(safeReturn(pending.return_to));
+});
+
+login.post("/login/passkey/options", async (c) => {
+  if (!(await attempt(c.env, `passkey-ip:${clientIp(c)}`, 120, WINDOW))) {
+    return c.json({ error: "Too many sign-in attempts. Wait a few minutes and try again." }, 429);
+  }
+  return c.json(await authenticationOptions(c.env));
+});
+
+login.post("/login/passkey/verify", async (c) => {
+  const body = await readJson<{ id?: string; response?: AuthenticationResponseJSON; return?: string }>(c);
+  if (!body?.id || !body.response) return c.json({ error: "Malformed request." }, 400);
+
+  const result = await finishAuthentication(c.env, body.id, body.response);
+  if (!result.ok) {
+    await audit(c, "login.failed", { actor: null, detail: "passkey" });
+    return c.json({ error: result.error }, 401);
+  }
+
+  const user = await getUser(c.env, result.userId);
+  if (!user || user.disabled) return c.json({ error: "This account is disabled." }, 403);
+
+  await startSession(c, user.id, result.amr);
+  await audit(c, "login.passkey", { actor: user.id, target: user.username });
+  return c.json({ redirect: safeReturn(body.return) });
+});
+
+login.get("/login/link/:token", async (c) => {
+  const target = await peekLoginLink(c.env, c.req.param("token"));
+  if (!target) {
+    return render(
+      c,
+      { title: "Link expired", narrow: true, status: 410 },
+      <div class="card">
+        <h1>This link can't be used</h1>
+        <p class="muted">It has expired, was already used, or was replaced by a newer one. Ask an admin for a new link.</p>
+      </div>,
+    );
+  }
+
+  const current = c.get("user");
+  // Link scanners follow GETs, so using the link takes a deliberate POST.
+  return render(
+    c,
+    { title: "Sign in", narrow: true },
+    <div class="card">
+      <h1>Sign in as {target.name ?? target.username}</h1>
+      <p class="muted">
+        This one-time link signs you in as <strong>@{target.username}</strong>. It stops working once it's used.
+      </p>
+      {current && current.id !== target.user_id && (
+        <p class="notice">You'll be signed out of @{current.username} on this browser.</p>
+      )}
+      <form method="post" action={`/login/link/${c.req.param("token")}`}>
+        <button type="submit" class="primary wide">
+          Continue
+        </button>
+      </form>
+    </div>,
+  );
+});
+
+login.post("/login/link/:token", async (c) => {
+  if (!(await attempt(c.env, `link-ip:${clientIp(c)}`, 30, WINDOW))) {
+    return c.text("Too many attempts. Wait a few minutes and try again.", 429);
+  }
+  const userId = await consumeLoginLink(c.env, c.req.param("token"));
+  if (!userId) return c.redirect(`/login/link/${encodeURIComponent(c.req.param("token"))}`);
+
+  await startSession(c, userId, ["link"]);
+  await audit(c, "login.link", { actor: userId, target: userId });
+  return c.redirect("/account?m=link-welcome");
+});
+
+login.post("/logout", async (c) => {
+  const session = c.get("session");
+  if (session) {
+    const body = await form(c);
+    if (!body._csrf || !timingSafeEqualStr(body._csrf, session.csrf)) {
+      return c.text("This form is out of date. Go back, reload the page and try again.", 403);
+    }
+    await audit(c, "logout");
+    await endSession(c);
+  }
+  return c.redirect("/login?m=signed-out");
+});
diff --git a/src/routes/setup.tsx b/src/routes/setup.tsx
new file mode 100644
index 0000000..afb9cd8
--- /dev/null
+++ b/src/routes/setup.tsx
@@ -0,0 +1,105 @@
+/* src/routes/setup.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 type { AppContext, AppEnv } from "../env";
+import { audit } from "../lib/audit";
+import { timingSafeEqualStr } from "../lib/crypto";
+import { clientIp, form } from "../lib/http";
+import { attempt } from "../lib/ratelimit";
+import { cleanText, emailProblem, normaliseUsername, usernameProblem } from "../lib/validate";
+import { startSession } from "../data/sessions";
+import { countUsers, createFirstAdmin } from "../data/users";
+import { render } from "../views/layout";
+import { ErrorNote, Field } from "../views/ui";
+
+export const setup = new Hono<AppEnv>();
+
+function closed(c: AppContext) {
+  return render(
+    c,
+    { title: "Setup", narrow: true, status: 404 },
+    <div class="card">
+      <h1>Setup is done</h1>
+      <p class="muted">This server already has accounts.</p>
+      <p>
+        <a href="/login">Sign in</a>
+      </p>
+    </div>,
+  );
+}
+
+function setupPage(c: AppContext, values: Record<string, string> = {}, error?: string) {
+  if (!c.env.SETUP_TOKEN) {
+    return render(
+      c,
+      { title: "Setup", narrow: true, status: 503 },
+      <div class="card">
+        <h1>Almost there</h1>
+        <p>
+          Set a <code>SETUP_TOKEN</code> secret (<code>wrangler secret put SETUP_TOKEN</code>, or{" "}
+          <code>.dev.vars</code> locally), then reload this page to create the first admin.
+        </p>
+      </div>,
+    );
+  }
+  return render(
+    c,
+    { title: "Setup", narrow: true, status: error ? 400 : 200 },
+    <div class="card">
+      <h1>Create the first admin</h1>
+      <p class="muted">
+        This page only works while the server has no accounts. You'll add a passkey or password straight after.
+      </p>
+      <ErrorNote error={error} />
+      <form method="post" action="/setup" class="stack">
+        <Field label="Setup token" name="token" type="password" required autocomplete="off" hint="The SETUP_TOKEN secret." />
+        <Field label="Username" name="username" value={values.username} required autocomplete="username" maxlength={32} />
+        <Field label="Display name" name="name" value={values.name} autocomplete="name" maxlength={100} />
+        <Field label="Email" name="email" type="email" value={values.email} autocomplete="email" maxlength={254} />
+        <button type="submit" class="primary wide">
+          Create admin account
+        </button>
+      </form>
+    </div>,
+  );
+}
+
+setup.get("/setup", async (c) => {
+  if ((await countUsers(c.env)) > 0) return closed(c);
+  return setupPage(c);
+});
+
+setup.post("/setup", async (c) => {
+  if ((await countUsers(c.env)) > 0 || !c.env.SETUP_TOKEN) return closed(c);
+
+  if (!(await attempt(c.env, `setup-ip:${clientIp(c)}`, 10, 60 * 60))) {
+    return c.text("Too many attempts. Try again later.", 429);
+  }
+
+  const body = await form(c);
+  if (!timingSafeEqualStr(body.token ?? "", c.env.SETUP_TOKEN)) {
+    await audit(c, "setup.bad_token", { actor: null });
+    return setupPage(c, body, "That setup token is wrong.");
+  }
+
+  const username = normaliseUsername(body.username);
+  const email = cleanText(body.email, 254);
+  const problem = usernameProblem(username) ?? emailProblem(email);
+  if (problem) return setupPage(c, body, problem);
+
+  const id = await createFirstAdmin(c.env, {
+    username,
+    name: cleanText(body.name, 100),
+    email,
+    emailVerified: false,
+  });
+  if (!id) return closed(c);
+
+  await startSession(c, id, ["setup"]);
+  await audit(c, "setup.complete", { actor: id, target: username });
+  return c.redirect("/account?m=setup-done");
+});
diff --git a/src/views/layout.tsx b/src/views/layout.tsx
new file mode 100644
index 0000000..17854d8
--- /dev/null
+++ b/src/views/layout.tsx
@@ -0,0 +1,60 @@
+/* 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 type { Child } from "hono/jsx";
+import type { ContentfulStatusCode } from "hono/utils/http-status";
+import { siteName, type AppContext } from "../env";
+
+interface PageOptions {
+  title: string;
+  /** Picks the behaviour in /static/app.js. */
+  page?: string;
+  /** Centered card layout for sign-in screens. */
+  narrow?: boolean;
+  status?: ContentfulStatusCode;
+}
+
+export async function render(c: AppContext, opts: PageOptions, body: Child): Promise<Response> {
+  const site = siteName(c.env);
+  const user = c.get("user");
+  const session = c.get("session");
+
+  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 light" />
+        <meta name="robots" content="noindex" />
+        <title>{`${opts.title} · ${site}`}</title>
+        <link rel="stylesheet" href="/static/style.css" />
+        <script src="/static/app.js" defer></script>
+      </head>
+      <body data-page={opts.page ?? ""} data-csrf={session?.csrf ?? ""}>
+        <header class="topbar">
+          <a class="brand" href={user ? "/account" : "/login"}>
+            {site}
+          </a>
+          {user && (
+            <nav>
+              <a href="/account">Account</a>
+              {user.isAdmin && <a href="/admin">Admin</a>}
+              <form method="post" action="/logout" class="inline">
+                <input type="hidden" name="_csrf" value={session?.csrf ?? ""} />
+                <button type="submit" class="link">
+                  Sign out
+                </button>
+              </form>
+            </nav>
+          )}
+        </header>
+        <main class={opts.narrow ? "narrow" : "wide"}>{body}</main>
+      </body>
+    </html>
+  );
+
+  return c.html(`<!doctype html>${await html}`, opts.status ?? 200);
+}
diff --git a/src/views/ui.tsx b/src/views/ui.tsx
new file mode 100644
index 0000000..e4a8a9f
--- /dev/null
+++ b/src/views/ui.tsx
@@ -0,0 +1,141 @@
+/* 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-out": "You're signed out.",
+  "setup-done": "Your admin account is ready. Add a passkey or password below so you can sign in again.",
+  "link-welcome": "You're signed in. Add a passkey (or a password) now so you can sign in next time.",
+  "profile-saved": "Profile saved.",
+  "passkey-added": "Passkey added.",
+  "passkey-renamed": "Passkey renamed.",
+  "passkey-removed": "Passkey removed.",
+  "password-set": "Password saved. Your other sessions were signed out.",
+  "password-removed": "Password removed. Sign in with a passkey from now on.",
+  "totp-enabled": "Two-factor codes are on for password sign-ins.",
+  "totp-disabled": "Two-factor codes are off.",
+  "session-revoked": "Session signed out.",
+  "sessions-revoked": "All other sessions are signed out.",
+  "user-created": "User created.",
+  "user-saved": "User saved.",
+  "user-deleted": "User deleted.",
+  "groups-saved": "Groups saved.",
+  "group-created": "Group created.",
+  "group-saved": "Group saved.",
+  "group-deleted": "Group deleted.",
+  "client-saved": "Application saved.",
+  "client-deleted": "Application deleted.",
+  "client-public": "Secret removed. The application is now a public (PKCE) client.",
+  "keys-rotated": "Signing key rotated. The old key stays published for two days.",
+  "credential-removed": "Sign-in method removed.",
+  "user-disabled": "Account disabled and signed out everywhere.",
+  "user-enabled": "Account enabled.",
+  "user-signed-out": "Signed out of every session and application.",
+  "link-revoked": "Sign-in link revoked.",
+};
+
+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 Field(props: {
+  label: string;
+  name: string;
+  type?: string;
+  value?: string | null;
+  required?: boolean;
+  autocomplete?: string;
+  hint?: string;
+  placeholder?: string;
+  maxlength?: number;
+  inputmode?: string;
+  pattern?: string;
+  autofocus?: boolean;
+}) {
+  return (
+    <label class="field">
+      <span>{props.label}</span>
+      <input
+        type={props.type ?? "text"}
+        name={props.name}
+        value={props.value ?? ""}
+        required={props.required}
+        autocomplete={props.autocomplete}
+        placeholder={props.placeholder}
+        maxlength={props.maxlength}
+        inputmode={props.inputmode as "numeric" | undefined}
+        pattern={props.pattern}
+        autofocus={props.autofocus}
+      />
+      {props.hint && <small class="muted">{props.hint}</small>}
+    </label>
+  );
+}
+
+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`;
+}
+
+/** Short, friendly browser + OS guess for session lists. */
+export function describeAgent(ua: string | null): string {
+  if (!ua) return "Unknown device";
+  const browser =
+    /Edg\//.test(ua) ? "Edge" :
+    /Firefox\//.test(ua) ? "Firefox" :
+    /Chrome\//.test(ua) ? "Chrome" :
+    /Safari\//.test(ua) ? "Safari" :
+    "Browser";
+  const os =
+    /Windows/.test(ua) ? "Windows" :
+    /iPhone|iPad/.test(ua) ? "iOS" :
+    /Mac OS X/.test(ua) ? "macOS" :
+    /Android/.test(ua) ? "Android" :
+    /Linux/.test(ua) ? "Linux" :
+    "unknown OS";
+  return `${browser} on ${os}`;
+}
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..194fdfe
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,25 @@
+{
+  "compilerOptions": {
+    "target": "ES2024",
+    "lib": ["ES2024"],
+    "module": "ESNext",
+    "moduleResolution": "bundler",
+    "moduleDetection": "force",
+    "types": ["@cloudflare/workers-types"],
+
+    "jsx": "react-jsx",
+    "jsxImportSource": "hono/jsx",
+
+    "allowImportingTsExtensions": true,
+    "verbatimModuleSyntax": true,
+    "resolveJsonModule": true,
+    "noEmit": true,
+
+    "strict": true,
+    "skipLibCheck": true,
+    "noFallthroughCasesInSwitch": true,
+    "noUncheckedIndexedAccess": true,
+    "noImplicitOverride": true
+  },
+  "include": ["src"]
+}
diff --git a/wrangler.jsonc b/wrangler.jsonc
new file mode 100644
index 0000000..b1448ae
--- /dev/null
+++ b/wrangler.jsonc
@@ -0,0 +1,44 @@
+{
+	"$schema": "node_modules/wrangler/config-schema.json",
+	"name": "auth-server",
+	"main": "src/main.ts",
+	"compatibility_date": "2026-09-01",
+	"compatibility_flags": [
+		"nodejs_compat"
+	],
+	"observability": {
+		"logs": {
+			"enabled": true,
+			"invocation_logs": true
+		}
+	},
+	// Stylesheet + browser script. Served straight from the edge; public/_headers
+	// gives them the same hardening headers the worker adds to its own responses.
+	"assets": {
+		"directory": "./public"
+	},
+	"d1_databases": [
+		{
+			"binding": "DB",
+			"database_name": "auth-server",
+			"database_id": "ce757d6d-ac0f-406a-baca-006163b31566",
+			"migrations_dir": "migrations"
+		}
+	],
+	// Hourly sweep of expired sessions, codes, tokens and challenges.
+	"triggers": {
+		"crons": [
+			"17 * * * *"
+		]
+	},
+	// "routes": [{ "pattern": "auth.doughmination.gay", "custom_domain": true }],
+	"vars": {
+		// Public origin of this server. It is the OIDC issuer and the passkey
+		// relying party, so it must never change once passkeys are registered.
+		"ISSUER": "https://auth.doughmination.gay",
+		"SITE_NAME": "Doughmination SSO"
+	}
+	// Secrets (wrangler secret put <NAME>):
+	//   KEY_ENCRYPTION_KEY  encrypts signing keys + TOTP secrets at rest
+	//   SETUP_TOKEN         unlocks /setup while there are no users yet
+}
\ No newline at end of file