The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Revert "Merge branch 'o/acc-1' into claude/fuobe-parity-4"
Claudeeea902e0847a
diff --git a/README.md b/README.mdindex d62bfbf9..15f8130a 100644--- a/README.md+++ b/README.md@@ -87,16 +87,11 @@ Share links are the one exception: `/s/<token>` and its files open for anyone wh| Variable | What it does ||---|---|-| `FUOBE_PASSWORD` (or `FUOBE_OWNER_PASSWORD`) | The owner's break-glass password, up to 500 characters: synced at every start (a new value signs every browser out) and turns sign-in on. Settings can't change it while it is set; once you unset it, it stays the password and sign-in stays on, and you change or remove it in Settings → Security |-| `FUOBE_SIGNIN` | `on` or `off` pins sign-in, whatever Settings says (Settings shows "Set by the server"). `on` needs a password (`FUOBE_PASSWORD`, or one set in Settings first), or Fuobe doesn't start |-| `FUOBE_SECRET` | The root secret sessions are signed with: 64 hex characters, or at least 32 characters. Without it Fuobe makes `data/secret.key`; back that file up with the database. A different key than the data folder was made with stops the start, unless `FUOBE_ACCEPT_NEW_SECRET=1` (everyone signs in again) |+| `FUOBE_PASSWORD` | Turns sign-in on; a password set this way can't be changed from Settings || `FUOBE_ALLOWED_ORIGINS` | Extra hosts Fuobe is reached at, comma-separated. Without a password, Fuobe answers only on IP addresses, localhost, single-label and LAN names (`.local`, `.lan`, `.home.arpa`, `.internal`) and the machine's hostname; add any other domain (a reverse proxy, a tunnel, a Tailscale name), or `*` to turn the check off. Also counts as "same site" for the cross-site write check behind a proxy that forwards neither Host nor X-Forwarded-Host |-| `FUOBE_TRUSTED_PROXIES` (or `FUOBE_TRUST_PROXY=1`, one hop) | Behind a reverse proxy: how many `X-Forwarded-For` hops to trust (`1`, `2`…), or the proxies' addresses as a comma-separated CIDR list. Then wrong passwords, and too many wrong share links, lock out only that visitor (60 s), and sign-ins record the visitor's address. Without it, everyone shares one limit (passwords are slowed to one attempt every 4 s and never locked, and wrong share links past 100 a minute get 429 while real links still open) and no address is recorded |-| `FUOBE_SITE_URL` | The address people open Fuobe at. An `https://` address makes the sign-in cookies `__Host-` (Secure, whole site) |-| `FUOBE_INSTALL_NAME` | The name the sign-in card shows ("Sign in to …", default Fuobe) |-| `FUOBE_MODE` | `personal` (the only mode so far; without `FUOBE_SIGNIN` or a password it is Just me on this computer). `studio` and `platform` stop the start with one line until accounts arrive |+| `FUOBE_TRUST_PROXY=1` | Behind a reverse proxy: trust the last `X-Forwarded-For` hop, so wrong passwords, and too many wrong share links, lock out only that visitor (60 s). Without it, everyone shares one limit: passwords are slowed to one attempt every 4 s and never locked, and wrong share links past 100 a minute get 429 while real links still open || `FUOBE_ALLOW_PRIVATE_URLS=1` | Let inputs, product links and project sources be fetched from private / LAN addresses (they are refused by default), and let Assist connectors use plain http beyond localhost (without it a connector needs https unless it is on localhost; a private https address is accepted, with a warning that Claude can only reach it through a public tunnel) |-| `FUOBE_DATA_DIR` | Where the database, files and `secret.key` live (default `./data`). An `auth.json` from before accounts is imported once at the first start and then left in place, unread |+| `FUOBE_DATA_DIR` | Where the database, files and `auth.json` live (default `./data`) || `FUOBE_DEMO_MODE` | `auto` (default: demo outputs only when a model's provider isn't connected), `on` or `off` || `FUOBE_SKILLS_DIR` | Where Assist's built-in skills are read from (default `./skills`) || `FUOBE_ENGINE_MODE`, `FUOBE_CLOUD_PROVIDER`, `FUOBE_ENHANCE_PROVIDER` | The Settings choices above |@@ -108,7 +103,6 @@ Uploads up to 200 MB work with sign-in on. Inputs given as URLs are fetched only- **Get the new code and rebuild.** Pull `main`. On Windows, run `start.bat` as usual: it installs packages on every start and rebuilds because the code changed. On Mac or Linux, run `pnpm install`, then `pnpm build` (or just `pnpm dev`). Round 4 adds only one dependency, `@types/three` (for development; PR #9, PR #10, PR #12, PR #13 and PR #14 add none, so `pnpm install` has nothing new for them); round 3 added `@xyflow/react`, `@google/model-viewer`, `three` and `unpdf`. In a checkout without `.next`, run `pnpm exec next typegen` (or a dev or build run) before `pnpm typecheck`.- **Your data upgrades on its own.** The database migrations run once each at start-up, in order, and an existing `data/` folder (or `FUOBE_DATA_DIR`) keeps everything it holds. Round 4 adds seven migrations: one for the Library's nested folders, pins and review status (PR #6), two new tables in PR #9, `lora_mirrors` (each LoRA copy Fuobe makes) and `content_series` (Content Factory), two in PR #12: `shares` (share links; only a hash of each link's token is stored) and Assist's `assist_schedules` and `assist_connectors`, with four new columns on `assist_thread_state`, and two in PR #13: `swap_projects` (one document per Character Swap Studio project) and the O7 cleanup, which deletes the saved Higgsfield key, turns "Higgsfield first" into Automatic and marks the ads Higgsfield drew `baked`. They are added at the first start. PR #12's and `swap_projects` only add tables and columns, but the O7 cleanup can't be undone, so back up `data/` (or `FUOBE_DATA_DIR`) first if you might go back to an earlier version. PR #7, PR #10 and PR #14 add none (still 23 migrations). Settings → Models & licences keeps its switches in the existing settings table (`models.access`), Soul ID uses the existing trainings table, and since PR #14 a skill's recipe lives with its other files in the skills table. The list is in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md#storage-srcserverdbts-storagets-settingsts).-- **Sign-in moves to accounts.** The first start copies the database to `data/backups/fuobe-<time>-pre-accounts.db` (without sign-in sessions), moves the password and API tokens from `data/auth.json` into the database (the file stays, unread) and makes `data/secret.key`: back that up with the database, since a different key stops the start. With a password, each browser signs in once more; API tokens, MCP clients, the CLI, share links and `FUOBE_PASSWORD` keep working. Without one nothing changes: Just me on this computer. Adds `better-auth` 1.7.10 and `kysely` 0.29.6 (both MIT).- **Canvases are saved in a new form (PR #10).** A board is rewritten with pages the next time it is saved, and older Fuobe builds can't read it after that. Back up the data folder if you might go back to an earlier version. Scripts that read a canvas through the API: `GET /api/canvases/:id` now returns `canvas.pages` (each page with its graph), not `canvas.graph`.- **If you ran one of the round-3 package branches** (`r3/*`, `r3b/*`) before they were merged, start with a fresh data folder. Those branches numbered their migrations differently, so tables can be missing. Move the old folder aside rather than deleting it if it holds results you want. A folder used by the `r4/assist-connectors` branch before its review fixes needs the same: its migration changed in place. The same goes for a folder used by the `r4/content-factory` branch on its own: there Content Factory's table took the Library migration's number, so the Library's folders, pins and review status would never be added.- **Start on Home now runs the job** in Image, Video or Edit instead of only opening the studio. With a saved key for the default model this is a paid run; the line under the box says first what will run and what it costs. **⌘K / Ctrl+K** opens the search palette instead of going Home.diff --git a/next.config.ts b/next.config.tsindex 4f45b4a8..60b44f74 100644--- a/next.config.ts+++ b/next.config.ts@@ -1,21 +1,5 @@import type { NextConfig } from "next";-/**- * Security headers (docs/research/accounts-8.md §7.1): no page may be framed by another site (clickjacking a- * signed-in owner), except share pages, which people embed. Sign-in pages and their APIs are never cached. The- * proxy sets no-store on the same paths too (src/proxy.ts NO_STORE).- */-export const SECURITY_HEADERS = [- {- source: "/((?!s/).*)",- headers: [- { key: "X-Frame-Options", value: "DENY" },- { key: "Content-Security-Policy", value: "frame-ancestors 'none'" },- ],- },- ...["/login", "/api/auth/:path*", "/api/identity/:path*"].map((source) => ({ source, headers: [{ key: "Cache-Control", value: "no-store" }] })),-];-const nextConfig: NextConfig = {/* config options here */cacheComponents: true,@@ -24,9 +8,6 @@ const nextConfig: NextConfig = {// The sign-in proxy buffers request bodies (10 MB by default): uploads take up to 200 MB plus the form overhead.proxyClientMaxBodySize: "210mb",},- async headers() {- return SECURITY_HEADERS;- },async redirects() {return [{ source: "/characters", destination: "/elements", permanent: true },diff --git a/package.json b/package.jsonindex 4bcd19a9..fc09910c 100644--- a/package.json+++ b/package.json@@ -35,12 +35,10 @@"@google/model-viewer": "4.3.1","@tanstack/react-query": "^5.104.3","@xyflow/react": "^12.12.0",- "better-auth": "1.7.10","better-sqlite3": "^13.0.3","class-variance-authority": "^0.7.1","cmdk": "^1.1.1","cn": "^0.5.0",- "kysely": "0.29.6","lucide-react": "^1.58.0","nanoid": "^6.0.2","next": "16.4.2",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 89403649..0e422101 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -23,9 +23,6 @@ importers:'@xyflow/react':specifier: ^12.12.0version: 12.12.0(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- better-auth:- specifier: 1.7.10- version: 1.7.10(@opentelemetry/[email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])))better-sqlite3:specifier: ^13.0.3version: 13.0.3@@ -38,9 +35,6 @@ importers:cn:specifier: ^0.5.0version: 0.5.0- kysely:- specifier: 0.29.6- version: 0.29.6lucide-react:specifier: ^1.58.0version: 1.58.0(@types/[email protected])([email protected])@@ -272,82 +266,6 @@ packages:resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}engines: {node: '>=6.9.0'}- '@better-auth/[email protected]':- resolution: {integrity: sha512-c5vxtnk7UxWe/iF/X5sKSgmPcN5n6biuwJBs2dMkceMwvMWBHLosue6h/vmvKns9SYKbkBNWsurFe7yIbv13dQ==}- peerDependencies:- '@better-auth/utils': ^0.4.2 || ^0.5.0- '@better-fetch/fetch': 1.3.2- '@opentelemetry/api': ^1.9.0- better-call: 1.4.2- jose: ^6.1.0- kysely: ^0.28.5 || ^0.29.0- nanostores: ^1.0.1- peerDependenciesMeta:- '@opentelemetry/api':- optional: true-- '@better-auth/[email protected]':- resolution: {integrity: sha512-Uc/Eh9cnvorIWA6J97Hv8zjR8sCVUP6G7M3xHJGTD9qJXC69zoY4ULmNGA73AmGJB1q+VEYs2cRMtJ6fR6HP6g==}- peerDependencies:- '@better-auth/core': ^1.7.10- '@better-auth/utils': ^0.4.2 || ^0.5.0- drizzle-orm: ^0.45.2 || >=1.0.0-rc.1 <2.0.0- peerDependenciesMeta:- drizzle-orm:- optional: true-- '@better-auth/[email protected]':- resolution: {integrity: sha512-ZWWc6h5lgcwQMTcqMLNWw+jTEMFfrqJHD+VamiCUdaAxZzVAkjLZzVA2r0vZ5w7xnTY9vWS7wuNVqAKNLRTlYQ==}- peerDependencies:- '@better-auth/core': ^1.7.10- '@better-auth/utils': ^0.4.2 || ^0.5.0- kysely: ^0.28.17 || ^0.29.0- peerDependenciesMeta:- kysely:- optional: true-- '@better-auth/[email protected]':- resolution: {integrity: sha512-3Di7y8BK5I2pCdpRaJ2ggkVliO/Swr6a/J+y9RFdwkbxhEMU1o9WD9IwoG3LFH8dvFF3kVo+GilsZsVNlYD+sw==}- peerDependencies:- '@better-auth/core': ^1.7.10- '@better-auth/utils': ^0.4.2 || ^0.5.0-- '@better-auth/[email protected]':- resolution: {integrity: sha512-7z48PlXtlSKGvdOXfVmbjZE1vRmYyOQqHiPbeLpw+NvAPSTI9N4r7OO47u2MebA3q25e3GoGEwk5BAEE07u+PQ==}- peerDependencies:- '@better-auth/core': ^1.7.10- '@better-auth/utils': ^0.4.2 || ^0.5.0- mongodb: ^6.0.0 || ^7.0.0- peerDependenciesMeta:- mongodb:- optional: true-- '@better-auth/[email protected]':- resolution: {integrity: sha512-hNlhn0Kcq/O76SehvqznFsjqfEMdM2m2ctazU/BLv+jT8+hGvvxCInXZi6x86/xpAyDTgU7t7KsK50r6mdNR1g==}- peerDependencies:- '@better-auth/core': ^1.7.10- '@better-auth/utils': ^0.4.2 || ^0.5.0- '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0- prisma: ^5.0.0 || ^6.0.0 || ^7.0.0- peerDependenciesMeta:- '@prisma/client':- optional: true- prisma:- optional: true-- '@better-auth/[email protected]':- resolution: {integrity: sha512-1OamUtbGRaYHB0tRjKK3Jv6hzI6mZMv3pujkg8k7tr3idQuToMoVXsWAD9oFbUTmOLeix58n+grzsl7r0fR0Sw==}- peerDependencies:- '@better-auth/core': ^1.7.10- '@better-auth/utils': ^0.4.2 || ^0.5.0- '@better-fetch/fetch': 1.3.2-- '@better-auth/[email protected]':- resolution: {integrity: sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA==}-- '@better-fetch/[email protected]':- resolution: {integrity: sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow==}-'@dimforge/[email protected]':resolution: {integrity: sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==}@@ -500,105 +418,89 @@ packages:resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}cpu: [arm64]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}cpu: [arm]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}cpu: [ppc64]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}cpu: [riscv64]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}cpu: [s390x]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}cpu: [x64]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}cpu: [arm64]os: [linux]- libc: [musl]'@img/[email protected]':resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}cpu: [x64]os: [linux]- libc: [musl]'@img/[email protected]':resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}engines: {node: '>=20.9.0'}cpu: [arm64]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}engines: {node: '>=20.9.0'}cpu: [arm]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}engines: {node: '>=20.9.0'}cpu: [ppc64]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}engines: {node: '>=20.9.0'}cpu: [riscv64]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}engines: {node: '>=20.9.0'}cpu: [s390x]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}engines: {node: '>=20.9.0'}cpu: [x64]os: [linux]- libc: [glibc]'@img/[email protected]':resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}engines: {node: '>=20.9.0'}cpu: [arm64]os: [linux]- libc: [musl]'@img/[email protected]':resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}engines: {node: '>=20.9.0'}cpu: [x64]os: [linux]- libc: [musl]'@img/[email protected]':resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}@@ -698,28 +600,24 @@ packages:engines: {node: '>= 10'}cpu: [arm64]os: [linux]- libc: [glibc]'@next/[email protected]':resolution: {integrity: sha512-T1PNmfbPcxr5ndtWUL/3wQtLXsz808lq6sc2GrNT5k2oquF7UyqZddHSuAewHVsWsGXe6nsl9HoN1YNriVjuSg==}engines: {node: '>= 10'}cpu: [arm64]os: [linux]- libc: [musl]'@next/[email protected]':resolution: {integrity: sha512-N9cDUOCGtkJG5PNKDFZUF3xXndrJJcpLp121uAGjIGvO/U2p9tfdNOM9htj7+5f72l0m8rMw/cvYacUJBQoudg==}engines: {node: '>= 10'}cpu: [x64]os: [linux]- libc: [glibc]'@next/[email protected]':resolution: {integrity: sha512-yY2uh1YhX6ufuYy2FCbw1dqblbhI57GLYAJfCkqD9auTv6pLrH67Uccjc3QMKBeCYAG6lkgu08ExmX1bbjejjQ==}engines: {node: '>= 10'}cpu: [x64]os: [linux]- libc: [musl]'@next/[email protected]':resolution: {integrity: sha512-j/ArWRIHpMMB6wYLMhr2puTguBt70lNU/Cmjl9p6dTDE8DGknYJMP9PdwPk2dqpCNL/KIX9yfngDvIesxJPmsg==}@@ -733,14 +631,6 @@ packages:cpu: [x64]os: [win32]- '@noble/[email protected]':- resolution: {integrity: sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==}- engines: {node: '>= 20.19.0'}-- '@noble/[email protected]':- resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==}- engines: {node: '>= 20.19.0'}-'@nodelib/[email protected]':resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}engines: {node: '>= 8'}@@ -761,10 +651,6 @@ packages:resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==}engines: {node: '>=8.0.0'}- '@opentelemetry/[email protected]':- resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==}- engines: {node: '>=14'}-'@oxc-project/[email protected]':resolution: {integrity: sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==}@@ -1499,42 +1385,36 @@ packages:engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [linux]- libc: [glibc]'@rolldown/[email protected]':resolution: {integrity: sha512-BJ2CL19M6uuWesMgnqJzgxoI+N+eV7b0A9O9vLV42y+gitC41fNa8KElau1tHVzuLWX5GzEuxMPhAO0tQXQMkg==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [arm64]os: [linux]- libc: [musl]'@rolldown/[email protected]':resolution: {integrity: sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [ppc64]os: [linux]- libc: [glibc]'@rolldown/[email protected]':resolution: {integrity: sha512-V/h8ePq1fKDrmtFMz6xcCN3DKvuvMRrwwD1q0PkBeeo4DpK64biaKvqWGVxqCeYKqeRk7gE7/iKPxLCn08O97A==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [s390x]os: [linux]- libc: [glibc]'@rolldown/[email protected]':resolution: {integrity: sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [x64]os: [linux]- libc: [glibc]'@rolldown/[email protected]':resolution: {integrity: sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==}engines: {node: ^20.19.0 || >=22.12.0}cpu: [x64]os: [linux]- libc: [musl]'@rolldown/[email protected]':resolution: {integrity: sha512-qyr5XiNGxm2ytx17vvtcJ9nXn6v1gENETi503bJx3OGwZ1tSonj7BosxbMa/xeAfSl5iS9X6KjEWYXLu6v1L7Q==}@@ -1574,9 +1454,6 @@ packages:'@stablelib/[email protected]':resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}- '@standard-schema/[email protected]':- resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}-'@swc/[email protected]':resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==}@@ -1618,28 +1495,24 @@ packages:engines: {node: '>= 20'}cpu: [arm64]os: [linux]- libc: [glibc]'@tailwindcss/[email protected]':resolution: {integrity: sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==}engines: {node: '>= 20'}cpu: [arm64]os: [linux]- libc: [musl]'@tailwindcss/[email protected]':resolution: {integrity: sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==}engines: {node: '>= 20'}cpu: [x64]os: [linux]- libc: [glibc]'@tailwindcss/[email protected]':resolution: {integrity: sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==}engines: {node: '>= 20'}cpu: [x64]os: [linux]- libc: [musl]'@tailwindcss/[email protected]':resolution: {integrity: sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==}@@ -1873,61 +1746,51 @@ packages:resolution: {integrity: sha512-zJc0H99FEPoFfSrNpa91HYfxzfAJCr502oxNK1cfdC9hlaFI43RT+JFCann9JUgZmLzzntChHyn13Sgn9ljHNg==}cpu: [arm64]os: [linux]- libc: [glibc]'@unrs/[email protected]':resolution: {integrity: sha512-KQ3Lki6l+Pz1k/eBipN41ES+YUK30beLGb9YqcB1O542cyLCNE6GaxrfcY3T6EezmGGk84wb5XyO9loTM9tkcA==}cpu: [arm64]os: [linux]- libc: [musl]'@unrs/[email protected]':resolution: {integrity: sha512-3SJGEh1DborhG6pyxvhPzCT4bbSIVihsvgJc13P1bHG7KLdNDaF9T3gsTwFc7Jw/5Y5/iWOjkEx7Zy0NvCGX3Q==}cpu: [loong64]os: [linux]- libc: [glibc]'@unrs/[email protected]':resolution: {integrity: sha512-jiuG/Obbel7uw1PwHNFfrkiKhLAF6mnyZ6aWlOAVN9WqKm8v0OFGnciJIHu8+CMvXLQ8AD51LPzAoUfT21D5Ew==}cpu: [loong64]os: [linux]- libc: [musl]'@unrs/[email protected]':resolution: {integrity: sha512-q7xRvVpmcfeL+LlZg8Pbbo6QaTZwDU5BaGZbwfhkEsXJn3Was8xYfE0RBH266xZt0rM6B7i8xAYIvjthuUIWHg==}cpu: [ppc64]os: [linux]- libc: [glibc]'@unrs/[email protected]':resolution: {integrity: sha512-0CVdx6lcnT3Q9inOH8tsMIOJ6ImndllMjqJHg8RLVdB7Vq4SfkEXl9mCSsVNuNA4MCYycRicCUxPCabVHJRr6A==}cpu: [riscv64]os: [linux]- libc: [glibc]'@unrs/[email protected]':resolution: {integrity: sha512-iOwlRo9vnp6R6ohHQS11n0NnfdXx/omhkocmIfaPRpQhKZ+3BDMkkdRVh53qjkFkpPddf+FETA28NwGN7l5l+w==}cpu: [riscv64]os: [linux]- libc: [musl]'@unrs/[email protected]':resolution: {integrity: sha512-HYJtLfXq94q8iZNFT1lknx258wlkkWhZeUXJRqzKBBUJ00CvZ+N33zgbCqimLjsyw5Va6uUxhVa12mI+kaveEw==}cpu: [s390x]os: [linux]- libc: [glibc]'@unrs/[email protected]':resolution: {integrity: sha512-mPsUhunKKDih5O96Y6enDQyHc1SqBPlY1E/SfMWDM3EdJ95Z9CArPeCVwCCqbP45ljvivdEk8Fxn+SIb1rDAJQ==}cpu: [x64]os: [linux]- libc: [glibc]'@unrs/[email protected]':resolution: {integrity: sha512-azrt6+5ydLd8Vt210AAFis/lZevSfPw93EJRIJG+xPu4WCJ8K0kppCTpMyLPcKT7H15M4Jnt2tMp5bOvCkRC6A==}cpu: [x64]os: [linux]- libc: [musl]'@unrs/[email protected]':resolution: {integrity: sha512-YZ9hP4O0X9PQb8eO980qmLNGH4zT3I9+SZTdt0Pr0YyuGQhYKoOZkV02VzrzyOZJ5xIJ3UFIenKkUkGg8GjgWQ==}@@ -2128,73 +1991,6 @@ packages:engines: {node: '>=6.0.0'}hasBin: true- resolution: {integrity: sha512-Paf0X8cHKQc8jCgM3vl4AoxRicWdNf0zw8Aggn1q6aNSWCDDxSZCb6rkXa/O9cPc8idjVPK0rV/eHPHAbs07ZA==}- peerDependencies:- '@lynx-js/react': '*'- '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0- '@sveltejs/kit': ^2.0.0 || ^3.0.0- '@tanstack/react-start': ^1.0.0- '@tanstack/solid-start': ^1.0.0- drizzle-kit: '>=0.31.4 || >=1.0.0-beta.1'- drizzle-orm: ^0.45.2 || >=1.0.0-rc.1 <2.0.0- mongodb: ^6.0.0 || ^7.0.0- mysql2: ^3.0.0- next: ^14.0.0 || ^15.0.0 || ^16.0.0- pg: ^8.0.0- prisma: ^5.0.0 || ^6.0.0 || ^7.0.0- react: ^18.0.0 || ^19.0.0- react-dom: ^18.0.0 || ^19.0.0- solid-js: ^1.0.0- svelte: ^4.0.0 || ^5.0.0- vitest: ^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0- vue: ^3.0.0- peerDependenciesMeta:- '@lynx-js/react':- optional: true- '@prisma/client':- optional: true- '@sveltejs/kit':- optional: true- '@tanstack/react-start':- optional: true- '@tanstack/solid-start':- optional: true- drizzle-kit:- optional: true- drizzle-orm:- optional: true- mongodb:- optional: true- mysql2:- optional: true- next:- optional: true- pg:- optional: true- prisma:- optional: true- react:- optional: true- react-dom:- optional: true- solid-js:- optional: true- svelte:- optional: true- vitest:- optional: true- vue:- optional: true-- resolution: {integrity: sha512-lOmFCTG1KcE60YWxoff2Wx0Fv7v7drP/fQTDYnhJUCdkA7V6QWXdLPUiMpOQCq7Fd0Ts3AkrRwD23xoiootlGA==}- peerDependencies:- zod: ^4.0.0- peerDependenciesMeta:- zod:- optional: true-resolution: {integrity: sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==}engines: {node: '>=22'}@@ -2493,9 +2289,6 @@ packages:resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}engines: {node: '>= 0.4'}- resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==}-resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}engines: {node: '>= 0.8'}@@ -3331,10 +3124,6 @@ packages:resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}engines: {node: '>=6'}- resolution: {integrity: sha512-hHaB8C/rfzDDtr/t8YZwxAuPJTT0zHyaPoVzcXwDYhYNAgH/4sIfVhi/XLLIY+bL/FqaIJnjATDbi8ObSELmxg==}- engines: {node: '>=22.0.0'}-resolution: {integrity: sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==}@@ -3414,56 +3203,48 @@ packages:engines: {node: '>= 12.0.0'}cpu: [arm64]os: [linux]- libc: [glibc]resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==}engines: {node: '>= 12.0.0'}cpu: [arm64]os: [linux]- libc: [glibc]resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}engines: {node: '>= 12.0.0'}cpu: [arm64]os: [linux]- libc: [musl]resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}engines: {node: '>= 12.0.0'}cpu: [arm64]os: [linux]- libc: [musl]resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}engines: {node: '>= 12.0.0'}cpu: [x64]os: [linux]- libc: [glibc]resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==}engines: {node: '>= 12.0.0'}cpu: [x64]os: [linux]- libc: [glibc]resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}engines: {node: '>= 12.0.0'}cpu: [x64]os: [linux]- libc: [musl]resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}engines: {node: '>= 12.0.0'}cpu: [x64]os: [linux]- libc: [musl]resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}@@ -3750,10 +3531,6 @@ packages:engines: {node: ^22 || ^24 || >=26}hasBin: true- resolution: {integrity: sha512-FixtE239Gl6Gz0ZGCK0WzvNwObNCIwVT+L7zQcf1QgcA6AzBxblzqe9OT88qiucNkhsjSOqiogSaF5jVbJiqSA==}- engines: {node: ^20.0.0 || >=22.0.0}-resolution: {integrity: sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==}engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0}@@ -4148,9 +3925,6 @@ packages:engines: {node: ^20.19.0 || >=22.12.0}hasBin: true- resolution: {integrity: sha512-3SOzvaAg8rkHrXtRjpCvCvbyO5to9oOO27Z/XqHEYXfMRVSw/qMIVdmaOk9W2lcRLtR6dlqTjo9hDeJk70QBYQ==}-resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}engines: {node: '>= 18'}@@ -4200,9 +3974,6 @@ packages:resolution: {integrity: sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==}- resolution: {integrity: sha512-xletSdAI5efyVJjsatBbzDkXl3M/Zmad3xfnQe7ZXuBB0yNwW7C2WFsNGjdRNfZunmNHQuX79xs/ACMTLCdcew==}-resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==}engines: {node: '>= 0.4'}@@ -4988,59 +4759,6 @@ snapshots:'@babel/helper-string-parser': 7.29.7'@babel/helper-validator-identifier': 7.29.7- '@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])':- dependencies:- '@better-auth/utils': 0.5.0- '@better-fetch/fetch': 1.3.2- '@opentelemetry/semantic-conventions': 1.43.0- '@standard-schema/spec': 1.1.0- better-call: 1.4.2([email protected])- jose: 6.2.12- kysely: 0.29.6- nanostores: 1.5.5- zod: 4.6.7- optionalDependencies:- '@opentelemetry/api': 1.9.1-- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':- dependencies:- '@better-auth/core': 1.7.10(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])- '@better-auth/utils': 0.5.0-- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])':- dependencies:- '@better-auth/core': 1.7.10(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])- '@better-auth/utils': 0.5.0- optionalDependencies:- kysely: 0.29.6-- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':- dependencies:- '@better-auth/core': 1.7.10(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])- '@better-auth/utils': 0.5.0-- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':- dependencies:- '@better-auth/core': 1.7.10(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])- '@better-auth/utils': 0.5.0-- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':- dependencies:- '@better-auth/core': 1.7.10(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])- '@better-auth/utils': 0.5.0-- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])':- dependencies:- '@better-auth/core': 1.7.10(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])- '@better-auth/utils': 0.5.0- '@better-fetch/fetch': 1.3.2-- '@better-auth/[email protected]':- dependencies:- '@noble/hashes': 2.4.0-- '@better-fetch/[email protected]': {}-'@dimforge/[email protected]': {}'@dotenvx/[email protected]':@@ -5386,10 +5104,6 @@ snapshots:'@next/[email protected]':optional: true- '@noble/[email protected]': {}-- '@noble/[email protected]': {}-'@nodelib/[email protected]':dependencies:'@nodelib/fs.stat': 2.0.5@@ -5406,8 +5120,6 @@ snapshots:'@opentelemetry/[email protected]': {}- '@opentelemetry/[email protected]': {}-'@oxc-project/[email protected]': {}'@radix-ui/[email protected]': {}@@ -6245,8 +5957,6 @@ snapshots:'@stablelib/[email protected]': {}- '@standard-schema/[email protected]': {}-'@swc/[email protected]':dependencies:tslib: 2.8.1@@ -6776,42 +6486,6 @@ snapshots:- [email protected](@opentelemetry/[email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected]))):- dependencies:- '@better-auth/core': 1.7.10(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])- '@better-auth/drizzle-adapter': 1.7.10(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/kysely-adapter': 1.7.10(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])- '@better-auth/memory-adapter': 1.7.10(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/mongo-adapter': 1.7.10(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/prisma-adapter': 1.7.10(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/telemetry': 1.7.10(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])- '@better-auth/utils': 0.5.0- '@better-fetch/fetch': 1.3.2- '@noble/ciphers': 2.4.0- '@noble/hashes': 2.4.0- better-call: 1.4.2([email protected])- defu: 6.1.7- jose: 6.2.12- kysely: 0.29.6- nanostores: 1.5.5- zod: 4.6.7- optionalDependencies:- next: 16.4.2(@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.3.0- react-dom: 19.3.0([email protected])- vitest: 5.0.5(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected]))- transitivePeerDependencies:- - '@opentelemetry/api'-- dependencies:- '@better-auth/utils': 0.5.0- '@better-fetch/fetch': 1.3.2- rou3: 0.9.2- set-cookie-parser: 3.1.3- optionalDependencies:- zod: 4.6.7-dependencies:node-addon-api: 8.9.2@@ -7086,8 +6760,6 @@ snapshots:has-property-descriptors: 1.0.2object-keys: 1.1.1- [email protected]: {}-@@ -8069,8 +7741,6 @@ snapshots:- [email protected]: {}-@@ -8639,8 +8309,6 @@ snapshots:- [email protected]: {}-@@ -9159,8 +8827,6 @@ snapshots:'@rolldown/binding-win32-arm64-msvc': 1.2.14'@rolldown/binding-win32-x64-msvc': 1.2.14- [email protected]: {}-dependencies:debug: 4.4.3@@ -9231,8 +8897,6 @@ snapshots:- [email protected]: {}-dependencies:define-data-property: 1.1.4diff --git a/scripts/auth-schema.mjs b/scripts/auth-schema.mjsdeleted file mode 100644index 9eb5cf6b..00000000--- a/scripts/auth-schema.mjs+++ /dev/null@@ -1,80 +0,0 @@-#!/usr/bin/env node-/**- * Better Auth's tables, frozen as SQL for Fuobe's migrations (docs/research/accounts-8.md §5.2, §7.1).- *- * Fuobe never lets Better Auth change the database at run time: its tables are created by an ordinary migration in- * src/server/db.ts, with exactly the SQL Better Auth would have run. This prints that SQL.- *- * node scripts/auth-schema.mjs the full SQL for an empty database (what the identity base froze)- * node scripts/auth-schema.mjs --db <file> what that database still lacks: append it as a new migration- * node scripts/auth-schema.mjs --db <file> --check- * exit 1 when anything is missing (the schema-guard test does the- * same against the running configuration)- *- * The table names and plugin list come from src/server/identity/schema.ts, the file auth.ts reads them from. A- * package that loads a plugin with tables adds it there and in PLUGINS below.- */-import fs from "node:fs";-import path from "node:path";-import { fileURLToPath } from "node:url";-import Database from "better-sqlite3";-import { getMigrations } from "better-auth/db/migration";--// schema.ts is plain TypeScript Node can strip; it only warns that package.json names no module type.-process.removeAllListeners("warning");-process.on("warning", (w) => w.code !== "MODULE_TYPELESS_PACKAGE_JSON" && console.warn(w));-const { AUTH_PLUGINS_WITH_TABLES, AUTH_TABLES } = await import("../src/server/identity/schema.ts");--/** Plugin id → a factory with the options that matter for its tables. Empty until a package loads one. */-const PLUGINS = {};--const args = process.argv.slice(2);-const flag = (name) => args.includes(name);-const value = (name) => {- const i = args.indexOf(name);- return i >= 0 ? args[i + 1] : undefined;-};--const file = value("--db");-if (file && !fs.existsSync(file)) {- console.error(`No database at ${file}`);- process.exit(2);-}-const missing = AUTH_PLUGINS_WITH_TABLES.filter((id) => !PLUGINS[id]);-if (missing.length) {- console.error(`scripts/auth-schema.mjs doesn't know how to load: ${missing.join(", ")}. Add them to PLUGINS.`);- process.exit(2);-}--const database = new Database(file ?? ":memory:", { readonly: !!file });-const options = {- database,- telemetry: { enabled: false },- logger: { disabled: true },- user: { modelName: AUTH_TABLES.user },- session: { modelName: AUTH_TABLES.session },- account: { modelName: AUTH_TABLES.account },- verification: { modelName: AUTH_TABLES.verification },- rateLimit: { enabled: true, storage: "database", modelName: AUTH_TABLES.rateLimit },- emailAndPassword: { enabled: true },- plugins: AUTH_PLUGINS_WITH_TABLES.map((id) => PLUGINS[id]()),-};--const m = await getMigrations(options, { throwOnUnsafe: false });-const pending = m.toBeCreated.length + m.toBeAdded.length + m.toBeAddedIndexes.length;-const sql = pending ? (await m.compileMigrations()).trim() : "";-database.close();--const self = path.relative(process.cwd(), fileURLToPath(import.meta.url));-if (flag("--check")) {- if (pending) {- console.error(`Better Auth wants schema changes in ${file ?? "an empty database"}:\n\n${sql}\n\nFreeze them in a new migration (node ${self} --db ${file ?? "<file>"}).`);- process.exit(1);- }- console.log("Better Auth's tables match.");-} else if (!pending) {- console.log(`-- Nothing to freeze: ${file ?? "the database"} already has every table and column Better Auth uses.`);-} else {- console.log(sql);- for (const u of m.unsafeChanges) console.error(`warning: ${u}`);-}diff --git a/src/app/(studio)/settings/about/page.tsx b/src/app/(studio)/settings/about/page.tsxindex 408fbcca..95970696 100644--- a/src/app/(studio)/settings/about/page.tsx+++ b/src/app/(studio)/settings/about/page.tsx@@ -8,7 +8,7 @@ import { PageHeader, PageShell } from "@/components/page-shell";import { MODELS } from "@/lib/catalog";import type { Manifest } from "@/lib/comfy";import { FUOBE_REPO } from "@/lib/connections";-import { ATTRIBUTIONS, buildLicenceList, PINNED_LIBRARIES } from "@/lib/licences";+import { ATTRIBUTIONS, buildLicenceList } from "@/lib/licences";export const metadata: Metadata = { title: "About & licences" };@@ -148,19 +148,6 @@ export default async function Page() {Models you pull into Ollama for Assist and prompt enhancement carry their own licences: <code className="font-mono text-[12px]">ollama show <model> --license</code>.</li><li>The optional TRIBE v2 worker for the Virality page isn't bundled; its weights are CC BY-NC 4.0 (non-commercial).</li>- <li>- Sign-in runs on{" "}- {PINNED_LIBRARIES.map((l, i) => (- <span key={l.name}>- {i ? (i === PINNED_LIBRARIES.length - 1 ? " and " : ", ") : ""}- <a href={l.licence.url} target="_blank" rel="noreferrer" className="text-brand-text underline underline-offset-2">- {l.name} {l.version}- </a>{" "}- ({l.licence.name})- </span>- ))}- .- </li><li>Each workflow's models, sizes and download links are on the{" "}<Link href="/workflows" className="text-brand-text underline underline-offset-2">diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsindex 03bc2ace..99c7da90 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -1,54 +1,40 @@+import { cookies } from "next/headers";import { z } from "zod";-import { LoginGuard } from "@/server/auth";-import { appendAudit } from "@/server/identity/audit-log";-import { signInOwner, type SignInResult } from "@/server/identity/owner";-import { PASSWORD_SIGN_IN_MAX } from "@/server/identity/password";-import { refusal } from "@/server/identity/refusals";-import { signInRequired } from "@/server/mode";+import { authEnabled, checkPassword, createSession, LoginGuard, SESSION_COOKIE } from "@/server/auth";-/**- * Personal sign-in (docs/research/accounts-8.md §8): one password field, no email. Signs u_owner in through Better- * Auth (its session, its cookies, the password upgrade); the page then does a full load, so nothing from before the- * sign-in stays in memory. Kept at this path so today's page and scripts work unchanged.- */--const Body = z.object({ password: z.string().min(1).max(PASSWORD_SIGN_IN_MAX) });+const Body = z.object({ password: z.string().min(1).max(500) });declare global {var __fuobeLoginGuard: LoginGuard | undefined;}const guard = (globalThis.__fuobeLoginGuard ??= new LoginGuard());-/** The pre-accounts session cookie: no longer accepted, cleared on the next sign-in or sign-out. */-const LEGACY_SESSION_COOKIE = "fuobe_session";-export async function POST(request: Request) {- if (!signInRequired()) return Response.json({ ok: true });+ if (!authEnabled()) return Response.json({ ok: true });const key = LoginGuard.clientKey(request.headers);const wait = guard.blockedFor(key);if (wait > 0) {const secs = Math.ceil(wait / 1000);// Without a trusted proxy every visitor shares one limit (the hint is for whoever runs the server).- const hint = key === LoginGuard.DIRECT ? " Behind a reverse proxy? Set FUOBE_TRUSTED_PROXIES=1 so each visitor gets their own limit." : "";+ const hint = key === LoginGuard.DIRECT ? " Behind a reverse proxy? Set FUOBE_TRUST_PROXY=1 so each visitor gets their own limit." : "";return Response.json({ error: `Too many wrong passwords. Try again in ${secs} second${secs === 1 ? "" : "s"}.${hint}` },{ status: 429, headers: { "Retry-After": String(secs) } },);}const parsed = Body.safeParse(await request.json().catch(() => null));- const result: SignInResult = parsed.success ? await signInOwner(parsed.data.password, request.headers) : { ok: false };- if (!result.ok) {- if (result.code) {- const r = refusal(result.code);- return Response.json({ error: r.message, code: r.code }, { status: r.status });- }+ if (!parsed.success || !checkPassword(parsed.data.password)) {guard.fail(key);- appendAudit({ action: "auth.sign_in_failed", via: "session", meta: { method: "password" }, userAgent: request.headers.get("user-agent") });- return Response.json({ error: "That password isn't right." }, { status: 401 });+ return Response.json({ error: "Wrong password" }, { status: 401 });}guard.succeed(key);- const headers = new Headers({ "Cache-Control": "no-store" });- for (const c of result.setCookies) headers.append("set-cookie", c);- headers.append("set-cookie", `${LEGACY_SESSION_COOKIE}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax`);- return Response.json({ ok: true }, { headers });+ const s = createSession();+ (await cookies()).set(SESSION_COOKIE, s.value, {+ httpOnly: true,+ sameSite: "lax",+ secure: new URL(request.url).protocol === "https:",+ path: "/",+ maxAge: s.maxAge,+ });+ return Response.json({ ok: true });}diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.tsindex e1fda938..240babb1 100644--- a/src/app/api/auth/logout/route.ts+++ b/src/app/api/auth/logout/route.ts@@ -1,14 +1,7 @@-import { appendAudit } from "@/server/identity/audit-log";-import { signOut } from "@/server/identity/owner";-import { resolvePrincipal } from "@/server/identity/principal";+import { cookies } from "next/headers";+import { SESSION_COOKIE } from "@/server/auth";-/** Sign out: Better Auth deletes the session (so the cookie is dead everywhere) and expires the cookie. */-export async function POST(request: Request) {- const { actor } = await resolvePrincipal(request);- const cookies = await signOut(request.headers);- if (actor?.via === "session") appendAudit({ action: "auth.sign_out", actorId: actor.userId, via: "session", targetKind: "session", targetId: actor.sessionId ?? null });- const headers = new Headers({ "Cache-Control": "no-store" });- for (const c of cookies) headers.append("set-cookie", c);- headers.append("set-cookie", "fuobe_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax");- return Response.json({ ok: true }, { headers });+export async function POST() {+ (await cookies()).delete(SESSION_COOKIE);+ return Response.json({ ok: true });}diff --git a/src/app/api/auth/password/route.ts b/src/app/api/auth/password/route.tsindex bb6bd631..98f33be8 100644--- a/src/app/api/auth/password/route.ts+++ b/src/app/api/auth/password/route.ts@@ -1,51 +1,33 @@+import { cookies } from "next/headers";import { connection } from "next/server";import { z } from "zod";-import { checkOwnerPassword, changeOwnerPassword, ownerPasswordStatus, signInOwner } from "@/server/identity/owner";-import { PASSWORD_SIGN_IN_MAX } from "@/server/identity/password";-import { resolvePrincipal } from "@/server/identity/principal";-import { listTokens } from "@/server/identity/tokens";-import { signInRequired } from "@/server/mode";+import { authEnabled, authStatus, checkPassword, createSession, SESSION_COOKIE, setPassword, validSession } from "@/server/auth";-/**- * Settings → Security in Personal: whether a password is required, and setting, changing or removing it (removing- * it turns sign-in off: Just me on this computer). Changing it needs the current one and a signed-in browser, signs- * every other browser out and keeps this one signed in.- */+const Body = z.object({ current: z.string().max(500).optional(), password: z.string().max(500).nullable() });-const Body = z.object({ current: z.string().max(PASSWORD_SIGN_IN_MAX).optional(), password: z.string().max(PASSWORD_SIGN_IN_MAX).nullable() });--async function status(request: Request) {- const { actor } = await resolvePrincipal(request);- return { enabled: signInRequired(), ...ownerPasswordStatus(), tokens: actor ? listTokens(actor.userId) : [] };-}--export async function GET(request: Request) {+export async function GET() {await connection();- return Response.json(await status(request));+ return Response.json(authStatus());}+/** Set, change or remove the password. Changing it needs the current one; this browser stays signed in. */export async function POST(request: Request) {const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Invalid request" }, { status: 400 });const { current, password } = parsed.data;- const { actor } = await resolvePrincipal(request);- if (signInRequired()) {- if (actor?.via !== "session" || actor.role !== "owner") return Response.json({ error: "Change the password from a signed-in browser" }, { status: 403 });- if (!(await checkOwnerPassword(current ?? ""))) return Response.json({ error: "The current password is wrong" }, { status: 403 });- } else if (actor?.via !== "local") {- return Response.json({ error: "Set a password from the computer Fuobe runs on" }, { status: 403 });- }+ const jar = await cookies();+ if (authEnabled() && !validSession(jar.get(SESSION_COOKIE)?.value)) return Response.json({ error: "Change the password from a signed-in browser" }, { status: 403 });+ if (authEnabled() && !checkPassword(current ?? "")) return Response.json({ error: "The current password is wrong" }, { status: 403 });try {- await changeOwnerPassword(password, { actorId: actor.userId, via: actor.via });+ setPassword(password);} catch (e) {return Response.json({ error: (e as Error).message }, { status: 400 });}- const headers = new Headers({ "Cache-Control": "no-store" });if (password) {- // Every browser was signed out; this one signs straight back in with the new password.- const signedIn = await signInOwner(password, request.headers);- if (signedIn.ok) for (const c of signedIn.setCookies) headers.append("set-cookie", c);+ const s = createSession();+ jar.set(SESSION_COOKIE, s.value, { httpOnly: true, sameSite: "lax", secure: new URL(request.url).protocol === "https:", path: "/", maxAge: s.maxAge });+ } else {+ jar.delete(SESSION_COOKIE);}- headers.append("set-cookie", "fuobe_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax");- return Response.json(await status(request), { headers });+ return Response.json(authStatus());}diff --git a/src/app/api/auth/tokens/route.ts b/src/app/api/auth/tokens/route.tsindex 8c7e6591..f7916d18 100644--- a/src/app/api/auth/tokens/route.ts+++ b/src/app/api/auth/tokens/route.ts@@ -1,39 +1,35 @@+import { cookies } from "next/headers";import { connection } from "next/server";import { z } from "zod";-import { resolvePrincipal, type Actor } from "@/server/identity/principal";-import { createToken, listTokens, revokeToken } from "@/server/identity/tokens";+import { authEnabled, authStatus, createToken, revokeToken, SESSION_COOKIE, validSession } from "@/server/auth";-/**- * API tokens, managed from a signed-in browser (or Just me on this computer): a token can't mint or revoke- * tokens. Each person sees and revokes their own (admins revoking anyone's arrives with the admin console).- */-async function browserActor(request: Request): Promise<Actor | Response> {- const { actor } = await resolvePrincipal(request);- if (actor && (actor.via === "session" || actor.via === "local")) return actor;+/** Tokens are managed from a signed-in browser only: a token can't mint or revoke tokens. */+async function browserOnly(): Promise<Response | null> {+ if (!authEnabled() || validSession((await cookies()).get(SESSION_COOKIE)?.value)) return null;return Response.json({ error: "Manage API tokens from a signed-in browser" }, { status: 403 });}-export async function GET(request: Request) {+export async function GET() {await connection();- const actor = await browserActor(request);- if (actor instanceof Response) return actor;- return Response.json({ tokens: listTokens(actor.userId) });+ const denied = await browserOnly();+ if (denied) return denied;+ return Response.json({ tokens: authStatus().tokens });}/** Create a token; the full value is in this response only. */export async function POST(request: Request) {- const actor = await browserActor(request);- if (actor instanceof Response) return actor;+ const denied = await browserOnly();+ if (denied) return denied;const parsed = z.object({ name: z.string().max(60) }).safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Name the token" }, { status: 400 });- return Response.json(createToken(actor.userId, parsed.data.name), { status: 201 });+ return Response.json(createToken(parsed.data.name), { status: 201 });}export async function DELETE(request: Request) {- const actor = await browserActor(request);- if (actor instanceof Response) return actor;+ const denied = await browserOnly();+ if (denied) return denied;const id = new URL(request.url).searchParams.get("id");if (!id) return Response.json({ error: "Which token?" }, { status: 400 });- if (!revokeToken(actor.userId, id)) return Response.json({ error: "No such token" }, { status: 404 });+ revokeToken(id);return new Response(null, { status: 204 });}diff --git a/src/app/api/identity/[...all]/route.ts b/src/app/api/identity/[...all]/route.tsdeleted file mode 100644index b853e61f..00000000--- a/src/app/api/identity/[...all]/route.ts+++ /dev/null@@ -1,16 +0,0 @@-import { getAuth } from "@/server/identity/auth";-import { signInRequired } from "@/server/mode";--/**- * Better Auth's router (docs/research/accounts-8.md §7.1), mounted at /api/identity. Only allowlisted endpoints- * answer browser traffic (src/server/identity/auth.ts ROUTER_ALLOWED); sign-up and social sign-in arrive with the- * sign-in package. With sign-in off (Just me on this computer) there is nothing to sign in to, so nothing is- * mounted. Personal installs sign in through POST /api/auth/login.- */-async function handle(request: Request): Promise<Response> {- if (!signInRequired()) return Response.json({ error: "Sign-in is off on this Fuobe." }, { status: 404 });- return getAuth().handler(request);-}--export const GET = handle;-export const POST = handle;diff --git a/src/app/login/page.tsx b/src/app/login/page.tsxindex 34e29a07..9d5f993c 100644--- a/src/app/login/page.tsx+++ b/src/app/login/page.tsx@@ -1,39 +1,14 @@import type { Metadata } from "next";-import { connection } from "next/server";-import { Lock } from "lucide-react";import { Suspense } from "react";import { LoginForm } from "@/components/login-form";-import { Skeleton } from "@/components/ui/skeleton";-import { installName } from "@/server/mode";export const metadata: Metadata = { title: "Sign in" };-/** The install's name for the card's line ("Sign in to Fuobe."): read per request, never prerendered. */-async function Card() {- await connection();- return <LoginForm installName={installName()} />;-}--/** The card's frame while the name loads (prerendered; no field yet). */-function CardShell() {- return (- <div className="w-full max-w-sm rounded-2xl border bg-background p-7 shadow-soft max-[400px]:p-6" aria-busy>- <div className="mb-5 grid size-11 place-items-center rounded-xl bg-primary text-primary-foreground">- <Lock className="size-5" aria-hidden />- </div>- <h1 className="font-heading text-[28px] leading-tight">Welcome back</h1>- <Skeleton className="mt-2 h-4 w-40" />- <Skeleton className="mt-6 h-11 w-full" />- <Skeleton className="mt-4 h-11 w-full" />- </div>- );-}-export default function Page() {return (<main className="grid min-h-svh place-items-center bg-sidebar px-4">- <Suspense fallback={<CardShell />}>- <Card />+ <Suspense>+ <LoginForm /></Suspense></main>);diff --git a/src/components/login-form.tsx b/src/components/login-form.tsxindex 57e24567..a93b01b8 100644--- a/src/components/login-form.tsx+++ b/src/components/login-form.tsx@@ -1,94 +1,53 @@"use client";-import { Eye, EyeOff, Loader2, Lock } from "lucide-react";+import { Loader2, Lock } from "lucide-react";import { useSearchParams } from "next/navigation";-import { useId, useState } from "react";+import { useState } from "react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";import { safeNext } from "@/lib/safe-redirect";-import { refusalMessage } from "@/lib/sign-in-refusals";-/**- * The Personal sign-in card (docs/research/accounts-8-screens.md §S2.1): one password field, never an email. A- * refusal the proxy sent here (?code=) shows above the field. After signing in the page loads in full, so nothing- * from before stays in memory.- */-export function LoginForm({ installName }: { installName: string }) {+export function LoginForm() {const params = useSearchParams();- const id = useId();const [password, setPassword] = useState("");- const [shown, setShown] = useState(false);- const [error, setError] = useState<string | null>(() => {- const code = params.get("code");- return code ? refusalMessage(code, { name: installName }) : null;- });+ const [error, setError] = useState<string | null>(null);const [busy, setBusy] = useState(false);- const [forgot, setForgot] = useState(false);const submit = async (e: React.FormEvent) => {e.preventDefault();setBusy(true);setError(null);- const res = await fetch("/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password }) }).catch(() => null);- if (res?.ok) {+ const res = await fetch("/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password }) });+ if (res.ok) {// Only a page on this site: never bounce to another origin after signing in.window.location.assign(safeNext(params.get("next"), window.location.origin));return;}- setError(res ? (((await res.json().catch(() => ({}))) as { error?: string }).error ?? "Couldn't sign in. Try again.") : "Can't reach Fuobe. Check your connection and try again.");+ setError(((await res.json().catch(() => ({}))) as { error?: string }).error ?? "Couldn't sign in");setBusy(false);};return (- <form onSubmit={submit} className="w-full max-w-sm animate-fade-up rounded-2xl border bg-background p-7 shadow-soft max-[400px]:p-6">+ <form onSubmit={submit} className="w-full max-w-sm animate-fade-up rounded-2xl border bg-background p-7 shadow-soft"><div className="mb-5 grid size-11 place-items-center rounded-xl bg-primary text-primary-foreground">- <Lock className="size-5" aria-hidden />+ <Lock className="size-5" /></div><h1 className="font-heading text-[28px] leading-tight">Welcome back</h1>- <p className="mt-1 text-[13px] text-muted-foreground [overflow-wrap:anywhere]">Sign in to {installName}.</p>- <Label htmlFor={`${id}-password`} className="mt-5 text-[13px]">- Password- </Label>- <div className="relative mt-1.5">- <Input- id={`${id}-password`}- type={shown ? "text" : "password"}- autoFocus- autoComplete="current-password"- value={password}- onChange={(e) => setPassword(e.target.value)}- className="h-11 pr-11"- aria-invalid={!!error}- aria-describedby={error ? `${id}-error` : undefined}- />- <button- type="button"- onClick={() => setShown((s) => !s)}- // One fixed name with a pressed state: "Show password, toggle button, pressed" (a swapping name would- // announce two states at once).- aria-pressed={shown}- aria-label="Show password"- aria-controls={`${id}-password`}- className="absolute inset-y-0 right-0 grid w-11 place-items-center rounded-r-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- {shown ? <EyeOff className="size-4" /> : <Eye className="size-4" />}- </button>- </div>- {error && (- <p id={`${id}-error`} role="alert" className="mt-2 text-[13px] text-destructive">- {error}- </p>- )}+ <p className="mt-1 text-[13px] text-muted-foreground">This Fuobe studio is password protected.</p>+ <Input+ type="password"+ autoFocus+ autoComplete="current-password"+ placeholder="Password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ className="mt-5 h-11"+ aria-invalid={!!error}+ />+ {error && <p className="mt-2 text-[13px] text-destructive">{error}</p>}<Button type="submit" className="mt-4 h-11 w-full" disabled={!password || busy}>{busy && <Loader2 className="animate-spin" />} Sign in</Button>- <button type="button" onClick={() => setForgot((f) => !f)} aria-expanded={forgot} aria-controls={`${id}-forgot`} className="mt-4 text-[13px] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">- Forgot password?- </button>- <p id={`${id}-forgot`} hidden={!forgot} className="mt-2 text-[13px] leading-relaxed text-muted-foreground">- On the computer where Fuobe runs, start it again with <code className="rounded bg-muted px-1 py-0.5 font-mono text-[12px] text-foreground">FUOBE_PASSWORD</code> set to a new password. That password works right away, and every browser signs in again.- </p></form>);}diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsxindex 589d999a..5b9a4677 100644--- a/src/components/security-settings.tsx+++ b/src/components/security-settings.tsx@@ -2,6 +2,7 @@import { useQuery, useQueryClient } from "@tanstack/react-query";import { Copy, KeyRound, Loader2, LogOut, ShieldAlert, ShieldCheck, Trash2 } from "lucide-react";+import { useRouter } from "next/navigation";import { useId, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";@@ -19,10 +20,7 @@ interface TokenInfo {}interface AuthStatus {enabled: boolean;- /** FUOBE_PASSWORD sets the password. */fromEnv: boolean;- /** FUOBE_SIGNIN pins sign-in on or off (null when unset). */- signinFromEnv?: boolean | null;tokens: TokenInfo[];}@@ -80,7 +78,7 @@ function PasswordForm({ status, onDone }: { status: AuthStatus; onDone: () => vo{busy && <Loader2 className="animate-spin" />}{status.enabled ? "Change password" : "Require a password"}</Button>- {status.enabled && status.signinFromEnv !== true && (+ {status.enabled && (<Button size="sm" variant="ghost" className="text-destructive" disabled={busy || !current} onClick={() => void run(null)}>Remove password</Button>@@ -198,6 +196,7 @@ function Tokens({ status, onChange }: { status: AuthStatus; onChange: () => voidexport function SecuritySettings() {const qc = useQueryClient();+ const router = useRouter();const status = useQuery({ queryKey: ["auth"], queryFn: () => call<AuthStatus>("/api/auth/password", "GET") });const refresh = () => void qc.invalidateQueries({ queryKey: ["auth"] });if (!status.data) return <Loader2 className="size-5 animate-spin text-muted-foreground" />;@@ -207,18 +206,14 @@ export function SecuritySettings() {{s.enabled ? (<div className="flex items-start gap-2.5 rounded-xl bg-brand-faint px-3 py-2.5 text-[13px]"><ShieldCheck className="mt-0.5 size-4 shrink-0 text-brand-text" />- <p className="flex-1">- Sign-in is required for every page and API call.{s.fromEnv && " The password is set by FUOBE_PASSWORD on the server."}- {s.signinFromEnv === true && " Set by the server (FUOBE_SIGNIN=on), so the password can be changed but not removed."}- </p>+ <p className="flex-1">Sign-in is required for every page and API call.{s.fromEnv && " The password is set by FUOBE_PASSWORD on the server."}</p><Buttonsize="sm"variant="ghost"className="-my-1 h-7"onClick={async () => {await fetch("/api/auth/logout", { method: "POST" });- // A full load (the proxy sends it to sign in): nothing from the signed-in session stays in memory.- window.location.reload();+ router.replace("/login");}}><LogOut /> Sign out@@ -227,14 +222,10 @@ export function SecuritySettings() {) : (<div className="flex items-start gap-2.5 rounded-xl bg-amber-500/10 px-3 py-2.5 text-[13px] text-amber-800 dark:text-amber-300"><ShieldAlert className="mt-0.5 size-4 shrink-0" />- <p>- {s.signinFromEnv === false- ? "Sign-in is off: set by the server (FUOBE_SIGNIN=off). Anyone who can reach this server can use your keys and GPU. Restart without it to require a password."- : "No password: anyone who can reach this server can use your keys and GPU. Fine on your own computer — set a password before you open it to a network."}- </p>+ <p>No password: anyone who can reach this server can use your keys and GPU. Fine on your own computer — set a password before you open it to a network.</p></div>)}- {!s.fromEnv && s.signinFromEnv !== false && <PasswordForm status={s} onDone={refresh} />}+ {!s.fromEnv && <PasswordForm status={s} onDone={refresh} />}<Tokens status={s} onChange={refresh} /></div>);diff --git a/src/instrumentation.ts b/src/instrumentation.tsindex d2bf1533..1471ecf0 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -1,16 +1,11 @@/**- * Runs once when the server starts, before it takes requests. First the identity bootstrap (accounts: the- * pre-accounts snapshot, the root secret and its fingerprint, the auth.json import, FUOBE_PASSWORD): a server- * that must not start (a changed secret key, an unknown FUOBE_MODE) stops here with one line. Then start the- * generation runner right away, so jobs that were in+ * Runs once when the server starts: start the generation runner right away, so jobs that were in* flight before a restart keep advancing (and live updates flow) even when the UI only lists them.* Also empties what has been in the Trash for 30 days (then daily), starts Assist's scheduled tasks and Character* Swap Studio's sweep.*/export async function register() {if (process.env.NEXT_RUNTIME !== "nodejs" || process.env.NEXT_PHASE === "phase-production-build") return;- const { startIdentity } = await import("./server/identity/bootstrap");- await startIdentity();const { ensureRunner } = await import("./server/generations");ensureRunner();const { ensureTrashPurge } = await import("./server/library");diff --git a/src/lib/licences.ts b/src/lib/licences.tsindex 57d08428..a0b10eb5 100644--- a/src/lib/licences.ts+++ b/src/lib/licences.ts@@ -470,39 +470,6 @@ export const ATTRIBUTIONS: Attribution[] = [{ for: "DBS (vendored code)", text: "TIGER / Look2Hear, copyright (c) 2026 Kai Li", licence: "MIT", url: "https://github.com/JusperLee/TIGER" },];-// ----------------------------------------------------------------------------// Libraries pinned under the accounts plan's version rule (docs/research/accounts-8.md §5.2): the newest release at-// least 14 days old and free of OSV advisories, pinned exact in package.json (a test keeps the two in step). Each-// package that adds one records it here with its licence.--export interface PinnedLibrary {- name: string;- /** The exact version in package.json. */- version: string;- /** What Fuobe uses it for. */- use: string;- /** When the rule was applied (the 14 days count back from here). */- pinnedOn: string;- licence: LicenceInfo;-}--export const PINNED_LIBRARIES: PinnedLibrary[] = [- {- name: "better-auth",- version: "1.7.10",- use: "Sign-in behind Fuobe: passwords and sessions (later passkeys, two-step, Google/GitHub/OIDC and company sign-in)",- pinnedOn: "2026-10-29",- licence: { name: "MIT", class: "commercial", url: "https://github.com/better-auth/better-auth/blob/main/LICENSE.md", note: "MIT; every @better-auth/* package it pulls in is the same version" },- },- {- name: "kysely",- version: "0.29.6",- use: "The SQL layer Better Auth runs on (Fuobe hands it the connection with transactions off)",- pinnedOn: "2026-10-29",- licence: { name: "MIT", class: "commercial", url: SPDX("MIT"), note: "MIT; already Better Auth's dependency, pinned so Fuobe and Better Auth share one copy" },- },-];-/** The parts of a LoRA's licence snapshot the class needs (src/lib/catalog/types.ts LoraLicence). */interface LoraLicenceLike {commercial: boolean;diff --git a/src/lib/sign-in-refusals.ts b/src/lib/sign-in-refusals.tsdeleted file mode 100644index 4f3f5f6c..00000000--- a/src/lib/sign-in-refusals.ts+++ /dev/null@@ -1,27 +0,0 @@-/**- * Why a sign-in or a request was refused, in the words /login shows (docs/research/accounts-8-screens.md §S2.7).- * Pure, so the sign-in card and the server share one table. `{contact}` is the install's contact ("the Fuobe- * admin" by default) and `{name}` its name; the server fills them (src/server/identity/refusals.ts). Packages add- * their codes to REFUSAL_COPY when they add the check that refuses (SEAT_WAIT, SSO_REQUIRED, ACCOUNT_BANNED…).- */--export interface RefusalCopy {- /** HTTP status an API request gets. */- status: number;- message: string;-}--export const REFUSAL_COPY: Record<string, RefusalCopy> = {- ACCOUNT_PENDING: { status: 403, message: "Your account is waiting for approval. Ask {contact} to approve it." },- ACCOUNT_DISABLED: { status: 403, message: "This account is turned off. Ask an admin to turn it back on." },- ACCOUNT_DORMANT: { status: 403, message: "This Fuobe is in personal mode right now, so other accounts can't sign in. Ask {contact} to switch it back." },- PASSWORD_LOCKED: { status: 423, message: "Too many wrong passwords. Run fuobe recover on the computer where Fuobe runs." },-};--/** The copy for a code with its placeholders filled; null for a code nobody registered. */-export function refusalMessage(code: string, vars: { contact?: string; name?: string } = {}): string | null {- const copy = REFUSAL_COPY[code];- if (!copy) return null;- const name = vars.name || "Fuobe";- return copy.message.replaceAll("{contact}", vars.contact || `the ${name} admin`).replaceAll("{name}", name);-}diff --git a/src/proxy.ts b/src/proxy.tsindex dba67ef8..570a4570 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -2,57 +2,12 @@ import { NextResponse, type NextRequest } from "next/server";import { APPS } from "@/lib/catalog/apps";import { recordForPath, unknownHubMode } from "@/lib/record-pages";import { countsAsView, SHARE_VIEW_HEADER, shareRoute } from "@/lib/share";-import { clientIp, crossSite, hostAllowed, LoginGuard } from "@/server/auth";-import { refreshSession, resolvePrincipal } from "@/server/identity/principal";-import { refusal } from "@/server/identity/refusals";-import { signInRequired } from "@/server/mode";+import { authEnabled, crossSite, hostAllowed, LoginGuard, SESSION_COOKIE, validSession, validToken } from "@/server/auth";import { recordExists } from "@/server/records";import { findShare, shareGuard, shareTargetExists } from "@/server/share-access";-/**- * The perimeter, on every request (docs/research/accounts-8.md §7.1, §5.4). It is optimistic: route handlers- * authorize for themselves (acc-2). In order: DNS rebinding (sign-in off), cross-site writes, share links, then- * who is signing in — an API token, Better Auth's session cookie, or "Just me on this computer" (Personal with- * sign-in off) — and pages for records that don't exist (a real 404).- *- * Packages add their public paths to OPEN (setup, sign-in, recovery, invites, webhooks) and the paths that- * legitimately receive cross-site POSTs to CROSS_SITE_EXEMPT (a SAML assertion consumer, a payment webhook).- */--/** A path rule: an exact path, or a prefix ending in "/" (every path under it). */-type PathRule = string;-const ruleMatches = (rule: PathRule, pathname: string) => (rule.endsWith("/") ? pathname.startsWith(rule) : pathname === rule);--/** Paths that work signed out (share links are handled on their own, by openShare). */-export const OPEN: PathRule[] = ["/login", "/api/auth/login", "/api/identity/"];--/** Paths whose POSTs come from other sites by design (each one verifies its own signature). */-export const CROSS_SITE_EXEMPT: PathRule[] = [];--/** Sign-in pages and their APIs: never cached by a browser or a proxy. */-export const NO_STORE: PathRule[] = ["/login", "/api/auth/", "/api/identity/"];--const isOpen = (pathname: string) => OPEN.some((r) => ruleMatches(r, pathname));-const crossSiteExempt = (pathname: string) => CROSS_SITE_EXEMPT.some((r) => ruleMatches(r, pathname));-const noStore = (pathname: string) => NO_STORE.some((r) => ruleMatches(r, pathname));--/** The header Better Auth reads the client's address from; only this proxy may write it. */-export const CLIENT_IP_HEADER = "x-fuobe-client-ip";--/**- * The request headers handed on: any x-fuobe-client-ip a client sent is dropped, and one is written only when a- * trusted proxy reports the address. Null when nothing changes (the request goes on as it came).- */-function forwardHeaders(request: NextRequest): Headers | null {- const ip = clientIp(request.headers);- if (!ip && !request.headers.has(CLIENT_IP_HEADER)) return null;- const headers = new Headers(request.headers);- headers.delete(CLIENT_IP_HEADER);- if (ip) headers.set(CLIENT_IP_HEADER, ip);- return headers;-}--const next = (headers: Headers | null) => (headers ? NextResponse.next({ request: { headers } }) : NextResponse.next());+/** Paths that work signed out: the login page and its API (and share links: openShare). */+const OPEN = new Set(["/login", "/api/auth/login"]);const APP_IDS = new Set(APPS.map((a) => a.id));@@ -63,13 +18,13 @@ const APP_IDS = new Set(APPS.map((a) => a.id));* the id is unknown. (The proxy can't tell a client-side navigation from a page load, so a link to* a deleted id reloads into the same 404 page.)*/-function pass(request: NextRequest, headers: Headers | null): NextResponse {+function pass(request: NextRequest): NextResponse {const { pathname } = request.nextUrl;const app = /^\/apps\/([^/]+)\/?$/.exec(pathname)?.[1];if ((app && !APP_IDS.has(safeDecode(app))) || unknownHubMode(pathname)) return notFound(request);const record = recordForPath(pathname);if (record && !recordExists(record)) return notFound(request);- return next(headers);+ return NextResponse.next();}const notFound = (request: NextRequest) => NextResponse.rewrite(new URL("/_fuobe-not-found", request.url), { status: 404 });@@ -77,6 +32,8 @@ const notFound = (request: NextRequest) => NextResponse.rewrite(new URL("/_fuobe/** Share pages and their files: never indexed, and the token never leaks to another site in a Referer. */const SHARE_HEADERS = { "X-Robots-Tag": "noindex, nofollow, noarchive", "Referrer-Policy": "no-referrer" };+const signedIn = (request: NextRequest) => validSession(request.cookies.get(SESSION_COOKIE)?.value) || validToken(request.headers.get("authorization"));+const tooMany = (seconds: number) =>new NextResponse("Too many wrong links. Try again in a minute.", { status: 429, headers: { ...SHARE_HEADERS, "Retry-After": String(seconds) } });@@ -89,8 +46,8 @@ const tooMany = (seconds: number) =>* page shows. A page view by a visitor (a browser's GET, not a prefetch, a HEAD or a link-preview* bot) is passed on to the page as SHARE_VIEW_HEADER, which the page counts.*/-async function openShare(request: NextRequest, token: string, file: boolean): Promise<NextResponse> {- const owner = signInRequired() && !!(await resolvePrincipal(request)).actor;+function openShare(request: NextRequest, token: string, file: boolean): NextResponse {+ const owner = authEnabled() && signedIn(request);const guard = shareGuard();const key = LoginGuard.clientKey(request.headers);if (!owner) {@@ -108,7 +65,7 @@ async function openShare(request: NextRequest, token: string, file: boolean): Prres = NextResponse.rewrite(new URL("/s/gone", request.url), { status: 404 });} else {// Only the proxy says what counts as a view: a visitor can't send the header themselves.- const headers = forwardHeaders(request) ?? new Headers(request.headers);+ const headers = new Headers(request.headers);headers.delete(SHARE_VIEW_HEADER);if (!file && !owner && countsAsView(request.method, request.headers)) headers.set(SHARE_VIEW_HEADER, "1");res = NextResponse.next({ request: { headers } });@@ -125,61 +82,35 @@ function safeDecode(s: string): string {}}-const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);--async function guard(request: NextRequest): Promise<NextResponse> {- const signIn = signInRequired();- const host = request.headers.get("host") ?? request.nextUrl.host;- const { pathname, search } = request.nextUrl;- // DNS rebinding: a page whose own name now points at this machine. Every method, reads too. With sign-in on- // the check below already stops it (the session cookie belongs to the real name).- if (!signIn && !hostAllowed(host)) {+export function proxy(request: NextRequest) {+ // DNS rebinding: a page whose own name now points at this machine. Every method, reads too. With a+ // password set the sign-in check below already stops it (the session cookie belongs to the real name).+ if (!authEnabled() && !hostAllowed(request.headers.get("host") ?? request.nextUrl.host)) {+ const host = request.headers.get("host") ?? request.nextUrl.host;return NextResponse.json({ error: `Blocked a request for ${host}, which isn't a local address. If that's how you reach Fuobe, add it to FUOBE_ALLOWED_ORIGINS (or set a password).` },{ status: 403 },);}// Before the sign-in check: a password-less install needs this most.- if (!crossSiteExempt(pathname) && crossSite(request, request.nextUrl.host)) {+ if (crossSite(request, request.nextUrl.host)) {return NextResponse.json({ error: "Blocked a request from another website. Use Fuobe from its own address (or add it to FUOBE_ALLOWED_ORIGINS)." }, { status: 403 });}+ const { pathname, search } = request.nextUrl;// Share links are read-only and public, password or not: exactly a share's page and its files.const share = (request.method === "GET" || request.method === "HEAD") && shareRoute(pathname);if (share) return openShare(request, share.token, !!share.file);- const headers = forwardHeaders(request);- if (!signIn) {- // Just me on this computer: there is nothing to sign in to.- if (pathname === "/login") return NextResponse.redirect(new URL("/", request.url));- return pass(request, headers);- }- if (isOpen(pathname)) return next(headers);- const principal = await resolvePrincipal(request);- if (principal.actor) {- const res = pass(request, headers);- // Sessions roll forward once a day, on a POST (GET stays read-only).- if (principal.needsRefresh && !SAFE_METHODS.has(request.method)) for (const c of await refreshSession(request)) res.headers.append("set-cookie", c);- return res;- }+ if (!authEnabled()) return pass(request);+ if (OPEN.has(pathname)) return NextResponse.next();+ if (signedIn(request)) return pass(request);if (pathname.startsWith("/api/")) {- if (principal.code && principal.code !== "INVALID_TOKEN") {- const r = refusal(principal.code);- return NextResponse.json({ error: r.message, code: r.code }, { status: r.status });- }- const error = principal.code === "INVALID_TOKEN" ? "That API token isn't valid. Create a new one in Settings → Security." : "Sign in, or send an API token as Authorization: Bearer fuobe_…";- return NextResponse.json({ error }, { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="fuobe"' } });+ return NextResponse.json({ error: "Sign in, or send an API token as Authorization: Bearer fuobe_…" }, { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="fuobe"' } });}const login = new URL("/login", request.url);if (pathname !== "/") login.searchParams.set("next", pathname + search);- if (principal.code && principal.code !== "INVALID_TOKEN") login.searchParams.set("code", principal.code);return NextResponse.redirect(login);}-export async function proxy(request: NextRequest) {- const res = await guard(request);- if (noStore(request.nextUrl.pathname)) res.headers.set("Cache-Control", "no-store");- return res;-}-export const config = {// Everything except build assets and the public folder's own files: the favicon, the demo// samples and the SVGs at the root. Generated SVGs under /api/files stay behind sign-in.diff --git a/src/server/auth.ts b/src/server/auth.tsindex 6469ac98..7909fda6 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -1,47 +1,128 @@/**- * The perimeter checks the proxy runs on every request, whoever is signed in: cross-site writes, DNS rebinding,- * the client's address behind a trusted reverse proxy, and the wrong-password throttle. Who is signed in is- * src/server/identity (Better Auth sessions, API tokens, "Just me on this computer"); whether sign-in is on is- * src/server/mode.ts.+ * Access protection. Off until a password is set (Settings → Security, or FUOBE_PASSWORD).+ * Then every page and API call needs a session cookie (from /login) or an API token+ * (`Authorization: Bearer fuobe_…`).*- * Before accounts, the password, the session secret and the API tokens lived in data/auth.json. The identity- * bootstrap imports them once (src/server/identity/bootstrap.ts) and leaves the file in place, unread, for one- * release as a rollback aid: readLegacyAuth is the only reader left.+ * Kept in a small JSON file next to the database, not in SQLite, so the proxy's sign-in check+ * needs nothing but `fs` and `crypto`. (The proxy does open SQLite, for one primary-key lookup on+ * record pages only, so an unknown id gets a real 404: src/server/records.ts.)*/+import crypto from "node:crypto";import fs from "node:fs";import net from "node:net";import os from "node:os";import path from "node:path";-import { signInRequired } from "./mode";const DATA_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.FUOBE_DATA_DIR ?? path.join(process.cwd(), "data"));+const FILE = path.join(DATA_DIR, "auth.json");-/** An API token as auth.json kept it. */-export interface LegacyToken {+export const SESSION_COOKIE = "fuobe_session";+const SESSION_DAYS = 30;++export interface ApiToken {id: string;name: string;- /** sha256 of the token, hex. */+ /** sha256 of the token; the token itself is shown once. */hash: string;prefix: string;createdAt: number;lastUsedAt?: number;}-/** The pre-accounts auth.json: a scrypt hash ("salt:hash", hex) and the API tokens. Null when there is none. */-export function readLegacyAuth(): { password?: string; tokens: LegacyToken[] } | null {+interface AuthFile {+ /** scrypt hash of the UI-set password ("salt:hash", hex). */+ password?: string;+ /** Signs session cookies; replaced when the password changes, which signs everyone out. */+ secret: string;+ tokens: ApiToken[];+}++let cache: { mtime: number; data: AuthFile } | null = null;++function read(): AuthFile {try {- const data = JSON.parse(fs.readFileSync(path.join(DATA_DIR, "auth.json"), "utf8")) as { password?: unknown; tokens?: unknown };- const tokens = Array.isArray(data.tokens)- ? (data.tokens as LegacyToken[]).filter((t) => t && typeof t.hash === "string" && /^[0-9a-f]{64}$/i.test(t.hash) && typeof t.id === "string")- : [];- return { password: typeof data.password === "string" && data.password ? data.password : undefined, tokens };+ const mtime = fs.statSync(FILE).mtimeMs;+ if (cache?.mtime === mtime) return cache.data;+ const data = JSON.parse(fs.readFileSync(FILE, "utf8")) as AuthFile;+ cache = { mtime, data };+ return data;} catch {- return null;+ return { secret: "", tokens: [] };+ }+}++function write(data: AuthFile): void {+ fs.mkdirSync(DATA_DIR, { recursive: true });+ const tmp = `${FILE}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });+ fs.renameSync(tmp, FILE);+ cache = null;+}++function withSecret(data: AuthFile): AuthFile {+ return data.secret ? data : { ...data, secret: crypto.randomBytes(32).toString("hex") };+}++const envPassword = () => process.env.FUOBE_PASSWORD || "";++export function authStatus(): { enabled: boolean; fromEnv: boolean; tokens: Omit<ApiToken, "hash">[] } {+ const d = read();+ return { enabled: !!(envPassword() || d.password), fromEnv: !!envPassword(), tokens: d.tokens.map(publicToken) };+}++const publicToken = (t: ApiToken): Omit<ApiToken, "hash"> => ({ id: t.id, name: t.name, prefix: t.prefix, createdAt: t.createdAt, lastUsedAt: t.lastUsedAt });++export const authEnabled = () => !!(envPassword() || read().password);++// ---------------------------------------------------------------------------+// Passwords++function hashPassword(pw: string): string {+ const salt = crypto.randomBytes(16);+ return `${salt.toString("hex")}:${crypto.scryptSync(pw, salt, 32).toString("hex")}`;+}++const same = (a: Buffer, b: Buffer) => a.length === b.length && crypto.timingSafeEqual(a, b);++export function checkPassword(pw: string): boolean {+ const env = envPassword();+ if (env) return same(crypto.createHash("sha256").update(pw).digest(), crypto.createHash("sha256").update(env).digest());+ const stored = read().password;+ if (!stored) return false;+ const [salt, hash] = stored.split(":");+ return same(crypto.scryptSync(pw, Buffer.from(salt, "hex"), 32), Buffer.from(hash, "hex"));+}++/** Set, change or (with null) remove the UI password. Signs every browser out. */+export function setPassword(pw: string | null): void {+ if (envPassword()) throw new Error("The password is set by FUOBE_PASSWORD on the server");+ if (pw !== null && pw.length < 8) throw new Error("Use at least 8 characters");+ const d = read();+ write({ ...d, password: pw === null ? undefined : hashPassword(pw), secret: crypto.randomBytes(32).toString("hex") });+}++// ---------------------------------------------------------------------------+// Sessions++const sign = (secret: string, payload: string) => crypto.createHmac("sha256", secret).update(payload).digest("base64url");++export function createSession(): { value: string; maxAge: number } {+ let d = read();+ if (!d.secret) {+ d = withSecret(d);+ write(d);}+ const exp = Date.now() + SESSION_DAYS * 86_400_000;+ return { value: `${exp}.${sign(d.secret, String(exp))}`, maxAge: SESSION_DAYS * 86_400 };}-/** Whether every page and API call needs a session or a token (Personal with sign-in, Studio, Platform). */-export const authEnabled = (): boolean => signInRequired();+export function validSession(value: string | undefined): boolean {+ if (!value) return false;+ const [exp, mac] = value.split(".");+ const secret = read().secret;+ if (!secret || !exp || !mac || Number(exp) < Date.now()) return false;+ return same(Buffer.from(mac), Buffer.from(sign(secret, exp)));+}// ---------------------------------------------------------------------------// Cross-site requests@@ -124,7 +205,7 @@ export function hostAllowed(host: string | null): boolean {/*** Wrong-password limits. Route handlers can't see the socket address, and Next keeps any* X-Forwarded-For a client sends, so that header only identifies a client behind a reverse proxy- * you trust (FUOBE_TRUSTED_PROXIES or FUOBE_TRUST_PROXY=1, see clientIp): such a client is locked+ * you trust (FUOBE_TRUST_PROXY=1; the proxy's own entry is the last one): such a client is locked* out for a minute after 5 misses. Otherwise every client shares the "direct" key, and a lock* would let anyone keep the owner out, so a spent budget slows sign-in down to one attempt every* few seconds instead (about 15 guesses a minute). Past the global budget the same throttle@@ -139,10 +220,11 @@ export class LoginGuard {private readonly o = { perClient: 5, global: 20, windowMs: 60_000, lockMs: 60_000, throttleMs: 4_000, maxClients: 5000 },) {}- /** Who is signing in: the client's address when a trusted proxy reports it (clientIp), else one shared key. */- static clientKey(headers: Headers, trust: boolean | TrustedProxies | null = trustedProxies()): string {- const t = trust === true ? { hops: 1 } : trust === false ? null : trust;- return clientIp(headers, t) ?? LoginGuard.DIRECT;+ /** Who is signing in: the last X-Forwarded-For hop when a trusted proxy sets it, else one shared key. */+ static clientKey(headers: Headers, trustProxy = process.env.FUOBE_TRUST_PROXY === "1"): string {+ if (!trustProxy) return LoginGuard.DIRECT;+ const hops = (headers.get("x-forwarded-for") ?? "").split(",").map((s) => s.trim()).filter(Boolean);+ return hops.at(-1) ?? LoginGuard.DIRECT;}/** Milliseconds until this client may try again (0 = now). */@@ -183,49 +265,36 @@ export class LoginGuard {}// ----------------------------------------------------------------------------// The client's address behind a trusted reverse proxy+// API tokens-/**- * Which reverse proxies in front of Fuobe are trusted to tell the client's address (§7.2): FUOBE_TRUSTED_PROXIES- * as a hop count ("1", "2": the address that many entries from the right of X-Forwarded-For) or a list of- * addresses and CIDR ranges (entries from the right that fall inside them are skipped). FUOBE_TRUST_PROXY=1 keeps- * meaning one hop. Null when nothing is trusted: X-Forwarded-For is then whatever the client wrote.- */-export type TrustedProxies = { hops: number } | { ranges: net.BlockList; list: string[] };--export function trustedProxies(): TrustedProxies | null {- const raw = (process.env.FUOBE_TRUSTED_PROXIES ?? "").trim();- if (raw) {- if (/^\d+$/.test(raw)) return Number(raw) > 0 ? { hops: Math.min(Number(raw), 10) } : null;- const ranges = new net.BlockList();- const list: string[] = [];- for (const entry of raw.split(",").map((s) => s.trim()).filter(Boolean)) {- const [addr, bits] = entry.split("/");- const family = net.isIP(addr);- if (!family) continue;- const type = family === 6 ? "ipv6" : "ipv4";- if (bits === undefined) ranges.addAddress(addr, type);- else if (/^\d+$/.test(bits) && Number(bits) <= (family === 6 ? 128 : 32)) ranges.addSubnet(addr, Number(bits), type);- else continue;- list.push(entry);- }- return list.length ? { ranges, list } : null;- }- return process.env.FUOBE_TRUST_PROXY === "1" ? { hops: 1 } : null;+const tokenHash = (t: string) => crypto.createHash("sha256").update(t).digest("hex");++export function createToken(name: string): { token: string; info: Omit<ApiToken, "hash"> } {+ const token = `fuobe_${crypto.randomBytes(24).toString("base64url")}`;+ const t: ApiToken = { id: crypto.randomBytes(6).toString("hex"), name: name.trim() || "API token", hash: tokenHash(token), prefix: token.slice(0, 12), createdAt: Date.now() };+ const d = withSecret(read());+ write({ ...d, tokens: [...d.tokens, t] });+ return { token, info: publicToken(t) };}-/** The client's address as a trusted proxy reported it; null without one (or when the header doesn't hold up). */-export function clientIp(headers: Headers, trust: TrustedProxies | null = trustedProxies()): string | null {- if (!trust) return null;- const hops = (headers.get("x-forwarded-for") ?? "").split(",").map((s) => s.trim()).filter(Boolean);- if ("hops" in trust) {- const ip = hops[hops.length - trust.hops];- return ip && net.isIP(ip) ? ip : null;- }- for (let i = hops.length - 1; i >= 0; i--) {- const family = net.isIP(hops[i]);- if (!family) return null;- if (!trust.ranges.check(hops[i], family === 6 ? "ipv6" : "ipv4")) return hops[i];+export function revokeToken(id: string): void {+ const d = read();+ write({ ...d, tokens: d.tokens.filter((t) => t.id !== id) });+}++const touched = new Map<string, number>();++export function validToken(header: string | null): boolean {+ const m = /^Bearer\s+(fuobe_[\w-]+)$/i.exec(header ?? "");+ if (!m) return false;+ const h = Buffer.from(tokenHash(m[1]));+ const d = read();+ const hit = d.tokens.find((t) => same(Buffer.from(t.hash), h));+ if (!hit) return false;+ // Record use at most once an hour per token (avoids a write per request).+ if (Date.now() - (touched.get(hit.id) ?? 0) > 3_600_000) {+ touched.set(hit.id, Date.now());+ write({ ...d, tokens: d.tokens.map((t) => (t.id === hit.id ? { ...t, lastUsedAt: Date.now() } : t)) });}- return null;+ return true;}diff --git a/src/server/backup/snapshot.ts b/src/server/backup/snapshot.tsdeleted file mode 100644index ff6b5ae8..00000000--- a/src/server/backup/snapshot.ts+++ /dev/null@@ -1,95 +0,0 @@-import "server-only";-import crypto from "node:crypto";-import fs from "node:fs";-import path from "node:path";-import Database from "better-sqlite3";-import { DATA_DIR, db, MIGRATION_COUNT } from "../db";-import { secretPath, secretSource } from "../identity/secret";--/**- * Database snapshots (docs/research/accounts-8.md §7.9, §7.16): a consistent copy of data/fuobe.db with the root- * secret beside it and a manifest, as data/backups/fuobe-<UTC>-<kind>.{db,secret.key,json}. Taken before accounts- * arrive ("pre-accounts"), before a mode switch ("before-studio"…) and, with the backup package, on a schedule.- *- * A snapshot never carries live credentials: session, verification, step-up, CLI-login and idempotency rows are- * deleted from the copy (with secure_delete and a VACUUM, so not even free pages keep them), and restoring one- * signs everyone out. Files are 0600 in a 0700 folder.- */--/** Tables whose rows are credentials or short-lived request state; packages add theirs. */-export const STRIPPED_TABLES = ["auth_session", "auth_verification", "session_step_up", "cli_connect_requests", "request_keys"];--export interface Snapshot {- kind: string;- createdAt: number;- db: string;- /** The copy of data/secret.key, or null when the root secret comes from FUOBE_SECRET. */- secret: string | null;- manifest: string;-}--export const backupsDir = () => path.join(DATA_DIR, "backups");--const utc = (t: number) => new Date(t).toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");--const sha256 = (file: string) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");--/**- * Copy the database (from `source`, Fuobe's own connection by default) into data/backups. `kind` names why- * ("pre-accounts", "before-studio", "manual"); letters, digits and dashes only.- */-export function snapshotDatabase(opts: { kind: string; source?: Database.Database; dir?: string; now?: number }): Snapshot {- if (!/^[a-z0-9-]{1,40}$/.test(opts.kind)) throw new Error(`Bad snapshot kind "${opts.kind}"`);- const source = opts.source ?? db();- const dir = opts.dir ?? backupsDir();- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });- const createdAt = opts.now ?? Date.now();- const base = path.join(dir, `fuobe-${utc(createdAt)}-${opts.kind}`);- const tmp = `${base}.db.partial`;- fs.rmSync(tmp, { force: true });- // VACUUM INTO writes a consistent, compacted copy from one read transaction, WAL and all.- source.prepare("VACUUM INTO ?").run(tmp);-- const copy = new Database(tmp);- try {- copy.pragma("journal_mode = DELETE");- copy.pragma("secure_delete = ON");- const tables = new Set((copy.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as { name: string }[]).map((r) => r.name));- const stripped = STRIPPED_TABLES.filter((t) => tables.has(t));- copy.transaction(() => {- for (const t of stripped) copy.prepare(`DELETE FROM "${t}"`).run();- })();- copy.exec("VACUUM");- const migrations = tables.has("_migrations") ? ((copy.prepare("SELECT COUNT(*) AS n FROM _migrations").get() as { n: number }).n ?? 0) : 0;- copy.close();-- const dbFile = `${base}.db`;- fs.renameSync(tmp, dbFile);- fs.chmodSync(dbFile, 0o600);-- let secret: string | null = null;- if (secretSource() === "file" && fs.existsSync(secretPath())) {- secret = `${base}.secret.key`;- fs.copyFileSync(secretPath(), secret);- fs.chmodSync(secret, 0o600);- }-- const manifest = `${base}.json`;- const body = {- kind: opts.kind,- createdAt: new Date(createdAt).toISOString(),- database: path.basename(dbFile),- sha256: sha256(dbFile),- migrations,- buildMigrations: MIGRATION_COUNT,- secret: secret ? path.basename(secret) : secretSource() === "env" ? "FUOBE_SECRET (not copied)" : null,- stripped,- };- fs.writeFileSync(manifest, `${JSON.stringify(body, null, 2)}\n`, { mode: 0o600 });- return { kind: opts.kind, createdAt, db: dbFile, secret, manifest };- } catch (e) {- if (copy.open) copy.close();- fs.rmSync(tmp, { force: true });- throw e;- }-}diff --git a/src/server/db.ts b/src/server/db.tsindex 6f90bf00..95c2a105 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -564,165 +564,8 @@ const MIGRATIONS: string[] = [UPDATE ad_batches SET route = 'baked' WHERE route = 'higgsfield';UPDATE ad_creatives SET meta_json = json_set(meta_json, '$.route', 'baked')WHERE json_valid(meta_json) AND json_extract(meta_json, '$.route') = 'higgsfield';`,- // originals (o/acc-1): accounts, part 1 (docs/research/accounts-8.md §7.1). Fuobe's identity tables — people- // (`users`: u_owner or u_<nanoid>, linked to a Better Auth user), workspaces and their members, invites, grants,- // per-viewer marks, API tokens (they move out of auth.json), the append-only audit log with its hash chain,- // per-person and per-workspace settings and step-up marks — seeded with the owner (unclaimed until the bootstrap- // or a first password links it), the owner's personal workspace and the install catalog. Then Better Auth's own- // tables, frozen exactly as `node scripts/auth-schema.mjs` printed them for better-auth 1.7.10 (the schema-guard- // test fails when a library upgrade would want a change). No foreign keys, and no CHECKs on roles, statuses or- // sources: their registries live in code, so later packages add values without rebuilding tables.- `CREATE TABLE IF NOT EXISTS users (- id TEXT PRIMARY KEY,- auth_user_id TEXT UNIQUE,- role TEXT NOT NULL,- status TEXT NOT NULL DEFAULT 'active',- pending_reason TEXT,- dormant INTEGER NOT NULL DEFAULT 0,- personal_workspace_id TEXT,- source TEXT NOT NULL DEFAULT 'unknown',- external_id TEXT,- provisioned_email TEXT,- provisioned_name TEXT,- invited_by TEXT,- approved_by TEXT,- avatar_asset_id TEXT,- created_at INTEGER NOT NULL,- updated_at INTEGER NOT NULL- );- CREATE UNIQUE INDEX IF NOT EXISTS users_one_owner ON users(role) WHERE role = 'owner';- CREATE UNIQUE INDEX IF NOT EXISTS users_provisioned_email ON users(lower(provisioned_email)) WHERE auth_user_id IS NULL AND provisioned_email IS NOT NULL;- CREATE TABLE IF NOT EXISTS workspaces (- id TEXT PRIMARY KEY,- kind TEXT NOT NULL,- name TEXT NOT NULL,- slug TEXT NOT NULL UNIQUE,- color TEXT,- created_by TEXT,- archived_at INTEGER,- delete_after INTEGER,- created_at INTEGER NOT NULL,- updated_at INTEGER NOT NULL- );- CREATE TABLE IF NOT EXISTS workspace_members (- workspace_id TEXT NOT NULL,- user_id TEXT NOT NULL,- role TEXT NOT NULL,- source TEXT NOT NULL DEFAULT 'manual',- added_by TEXT,- created_at INTEGER NOT NULL,- PRIMARY KEY (workspace_id, user_id)- );- CREATE INDEX IF NOT EXISTS workspace_members_user ON workspace_members(user_id);- CREATE TABLE IF NOT EXISTS invites (- id TEXT PRIMARY KEY,- token_hash TEXT NOT NULL UNIQUE,- email TEXT,- role TEXT NOT NULL,- workspace_id TEXT,- inviter_id TEXT NOT NULL,- used_by TEXT,- used_at INTEGER,- revoked_at INTEGER,- expires_at INTEGER NOT NULL,- created_at INTEGER NOT NULL- );- CREATE TABLE IF NOT EXISTS grants (- id TEXT PRIMARY KEY,- resource_kind TEXT NOT NULL,- resource_id TEXT NOT NULL,- grantee_kind TEXT NOT NULL,- grantee_id TEXT NOT NULL,- level TEXT NOT NULL,- granted_by TEXT NOT NULL,- created_at INTEGER NOT NULL,- UNIQUE (resource_kind, resource_id, grantee_kind, grantee_id)- );- CREATE INDEX IF NOT EXISTS grants_grantee ON grants(grantee_kind, grantee_id);- CREATE TABLE IF NOT EXISTS item_marks (- user_id TEXT NOT NULL,- item_kind TEXT NOT NULL,- item_id TEXT NOT NULL,- favorite INTEGER NOT NULL DEFAULT 0,- pinned_at INTEGER,- PRIMARY KEY (user_id, item_kind, item_id)- );- CREATE TABLE IF NOT EXISTS api_tokens (- id TEXT PRIMARY KEY,- user_id TEXT NOT NULL,- workspace_id TEXT,- name TEXT NOT NULL,- prefix TEXT NOT NULL,- hash TEXT NOT NULL UNIQUE,- scopes TEXT NOT NULL DEFAULT 'full',- legacy INTEGER NOT NULL DEFAULT 0,- expires_at INTEGER,- last_used_at INTEGER,- revoked_at INTEGER,- created_at INTEGER NOT NULL- );- CREATE INDEX IF NOT EXISTS api_tokens_user ON api_tokens(user_id);- CREATE TABLE IF NOT EXISTS audit_log (- seq INTEGER PRIMARY KEY AUTOINCREMENT,- at INTEGER NOT NULL,- actor_id TEXT,- actor_via TEXT,- action TEXT NOT NULL,- target_kind TEXT,- target_id TEXT,- meta_json TEXT NOT NULL DEFAULT '{}',- ip TEXT,- user_agent TEXT,- prev_hash TEXT NOT NULL,- hash TEXT NOT NULL- );- CREATE INDEX IF NOT EXISTS audit_log_at ON audit_log(at);- CREATE TRIGGER IF NOT EXISTS audit_log_append_only BEFORE UPDATE ON audit_log- BEGIN SELECT RAISE(ABORT, 'audit_log is append-only'); END;- CREATE TABLE IF NOT EXISTS user_settings (- user_id TEXT NOT NULL,- key TEXT NOT NULL,- value TEXT NOT NULL,- updated_at INTEGER NOT NULL,- PRIMARY KEY (user_id, key)- );- CREATE TABLE IF NOT EXISTS workspace_settings (- workspace_id TEXT NOT NULL,- key TEXT NOT NULL,- value TEXT NOT NULL,- updated_at INTEGER NOT NULL,- PRIMARY KEY (workspace_id, key)- );- CREATE TABLE IF NOT EXISTS session_step_up (- session_id TEXT PRIMARY KEY,- user_id TEXT NOT NULL,- confirmed_at INTEGER NOT NULL,- expires_at INTEGER NOT NULL- );- INSERT OR IGNORE INTO workspaces (id, kind, name, slug, created_by, created_at, updated_at) VALUES- ('w_owner', 'personal', 'Personal', 'personal', 'u_owner', CAST(strftime('%s', 'now') AS INTEGER) * 1000, CAST(strftime('%s', 'now') AS INTEGER) * 1000),- ('w_install', 'install', 'Install', 'install', NULL, CAST(strftime('%s', 'now') AS INTEGER) * 1000, CAST(strftime('%s', 'now') AS INTEGER) * 1000);- INSERT OR IGNORE INTO users (id, role, status, personal_workspace_id, source, created_at, updated_at) VALUES- ('u_owner', 'owner', 'active', 'w_owner', 'setup', CAST(strftime('%s', 'now') AS INTEGER) * 1000, CAST(strftime('%s', 'now') AS INTEGER) * 1000);- INSERT OR IGNORE INTO workspace_members (workspace_id, user_id, role, source, created_at) VALUES- ('w_owner', 'u_owner', 'owner', 'manual', CAST(strftime('%s', 'now') AS INTEGER) * 1000);- create table "auth_user" ("id" text not null primary key, "name" text not null, "email" text not null unique, "emailVerified" integer not null, "image" text, "createdAt" date not null, "updatedAt" date not null);- create table "auth_session" ("id" text not null primary key, "expiresAt" date not null, "token" text not null unique, "createdAt" date not null, "updatedAt" date not null, "ipAddress" text, "userAgent" text, "userId" text not null references "auth_user" ("id") on delete cascade);- create table "auth_account" ("id" text not null primary key, "accountId" text not null, "providerId" text not null, "userId" text not null references "auth_user" ("id") on delete cascade, "accessToken" text, "refreshToken" text, "idToken" text, "accessTokenExpiresAt" date, "refreshTokenExpiresAt" date, "scope" text, "password" text, "createdAt" date not null, "updatedAt" date not null);- create table "auth_verification" ("id" text not null primary key, "identifier" text not null, "value" text not null, "expiresAt" date not null, "createdAt" date not null, "updatedAt" date not null);- create table "auth_rate_limit" ("id" text not null primary key, "key" text not null unique, "count" integer not null, "lastRequest" bigint not null);- create index "auth_session_userId_idx" on "auth_session" ("userId");- create index "auth_account_userId_idx" on "auth_account" ("userId");- create index "auth_verification_identifier_idx" on "auth_verification" ("identifier");`,];-/** The index of the migration whose SQL contains `fragment` (-1 when none does): tests and the bootstrap name migrations by what they do. */-export const migrationIndexOf = (fragment: string): number => MIGRATIONS.findIndex((sql) => sql.includes(fragment));-/** The migration that creates the identity tables: the bootstrap snapshots an existing database before it runs (src/server/identity/bootstrap.ts). */-export const IDENTITY_MIGRATION = migrationIndexOf("CREATE TABLE IF NOT EXISTS users (");-/** How many migrations this build has (a snapshot's manifest records it). */-export const MIGRATION_COUNT = MIGRATIONS.length;-declare global {var __fuobeDb: Database.Database | undefined;}diff --git a/src/server/generations.ts b/src/server/generations.tsindex cc532fe5..ff5843f0 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -326,8 +326,6 @@ export const ASSET_REFS: AssetRef[] = [{ table: "swap_projects", cols: ["data_json"], what: "Character Swap project", name: "name" },// A user skill's bundled text files: its recipe.json names the files a run starts from (an example, a fixed logo).{ table: "skills", cols: ["files_json"], what: "skill", key: "name", name: "title" },- // Accounts (o/acc-1): a person's picture is an uploaded asset.- { table: "users", cols: ["avatar_asset_id"], what: "account picture", name: "provisioned_name" },];/**@@ -358,7 +356,6 @@ export const ASSET_FREE: Record<string, string> = {"assist_schedules.mode_json": "the Assist mode a scheduled run starts in","assist_connectors.url": "a remote MCP server Claude connects to, never one of ours","assist_connectors.tools_json": "the tool names a connector is limited to",- "audit_log.meta_json": "what an audit entry is about: ids, setting names and masked prefixes, never files",};/** The query that finds the rows of one ASSET_REFS table naming a file (@id), except the purged generation's own (@g). */diff --git a/src/server/identity/admin-ops.ts b/src/server/identity/admin-ops.tsdeleted file mode 100644index 12998515..00000000--- a/src/server/identity/admin-ops.ts+++ /dev/null@@ -1,119 +0,0 @@-import "server-only";-import { appendAudit } from "./audit-log";-import { getAuth, withCreateIntent } from "./auth";-import { hashPassword, needsRehash, verifyPassword } from "./password";--/**- * The one place Fuobe writes Better Auth's tables (docs/research/accounts-8.md §7.1): through the internal adapter- * of the running instance, `(await auth.$context).internalAdapter`, so Better Auth's own hooks run and its storage- * rules hold. Every call is audited with who did it. A test pins that the adapter and these methods are reachable- * in the pinned version (tests/identity-better-auth.test.ts).- */--/** Who is acting, for the audit log. */-export interface By {- actorId: string | null;- via: string;-}--export const SYSTEM: By = { actorId: null, via: "system" };--const adapter = async () => (await getAuth().$context).internalAdapter;--function audit(action: string, by: By, targetId: string | null, meta?: Record<string, unknown>) {- appendAudit({ action, actorId: by.actorId, via: by.via, targetKind: "auth_user", targetId, meta });-}--/** Create a sign-in account for a person, under a create intent (claim-owner, bootstrap-import; later invite, sso…). */-export async function createAuthUser(intent: string, user: { email: string; name: string }, by: By): Promise<string> {- const ia = await adapter();- const made = await withCreateIntent(intent, () => ia.createUser({ email: user.email.toLowerCase(), name: user.name, emailVerified: false }, { method: `fuobe:${intent}` }));- audit("people.auth_user_created", by, made.id, { intent });- return made.id;-}--export async function findAuthUserByEmail(email: string): Promise<string | null> {- return (await (await adapter()).findUserByEmail(email.toLowerCase()))?.user.id ?? null;-}--export async function authUserExists(authUserId: string): Promise<boolean> {- return !!(await (await adapter()).findUserById(authUserId));-}--/** The person's sign-in email (the owner of a Personal install has the never-shown [email protected]). */-export async function authUserEmail(authUserId: string): Promise<string | null> {- return (await (await adapter()).findUserById(authUserId))?.email ?? null;-}--/** Whether the account has a password (a credential account with a hash). */-export async function hasPassword(authUserId: string): Promise<boolean> {- return !!(await (await adapter()).findCredentialAccount(authUserId))?.password;-}--/** Whether the account's password is stored in an older format (rewritten at the next sign-in). */-export async function passwordNeedsRehash(authUserId: string): Promise<boolean> {- const hash = (await (await adapter()).findCredentialAccount(authUserId))?.password;- return !!hash && needsRehash(hash);-}--/** Check a password against the account's own, without signing in. */-export async function verifyPasswordFor(authUserId: string, password: string): Promise<boolean> {- const hash = (await (await adapter()).findCredentialAccount(authUserId))?.password;- return !!hash && verifyPassword({ hash, password });-}--/**- * Set a person's password: a plain password is hashed (scrypt v2); `{ hash }` stores one as is (the auth.json- * import keeps the old salt:hash, rewritten at the next sign-in). Creates the credential account when there is none.- */-export async function setPasswordFor(authUserId: string, password: string | { hash: string }, by: By): Promise<void> {- const ia = await adapter();- const hash = typeof password === "string" ? await hashPassword(password) : password.hash;- const account = await ia.findCredentialAccount(authUserId);- if (account) await ia.updatePassword(authUserId, hash);- else await ia.linkAccount({ userId: authUserId, providerId: "credential", accountId: authUserId, password: hash });- audit("auth.password_set", by, authUserId, { imported: typeof password !== "string" });-}--/** Remove a person's password (their credential account). Other sign-in methods stay. */-export async function removePasswordFor(authUserId: string, by: By): Promise<void> {- const ia = await adapter();- const account = await ia.findCredentialAccount(authUserId);- if (account) await ia.deleteAccount(account.id);- audit("auth.password_removed", by, authUserId);-}--/** Sign a person out everywhere. */-export async function revokeAllSessions(authUserId: string, by: By): Promise<void> {- await (await adapter()).deleteUserSessions(authUserId);- audit("auth.sessions_revoked", by, authUserId);-}--/** End one session (by its id, as session lists show it; Better Auth deletes by token). */-export async function revokeSessionById(authUserId: string, sessionId: string, by: By): Promise<boolean> {- const ia = await adapter();- const session = (await ia.listSessions(authUserId)).find((s) => s.id === sessionId);- if (!session) return false;- await ia.deleteSession(session.token);- audit("auth.session_revoked", by, authUserId, { session: sessionId });- return true;-}--export async function setEmail(authUserId: string, email: string, by: By): Promise<void> {- await (await adapter()).updateUser(authUserId, { email: email.toLowerCase(), emailVerified: false });- audit("people.email_changed", by, authUserId);-}--export async function updateName(authUserId: string, name: string, by: By): Promise<void> {- await (await adapter()).updateUser(authUserId, { name: name.trim().slice(0, 80) });- audit("people.name_changed", by, authUserId);-}--/** Delete the sign-in account (its sessions and linked accounts go with it). The Fuobe person stays. */-export async function deleteAuthUser(authUserId: string, by: By): Promise<void> {- const ia = await adapter();- await ia.deleteUserSessions(authUserId);- await ia.deleteAccounts(authUserId);- await ia.deleteUser(authUserId);- audit("people.auth_user_deleted", by, authUserId);-}diff --git a/src/server/identity/audit-log.ts b/src/server/identity/audit-log.tsdeleted file mode 100644index 98622d9f..00000000--- a/src/server/identity/audit-log.ts+++ /dev/null@@ -1,80 +0,0 @@-import "server-only";-import crypto from "node:crypto";-import { db } from "../db";--/**- * The append-only audit log's storage (docs/research/accounts-8.md §7.14): each row carries the hash of the row- * before it, so a changed or removed row breaks the chain from there on. This is the bare writer the identity core- * needs (imports, sign-ins, admin operations); the actor-aware `audit()` that reads the request scope arrives with- * acc-2 and writes through it. Never put a secret in `meta` (a password, a token, a key): names and prefixes only.- */--export interface AuditEntry {- action: string;- actorId?: string | null;- via?: string | null;- targetKind?: string | null;- targetId?: string | null;- meta?: Record<string, unknown>;- ip?: string | null;- userAgent?: string | null;-}--interface Row {- seq: number;- at: number;- actor_id: string | null;- actor_via: string | null;- action: string;- target_kind: string | null;- target_id: string | null;- meta_json: string;- ip: string | null;- user_agent: string | null;- prev_hash: string;- hash: string;-}--const rowHash = (prev: string, r: Omit<Row, "seq" | "prev_hash" | "hash">) =>- crypto- .createHash("sha256")- .update(prev)- .update(JSON.stringify([r.at, r.actor_id, r.actor_via, r.action, r.target_kind, r.target_id, r.meta_json, r.ip, r.user_agent]))- .digest("hex");--export function appendAudit(e: AuditEntry): void {- const d = db();- d.transaction(() => {- const prev = (d.prepare("SELECT hash FROM audit_log ORDER BY seq DESC LIMIT 1").get() as { hash: string } | undefined)?.hash ?? "";- const r = {- at: Date.now(),- actor_id: e.actorId ?? null,- actor_via: e.via ?? null,- action: e.action,- target_kind: e.targetKind ?? null,- target_id: e.targetId ?? null,- meta_json: JSON.stringify(e.meta ?? {}),- ip: e.ip ?? null,- user_agent: e.userAgent ? e.userAgent.slice(0, 300) : null,- };- d.prepare(- `INSERT INTO audit_log (at, actor_id, actor_via, action, target_kind, target_id, meta_json, ip, user_agent, prev_hash, hash)- VALUES (@at, @actor_id, @actor_via, @action, @target_kind, @target_id, @meta_json, @ip, @user_agent, @prev_hash, @hash)`,- ).run({ ...r, prev_hash: prev, hash: rowHash(prev, r) });- }).immediate();-}--/** The newest entries, newest first (tests and, later, the audit viewer). */-export function recentAudit(limit = 50): Row[] {- return db().prepare("SELECT * FROM audit_log ORDER BY seq DESC LIMIT ?").all(limit) as Row[];-}--/** Whether every row still hashes to what the next one remembers: false from the first changed row on. */-export function auditChainIntact(): boolean {- let prev = "";- for (const r of db().prepare("SELECT * FROM audit_log ORDER BY seq").iterate() as Iterable<Row>) {- if (r.prev_hash !== prev || r.hash !== rowHash(prev, r)) return false;- prev = r.hash;- }- return true;-}diff --git a/src/server/identity/auth.ts b/src/server/identity/auth.tsdeleted file mode 100644index b573f337..00000000--- a/src/server/identity/auth.ts+++ /dev/null@@ -1,414 +0,0 @@-import "server-only";-import { AsyncLocalStorage } from "node:async_hooks";-import path from "node:path";-import Database from "better-sqlite3";-import { betterAuth, type BetterAuthOptions } from "better-auth";-import { nanoid } from "nanoid";-import { APIError, createAuthMiddleware } from "better-auth/api";-import { Kysely, SqliteDialect } from "kysely";-import { hostAllowed, trustedProxies } from "../auth";-import { DATA_DIR, db } from "../db";-import { INSTALL, installMode, installValue, siteUrl } from "../mode";-import { appendAudit } from "./audit-log";-import { hashPassword, needsRehash, PASSWORD_MAX, PASSWORD_MIN, PASSWORD_SIGN_IN_MAX, verifyPassword } from "./password";-import { refusal } from "./refusals";-import { AUTH_TABLES } from "./schema";-import { deriveKey } from "./secret";--/**- * Better Auth, behind Fuobe (docs/research/accounts-8.md §5.2, §7.1). It answers "who is this": passwords,- * sessions and (in later packages) passkeys, two-step, Google/GitHub/OIDC and company sign-in. Fuobe answers what- * they may do. Fuobe reaches its tables in three places only: principal.ts (auth.api.getSession), people lists- * (read-only joins) and admin-ops.ts (the internal adapter).- *- * How it is set up, and why:- * - Its own better-sqlite3 connection to data/fuobe.db (WAL, busy_timeout 5000), tables named auth_*, no extra- * fields, telemetry off; the schema is frozen in Fuobe's migrations (scripts/auth-schema.mjs prints it).- * Better Auth's multi-statement transactions are off: on SQLite they would hold the write lock across awaits- * (sign-up hashes the password inside one), and a Fuobe write on the other connection in that window would- * busy-wait on the event loop the transaction needs to finish. Each statement commits on its own instead.- * - The secret is HKDF(root secret, "better-auth/v1"), so it never sits in the database or the environment as is.- * - Cookies are named fuobe.*; on an https site address they become __Host-fuobe.* with Secure and Path=/ and no- * Domain (useSecureCookies stays false: Better Auth would otherwise prefix __Secure-). Plain http (localhost,- * the LAN) keeps the plain names, without Secure.- * - Client IPs come only from x-fuobe-client-ip, which the proxy deletes from every request and writes only when- * a trusted proxy is configured. Without one, IP tracking is off, so Better Auth's limiter skips its IP rules- * instead of putting every client in one bucket that anyone could fill.- * - Sessions last 30 days, refreshed once a day, and only on POST (GET stays read-only); no cookie cache.- * - Router traffic (/api/identity/*) may reach only the allowlisted endpoints; Fuobe's own auth.api calls pass.- * Sign-up and social sign-in are off the list until the sign-in package adds them with their policy.- * - A new Better Auth user needs a Fuobe intent (claiming the owner, the auth.json import) until the meter- * package sets accounts.multi_user, so no second account can exist before isolation and limits do. Each intent- * has its own check: the owner's two refuse once the owner has a live sign-in account.- * - Passwords: new ones are 8 to 128 characters on every path; sign-in takes up to 500, so a longer password from- * before accounts (or FUOBE_PASSWORD) still works.- */--declare global {- var __fuobeAuthDb: { file: string; db: Database.Database; kysely: Kysely<unknown> } | undefined;-}--/** Better Auth's connection. Opened after Fuobe's own, so the frozen tables exist before Better Auth reads them. */-export function authDb(): Database.Database {- db();- const file = path.join(DATA_DIR, "fuobe.db");- if (globalThis.__fuobeAuthDb?.file !== file) {- const conn = new Database(file);- conn.pragma("journal_mode = WAL");- conn.pragma("busy_timeout = 5000");- conn.pragma("foreign_keys = ON");- globalThis.__fuobeAuthDb = { file, db: conn, kysely: new Kysely({ dialect: new SqliteDialect({ database: conn }) }) };- }- return globalThis.__fuobeAuthDb.db;-}--/** The same connection as Better Auth's adapter sees it (transactions off, see above). */-function authDatabase() {- authDb();- return { db: globalThis.__fuobeAuthDb!.kysely, type: "sqlite" as const, transaction: false };-}--// ----------------------------------------------------------------------------// Registries--/** A path rule for the router allowlist: an exact Better Auth path, or a prefix ending in "/*". */-type PathRule = string;-const matches = (rule: PathRule, p: string) => (rule.endsWith("/*") ? p.startsWith(rule.slice(0, -1)) : p === rule);--/**- * Endpoints the browser may reach at /api/identity/*. Built from what is loaded: each package that loads a plugin or- * opens a flow adds its paths (sign-in pages add /sign-in/email, /sign-up/email and the social paths with their- * policy, acc-11). Everything else answers 403 to router traffic.- */-export const ROUTER_ALLOWED: PathRule[] = ["/get-session", "/sign-out", "/update-user", "/ok", "/error"];--/** Never reachable from the browser, whatever a package adds (§7.1). */-export const ROUTER_BLOCKED: PathRule[] = [- "/delete-user",- "/delete-user/*",- "/update-session",- "/get-access-token",- "/refresh-token",- "/account-info",- "/change-email",- "/send-verification-email",- "/sign-in/email-otp",- "/list-sessions",- "/revoke-session",- "/revoke-sessions",- "/two-factor/send-otp",- "/two-factor/verify-otp",- "/sso/register",- "/sso/update-provider",- "/sso/delete-provider",- "/sso/providers",- "/sso/get-provider",-];--export const routerAllows = (p: string): boolean => !ROUTER_BLOCKED.some((r) => matches(r, p)) && ROUTER_ALLOWED.some((r) => matches(r, p));--/**- * Why Fuobe is creating a Better Auth user, each with its own check (a refusal code, or null to go ahead). The two- * core intents only ever make the owner's sign-in account, so they refuse once the owner has a live one. Packages- * add theirs (invite, sso, scim, admin) with registerCreateIntent.- */-export type CreateIntentCheck = () => string | null;-export const CREATE_INTENTS = new Map<string, CreateIntentCheck>([- ["claim-owner", () => (ownerClaimable() ? null : "OWNER_CLAIMED")],- ["bootstrap-import", () => (ownerClaimable() ? null : "OWNER_CLAIMED")],-]);--export function registerCreateIntent(intent: string, check: CreateIntentCheck): void {- CREATE_INTENTS.set(intent, check);-}--const createIntent = new AsyncLocalStorage<string>();--/** Run `fn` with a create intent, so user.create.before lets the new user through. */-export function withCreateIntent<T>(intent: string, fn: () => Promise<T>): Promise<T> {- return createIntent.run(intent, fn);-}--/** The intent of the create in progress (null outside withCreateIntent). */-export const currentCreateIntent = (): string | null => createIntent.getStore() ?? null;--/** A person row as session checks see it. */-export interface PersonRow {- id: string;- role: string;- status: string;- dormant: number;-}--/**- * Checks before a session is created, in order: each may refuse with a code (core codes ACCOUNT_PENDING,- * ACCOUNT_DISABLED, ACCOUNT_DORMANT). Packages add theirs (network policy, seats, bans…).- */-export type SessionCheck = (person: PersonRow, session: { userId: string; userAgent?: string | null }, path: string | null) => string | null;-export const SESSION_CHECKS: SessionCheck[] = [- (p) => (p.status === "pending" ? "ACCOUNT_PENDING" : null),- (p) => (p.status === "disabled" || p.status === "deleted" ? "ACCOUNT_DISABLED" : null),- (p) => (p.dormant ? "ACCOUNT_DORMANT" : null),-];--/** What happens after a session is created (audit; later: alerts, two-step marks). */-export type SessionAfter = (person: PersonRow, session: { id: string; userId: string; userAgent?: string | null; ipAddress?: string | null }) => void;-export const SESSION_AFTER: SessionAfter[] = [- (p, s) => appendAudit({ action: "auth.sign_in", actorId: p.id, via: "session", targetKind: "session", targetId: s.id, ip: s.ipAddress, userAgent: s.userAgent }),-];--/**- * Endpoints that set a new password, and the body field that holds it. New passwords keep the 8 to 128 rule- * (§7.2) on every path, Fuobe's own calls included; Better Auth's own limit is the higher sign-in one, so passwords- * from before accounts (and FUOBE_PASSWORD) still sign in. Packages that load a plugin with its own path add it.- */-export const NEW_PASSWORD_FIELDS: Record<string, string> = {- "/sign-up/email": "password",- "/reset-password": "newPassword",- "/change-password": "newPassword",- "/set-password": "newPassword",- "/admin/create-user": "password",- "/admin/set-user-password": "newPassword",-};--/** Better Auth cookies Fuobe renames (and makes __Host- on https). Plugins add theirs (two_factor, passkey…). */-export const AUTH_COOKIES = ["session_token", "session_data", "dont_remember", "account_data"];--// ----------------------------------------------------------------------------// People--const now = () => Date.now();--/** The Fuobe person for a Better Auth user, or null. */-export function personFor(authUserId: string): PersonRow | null {- return (db().prepare("SELECT id, role, status, dormant FROM users WHERE auth_user_id = ?").get(authUserId) as PersonRow | undefined) ?? null;-}--/**- * A Better Auth user without a Fuobe person (a link lost, or a user created with multi_user on before its package- * links people). Created idempotently, pending, with no memberships, and audited: never active (review 1).- */-export function ensurePendingPerson(authUserId: string): PersonRow {- const existing = personFor(authUserId);- if (existing) return existing;- const id = `u_${nanoid(12)}`;- const t = now();- const made = db()- .prepare("INSERT OR IGNORE INTO users (id, auth_user_id, role, status, pending_reason, source, created_at, updated_at) VALUES (?, ?, 'member', 'pending', 'unlinked', 'unknown', ?, ?)")- .run(id, authUserId, t, t);- if (made.changes) appendAudit({ action: "people.link_pending", targetKind: "user", targetId: id, meta: { reason: "a sign-in account had no Fuobe person" } });- return personFor(authUserId)!;-}--/** Whether the owner can still be given a sign-in account: none linked, or the linked one is gone. */-export function ownerClaimable(): boolean {- const row = db()- .prepare(`SELECT u.auth_user_id AS linked, EXISTS (SELECT 1 FROM "${AUTH_TABLES.user}" a WHERE a.id = u.auth_user_id) AS live FROM users u WHERE u.id = 'u_owner'`)- .get() as { linked: string | null; live: number } | undefined;- return !!row && (!row.linked || !row.live);-}--/** Link a new Better Auth user to the Fuobe person its intent names. */-function linkPerson(authUserId: string, intent: string | null): void {- if (intent === "claim-owner" || intent === "bootstrap-import") {- db().prepare("UPDATE users SET auth_user_id = ?, updated_at = ? WHERE id = 'u_owner' AND auth_user_id IS NULL").run(authUserId, now());- return;- }- ensurePendingPerson(authUserId);-}--// ----------------------------------------------------------------------------// The instance--/** The address Better Auth runs at and whether cookies are __Host-: from the site address, else the request. */-export interface AuthSite {- siteUrl: string | null;- /** A trusted proxy writes x-fuobe-client-ip; without one IP tracking is off. */- trustedProxy: boolean;-}--export const currentSite = (): AuthSite => ({ siteUrl: siteUrl(), trustedProxy: !!trustedProxies() });--/** The cookie names this site uses (the proxy checks for one before asking Better Auth). */-export function sessionCookieName(site: AuthSite = currentSite()): string {- return site.siteUrl?.startsWith("https://") ? "__Host-fuobe.session_token" : "fuobe.session_token";-}--function cookieConfig(secure: boolean): NonNullable<BetterAuthOptions["advanced"]>["cookies"] {- if (!secure) return undefined;- return Object.fromEntries(AUTH_COOKIES.map((c) => [c, { name: `__Host-fuobe.${c}`, attributes: { secure: true, path: "/" } }]));-}--/** Origins a browser may post from (§7.1). SSO issuers are never added. */-function trustedOriginsFor(request?: Request): string[] {- const out = new Set<string>();- const site = siteUrl();- if (site) out.add(site);- for (const entry of (process.env.FUOBE_ALLOWED_ORIGINS ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {- if (entry === "*") continue;- if (entry.includes("://")) {- try {- out.add(new URL(entry).origin);- } catch {- // skip- }- } else {- out.add(`https://${entry}`);- out.add(`http://${entry}`);- }- }- for (const entry of (installValue("access.allowed_hosts") ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {- out.add(`https://${entry}`);- out.add(`http://${entry}`);- }- // The address the browser used, in Personal only and only when it's one Fuobe may be reached at without a password.- if (request && installMode() === "personal") {- const host = request.headers.get("host");- if (hostAllowed(host)) {- const url = new URL(request.url);- out.add(url.origin);- if (host) out.add(`${url.protocol}//${host}`);- }- }- return [...out];-}--const QUIET = [/Base URL is not set/];--export function buildAuthOptions(site: AuthSite) {- const secure = !!site.siteUrl?.startsWith("https://");- return {- appName: "Fuobe",- basePath: "/api/identity",- ...(site.siteUrl && { baseURL: site.siteUrl }),- secret: deriveKey("better-auth/v1").toString("hex"),- database: authDatabase(),- telemetry: { enabled: false },- logger: {- // "info", not "warn": at warn Better Auth's router also prints every refused request (each 403 from the- // allowlist) through its own logger. Warnings and errors still come here, minus the known-harmless ones.- level: "info" as const,- log: (level: string, message: string, ...args: unknown[]) => {- if ((level !== "warn" && level !== "error") || QUIET.some((q) => q.test(message))) return;- (level === "error" ? console.error : console.warn)(`[identity] ${message}`, ...args);- },- },- trustedOrigins: (request?: Request) => trustedOriginsFor(request),- user: { modelName: AUTH_TABLES.user },- account: {- modelName: AUTH_TABLES.account,- accountLinking: { trustedProviders: [] as string[], allowDifferentEmails: false },- },- session: {- modelName: AUTH_TABLES.session,- expiresIn: 30 * 86_400,- updateAge: 86_400,- deferSessionRefresh: true,- freshAge: 600,- cookieCache: { enabled: false },- },- verification: { modelName: AUTH_TABLES.verification, storeIdentifier: "hashed" as const },- rateLimit: { enabled: true, storage: "database" as const, modelName: AUTH_TABLES.rateLimit },- emailAndPassword: {- enabled: true,- minPasswordLength: PASSWORD_MIN,- // The sign-in limit, not the new-password one: Better Auth checks it before verifying, and a longer password- // from before accounts must still sign in. New passwords meet PASSWORD_MAX in the before hook.- maxPasswordLength: PASSWORD_SIGN_IN_MAX,- revokeSessionsOnPasswordReset: true,- password: { hash: hashPassword, verify: verifyPassword },- },- advanced: {- cookiePrefix: "fuobe",- useSecureCookies: false,- cookies: cookieConfig(secure),- ipAddress: { ipAddressHeaders: ["x-fuobe-client-ip"], disableIpTracking: !site.trustedProxy },- },- databaseHooks: {- user: {- create: {- before: async () => {- const intent = currentCreateIntent();- const check = intent ? CREATE_INTENTS.get(intent) : undefined;- if (check) {- const code = check();- if (code) throw new APIError("FORBIDDEN", { message: "This Fuobe's owner already has a sign-in account.", code });- return;- }- if (installValue(INSTALL.multiUser) === "1") return;- throw new APIError("FORBIDDEN", { message: "New accounts can't be created on this Fuobe.", code: "SIGN_UP_CLOSED" });- },- after: async (user: { id: string }) => linkPerson(user.id, currentCreateIntent()),- },- },- session: {- create: {- before: async (session: { userId: string; userAgent?: string | null }, ctx: { path?: string } | null) => {- const person = ensurePendingPerson(session.userId);- for (const check of SESSION_CHECKS) {- const code = check(person, session, ctx?.path ?? null);- if (code) {- const r = refusal(code);- throw new APIError("FORBIDDEN", { message: r.message, code });- }- }- },- after: async (session: { id: string; userId: string; userAgent?: string | null; ipAddress?: string | null }) => {- const person = personFor(session.userId);- if (person) for (const fn of SESSION_AFTER) fn(person, session);- },- },- },- },- hooks: {- // New passwords stay within 8 to 128 characters; then the router allowlist.- before: createAuthMiddleware(async (ctx) => {- const field = NEW_PASSWORD_FIELDS[ctx.path];- const next = field && ctx.body && typeof ctx.body === "object" ? (ctx.body as Record<string, unknown>)[field] : undefined;- if (typeof next === "string" && next.length > PASSWORD_MAX) {- throw new APIError("BAD_REQUEST", { message: `Use at most ${PASSWORD_MAX} characters.`, code: "PASSWORD_TOO_LONG" });- }- // The router allowlist: only browser traffic carries ctx.request; Fuobe's auth.api calls pass.- if (!ctx.request) return;- if (!routerAllows(ctx.path)) throw new APIError("FORBIDDEN", { message: "That isn't available on this Fuobe.", code: "ENDPOINT_BLOCKED" });- if (ctx.path === "/update-user" && ctx.body && typeof ctx.body === "object") {- const body = ctx.body as Record<string, unknown>;- // Fuobe's own avatar upload is the only way to set a picture; names stay short.- delete body.image;- if (typeof body.name === "string" && body.name.trim().length > 80) throw new APIError("BAD_REQUEST", { message: "Use a name of at most 80 characters.", code: "NAME_TOO_LONG" });- }- }),- // A password that verified in the old auth.json format is rewritten in the current one.- after: createAuthMiddleware(async (ctx) => {- if (ctx.path !== "/sign-in/email") return;- const session = ctx.context.newSession;- const password = (ctx.body as { password?: unknown } | undefined)?.password;- if (!session || typeof password !== "string") return;- const account = await ctx.context.internalAdapter.findCredentialAccount(session.user.id);- if (account?.password && needsRehash(account.password)) {- await ctx.context.internalAdapter.updatePassword(session.user.id, await hashPassword(password));- appendAudit({ action: "auth.password_upgraded", actorId: personFor(session.user.id)?.id ?? null, via: "session", targetKind: "user", targetId: personFor(session.user.id)?.id ?? null });- }- }),- },- } satisfies BetterAuthOptions;-}--export function createFuobeAuth(site: AuthSite = currentSite()) {- return betterAuth(buildAuthOptions(site));-}--export type FuobeAuth = ReturnType<typeof createFuobeAuth>;--let memo: { key: string; auth: FuobeAuth } | null = null;--/**- * The Better Auth instance for the current settings, rebuilt when identity.config_version, the site address or- * the trusted-proxy setting changes (and when a test swaps data folders).- */-export function getAuth(): FuobeAuth {- const site = currentSite();- const key = [DATA_DIR, installValue(INSTALL.configVersion) ?? "0", site.siteUrl ?? "", site.trustedProxy ? "proxy" : "direct"].join("|");- if (memo?.key !== key) memo = { key, auth: createFuobeAuth(site) };- return memo.auth;-}diff --git a/src/server/identity/bootstrap.ts b/src/server/identity/bootstrap.tsdeleted file mode 100644index 524ae092..00000000--- a/src/server/identity/bootstrap.ts+++ /dev/null@@ -1,178 +0,0 @@-import "server-only";-import fs from "node:fs";-import path from "node:path";-import Database from "better-sqlite3";-import { readLegacyAuth } from "../auth";-import { snapshotDatabase, type Snapshot } from "../backup/snapshot";-import { DATA_DIR, db, IDENTITY_MIGRATION } from "../db";-import { envMode, envOwnerPassword, envOwnerPasswordName, envSignIn, INSTALL, installValue, legacyPasswordSet, setInstallValue } from "../mode";-import * as ops from "./admin-ops";-import { appendAudit } from "./audit-log";-import { ensureOwnerAuthUser, ownerAuthUserId } from "./owner";-import { PASSWORD_SIGN_IN_MAX } from "./password";-import { resetSecretCache, secretFingerprint } from "./secret";-import { importLegacyToken } from "./tokens";--/**- * The identity bootstrap, awaited in instrumentation.ts before the server takes requests (docs/research/accounts-8.md- * §7.16). It runs at every start and does only what is still missing:- *- * 1. An existing database that predates accounts: a WAL checkpoint, then a "pre-accounts" snapshot (sessions- * stripped), before the identity migration runs.- * 2. The root secret (data/secret.key or FUOBE_SECRET) and its fingerprint: a server that finds a different key- * than its data was made with refuses to start, unless FUOBE_ACCEPT_NEW_SECRET=1.- * 3. Install values: Personal; sign-in on when the install had a password (auth.json or FUOBE_PASSWORD), else off- * (Just me on this computer); setup done. A fresh data folder boots exactly as before accounts.- * 4. auth.json, once: its password becomes the owner's (the old salt:hash verifies and is rewritten at the next- * sign-in) and its API tokens become legacy Full tokens with the same hashes, so the CLI and MCP keep working.- * The file stays in place, unread, for one release as a rollback aid. Old session cookies are not accepted:- * password installs sign in once more.- * 5. FUOBE_PASSWORD (or FUOBE_OWNER_PASSWORD), at every start: the owner's break-glass password. A changed value- * replaces the old one and signs every browser out. It stays the owner's password after the variable is unset- * (sign-in stays on), and can then be changed or removed in Settings → Security.- * 6. FUOBE_SIGNIN=on needs a password to sign in with: without one the server doesn't start.- *- * A bad value stops the server with one line naming it (StartupError), never a stack trace.- */--export class StartupError extends Error {}--export interface BootstrapReport {- snapshot: Snapshot | null;- importedPassword: boolean;- importedTokens: number;- syncedEnvPassword: boolean;- signin: "on" | "off";-}--const SYSTEM: ops.By = { actorId: null, via: "system" };--/** Before the identity migration: is there an older database to keep a copy of? */-function preAccountsSnapshot(): Snapshot | null {- const file = path.join(DATA_DIR, "fuobe.db");- if (globalThis.__fuobeDb || !fs.existsSync(file)) return null;- const raw = new Database(file);- try {- const hasMigrations = raw.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '_migrations'").get();- if (!hasMigrations) return null;- if (raw.prepare("SELECT 1 FROM _migrations WHERE id = ?").get(IDENTITY_MIGRATION)) return null;- raw.pragma("wal_checkpoint(TRUNCATE)");- return snapshotDatabase({ kind: "pre-accounts", source: raw });- } finally {- raw.close();- }-}--function checkModeEnv(): void {- const raw = (process.env.FUOBE_MODE ?? "").trim();- if (!raw) return;- const mode = envMode();- if (!mode) throw new StartupError(`FUOBE_MODE=${raw} isn't a mode: use personal (studio and platform arrive with accounts).`);- if (mode === "studio") throw new StartupError("FUOBE_MODE=studio needs the first-run setup, which isn't in this version yet. Use FUOBE_MODE=personal.");- if (mode === "platform" && process.env.FUOBE_DEV_PLATFORM !== "1") {- throw new StartupError("FUOBE_MODE=platform isn't ready in this version yet. For development only, set FUOBE_DEV_PLATFORM=1.");- }-}--/** FUOBE_PASSWORD must fit the sign-in form (it did before accounts too), or nobody could ever type it in. */-function checkEnvPassword(): void {- const pw = envOwnerPassword();- if (pw.length > PASSWORD_SIGN_IN_MAX) {- throw new StartupError(`${envOwnerPasswordName()} is longer than ${PASSWORD_SIGN_IN_MAX} characters, so it could never be typed in to sign in. Use a shorter one.`);- }-}--function checkSecret(): void {- resetSecretCache();- let fingerprint: string;- try {- fingerprint = secretFingerprint();- } catch (e) {- // A FUOBE_SECRET that is too short, or a damaged data/secret.key: one line naming it.- throw new StartupError((e as Error).message);- }- const stored = installValue(INSTALL.secretCheck);- if (stored === fingerprint) return;- if (stored && process.env.FUOBE_ACCEPT_NEW_SECRET !== "1") {- throw new StartupError(- "The secret key doesn't match this data folder (data/secret.key or FUOBE_SECRET changed). Restore the original key, or start once with FUOBE_ACCEPT_NEW_SECRET=1 to accept the new one: everyone signs in again.",- );- }- setInstallValue(INSTALL.secretCheck, fingerprint);- if (stored) {- // Sessions were signed with the old key; they are dead anyway.- db().prepare("DELETE FROM auth_session").run();- appendAudit({ action: "install.secret_accepted", via: "system" });- }-}--/** Run the bootstrap. Throws StartupError when the server must not start. */-export async function bootstrapIdentity(): Promise<BootstrapReport> {- checkModeEnv();- checkEnvPassword();- const snapshot = preAccountsSnapshot();- db();- checkSecret();-- const legacy = readLegacyAuth();- const envPassword = envOwnerPassword();- if (installValue(INSTALL.mode) === null) setInstallValue(INSTALL.mode, "personal");- if (installValue(INSTALL.setupState) === null) setInstallValue(INSTALL.setupState, "done");- if (installValue(INSTALL.signin) === null) setInstallValue(INSTALL.signin, legacyPasswordSet() || envPassword ? "on" : "off");-- const report: BootstrapReport = { snapshot, importedPassword: false, importedTokens: 0, syncedEnvPassword: false, signin: "off" };-- // auth.json, once.- if (legacy && installValue(INSTALL.legacyImported) === null) {- if (legacy.password) {- const id = await ensureOwnerAuthUser("bootstrap-import", SYSTEM);- if (!(await ops.hasPassword(id))) {- await ops.setPasswordFor(id, { hash: legacy.password }, SYSTEM);- report.importedPassword = true;- }- db().prepare("UPDATE users SET source = 'legacy', updated_at = ? WHERE id = 'u_owner' AND source = 'setup'").run(Date.now());- }- for (const t of legacy.tokens) if (importLegacyToken("u_owner", t)) report.importedTokens++;- setInstallValue(INSTALL.legacyImported, String(Date.now()));- appendAudit({ action: "install.legacy_imported", via: "system", meta: { password: report.importedPassword, tokens: report.importedTokens } });- }-- // The break-glass password, at every start.- if (envPassword) {- const id = await ensureOwnerAuthUser(ownerAuthUserId() ? "claim-owner" : "bootstrap-import", SYSTEM);- if (!(await ops.verifyPasswordFor(id, envPassword))) {- const had = await ops.hasPassword(id);- await ops.setPasswordFor(id, envPassword, SYSTEM);- if (had) await ops.revokeAllSessions(id, SYSTEM);- report.syncedEnvPassword = true;- db().prepare("UPDATE users SET source = 'env', updated_at = ? WHERE id = 'u_owner' AND source IN ('setup', 'legacy')").run(Date.now());- }- setInstallValue(INSTALL.signin, "on");- }-- // FUOBE_SIGNIN=on with nothing to sign in with would turn every visitor away, the owner too.- if (envSignIn() === true) {- const id = ownerAuthUserId();- if (!id || !(await ops.hasPassword(id))) {- throw new StartupError("FUOBE_SIGNIN=on needs the owner's password: set FUOBE_PASSWORD as well, or set a password in Settings → Security before turning FUOBE_SIGNIN on.");- }- }-- report.signin = installValue(INSTALL.signin) === "on" ? "on" : "off";- return report;-}--/** The bootstrap as the server runs it (instrumentation.ts): a few lines for the terminal, or one line and exit. */-export async function startIdentity(): Promise<void> {- try {- const report = await bootstrapIdentity();- if (report.snapshot) console.log(`Fuobe saved a copy of the database before accounts: ${report.snapshot.db}`);- if (report.importedPassword) console.log("Fuobe moved the password to accounts: sign in once more in each browser.");- if (report.syncedEnvPassword) {- console.log(`Fuobe set the owner's password from ${envOwnerPasswordName()}. It stays the password if you unset the variable: change or remove it in Settings → Security.`);- }- } catch (e) {- console.error(e instanceof StartupError ? `Fuobe can't start: ${e.message}` : e);- process.exit(1);- }-}diff --git a/src/server/identity/owner.ts b/src/server/identity/owner.tsdeleted file mode 100644index 77ed68e7..00000000--- a/src/server/identity/owner.ts+++ /dev/null@@ -1,114 +0,0 @@-import "server-only";-import { isAPIError } from "better-auth/api";-import { REFUSAL_COPY } from "@/lib/sign-in-refusals";-import { db } from "../db";-import { bumpIdentityConfig, envOwnerPassword, envOwnerPasswordName, envSignIn, INSTALL, setInstallValue } from "../mode";-import * as ops from "./admin-ops";-import { appendAudit } from "./audit-log";-import { getAuth } from "./auth";-import { passwordProblem } from "./password";--/**- * The owner of a Personal install: one password, no email (docs/research/accounts-8.md §8). Their Better Auth user- * carries the placeholder [email protected], which is never shown; the sign-in card asks for the password only and- * the /api/auth/login shim signs u_owner in with it. Settings → Security sets, changes and removes that password as- * it always has; removing it turns sign-in off (Just me on this computer).- */--export const OWNER_EMAIL = "[email protected]";-export const OWNER_NAME = "Owner";--/** The owner's Better Auth user, when one is linked. */-export function ownerAuthUserId(): string | null {- return (db().prepare("SELECT auth_user_id FROM users WHERE id = 'u_owner'").get() as { auth_user_id: string | null } | undefined)?.auth_user_id ?? null;-}--/**- * The owner's Better Auth user, created (under `intent`) and linked when there is none yet. A user left by an- * interrupted run (the placeholder email exists but isn't linked) is linked rather than duplicated.- */-export async function ensureOwnerAuthUser(intent: "claim-owner" | "bootstrap-import", by: ops.By): Promise<string> {- const linked = ownerAuthUserId();- if (linked && (await ops.authUserExists(linked))) return linked;- const id = (await ops.findAuthUserByEmail(OWNER_EMAIL)) ?? (await ops.createAuthUser(intent, { email: OWNER_EMAIL, name: OWNER_NAME }, by));- db().prepare("UPDATE users SET auth_user_id = ?, updated_at = ? WHERE id = 'u_owner'").run(id, Date.now());- return id;-}--/** Whether `password` is the owner's (false when the owner has none). */-export async function checkOwnerPassword(password: string): Promise<boolean> {- const id = ownerAuthUserId();- return !!id && ops.verifyPasswordFor(id, password);-}--export type SignInResult = { ok: true; setCookies: string[] } | { ok: false; code?: string; message?: string };--/**- * Sign the owner in through Better Auth (its session checks, cookies and the password upgrade run as for anyone).- * The Set-Cookie headers go on the shim's answer.- */-export async function signInOwner(password: string, headers: Headers): Promise<SignInResult> {- const id = ownerAuthUserId();- const email = id ? await ops.authUserEmail(id) : null;- if (!email) return { ok: false };- try {- const res = await getAuth().api.signInEmail({ body: { email, password, rememberMe: true }, headers, returnHeaders: true });- return { ok: true, setCookies: res.headers?.getSetCookie() ?? [] };- } catch (e) {- if (isAPIError(e)) {- // A refusal with its own copy (pending, turned off, dormant…); anything else reads as a wrong password.- const code = (e.body as { code?: string } | undefined)?.code;- if (code && code in REFUSAL_COPY) return { ok: false, code, message: e.message };- return { ok: false };- }- throw e;- }-}--/** Sign out: the session row goes (so the cookie is dead everywhere), and the answer expires the cookie. */-export async function signOut(headers: Headers): Promise<string[]> {- try {- const res = await getAuth().api.signOut({ headers, returnHeaders: true });- return res.headers?.getSetCookie() ?? [];- } catch {- return [];- }-}--/**- * Settings → Security's view of what the server sets: the password (FUOBE_PASSWORD) and whether sign-in is on- * (FUOBE_SIGNIN, null when unset). Either one locks its control ("Set by the server", §7.9).- */-export function ownerPasswordStatus(): { fromEnv: boolean; signinFromEnv: boolean | null } {- return { fromEnv: !!envOwnerPassword(), signinFromEnv: envSignIn() };-}--/**- * Set, change or (with null) remove the owner's password. Signs every browser out; the caller signs this one back- * in. Setting one turns sign-in on; removing it turns sign-in off.- */-export async function changeOwnerPassword(next: string | null, by: ops.By): Promise<void> {- if (envOwnerPassword()) throw new Error(`The password is set by ${envOwnerPasswordName()} on the server`);- // FUOBE_SIGNIN wins over the stored switch: refuse what it would silently undo (an install nobody can sign in to,- // or "sign-in is now required" on one that stays open).- const pinned = envSignIn();- if (pinned === true && next === null) throw new Error("Sign-in is required by FUOBE_SIGNIN on the server, so the password can't be removed. Change it instead.");- if (pinned === false && next !== null) throw new Error("Sign-in is turned off by FUOBE_SIGNIN on the server. Restart without it to require a password.");- if (next !== null) {- const problem = passwordProblem(next);- if (problem) throw new Error(problem);- const id = await ensureOwnerAuthUser("claim-owner", by);- await ops.setPasswordFor(id, next, by);- await ops.revokeAllSessions(id, by);- setInstallValue(INSTALL.signin, "on");- } else {- const id = ownerAuthUserId();- if (id) {- await ops.removePasswordFor(id, by);- await ops.revokeAllSessions(id, by);- }- setInstallValue(INSTALL.signin, "off");- }- bumpIdentityConfig();- appendAudit({ action: next === null ? "install.sign_in_off" : "install.sign_in_on", actorId: by.actorId, via: by.via });-}diff --git a/src/server/identity/password.ts b/src/server/identity/password.tsdeleted file mode 100644index cdd6bcb0..00000000--- a/src/server/identity/password.ts+++ /dev/null@@ -1,80 +0,0 @@-import "server-only";-import crypto from "node:crypto";-import { promisify } from "node:util";--/**- * Password hashes (docs/research/accounts-8.md §7.2). New hashes are scrypt with N=2^15, r=8, p=3 and a 64-byte key- * (the OWASP table's choice), stored as `scrypt$v2$N$r$p$salt$hash` with base64url salt and hash, so the cost can- * rise later without losing old hashes. The pre-accounts `salt:hash` from auth.json (hex; N=2^14, r=8, p=1, 32- * bytes) still verifies and is rewritten in the new format on the next successful sign-in (needsRehash).- *- * Better Auth calls hashPassword and verifyPassword for every password it handles (emailAndPassword.password).- */--const scrypt = promisify(crypto.scrypt) as (pw: crypto.BinaryLike, salt: crypto.BinaryLike, len: number, opts: crypto.ScryptOptions) => Promise<Buffer>;--export const PASSWORD_MIN = 8;-/** The longest new password (§7.2): Settings, sign-up, resets and changes. */-export const PASSWORD_MAX = 128;-/**- * The longest password that may still sign in: what Fuobe accepted before accounts (Settings and the sign-in form- * took up to 500 characters, FUOBE_PASSWORD had to fit the same form). Imported and FUOBE_PASSWORD passwords up to- * this length keep working; the bootstrap refuses a longer FUOBE_PASSWORD with one line.- */-export const PASSWORD_SIGN_IN_MAX = 500;--const V2 = { N: 2 ** 15, r: 8, p: 3, keyLength: 64 } as const;-const LEGACY = { N: 2 ** 14, r: 8, p: 1, keyLength: 32 } as const;-// scrypt needs 128·N·r bytes; Node's default limit (32 MiB) is exactly that for N=2^15, r=8, so give it room.-const MAXMEM = 128 * 1024 * 1024;--/** The first thing wrong with a new password, in words a person can act on; null when it's fine. */-export function passwordProblem(pw: string): string | null {- if (pw.length < PASSWORD_MIN) return `Use at least ${PASSWORD_MIN} characters`;- if (pw.length > PASSWORD_MAX) return `Use at most ${PASSWORD_MAX} characters`;- return null;-}--export async function hashPassword(password: string): Promise<string> {- const salt = crypto.randomBytes(16);- const hash = await scrypt(password.normalize("NFKC"), salt, V2.keyLength, { N: V2.N, r: V2.r, p: V2.p, maxmem: MAXMEM });- return `scrypt$v2$${V2.N}$${V2.r}$${V2.p}$${salt.toString("base64url")}$${hash.toString("base64url")}`;-}--const LEGACY_FORMAT = /^([0-9a-f]{32}):([0-9a-f]{64})$/i;--/** Which format a stored hash is in. */-export function hashFormat(stored: string): "v2" | "legacy" | "unknown" {- if (stored.startsWith("scrypt$v2$")) return "v2";- return LEGACY_FORMAT.test(stored) ? "legacy" : "unknown";-}--/** Whether a hash that just verified should be rewritten in the current format. */-export const needsRehash = (stored: string): boolean => hashFormat(stored) !== "v2";--const same = (a: Buffer, b: Buffer) => a.length === b.length && crypto.timingSafeEqual(a, b);--// Bounds on a stored v2 hash's parameters, so a damaged row can't ask for gigabytes of memory.-const sane = (N: number, r: number, p: number, len: number) => Number.isInteger(Math.log2(N)) && N >= 2 ** 14 && N <= 2 ** 20 && r >= 1 && r <= 32 && p >= 1 && p <= 16 && len >= 32 && len <= 128;--export async function verifyPassword({ hash, password }: { hash: string; password: string }): Promise<boolean> {- try {- if (hash.startsWith("scrypt$v2$")) {- const [, , n, r, p, salt, key] = hash.split("$");- const N = Number(n), R = Number(r), P = Number(p);- const expected = Buffer.from(key ?? "", "base64url");- if (!salt || !sane(N, R, P, expected.length)) return false;- const got = await scrypt(password.normalize("NFKC"), Buffer.from(salt, "base64url"), expected.length, { N, r: R, p: P, maxmem: MAXMEM });- return same(got, expected);- }- const legacy = LEGACY_FORMAT.exec(hash);- if (legacy) {- // auth.json hashed the password exactly as typed (no normalisation): keep that, or old passwords stop working.- const got = await scrypt(password, Buffer.from(legacy[1], "hex"), LEGACY.keyLength, { N: LEGACY.N, r: LEGACY.r, p: LEGACY.p, maxmem: MAXMEM });- return same(got, Buffer.from(legacy[2], "hex"));- }- } catch {- // An unreadable hash never signs anyone in.- }- return false;-}diff --git a/src/server/identity/principal.ts b/src/server/identity/principal.tsdeleted file mode 100644index 2557a5ad..00000000--- a/src/server/identity/principal.ts+++ /dev/null@@ -1,142 +0,0 @@-import "server-only";-import { hostAllowed } from "../auth";-import { db } from "../db";-import { installMode, signInOn } from "../mode";-import { ensurePendingPerson, getAuth, sessionCookieName } from "./auth";-import { tokenFromHeader } from "./tokens";--/**- * Who is making a request (docs/research/accounts-8.md §7.1), memoised per request:- *- * 1. `Authorization: Bearer fuobe_…` → api_tokens. An invalid bearer is 401, except in Just me, where it is- * ignored (a valid one still names its owner).- * 2. The Better Auth session cookie → auth.api.getSession → the Fuobe person. A missing link is created pending.- * A person who is pending, turned off or dormant gets no actor, only the refusal code.- * 3. Just me (Personal, sign-in off, a local address) → the owner, via `local`.- * 4. Otherwise nobody.- *- * The proxy uses it optimistically; route handlers that need a person ask again (acc-2 puts an actor on every- * route).- */--export type ActorVia = "session" | "token" | "local" | "system" | "runner" | "scim";--export interface Actor {- userId: string;- role: string;- via: ActorVia;- sessionId?: string;- tokenId?: string;- scopes: string[];- workspacePin?: string | null;- /** A restricted session kind (enroll-2fa, verify-2fa, view-as, restore-account, accept-terms): only its routes. */- restricted?: string;- impersonatorId?: string;-}--export interface Principal {- actor: Actor | null;- /** Why there is no actor: INVALID_TOKEN (401), or a refusal code (ACCOUNT_PENDING…). */- code?: string;- /** The session is due for its daily refresh, which only a POST performs (deferSessionRefresh). */- needsRefresh?: boolean;-}--/**- * Restricted session kinds and the routes each may reach (packages add theirs: two-step enrolment, view-as…). A- * restricted actor outside its routes is treated as signed out.- */-export const RESTRICTED_KINDS = new Map<string, (pathname: string) => boolean>();--interface PersonRow {- id: string;- role: string;- status: string;- dormant: number;-}--const person = (id: string) => db().prepare("SELECT id, role, status, dormant FROM users WHERE id = ?").get(id) as PersonRow | undefined;--/** Why an existing person may not act right now, or null. */-function blocked(p: PersonRow): string | null {- if (p.status === "pending") return "ACCOUNT_PENDING";- if (p.status === "disabled" || p.status === "deleted") return "ACCOUNT_DISABLED";- if (p.dormant) return "ACCOUNT_DORMANT";- return null;-}--/** Just me on this computer: Personal with sign-in off, reached at an address that can't be rebound. */-export function justMe(request: Request): boolean {- return installMode() === "personal" && !signInOn() && hostAllowed(request.headers.get("host"));-}--/** Whether the request carries Better Auth's session cookie (checked before asking Better Auth anything). */-export function hasSessionCookie(request: Request): boolean {- const name = sessionCookieName();- return (request.headers.get("cookie") ?? "").split(";").some((c) => c.trim().startsWith(`${name}=`));-}--const LOCAL: Actor = { userId: "u_owner", role: "owner", via: "local", scopes: ["full"] };--async function resolve(request: Request): Promise<Principal> {- const local = justMe(request);- const bearer = tokenFromHeader(request.headers.get("authorization"));- if (bearer === "invalid") {- if (!local) return { actor: null, code: "INVALID_TOKEN" };- } else if (bearer !== "missing") {- const p = person(bearer.userId);- if (!p) return { actor: null, code: "INVALID_TOKEN" };- const code = blocked(p);- if (code) return { actor: null, code };- return { actor: { userId: p.id, role: p.role, via: "token", tokenId: bearer.tokenId, scopes: bearer.scopes, workspacePin: bearer.workspacePin } };- }- if (hasSessionCookie(request)) {- const found = await getAuth()- .api.getSession({ headers: request.headers })- .catch(() => null);- if (found) {- const p = ensurePendingPerson(found.user.id);- const code = blocked(p);- if (code) return { actor: null, code };- return {- actor: { userId: p.id, role: p.role, via: "session", sessionId: found.session.id, scopes: ["full"] },- needsRefresh: !!(found as { needsRefresh?: boolean }).needsRefresh,- };- }- }- if (local) return { actor: LOCAL };- return { actor: null };-}--const memo = new WeakMap<Request, Promise<Principal>>();--export function resolvePrincipal(request: Request): Promise<Principal> {- let p = memo.get(request);- if (!p) {- p = resolve(request);- memo.set(request, p);- }- return p;-}--/** Act as someone else for this request (view-as, §9.5 E5b). The real actor is kept as the impersonator. */-export function substituteActor(actor: Actor, request: Request): void {- const real = memo.get(request);- memo.set(- request,- (real ?? Promise.resolve({ actor: null } as Principal)).then((r) => ({ actor: { ...actor, impersonatorId: r.actor?.userId ?? actor.impersonatorId } })),- );-}--/**- * Refresh a session that is due (once a day), on a POST: Better Auth extends it and sends the cookie again. Returns- * the Set-Cookie headers to add to the response (none when nothing was due or it failed).- */-export async function refreshSession(request: Request): Promise<string[]> {- try {- const { headers } = await getAuth().api.getSession({ headers: request.headers, method: "POST", returnHeaders: true });- return headers?.getSetCookie() ?? [];- } catch {- return [];- }-}diff --git a/src/server/identity/refusals.ts b/src/server/identity/refusals.tsdeleted file mode 100644index d0366350..00000000--- a/src/server/identity/refusals.ts+++ /dev/null@@ -1,33 +0,0 @@-import "server-only";-import { REFUSAL_COPY, refusalMessage, type RefusalCopy } from "@/lib/sign-in-refusals";-import { installName, installValue } from "../mode";--/**- * Refusal codes (docs/research/accounts-8.md §7.1): a check that turns a person away — at sign-in- * (session.create.before) or on a request (the principal) — answers with a code and the sign-in card's words for- * it. Core codes are ACCOUNT_PENDING, ACCOUNT_DISABLED and ACCOUNT_DORMANT; packages register theirs.- */--export interface Refusal {- code: string;- status: number;- message: string;-}--/** Add a code (or reword one). */-export function registerRefusal(code: string, copy: RefusalCopy): void {- REFUSAL_COPY[code] = copy;-}--/** The refusal for a code, with the install's name and contact filled in. */-export function refusal(code: string): Refusal {- const copy = REFUSAL_COPY[code];- const message = refusalMessage(code, { name: installName(), contact: installValue("install.contact") ?? undefined }) ?? "You can't sign in right now.";- return { code, status: copy?.status ?? 403, message };-}--/** A JSON answer for an API request. */-export function refusalResponse(code: string, init: ResponseInit = {}): Response {- const r = refusal(code);- return Response.json({ error: r.message, code: r.code }, { ...init, status: r.status });-}diff --git a/src/server/identity/schema.ts b/src/server/identity/schema.tsdeleted file mode 100644index c45e82ad..00000000--- a/src/server/identity/schema.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * The parts of Better Auth's options that decide its tables (docs/research/accounts-8.md §7.1): table names and- * the plugins whose tables are frozen in Fuobe's migrations. Plain data with no imports, so scripts/auth-schema.mjs- * reads the same values as src/server/identity/auth.ts. A package that loads a plugin with tables (two-factor,- * passkey, sso) adds its id here and to the script's plugin map, runs the script against a database and appends- * the SQL it prints as that package's migration.- */--export const AUTH_TABLES = {- user: "auth_user",- session: "auth_session",- account: "auth_account",- verification: "auth_verification",- rateLimit: "auth_rate_limit",-} as const;--/** Plugins whose tables exist in the migrations (none in the identity base). */-export const AUTH_PLUGINS_WITH_TABLES: readonly string[] = [];diff --git a/src/server/identity/secret.ts b/src/server/identity/secret.tsdeleted file mode 100644index 073df16f..00000000--- a/src/server/identity/secret.ts+++ /dev/null@@ -1,72 +0,0 @@-import "server-only";-import crypto from "node:crypto";-import fs from "node:fs";-import path from "node:path";-import { DATA_DIR } from "../db";--/**- * The root secret (docs/research/accounts-8.md §7.1, §7.15): FUOBE_SECRET, else 32 random bytes in data/secret.key- * (mode 0600, written once). Every key Fuobe signs or encrypts with is derived from it with HKDF-SHA256 under its- * own label ("better-auth/v1" for sessions; later "keys/v1", "recover/v1"…), so one file backs them all and none is- * reused for two purposes. The fingerprint (another label) is stored in the database: a server that finds a- * different key than the one its data was made with refuses to start, instead of silently signing everyone out- * and losing every encrypted key.- */--export const SECRET_FILE = "secret.key";-const MIN_ENV_LENGTH = 32;--/** FUOBE_SECRET as bytes: 64 hex characters are read as hex, anything else (at least 32 characters) as text. */-function envSecret(): Buffer | null {- const raw = (process.env.FUOBE_SECRET ?? "").trim();- if (!raw) return null;- if (/^[0-9a-f]{64}$/i.test(raw)) return Buffer.from(raw, "hex");- if (raw.length < MIN_ENV_LENGTH) throw new Error(`FUOBE_SECRET is too short: use at least ${MIN_ENV_LENGTH} random characters (openssl rand -hex 32).`);- return Buffer.from(raw, "utf8");-}--export const secretPath = () => path.join(DATA_DIR, SECRET_FILE);--/** Where the root secret comes from: the environment or the data folder's file. */-export const secretSource = (): "env" | "file" => ((process.env.FUOBE_SECRET ?? "").trim() ? "env" : "file");--let cached: { key: string; secret: Buffer } | null = null;--/** The root secret, creating data/secret.key on first use when FUOBE_SECRET isn't set. */-export function rootSecret(): Buffer {- const fromEnv = envSecret();- if (fromEnv) return fromEnv;- const file = secretPath();- if (cached?.key === file) return cached.secret;- let secret: Buffer;- try {- secret = fs.readFileSync(file);- } catch {- fs.mkdirSync(DATA_DIR, { recursive: true });- secret = crypto.randomBytes(32);- try {- // "wx": never overwrite a key another process wrote first; read theirs instead.- fs.writeFileSync(file, secret, { mode: 0o600, flag: "wx" });- } catch {- secret = fs.readFileSync(file);- }- }- if (secret.length < 32) throw new Error(`${file} is damaged (shorter than 32 bytes). Restore it from a backup, or delete it and start with FUOBE_ACCEPT_NEW_SECRET=1 (everyone signs in again).`);- cached = { key: file, secret };- return secret;-}--/** A key for one purpose: HKDF-SHA256(root, salt "fuobe", info). */-export function deriveKey(info: string, length = 32): Buffer {- return Buffer.from(crypto.hkdfSync("sha256", rootSecret(), "fuobe", info, length));-}--/** What the database remembers about the root secret: never the secret, only a derived value. */-export function secretFingerprint(): string {- return deriveKey("secret-check/v1", 16).toString("hex");-}--/** Forget the cached file (tests swap data folders and secrets). */-export function resetSecretCache(): void {- cached = null;-}diff --git a/src/server/identity/tokens.ts b/src/server/identity/tokens.tsdeleted file mode 100644index 9d532ae8..00000000--- a/src/server/identity/tokens.ts+++ /dev/null@@ -1,129 +0,0 @@-import "server-only";-import crypto from "node:crypto";-import { db } from "../db";-import { appendAudit } from "./audit-log";--/**- * API tokens (docs/research/accounts-8.md §7.10): `fuobe_` + 24 random bytes, shown once; only the SHA-256 and a- * 12-character prefix are kept, in `api_tokens`, owned by a person. auth.json's tokens were imported as `legacy`- * Full tokens owned by u_owner with their hashes and prefixes, so the CLI, MCP clients and the eval harness keep- * working unchanged. Scopes (Full, Generate only, Read only, Admin), expiry choices and workspace pins arrive with- * the account page (acc-13) and the CLI login (acc-22); until then every token is Full and never expires.- */--export const TOKEN_PATTERN = /^Bearer\s+(fuobe_[\w-]+)$/i;--export interface TokenInfo {- id: string;- name: string;- prefix: string;- createdAt: number;- lastUsedAt?: number;- expiresAt?: number;- legacy?: boolean;-}--interface TokenRow {- id: string;- user_id: string;- workspace_id: string | null;- name: string;- prefix: string;- hash: string;- scopes: string;- legacy: number;- expires_at: number | null;- last_used_at: number | null;- revoked_at: number | null;- created_at: number;-}--export const tokenHash = (token: string) => crypto.createHash("sha256").update(token).digest("hex");--const info = (r: TokenRow): TokenInfo => ({- id: r.id,- name: r.name,- prefix: r.prefix,- createdAt: r.created_at,- ...(r.last_used_at && { lastUsedAt: r.last_used_at }),- ...(r.expires_at && { expiresAt: r.expires_at }),- ...(r.legacy && { legacy: true }),-});--/** A person's live tokens, oldest first (the order Settings has always listed them in). */-export function listTokens(userId: string): TokenInfo[] {- return (db().prepare("SELECT * FROM api_tokens WHERE user_id = ? AND revoked_at IS NULL ORDER BY created_at, id").all(userId) as TokenRow[]).map(info);-}--export function createToken(userId: string, name: string): { token: string; info: TokenInfo } {- const token = `fuobe_${crypto.randomBytes(24).toString("base64url")}`;- const row: TokenRow = {- id: crypto.randomBytes(6).toString("hex"),- user_id: userId,- workspace_id: null,- name: name.trim() || "API token",- prefix: token.slice(0, 12),- hash: tokenHash(token),- scopes: "full",- legacy: 0,- expires_at: null,- last_used_at: null,- revoked_at: null,- created_at: Date.now(),- };- db()- .prepare(- `INSERT INTO api_tokens (id, user_id, workspace_id, name, prefix, hash, scopes, legacy, expires_at, last_used_at, revoked_at, created_at)- VALUES (@id, @user_id, @workspace_id, @name, @prefix, @hash, @scopes, @legacy, @expires_at, @last_used_at, @revoked_at, @created_at)`,- )- .run(row);- appendAudit({ action: "token.created", actorId: userId, targetKind: "token", targetId: row.id, meta: { name: row.name, prefix: row.prefix } });- return { token, info: info(row) };-}--/** Revoke one of a person's tokens; false when they have no such live token. */-export function revokeToken(userId: string, id: string): boolean {- const done = db().prepare("UPDATE api_tokens SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL").run(Date.now(), id, userId).changes > 0;- if (done) appendAudit({ action: "token.revoked", actorId: userId, targetKind: "token", targetId: id });- return done;-}--/** Import one auth.json token as a legacy Full token (its id, name, hash and prefix kept); false if it was there. */-export function importLegacyToken(userId: string, t: { id: string; name: string; hash: string; prefix: string; createdAt: number; lastUsedAt?: number }): boolean {- return (- db()- .prepare(- `INSERT OR IGNORE INTO api_tokens (id, user_id, name, prefix, hash, scopes, legacy, last_used_at, created_at)- VALUES (?, ?, ?, ?, ?, 'full', 1, ?, ?)`,- )- .run(t.id, userId, t.name || "API token", t.prefix || "fuobe_", t.hash.toLowerCase(), t.lastUsedAt ?? null, t.createdAt || Date.now()).changes > 0- );-}--export interface TokenOwner {- tokenId: string;- userId: string;- scopes: string[];- workspacePin: string | null;-}--const touched = new Map<string, number>();--/**- * The live token an Authorization header carries: "missing" when it carries none (or not a fuobe_ one), "invalid"- * when the token is unknown, revoked or expired. `fuobe_scim_` tokens are never API tokens. Use is recorded at most- * once an hour per token, to avoid a write per request.- */-export function tokenFromHeader(header: string | null): TokenOwner | "missing" | "invalid" {- const m = TOKEN_PATTERN.exec(header?.trim() ?? "");- if (!m) return "missing";- if (m[1].startsWith("fuobe_scim_")) return "invalid";- const row = db().prepare("SELECT * FROM api_tokens WHERE hash = ?").get(tokenHash(m[1])) as TokenRow | undefined;- const now = Date.now();- if (!row || row.revoked_at || (row.expires_at && row.expires_at <= now)) return "invalid";- if (now - (touched.get(row.id) ?? 0) > 3_600_000) {- touched.set(row.id, now);- db().prepare("UPDATE api_tokens SET last_used_at = ? WHERE id = ?").run(now, row.id);- }- return { tokenId: row.id, userId: row.user_id, scopes: row.scopes.split(",").filter(Boolean), workspacePin: row.workspace_id };-}diff --git a/src/server/mode.ts b/src/server/mode.tsdeleted file mode 100644index cd8e43eb..00000000--- a/src/server/mode.ts+++ /dev/null@@ -1,176 +0,0 @@-import "server-only";-import fs from "node:fs";-import path from "node:path";-import { DATA_DIR, db } from "./db";--/**- * How this Fuobe runs (docs/research/accounts-8.md §7.9): the mode (Personal, In-house studio or Platform), whether- * sign-in is on, and the setup state, as install values in the `settings` table (outside SETTINGS, so the settings- * API never lists or writes them). UI and API gates read feature flags, never the mode string: each package- * registers its flags as functions of (mode, sign-in, install values).- *- * Until the first-run setup package (acc-14), a fresh data folder boots as Personal with sign-in off and setup done:- * "Just me on this computer", exactly as before accounts. A password (auth.json, Settings → Security or- * FUOBE_PASSWORD) means Personal with sign-in. Studio is not selectable yet, and Platform is a development mode- * (FUOBE_DEV_PLATFORM=1) until the launch package (acc-57).- */--export type InstallMode = "personal" | "studio" | "platform";-export const INSTALL_MODES: readonly InstallMode[] = ["personal", "studio", "platform"];--/** Install values this package reads and writes (more arrive with their packages). */-export const INSTALL = {- mode: "install.mode",- signin: "install.signin",- setupState: "setup.state",- siteUrl: "install.site_url",- name: "install.name",- /** "1" lets Better Auth create people without a Fuobe intent: set only by the meter package (acc-8). */- multiUser: "accounts.multi_user",- /** Bumped whenever sign-in settings change: getAuth() rebuilds Better Auth on the next call. */- configVersion: "identity.config_version",- /** HKDF fingerprint of the root secret (src/server/identity/secret.ts): a server finding another key refuses to start. */- secretCheck: "identity.secret_check",- /** When the bootstrap imported auth.json (its password and API tokens), so it does so once. */- legacyImported: "identity.legacy_imported",-} as const;--export function installValue(key: string): string | null {- const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(key) as { value: string } | undefined;- return row ? row.value : null;-}--export function setInstallValue(key: string, value: string | null): void {- if (value === null) db().prepare("DELETE FROM settings WHERE key = ?").run(key);- else db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);-}--/** Sign-in settings changed (password set or removed, site address, trusted proxies): the next getAuth() rebuilds. */-export function bumpIdentityConfig(): void {- setInstallValue(INSTALL.configVersion, String(Number(installValue(INSTALL.configVersion) ?? "0") + 1));-}--/** FUOBE_MODE as written, or null when unset. An unknown value is an error the bootstrap reports. */-export function envMode(): InstallMode | null {- const v = (process.env.FUOBE_MODE ?? "").trim().toLowerCase();- return v ? ((INSTALL_MODES as readonly string[]).includes(v) ? (v as InstallMode) : null) : null;-}--export function installMode(): InstallMode {- const fromEnv = envMode();- if (fromEnv) return fromEnv;- const stored = installValue(INSTALL.mode);- return stored && (INSTALL_MODES as readonly string[]).includes(stored) ? (stored as InstallMode) : "personal";-}--const ON = new Set(["1", "on", "true", "yes"]);-const OFF = new Set(["0", "off", "false", "no"]);--/** FUOBE_SIGNIN=on|off, or null when unset (or unreadable). */-export function envSignIn(): boolean | null {- const v = (process.env.FUOBE_SIGNIN ?? "").trim().toLowerCase();- return ON.has(v) ? true : OFF.has(v) ? false : null;-}--/** The break-glass owner password (FUOBE_OWNER_PASSWORD, or its older name FUOBE_PASSWORD). Synced at every boot. */-export function envOwnerPassword(): string {- return process.env.FUOBE_OWNER_PASSWORD || process.env.FUOBE_PASSWORD || "";-}--/** Which variable the break-glass password came from, for messages. */-export function envOwnerPasswordName(): "FUOBE_OWNER_PASSWORD" | "FUOBE_PASSWORD" {- return process.env.FUOBE_OWNER_PASSWORD ? "FUOBE_OWNER_PASSWORD" : "FUOBE_PASSWORD";-}--/** A password in the pre-accounts auth.json: the install had sign-in before this build. */-export function legacyPasswordSet(): boolean {- try {- const data = JSON.parse(fs.readFileSync(path.join(DATA_DIR, "auth.json"), "utf8")) as { password?: unknown };- return typeof data.password === "string" && data.password.length > 0;- } catch {- return false;- }-}--/**- * Whether people sign in. FUOBE_SIGNIN wins; a break-glass password turns it on; then the stored value. With nothing- * stored yet (a build whose bootstrap hasn't run, or a test), a password in auth.json still means on: never open.- */-export function signInOn(): boolean {- const env = envSignIn();- if (env !== null) return env;- if (envOwnerPassword()) return true;- if (installMode() !== "personal") return true;- const stored = installValue(INSTALL.signin);- if (stored !== null) return ON.has(stored);- return legacyPasswordSet();-}--export type SetupState = "fresh" | "in-progress" | "done";--/** Until acc-14 there is no setup wizard: every install reads as done, and the proxy's setup gate stays inert. */-export function setupState(): SetupState {- const v = installValue(INSTALL.setupState);- return v === "fresh" || v === "in-progress" ? v : "done";-}--/** The public site address (FUOBE_SITE_URL, else Settings), without a trailing slash; null when unset. */-export function siteUrl(): string | null {- const raw = (process.env.FUOBE_SITE_URL || installValue(INSTALL.siteUrl) || "").trim().replace(/\/+$/, "");- if (!raw) return null;- try {- const u = new URL(raw);- return u.protocol === "https:" || u.protocol === "http:" ? u.origin : null;- } catch {- return null;- }-}--export function installName(): string {- return (process.env.FUOBE_INSTALL_NAME || installValue(INSTALL.name) || "Fuobe").trim() || "Fuobe";-}--// ----------------------------------------------------------------------------// Feature flags--/** Core flags (§7.9). Mode packages register more (passkeys, twoStep, sso, plans, payments…). */-export type CoreFlag = "signInRequired" | "signUp" | "teams" | "invites" | "admin" | "limits" | "ownKeys" | "teamKeys" | "credits" | "enterprise";--export type FlagFn = (mode: InstallMode, signin: boolean, value: (key: string) => string | null) => boolean;--const studioOrPlatform: FlagFn = (mode) => mode !== "personal";--/**- * The registry. Core flags are what each mode turns on; the packages that build a feature refine its flag (sign-up- * policy, plans). A flag nobody registered reads as off.- */-const FEATURES = new Map<string, FlagFn>([- ["signInRequired", (mode, signin) => mode !== "personal" || signin],- ["signUp", studioOrPlatform],- ["teams", studioOrPlatform],- ["invites", studioOrPlatform],- ["admin", studioOrPlatform],- ["limits", studioOrPlatform],- ["ownKeys", (mode) => mode === "studio"],- ["teamKeys", studioOrPlatform],- ["credits", (mode) => mode === "platform"],- ["enterprise", (mode) => mode === "studio"],-]);--/** Add or replace a flag (a package's own, or a refinement of a core one). */-export function registerFeature(name: string, fn: FlagFn): void {- FEATURES.set(name, fn);-}--export type Flags = Record<CoreFlag, boolean> & Record<string, boolean>;--export function features(): Flags {- const mode = installMode();- const signin = signInOn();- const out: Record<string, boolean> = {};- for (const [name, fn] of FEATURES) out[name] = fn(mode, signin, installValue);- return out as Flags;-}--/** The one flag the proxy reads on every request. */-export const signInRequired = (): boolean => features().signInRequired;diff --git a/tests/assist-polish.test.ts b/tests/assist-polish.test.tsindex 687adcf2..137d9557 100644--- a/tests/assist-polish.test.ts+++ b/tests/assist-polish.test.ts@@ -15,15 +15,15 @@ describe("/apps/<unknown> is a real 404", () => {it("the proxy rewrites unknown app ids to the not-found page with status 404", async () => {delete process.env.FUOBE_PASSWORD;const { proxy } = await import("@/proxy");- const unknown = await proxy(new NextRequest("http://localhost:3000/apps/does-not-exist"));+ const unknown = proxy(new NextRequest("http://localhost:3000/apps/does-not-exist"));expect(unknown.status).toBe(404);expect(unknown.headers.get("x-middleware-rewrite")).toMatch(/\/_fuobe-not-found$/);- const known = await proxy(new NextRequest("http://localhost:3000/apps/app-packshot"));+ const known = proxy(new NextRequest("http://localhost:3000/apps/app-packshot"));expect(known.status).toBe(200);expect(known.headers.get("x-middleware-rewrite")).toBeNull();- expect((await proxy(new NextRequest("http://localhost:3000/apps"))).headers.get("x-middleware-rewrite")).toBeNull();+ expect(proxy(new NextRequest("http://localhost:3000/apps")).headers.get("x-middleware-rewrite")).toBeNull();// A malformed escape doesn't crash the proxy.- expect((await proxy(new NextRequest("http://localhost:3000/apps/%E0%A4%A"))).status).toBe(404);+ expect(proxy(new NextRequest("http://localhost:3000/apps/%E0%A4%A")).status).toBe(404);});});diff --git a/tests/auth.test.ts b/tests/auth.test.tsindex 87789a55..13c39f13 100644--- a/tests/auth.test.ts+++ b/tests/auth.test.ts@@ -1,142 +1,59 @@-/**- * Personal sign-in after accounts (docs/research/accounts-8.md §7.2, §8): the owner's password (formats, the- * upgrade from auth.json's salt:hash), Settings → Security's set / change / remove, and API tokens in api_tokens.- */-import crypto from "node:crypto";import fs from "node:fs";import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";--// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.-vi.setConfig({ testTimeout: 60_000 });+import { afterAll, describe, expect, it } from "vitest";const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-auth-"));process.env.FUOBE_DATA_DIR = dir;-for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET"]) delete process.env[k];-+delete process.env.FUOBE_PASSWORD;const auth = await import("@/server/auth");-const pw = await import("@/server/identity/password");-const owner = await import("@/server/identity/owner");-const ops = await import("@/server/identity/admin-ops");-const tokens = await import("@/server/identity/tokens");-const { db } = await import("@/server/db");-const { setOwnerPassword, ownerCookie } = await import("./helpers/identity");-const { getAuth } = await import("@/server/identity/auth");afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));-/** How auth.json stored a password before accounts. */-const legacyHash = (password: string) => {- const salt = crypto.randomBytes(16);- return `${salt.toString("hex")}:${crypto.scryptSync(password, salt, 32).toString("hex")}`;-};--describe("password hashes (§7.2)", () => {- it("are scrypt v2 (N=2^15, r=8, p=3, 64 bytes) with their parameters in the string", async () => {- const h = await pw.hashPassword("correct horse battery");- const [scheme, version, N, r, p, salt, key] = h.split("$");- expect([scheme, version, N, r, p]).toEqual(["scrypt", "v2", "32768", "8", "3"]);- expect(Buffer.from(salt, "base64url")).toHaveLength(16);- expect(Buffer.from(key, "base64url")).toHaveLength(64);- expect(pw.hashFormat(h)).toBe("v2");- expect(pw.needsRehash(h)).toBe(false);- expect(await pw.verifyPassword({ hash: h, password: "correct horse battery" })).toBe(true);- expect(await pw.verifyPassword({ hash: h, password: "correct horse batterY" })).toBe(false);- expect(h).not.toContain("correct horse");- });-- it("still verify auth.json's salt:hash, which needs a rehash", async () => {- const old = legacyHash("old password here");- expect(pw.hashFormat(old)).toBe("legacy");- expect(pw.needsRehash(old)).toBe(true);- expect(await pw.verifyPassword({ hash: old, password: "old password here" })).toBe(true);- expect(await pw.verifyPassword({ hash: old, password: "old password her" })).toBe(false);- });-- it("never verify a damaged or unknown hash, nor one asking for absurd parameters", async () => {- for (const hash of ["", "nope", "scrypt$v2$1024$8$1$AAAA$BBBB", `scrypt$v2$${2 ** 30}$8$1$${"A".repeat(22)}$${"B".repeat(86)}`, "zz:zz"]) {- expect(await pw.verifyPassword({ hash, password: "anything at all" }), hash).toBe(false);- }- });-- it("are 8 to 128 characters", () => {- expect(pw.passwordProblem("short")).toMatch(/8 characters/);- expect(pw.passwordProblem("x".repeat(129))).toMatch(/128 characters/);- expect(pw.passwordProblem("eight ch")).toBeNull();- });-});--describe("the owner's password", () => {- it("is off until a password is set", async () => {+describe("auth", () => {+ it("is off until a password is set", () => {expect(auth.authEnabled()).toBe(false);- expect(await owner.checkOwnerPassword("anything")).toBe(false);+ expect(auth.checkPassword("anything")).toBe(false);});- it("is set, checked and stored only as a hash; short ones are refused", async () => {- await expect(setOwnerPassword("short")).rejects.toThrow(/8 characters/);- await setOwnerPassword("correct horse");+ it("hashes the password, checks it and rejects short ones", () => {+ expect(() => auth.setPassword("short")).toThrow(/8 characters/);+ auth.setPassword("correct horse");expect(auth.authEnabled()).toBe(true);- expect(await owner.checkOwnerPassword("correct horse")).toBe(true);- expect(await owner.checkOwnerPassword("wrong horse")).toBe(false);- const stored = db().prepare("SELECT password FROM auth_account WHERE userId = ?").get(owner.ownerAuthUserId()) as { password: string };- expect(pw.hashFormat(stored.password)).toBe("v2");- expect(fs.existsSync(path.join(dir, "auth.json"))).toBe(false);- });-- it("signs every browser out when it changes", async () => {- const cookie = await ownerCookie("correct horse");- expect(await getAuth().api.getSession({ headers: new Headers({ cookie }) })).not.toBeNull();- await setOwnerPassword("another secret");- expect(await getAuth().api.getSession({ headers: new Headers({ cookie }) })).toBeNull();- expect(await owner.checkOwnerPassword("another secret")).toBe(true);- });-- it("is upgraded from auth.json's format at the next sign-in", async () => {- const id = owner.ownerAuthUserId()!;- await ops.setPasswordFor(id, { hash: legacyHash("from the old file") }, ops.SYSTEM);- expect(await ops.passwordNeedsRehash(id)).toBe(true);- const r = await owner.signInOwner("from the old file", new Headers());- expect(r.ok).toBe(true);- expect(await ops.passwordNeedsRehash(id)).toBe(false);- expect(await owner.checkOwnerPassword("from the old file")).toBe(true);- // A wrong password neither signs in nor rewrites anything.- expect((await owner.signInOwner("from the old filE", new Headers())).ok).toBe(false);- });-- it("is the server's when FUOBE_PASSWORD is set: Settings can't change it", async () => {+ expect(auth.checkPassword("correct horse")).toBe(true);+ expect(auth.checkPassword("wrong horse")).toBe(false);+ expect(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).not.toContain("correct horse");+ });++ it("signs sessions and signs everyone out when the password changes", () => {+ const s = auth.createSession();+ expect(auth.validSession(s.value)).toBe(true);+ expect(auth.validSession(s.value.replace(/.$/, (c) => (c === "A" ? "B" : "A")))).toBe(false);+ expect(auth.validSession(`${Date.now() - 1}.${s.value.split(".")[1]}`)).toBe(false);+ expect(auth.validSession(undefined)).toBe(false);+ auth.setPassword("another secret");+ expect(auth.validSession(s.value)).toBe(false);+ });++ it("issues bearer tokens that can be revoked and stores only their hash", () => {+ const { token, info } = auth.createToken("CI");+ expect(token).toMatch(/^fuobe_/);+ expect(auth.validToken(`Bearer ${token}`)).toBe(true);+ expect(auth.validToken(`Bearer ${token}x`)).toBe(false);+ expect(auth.validToken(token)).toBe(false);+ expect(fs.readFileSync(path.join(dir, "auth.json"), "utf8")).not.toContain(token);+ expect(auth.authStatus().tokens[0]).toMatchObject({ name: "CI", prefix: token.slice(0, 12) });+ expect(auth.authStatus().tokens[0]).not.toHaveProperty("hash");+ auth.revokeToken(info.id);+ expect(auth.validToken(`Bearer ${token}`)).toBe(false);+ });++ it("uses FUOBE_PASSWORD when set and refuses UI changes", () => {process.env.FUOBE_PASSWORD = "from the env";- try {- expect(owner.ownerPasswordStatus().fromEnv).toBe(true);- await expect(setOwnerPassword(null)).rejects.toThrow(/FUOBE_PASSWORD/);- } finally {- delete process.env.FUOBE_PASSWORD;- }- });-- it("turns sign-in off when removed (Just me on this computer)", async () => {- await setOwnerPassword(null);+ expect(auth.checkPassword("from the env")).toBe(true);+ expect(auth.checkPassword("another secret")).toBe(false);+ expect(() => auth.setPassword(null)).toThrow(/FUOBE_PASSWORD/);+ delete process.env.FUOBE_PASSWORD;+ auth.setPassword(null);expect(auth.authEnabled()).toBe(false);- expect(await owner.checkOwnerPassword("from the old file")).toBe(false);- });-});--describe("API tokens", () => {- it("are issued once, stored only as a hash, verified by Bearer and revoked", () => {- const { token, info } = tokens.createToken("u_owner", "CI");- expect(token).toMatch(/^fuobe_[\w-]{32}$/);- const ok = tokens.tokenFromHeader(`Bearer ${token}`);- expect(ok).toMatchObject({ tokenId: info.id, userId: "u_owner", scopes: ["full"] });- expect(tokens.tokenFromHeader(`Bearer ${token}x`)).toBe("invalid");- expect(tokens.tokenFromHeader(token)).toBe("missing");- expect(tokens.tokenFromHeader(null)).toBe("missing");- expect(tokens.tokenFromHeader("Bearer fuobe_scim_abc")).toBe("invalid");- const row = JSON.stringify(db().prepare("SELECT * FROM api_tokens WHERE id = ?").get(info.id));- expect(row).not.toContain(token);- expect(tokens.listTokens("u_owner")[0]).toMatchObject({ name: "CI", prefix: token.slice(0, 12) });- expect(tokens.listTokens("u_owner")[0]).not.toHaveProperty("hash");- expect(tokens.revokeToken("u_someone_else", info.id)).toBe(false);- expect(tokens.revokeToken("u_owner", info.id)).toBe(true);- expect(tokens.tokenFromHeader(`Bearer ${token}`)).toBe("invalid");- expect(tokens.listTokens("u_owner")).toEqual([]);});});diff --git a/tests/e2e/no-horizontal-scroll.mjs b/tests/e2e/no-horizontal-scroll.mjsindex ea7cd0fa..22fc5a18 100644--- a/tests/e2e/no-horizontal-scroll.mjs+++ b/tests/e2e/no-horizontal-scroll.mjs@@ -10,9 +10,6 @@// dynamic route without a sample is visited with "does-not-exist" for each segment, and named. For each route it// asserts document.documentElement.scrollWidth === clientWidth once the page has rendered, and names// the widest elements when it isn't. Pages that don't load are reported apart from layout failures.-// A route that redirects is measured where it lands and named with that page (`/login → /`), so a page that was-// never shown isn't counted as checked: in Just me (demo mode) /login goes to /, and the sign-in card is only-// measured on a server with a password.import { launch, openRoute, PHONE, post, root } from "./_browser.mjs";import { dynamicSamples, querySamples, studioRoutes } from "./_routes.mjs";@@ -76,7 +73,6 @@ const routes = only ?? (await discoverRoutes());const browser = await launch();const wide = [];const broken = [];-const redirected = new Map();for (const scheme of schemes) {console.log(`\n${scheme} mode, 390 × 844`);const ctx = await browser.newContext({ ...PHONE, colorScheme: scheme });@@ -90,9 +86,6 @@ for (const scheme of schemes) {await page.close();continue;}- const landed = new URL(page.url());- const shown = landed.pathname === new URL(app + route).pathname ? route : `${route} → ${landed.pathname}`;- if (shown !== route) redirected.set(route, landed.pathname);try {const r = await page.evaluate(() => {const W = document.documentElement.clientWidth;@@ -117,7 +110,7 @@ for (const scheme of schemes) {return { scrollWidth: document.documentElement.scrollWidth, clientWidth: W, culprits };});const ok = r.scrollWidth === r.clientWidth;- console.log(`${ok ? "ok " : "WIDE"} ${shown.padEnd(36)} ${r.scrollWidth}/${r.clientWidth}`);+ console.log(`${ok ? "ok " : "WIDE"} ${route.padEnd(36)} ${r.scrollWidth}/${r.clientWidth}`);if (!ok) {for (const c of r.culprits) console.log(` ${c}`);wide.push(`${route} (${scheme})`);@@ -138,6 +131,5 @@ const checks = routes.length * schemes.length;console.log("");if (wide.length) console.log(`${wide.length} of ${checks} pages scroll sideways at 390 px: ${wide.join(", ")}`);if (broken.length) console.log(`${broken.length} of ${checks} pages didn't load: ${broken.join(", ")}`);-if (redirected.size) console.log(`${redirected.size} redirected, measured where they landed (not their own page): ${[...redirected].map(([a, b]) => `${a} → ${b}`).join(", ")}`);if (!wide.length && !broken.length) console.log(`All ${routes.length} routes fit 390 px (${schemes.join(" and ")}).`);process.exit(wide.length || broken.length ? 1 : 0);diff --git a/tests/helpers/identity.ts b/tests/helpers/identity.tsdeleted file mode 100644index edbb6686..00000000--- a/tests/helpers/identity.ts+++ /dev/null@@ -1,27 +0,0 @@-/**- * Accounts in tests: set the owner's password (Personal with sign-in), sign in and get the session cookie, the way- * Settings → Security and the /login card do. Each test file sets FUOBE_DATA_DIR before importing Fuobe.- */-import { changeOwnerPassword, signInOwner } from "@/server/identity/owner";--const BY = { actorId: "u_owner", via: "local" };--/** Require a password (or, with null, turn sign-in off: Just me on this computer). */-export async function setOwnerPassword(password: string | null): Promise<void> {- await changeOwnerPassword(password, BY);-}--/** Sign the owner in and return the Cookie header a browser would send next. */-export async function ownerCookie(password: string, headers: Record<string, string> = {}): Promise<string> {- const r = await signInOwner(password, new Headers(headers));- if (!r.ok) throw new Error(`sign-in failed${r.code ? `: ${r.code}` : ""}`);- return cookieHeader(r.setCookies);-}--/** Set-Cookie lines → the Cookie header (name=value pairs, skipping cookies being cleared). */-export function cookieHeader(setCookies: string[]): string {- return setCookies- .filter((c) => !/max-age=0/i.test(c))- .map((c) => c.split(";")[0])- .join("; ");-}diff --git a/tests/identity-better-auth.test.ts b/tests/identity-better-auth.test.tsdeleted file mode 100644index 4085aa07..00000000--- a/tests/identity-better-auth.test.ts+++ /dev/null@@ -1,231 +0,0 @@-/**- * Better Auth behind Fuobe (docs/research/accounts-8.md §5.2, §7.1): pins of the pinned version's behaviour that- * Fuobe relies on — cookie names and attributes, IP tracking, the router-only allowlist, create intents reaching- * database hooks, returnHeaders, the internal adapter — and the schema guard. A library upgrade that changes any- * of these fails here first.- */-import { execFileSync } from "node:child_process";-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";--// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.-vi.setConfig({ testTimeout: 60_000 });--const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-ba-"));-process.env.FUOBE_DATA_DIR = dir;-for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SITE_URL", "FUOBE_TRUST_PROXY", "FUOBE_TRUSTED_PROXIES", "FUOBE_SECRET", "FUOBE_MODE", "FUOBE_SIGNIN"]) delete process.env[k];--const identity = await import("@/server/identity/auth");-const { db } = await import("@/server/db");-const { bootstrapIdentity } = await import("@/server/identity/bootstrap");-const { setOwnerPassword, cookieHeader } = await import("./helpers/identity");-const { OWNER_EMAIL, ownerAuthUserId } = await import("@/server/identity/owner");-const route = await import("@/app/api/identity/[...all]/route");-const { getMigrations } = await import("better-auth/db/migration");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));--const PASSWORD = "correct horse battery";-await bootstrapIdentity();-await setOwnerPassword(PASSWORD);--const authUsers = () => (db().prepare("SELECT COUNT(*) AS n FROM auth_user").get() as { n: number }).n;--/** A browser request to Better Auth's router, from this site. */-const routerPost = (p: string, body: unknown, headers: Record<string, string> = {}) =>- new Request(`http://localhost:3000/api/identity${p}`, {- method: "POST",- headers: { "content-type": "application/json", origin: "http://localhost:3000", host: "localhost:3000", ...headers },- body: JSON.stringify(body),- });--describe("the schema guard", () => {- it("finds nothing to create or add: Better Auth's tables are frozen in Fuobe's migrations", async () => {- const m = await getMigrations(identity.getAuth().options);- expect(m.toBeCreated.map((t) => t.table)).toEqual([]);- expect(m.toBeAdded.map((t) => `${t.table}: ${Object.keys(t.fields).join(", ")}`)).toEqual([]);- expect(m.toBeAddedIndexes.map((i) => i.name)).toEqual([]);- });-});--describe("cookies (§7.1)", () => {- it("are fuobe.* without Secure on plain http", async () => {- const auth = identity.createFuobeAuth({ siteUrl: null, trustedProxy: false });- const { headers } = await auth.api.signInEmail({ body: { email: OWNER_EMAIL, password: PASSWORD }, headers: new Headers(), returnHeaders: true });- const session = headers.getSetCookie().find((c) => c.startsWith("fuobe.session_token="))!;- expect(session).toBeTruthy();- expect(session).toMatch(/HttpOnly/i);- expect(session).toMatch(/SameSite=Lax/i);- expect(session).toMatch(/Path=\//);- expect(session).not.toMatch(/Secure/i);- expect(session).not.toMatch(/Domain=/i);- });-- it("are __Host-fuobe.* with Secure, Path=/ and no Domain on an https site address (never __Secure-)", async () => {- const auth = identity.createFuobeAuth({ siteUrl: "https://studio.example.com", trustedProxy: false });- const { headers } = await auth.api.signInEmail({ body: { email: OWNER_EMAIL, password: PASSWORD }, headers: new Headers(), returnHeaders: true });- const all = headers.getSetCookie();- const session = all.find((c) => c.startsWith("__Host-fuobe.session_token="))!;- expect(session, all.join("\n")).toBeTruthy();- expect(session).toMatch(/; Secure/i);- expect(session).toMatch(/Path=\//);- expect(session).not.toMatch(/Domain=/i);- expect(all.some((c) => c.startsWith("__Secure-"))).toBe(false);- expect(identity.sessionCookieName({ siteUrl: "https://studio.example.com", trustedProxy: false })).toBe("__Host-fuobe.session_token");- expect(identity.sessionCookieName({ siteUrl: null, trustedProxy: false })).toBe("fuobe.session_token");- });-- it("returnHeaders hands back the Set-Cookie lines, and the cookie names a live session", async () => {- const { headers, response } = await identity.getAuth().api.signInEmail({ body: { email: OWNER_EMAIL, password: PASSWORD }, headers: new Headers(), returnHeaders: true });- expect(response.user.email).toBe(OWNER_EMAIL);- const session = await identity.getAuth().api.getSession({ headers: new Headers({ cookie: cookieHeader(headers.getSetCookie()) }) });- expect(session?.user.id).toBe(ownerAuthUserId());- // GET stays read-only (deferSessionRefresh): it reports instead of writing.- expect(session).toHaveProperty("needsRefresh", false);- });-});--describe("the router allowlist (§7.1)", () => {- it("answers 403 to sign-up from a browser and creates no user", async () => {- const before = authUsers();- const res = await route.POST(routerPost("/sign-up/email", { email: "[email protected]", password: "another long password", name: "Someone" }));- expect(res.status).toBe(403);- expect(((await res.json()) as { code?: string }).code).toBe("ENDPOINT_BLOCKED");- expect(authUsers()).toBe(before);- });-- it("blocks social sign-in, OAuth callbacks and the always-blocked list, and lets the allowlist through", async () => {- for (const p of ["/sign-in/social", "/sign-in/oauth2", "/sign-in/email", "/delete-user", "/list-sessions", "/revoke-sessions", "/change-email", "/get-access-token"]) {- expect(identity.routerAllows(p), p).toBe(false);- // 403 from the allowlist, or 404 where no plugin defines the path at all.- expect([403, 404], p).toContain((await route.POST(routerPost(p, {}))).status);- }- for (const p of ["/get-session", "/sign-out", "/update-user", "/ok"]) expect(identity.routerAllows(p), p).toBe(true);- expect((await route.GET(new Request("http://localhost:3000/api/identity/ok", { headers: { host: "localhost:3000" } }))).status).toBe(200);- });-- it("lets Fuobe's own auth.api calls pass the allowlist: their creates meet the create-intent check instead", async () => {- const before = authUsers();- // No request, so the allowlist doesn't apply; no intent, so user.create.before refuses.- await expect(identity.getAuth().api.signUpEmail({ body: { email: "[email protected]", password: "another long password", name: "Second" } })).rejects.toMatchObject({- body: { code: "SIGN_UP_CLOSED" },- });- expect(authUsers()).toBe(before);- });-- it("carries Fuobe's request scope into database hooks: a create under an intent goes through, and its session check still runs", async () => {- const before = authUsers();- // A package's own intent (as invites will register one). Its user isn't the owner, so it gets a pending person- // of its own (never active), and the sign-in that sign-up attempts is refused with that code. Better Auth's- // transactions are off: the user stays.- identity.registerCreateIntent("test-scope", () => null);- try {- await expect(- identity.withCreateIntent("test-scope", () => identity.getAuth().api.signUpEmail({ body: { email: "[email protected]", password: "another long password", name: "Scope" } })),- ).rejects.toMatchObject({ body: { code: "ACCOUNT_PENDING" } });- } finally {- identity.CREATE_INTENTS.delete("test-scope");- }- expect(authUsers()).toBe(before + 1);- const person = db().prepare("SELECT u.status, u.source FROM users u JOIN auth_user a ON a.id = u.auth_user_id WHERE a.email = ?").get("[email protected]");- expect(person).toEqual({ status: "pending", source: "unknown" });- });-- it("refuses the owner's intents once the owner has a live sign-in account, so they never make a second user", async () => {- expect(identity.ownerClaimable()).toBe(false);- const before = authUsers();- for (const intent of ["claim-owner", "bootstrap-import"]) {- await expect(- identity.withCreateIntent(intent, () => identity.getAuth().api.signUpEmail({ body: { email: `${intent}@example.com`, password: "another long password", name: "Again" } })),- intent,- ).rejects.toMatchObject({ body: { code: "OWNER_CLAIMED" } });- }- // multi_user (the meter package) doesn't loosen them either.- db().prepare("INSERT INTO settings (key, value) VALUES ('accounts.multi_user', '1')").run();- try {- await expect(- identity.withCreateIntent("claim-owner", () => identity.getAuth().api.signUpEmail({ body: { email: "[email protected]", password: "another long password", name: "Again" } })),- ).rejects.toMatchObject({ body: { code: "OWNER_CLAIMED" } });- } finally {- db().prepare("DELETE FROM settings WHERE key = 'accounts.multi_user'").run();- }- expect(authUsers()).toBe(before);- });-- it("keeps new passwords to 128 characters on every path, while Better Auth's own limit is the sign-in one (500)", async () => {- identity.registerCreateIntent("test-long", () => null);- try {- await expect(- identity.withCreateIntent("test-long", () => identity.getAuth().api.signUpEmail({ body: { email: "[email protected]", password: "x".repeat(129), name: "Long" } })),- ).rejects.toMatchObject({ body: { code: "PASSWORD_TOO_LONG", message: "Use at most 128 characters." } });- } finally {- identity.CREATE_INTENTS.delete("test-long");- }- expect(db().prepare("SELECT 1 FROM auth_user WHERE email = '[email protected]'").get()).toBeUndefined();- expect((await identity.getAuth().$context).password.config.maxPasswordLength).toBe(500);- for (const p of Object.keys(identity.NEW_PASSWORD_FIELDS)) expect(p.startsWith("/"), p).toBe(true);- });-- it("refuses a session for a pending person with its code", async () => {- await expect(identity.getAuth().api.signInEmail({ body: { email: "[email protected]", password: "another long password" } })).rejects.toMatchObject({- body: { code: "ACCOUNT_PENDING" },- });- });-- it("strips the picture and caps the name on /update-user", async () => {- const { headers } = await identity.getAuth().api.signInEmail({ body: { email: OWNER_EMAIL, password: PASSWORD }, headers: new Headers(), returnHeaders: true });- const cookie = cookieHeader(headers.getSetCookie());- const ok = await route.POST(routerPost("/update-user", { name: "Mina", image: "https://evil.example/x.png" }, { cookie }));- expect(ok.status).toBe(200);- const row = db().prepare("SELECT name, image FROM auth_user WHERE id = ?").get(ownerAuthUserId()) as { name: string; image: string | null };- expect(row).toEqual({ name: "Mina", image: null });- const long = await route.POST(routerPost("/update-user", { name: "x".repeat(81) }, { cookie }));- expect(long.status).toBe(400);- });-});--describe("client IPs (§7.1, §7.2)", () => {- const tries = async (auth: ReturnType<typeof identity.createFuobeAuth>, headers: Record<string, string>) => {- const statuses: number[] = [];- for (let i = 0; i < 6; i++) statuses.push((await auth.handler(routerPost("/sign-in/email", { email: `x${i}@example.com`, password: "nope nope nope" }, headers))).status);- return statuses;- };-- it("without a trusted proxy, tracking is off and the limiter skips its IP rules (no shared bucket to fill)", async () => {- const statuses = await tries(identity.createFuobeAuth({ siteUrl: null, trustedProxy: false }), { "x-fuobe-client-ip": "203.0.113.7" });- expect(statuses).not.toContain(429);- });-- it("behind a trusted proxy, the limiter keys on x-fuobe-client-ip", async () => {- const statuses = await tries(identity.createFuobeAuth({ siteUrl: null, trustedProxy: true }), { "x-fuobe-client-ip": "203.0.113.8" });- expect(statuses).toContain(429);- // Another client still gets in.- const other = await identity.createFuobeAuth({ siteUrl: null, trustedProxy: true }).handler(routerPost("/get-session", {}, { "x-fuobe-client-ip": "198.51.100.9" }));- expect(other.status).not.toBe(429);- });-});--describe("admin operations (§7.1)", () => {- it("can reach Better Auth's internal adapter and the methods admin-ops.ts uses", async () => {- const ctx = await identity.getAuth().$context;- for (const m of ["createUser", "findUserByEmail", "findUserById", "findCredentialAccount", "updatePassword", "linkAccount", "deleteAccount", "deleteUserSessions", "listSessions", "deleteSession", "updateUser", "deleteAccounts", "deleteUser"] as const) {- expect(typeof ctx.internalAdapter[m], m).toBe("function");- }- });-});--describe("scripts/auth-schema.mjs", () => {- const run = (...args: string[]) => execFileSync(process.execPath, ["scripts/auth-schema.mjs", ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });-- it("prints exactly the SQL frozen in the identity migration", () => {- const frozen = fs.readFileSync(path.join(process.cwd(), "src/server/db.ts"), "utf8");- const statements = run().split(/;\s*\n/).map((s) => s.trim().replace(/;$/, "")).filter(Boolean);- expect(statements.length).toBeGreaterThanOrEqual(8);- for (const s of statements) expect(frozen, s).toContain(`${s};`);- });-- it("finds nothing missing in a migrated database", () => {- expect(run("--db", path.join(dir, "fuobe.db"), "--check")).toMatch(/match/);- });-});diff --git a/tests/identity-bootstrap.test.ts b/tests/identity-bootstrap.test.tsdeleted file mode 100644index 3aa91b8a..00000000--- a/tests/identity-bootstrap.test.ts+++ /dev/null@@ -1,431 +0,0 @@-/**- * The identity bootstrap (docs/research/accounts-8.md §7.9, §7.15, §7.16), as a matrix of data folders: fresh, an- * install from before accounts with and without a password and API tokens, FUOBE_PASSWORD, a second start, a- * changed secret key and FUOBE_MODE. Each case boots fresh modules on its own folder, as a server start would.- */-import crypto from "node:crypto";-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import Database from "better-sqlite3";-import { NextRequest } from "next/server";-import { afterAll, afterEach, describe, expect, it, vi } from "vitest";--// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.-vi.setConfig({ testTimeout: 60_000 });--const ENV = ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET", "FUOBE_ACCEPT_NEW_SECRET", "FUOBE_DEV_PLATFORM", "FUOBE_SITE_URL", "FUOBE_TRUST_PROXY", "FUOBE_TRUSTED_PROXIES"];-for (const k of ENV) delete process.env[k];-const dirs: string[] = [];-afterAll(() => {- closeDbs();- for (const d of dirs) fs.rmSync(d, { recursive: true, force: true });-});-afterEach(() => {- for (const k of ENV) delete process.env[k];-});--function closeDbs() {- globalThis.__fuobeDb?.close();- globalThis.__fuobeDb = undefined;- globalThis.__fuobeAuthDb?.db.close();- globalThis.__fuobeAuthDb = undefined;-}--const newDir = () => {- const d = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-boot-"));- dirs.push(d);- return d;-};--/** Fresh modules on `dir`, as a new server process would load them. */-async function load(dir: string) {- closeDbs();- vi.resetModules();- process.env.FUOBE_DATA_DIR = dir;- return {- bootstrap: await import("@/server/identity/bootstrap"),- mode: await import("@/server/mode"),- dbm: await import("@/server/db"),- owner: await import("@/server/identity/owner"),- ops: await import("@/server/identity/admin-ops"),- tokens: await import("@/server/identity/tokens"),- principal: await import("@/server/identity/principal"),- proxy: (await import("@/proxy")).proxy,- login: await import("@/app/api/auth/login/route"),- password: await import("@/app/api/auth/password/route"),- };-}--async function boot(dir: string) {- const m = await load(dir);- const report = await m.bootstrap.bootstrapIdentity();- return { ...m, report };-}--/** A database as a build from before accounts left it: every migration but the identity one. */-async function preAccountsDb(dir: string) {- const { dbm } = await load(dir);- const d = dbm.db();- for (const t of ["users", "workspaces", "workspace_members", "invites", "grants", "item_marks", "api_tokens", "audit_log", "user_settings", "workspace_settings", "session_step_up", "auth_user", "auth_session", "auth_account", "auth_verification", "auth_rate_limit"]) d.exec(`DROP TABLE IF EXISTS "${t}"`);- d.prepare("DELETE FROM _migrations WHERE id = ?").run(dbm.IDENTITY_MIGRATION);- d.prepare("INSERT INTO settings (key, value) VALUES ('engine.mode', 'open')").run();- closeDbs();-}--const legacyHash = (password: string) => {- const salt = crypto.randomBytes(16);- return `${salt.toString("hex")}:${crypto.scryptSync(password, salt, 32).toString("hex")}`;-};-const sha = (t: string) => crypto.createHash("sha256").update(t).digest("hex");-const TOKEN_A = `fuobe_${"a".repeat(32)}`;-const TOKEN_B = `fuobe_${"b".repeat(32)}`;--function writeAuthJson(dir: string, opts: { password?: string; tokens?: boolean }) {- const data = {- ...(opts.password && { password: legacyHash(opts.password) }),- secret: crypto.randomBytes(32).toString("hex"),- tokens: opts.tokens- ? [- { id: "aaaaaaaaaaaa", name: "CLI", hash: sha(TOKEN_A), prefix: TOKEN_A.slice(0, 12), createdAt: 1_700_000_000_000, lastUsedAt: 1_700_000_100_000 },- { id: "bbbbbbbbbbbb", name: "MCP", hash: sha(TOKEN_B), prefix: TOKEN_B.slice(0, 12), createdAt: 1_700_000_200_000 },- ]- : [],- };- fs.writeFileSync(path.join(dir, "auth.json"), JSON.stringify(data), { mode: 0o600 });- return data;-}--const BY = { actorId: "u_owner", via: "local" };-/** A password of exactly `n` characters. */-const longPassword = (n: number) => "correct horse battery staple ".repeat(Math.ceil(n / 29)).slice(0, n);-/** Set-Cookie lines → the Cookie header a browser would send next. */-const cookieOf = (setCookies: string[]) =>- setCookies- .filter((c) => !/max-age=0/i.test(c))- .map((c) => c.split(";")[0])- .join("; ");--const req = (url: string, headers: Record<string, string> = {}) => new NextRequest(url, { headers: { host: new URL(url).host, ...headers } });-const loginPost = (password: string) =>- new Request("http://localhost:3000/api/auth/login", { method: "POST", headers: { "content-type": "application/json", host: "localhost:3000", origin: "http://localhost:3000" }, body: JSON.stringify({ password }) });--describe("a fresh data folder", () => {- it("boots as Personal, sign-in off, setup done: Just me on this computer, as before accounts", async () => {- const dir = newDir();- const m = await boot(dir);- expect(m.report).toMatchObject({ snapshot: null, importedPassword: false, importedTokens: 0, signin: "off" });- expect(m.mode.installMode()).toBe("personal");- expect(m.mode.setupState()).toBe("done");- expect(m.mode.signInRequired()).toBe(false);- expect(m.principal.justMe(req("http://localhost:3000/"))).toBe(true);- expect((await m.principal.resolvePrincipal(req("http://localhost:3000/library"))).actor).toMatchObject({ userId: "u_owner", via: "local", role: "owner" });- // The owner exists, unclaimed, with a personal workspace; the install catalog too.- const d = m.dbm.db();- expect(d.prepare("SELECT id, role, status, auth_user_id, personal_workspace_id FROM users").all()).toEqual([- { id: "u_owner", role: "owner", status: "active", auth_user_id: null, personal_workspace_id: "w_owner" },- ]);- expect(d.prepare("SELECT id, kind FROM workspaces ORDER BY id").all()).toEqual([- { id: "w_install", kind: "install" },- { id: "w_owner", kind: "personal" },- ]);- // The root secret, private, and its fingerprint (never the secret) in the database.- const key = path.join(dir, "secret.key");- expect(fs.statSync(key).size).toBe(32);- expect(fs.statSync(key).mode & 0o777).toBe(0o600);- expect(m.mode.installValue("identity.secret_check")).toMatch(/^[0-9a-f]{32}$/);- expect(fs.existsSync(path.join(dir, "backups"))).toBe(false);- });-});--describe("an install from before accounts", () => {- it("is copied first, then its password and tokens move to accounts; old cookies stop, tokens keep working", async () => {- const dir = newDir();- await preAccountsDb(dir);- const before = writeAuthJson(dir, { password: "the old password", tokens: true });- const m = await boot(dir);-- // 1. The pre-accounts snapshot: the database as it was, beside a manifest, private.- const snap = m.report.snapshot!;- expect(path.basename(snap.db)).toMatch(/^fuobe-\d{8}T\d{6}Z-pre-accounts\.db$/);- expect(fs.statSync(snap.db).mode & 0o777).toBe(0o600);- const copy = new Database(snap.db, { readonly: true });- const tables = (copy.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as { name: string }[]).map((r) => r.name);- expect(tables).not.toContain("users");- expect(copy.prepare("SELECT value FROM settings WHERE key = 'engine.mode'").get()).toEqual({ value: "open" });- copy.close();- expect(JSON.parse(fs.readFileSync(snap.manifest, "utf8"))).toMatchObject({ kind: "pre-accounts", stripped: [] });-- // 2. Personal with sign-in; the password and both tokens imported once.- expect(m.report).toMatchObject({ importedPassword: true, importedTokens: 2, signin: "on" });- expect(m.mode.signInRequired()).toBe(true);- expect(m.mode.installValue("engine.mode")).toBe("open");- expect(m.dbm.db().prepare("SELECT source FROM users WHERE id = 'u_owner'").get()).toEqual({ source: "legacy" });- const id = m.owner.ownerAuthUserId()!;- expect(await m.ops.passwordNeedsRehash(id)).toBe(true);-- // 3. The old password signs in (one password field), and is rewritten as scrypt v2.- expect((await m.login.POST(loginPost("not it at all"))).status).toBe(401);- const ok = await m.login.POST(loginPost("the old password"));- expect(ok.status).toBe(200);- expect(ok.headers.getSetCookie().some((c) => c.startsWith("fuobe.session_token="))).toBe(true);- expect(await m.ops.passwordNeedsRehash(id)).toBe(false);-- // 4. The tokens are legacy Full tokens with the same hashes: the CLI and MCP keep working.- expect(m.tokens.listTokens("u_owner")).toEqual([- { id: "aaaaaaaaaaaa", name: "CLI", prefix: TOKEN_A.slice(0, 12), createdAt: 1_700_000_000_000, lastUsedAt: 1_700_000_100_000, legacy: true },- { id: "bbbbbbbbbbbb", name: "MCP", prefix: TOKEN_B.slice(0, 12), createdAt: 1_700_000_200_000, legacy: true },- ]);- const api = await m.proxy(req("http://localhost:3000/api/generations", { authorization: `Bearer ${TOKEN_B}` }));- expect(api.headers.get("x-middleware-next")).toBe("1");- // A pre-accounts session cookie is no longer accepted.- const old = await m.proxy(req("http://localhost:3000/library", { cookie: `fuobe_session=${Date.now() + 1e9}.abc` }));- expect(old.status).toBe(307);-- // 5. auth.json stays, untouched, for one release.- expect(JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8"))).toEqual(before);-- // A second start changes nothing and imports nothing again.- const again = await boot(dir);- expect(again.report).toMatchObject({ snapshot: null, importedPassword: false, importedTokens: 0, signin: "on" });- expect(again.tokens.listTokens("u_owner")).toHaveLength(2);- });-- it("without a password stays Just me, and its tokens still move", async () => {- const dir = newDir();- await preAccountsDb(dir);- writeAuthJson(dir, { tokens: true });- const m = await boot(dir);- expect(m.report).toMatchObject({ importedPassword: false, importedTokens: 2, signin: "off" });- expect(m.report.snapshot).not.toBeNull();- expect(m.mode.signInRequired()).toBe(false);- expect(m.owner.ownerAuthUserId()).toBeNull();- expect(m.tokens.tokenFromHeader(`Bearer ${TOKEN_A}`)).toMatchObject({ userId: "u_owner" });- });-});--describe("FUOBE_PASSWORD", () => {- it("turns sign-in on, is the owner's password, and is synced at every start", async () => {- const dir = newDir();- process.env.FUOBE_PASSWORD = "break glass one";- const m = await boot(dir);- expect(m.report).toMatchObject({ syncedEnvPassword: true, signin: "on" });- expect(m.dbm.db().prepare("SELECT source FROM users WHERE id = 'u_owner'").get()).toEqual({ source: "env" });- expect(await m.owner.checkOwnerPassword("break glass one")).toBe(true);- const cookie = (await m.login.POST(loginPost("break glass one"))).headers.getSetCookie()[0].split(";")[0];- expect((await m.proxy(req("http://localhost:3000/library", { cookie }))).headers.get("x-middleware-next")).toBe("1");-- // Same value: nothing rewritten, sessions kept.- const same = await boot(dir);- expect(same.report.syncedEnvPassword).toBe(false);- expect((await same.proxy(req("http://localhost:3000/library", { cookie }))).headers.get("x-middleware-next")).toBe("1");-- // A new value replaces the old one and signs every browser out.- process.env.FUOBE_PASSWORD = "break glass two";- const changed = await boot(dir);- expect(changed.report.syncedEnvPassword).toBe(true);- expect(await changed.owner.checkOwnerPassword("break glass two")).toBe(true);- expect(await changed.owner.checkOwnerPassword("break glass one")).toBe(false);- expect((await changed.proxy(req("http://localhost:3000/library", { cookie }))).status).toBe(307);- });-- it("also works as FUOBE_OWNER_PASSWORD", async () => {- process.env.FUOBE_OWNER_PASSWORD = "owner from env";- const m = await boot(newDir());- expect(m.report.signin).toBe("on");- expect(await m.owner.checkOwnerPassword("owner from env")).toBe(true);- });-});--describe("the secret key's fingerprint (§7.15)", () => {- it("refuses to start with another key, unless FUOBE_ACCEPT_NEW_SECRET=1 (which signs everyone out)", async () => {- const dir = newDir();- process.env.FUOBE_PASSWORD = "a password here";- const m = await boot(dir);- const cookie = (await m.login.POST(loginPost("a password here"))).headers.getSetCookie()[0].split(";")[0];- const sessions = () => (m.dbm.db().prepare("SELECT COUNT(*) AS n FROM auth_session").get() as { n: number }).n;- expect(sessions()).toBe(1);-- process.env.FUOBE_SECRET = "f".repeat(64);- const refused = await load(dir);- await expect(refused.bootstrap.bootstrapIdentity()).rejects.toThrow(/secret key doesn't match/);- await expect(refused.bootstrap.bootstrapIdentity()).rejects.toBeInstanceOf(refused.bootstrap.StartupError);-- process.env.FUOBE_ACCEPT_NEW_SECRET = "1";- const accepted = await boot(dir);- expect((accepted.dbm.db().prepare("SELECT COUNT(*) AS n FROM auth_session").get() as { n: number }).n).toBe(0);- expect((await accepted.proxy(req("http://localhost:3000/library", { cookie }))).status).toBe(307);- // From now on the new key is the expected one.- delete process.env.FUOBE_ACCEPT_NEW_SECRET;- expect((await boot(dir)).report.signin).toBe("on");- });-- it("refuses a FUOBE_SECRET that is too short, as a start-up error", async () => {- process.env.FUOBE_SECRET = "short";- const m = await load(newDir());- await expect(m.bootstrap.bootstrapIdentity()).rejects.toThrow(/FUOBE_SECRET is too short/);- await expect(m.bootstrap.bootstrapIdentity()).rejects.toBeInstanceOf(m.bootstrap.StartupError);- });-});--describe("FUOBE_MODE", () => {- it("personal boots (Just me unless a password says otherwise); studio and platform aren't ready yet", async () => {- process.env.FUOBE_MODE = "personal";- expect((await boot(newDir())).report.signin).toBe("off");- process.env.FUOBE_MODE = "studio";- await expect((await load(newDir())).bootstrap.bootstrapIdentity()).rejects.toThrow(/FUOBE_MODE=studio needs the first-run setup/);- process.env.FUOBE_MODE = "platform";- await expect((await load(newDir())).bootstrap.bootstrapIdentity()).rejects.toThrow(/FUOBE_DEV_PLATFORM=1/);- process.env.FUOBE_MODE = "public";- await expect((await load(newDir())).bootstrap.bootstrapIdentity()).rejects.toThrow(/isn't a mode/);- });-});--describe("long passwords (they signed in before accounts, so they still do)", () => {- it("an auth.json password over 128 characters signs in, and is rewritten", async () => {- const dir = newDir();- await preAccountsDb(dir);- const pw = longPassword(150);- writeAuthJson(dir, { password: pw });- const m = await boot(dir);- expect(m.report).toMatchObject({ importedPassword: true, signin: "on" });- expect((await m.login.POST(loginPost(pw))).status).toBe(200);- const id = m.owner.ownerAuthUserId()!;- expect(await m.ops.passwordNeedsRehash(id)).toBe(false);- expect((await m.owner.signInOwner(pw, new Headers())).ok).toBe(true);- });-- it("FUOBE_PASSWORD up to 500 characters signs in; a longer one stops the start with one line", async () => {- process.env.FUOBE_PASSWORD = longPassword(129);- const m = await boot(newDir());- expect(m.report).toMatchObject({ syncedEnvPassword: true, signin: "on" });- expect((await m.login.POST(loginPost(longPassword(129)))).status).toBe(200);-- process.env.FUOBE_PASSWORD = longPassword(500);- expect((await (await boot(newDir())).owner.signInOwner(longPassword(500), new Headers())).ok).toBe(true);-- // Nor was there a shortest one: a short FUOBE_PASSWORD still signs in (Better Auth checks no minimum at sign-in).- process.env.FUOBE_PASSWORD = "pw1";- expect((await (await boot(newDir())).login.POST(loginPost("pw1"))).status).toBe(200);-- process.env.FUOBE_PASSWORD = longPassword(501);- const tooLong = await load(newDir());- await expect(tooLong.bootstrap.bootstrapIdentity()).rejects.toThrow(/^FUOBE_PASSWORD is longer than 500 characters/);- await expect(tooLong.bootstrap.bootstrapIdentity()).rejects.toBeInstanceOf(tooLong.bootstrap.StartupError);- delete process.env.FUOBE_PASSWORD;- process.env.FUOBE_OWNER_PASSWORD = longPassword(501);- await expect((await load(newDir())).bootstrap.bootstrapIdentity()).rejects.toThrow(/^FUOBE_OWNER_PASSWORD is longer/);- });-- it("a new password still stops at 128 characters", async () => {- const m = await boot(newDir());- await expect(m.owner.changeOwnerPassword(longPassword(129), BY)).rejects.toThrow(/at most 128/);- await m.owner.changeOwnerPassword(longPassword(128), BY);- expect(await m.owner.checkOwnerPassword(longPassword(128))).toBe(true);- });-});--describe("FUOBE_SIGNIN locks the switch (§7.9)", () => {- it("on, with no password to sign in with, stops the start with one line", async () => {- process.env.FUOBE_SIGNIN = "on";- const m = await load(newDir());- await expect(m.bootstrap.bootstrapIdentity()).rejects.toThrow(/^FUOBE_SIGNIN=on needs the owner's password/);- await expect(m.bootstrap.bootstrapIdentity()).rejects.toBeInstanceOf(m.bootstrap.StartupError);- // With FUOBE_PASSWORD (or an auth.json password) it starts.- process.env.FUOBE_PASSWORD = "break glass pw";- expect((await boot(newDir())).report.signin).toBe("on");- delete process.env.FUOBE_PASSWORD;- const dir = newDir();- await preAccountsDb(dir);- writeAuthJson(dir, { password: "the old password" });- expect((await boot(dir)).report.signin).toBe("on");- });-- it("on: the Settings password can be changed but not removed (no install nobody can sign in to)", async () => {- const dir = newDir();- await (await boot(dir)).owner.changeOwnerPassword("settings password", BY);- process.env.FUOBE_SIGNIN = "on";- const m = await boot(dir);- expect(m.owner.ownerPasswordStatus()).toEqual({ fromEnv: false, signinFromEnv: true });- await expect(m.owner.changeOwnerPassword(null, BY)).rejects.toThrow(/FUOBE_SIGNIN/);- expect(m.mode.signInRequired()).toBe(true);- expect(await m.owner.checkOwnerPassword("settings password")).toBe(true);-- // As Settings → Security sends it, from the signed-in browser: refused, and the password still works.- const signedIn = await m.owner.signInOwner("settings password", new Headers());- expect(signedIn.ok).toBe(true);- const cookie = cookieOf(signedIn.ok ? signedIn.setCookies : []);- const remove = await m.password.POST(- new Request("http://localhost:3000/api/auth/password", {- method: "POST",- headers: { "content-type": "application/json", host: "localhost:3000", origin: "http://localhost:3000", cookie },- body: JSON.stringify({ current: "settings password", password: null }),- }),- );- expect(remove.status).toBe(400);- expect(((await remove.json()) as { error: string }).error).toMatch(/FUOBE_SIGNIN/);- expect((await m.login.POST(loginPost("settings password"))).status).toBe(200);-- // Changing it still works.- await m.owner.changeOwnerPassword("another settings pw", BY);- expect(await m.owner.checkOwnerPassword("another settings pw")).toBe(true);- });-- it("off: the install stays open, and Settings can't claim to require a password", async () => {- process.env.FUOBE_SIGNIN = "off";- const m = await boot(newDir());- expect(m.mode.signInRequired()).toBe(false);- expect(m.owner.ownerPasswordStatus()).toEqual({ fromEnv: false, signinFromEnv: false });- await expect(m.owner.changeOwnerPassword("a new password", BY)).rejects.toThrow(/FUOBE_SIGNIN/);- expect(m.owner.ownerAuthUserId()).toBeNull();- expect(m.mode.signInRequired()).toBe(false);- });-});--describe("FUOBE_PASSWORD after it is unset", () => {- it("stays the owner's password with sign-in on, and Settings can then change or remove it", async () => {- const dir = newDir();- process.env.FUOBE_PASSWORD = "temporary env pw";- await boot(dir);- delete process.env.FUOBE_PASSWORD;- const m = await boot(dir);- expect(m.report).toMatchObject({ syncedEnvPassword: false, signin: "on" });- expect(await m.owner.checkOwnerPassword("temporary env pw")).toBe(true);- expect(m.owner.ownerPasswordStatus().fromEnv).toBe(false);- await m.owner.changeOwnerPassword(null, BY);- expect(m.mode.signInRequired()).toBe(false);- });-});--describe("start-up errors", () => {- it("are one line naming the problem, never a stack trace", async () => {- const exit = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never);- const err = vi.spyOn(console, "error").mockImplementation(() => {});- try {- process.env.FUOBE_SECRET = "short";- await (await load(newDir())).bootstrap.startIdentity();- delete process.env.FUOBE_SECRET;- const damaged = newDir();- fs.writeFileSync(path.join(damaged, "secret.key"), Buffer.alloc(10), { mode: 0o600 });- await (await load(damaged)).bootstrap.startIdentity();- process.env.FUOBE_SIGNIN = "on";- await (await load(newDir())).bootstrap.startIdentity();-- expect(exit.mock.calls).toEqual([[1], [1], [1]]);- expect(err.mock.calls.map((c) => c.length)).toEqual([1, 1, 1]);- const lines = err.mock.calls.map((c) => c[0] as unknown);- for (const line of lines) {- expect(typeof line).toBe("string");- expect(line as string).toMatch(/^Fuobe can't start: /);- // No stack trace: a single line.- expect(line as string).not.toMatch(/\n/);- }- expect(lines[0]).toMatch(/FUOBE_SECRET is too short/);- expect(lines[1]).toMatch(/secret\.key is damaged/);- expect(lines[2]).toMatch(/FUOBE_SIGNIN=on needs/);- } finally {- exit.mockRestore();- err.mockRestore();- }- });-});diff --git a/tests/identity-load.test.ts b/tests/identity-load.test.tsdeleted file mode 100644index 6265d0d2..00000000--- a/tests/identity-load.test.ts+++ /dev/null@@ -1,72 +0,0 @@-/**- * Better Auth's connection and Fuobe's share one SQLite file (docs/research/accounts-8.md §7.1). Busy waits- * block the event loop, so a lock held across an await would stall everything: 50 sign-ins while a runner keeps- * writing must never wait anywhere near the 5 s busy timeout (each wait stays under 1 s), and nothing fails.- */-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { monitorEventLoopDelay } from "node:perf_hooks";-import { afterAll, describe, expect, it, vi } from "vitest";--// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.-vi.setConfig({ testTimeout: 60_000 });--const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-load-"));-process.env.FUOBE_DATA_DIR = dir;-for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET"]) delete process.env[k];--const { db } = await import("@/server/db");-const { bootstrapIdentity } = await import("@/server/identity/bootstrap");-const { signInOwner } = await import("@/server/identity/owner");-const { setOwnerPassword } = await import("./helpers/identity");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));--await bootstrapIdentity();-const PASSWORD = "correct horse battery";-await setOwnerPassword(PASSWORD);--describe("sign-ins while the runner writes", () => {- it("50 sign-ins succeed, the runner's writes all land, and no busy wait reaches 1 s", { timeout: 60_000 }, async () => {- // A runner: a write transaction every couple of milliseconds, like the generation runner's ticks.- let writes = 0;- const failures: string[] = [];- const upsert = db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");- const tick = db().transaction((n: number) => {- for (let i = 0; i < 20; i++) upsert.run(`load.${n % 50}.${i}`, String(n));- });- const runner = setInterval(() => {- try {- tick(writes++);- } catch (e) {- failures.push((e as Error).message);- }- }, 2);-- const delay = monitorEventLoopDelay({ resolution: 10 });- delay.enable();- const durations: number[] = [];- try {- for (let batch = 0; batch < 10; batch++) {- await Promise.all(- Array.from({ length: 5 }, async () => {- const t = performance.now();- const r = await signInOwner(PASSWORD, new Headers({ "user-agent": `load test ${batch}` }));- durations.push(performance.now() - t);- if (!r.ok) failures.push(`sign-in: ${r.code ?? "refused"}`);- }),- );- }- } finally {- clearInterval(runner);- delay.disable();- }-- expect(failures).toEqual([]);- expect(durations).toHaveLength(50);- expect(writes).toBeGreaterThan(50);- expect((db().prepare("SELECT COUNT(*) AS n FROM auth_session").get() as { n: number }).n).toBe(50);- // A busy wait blocks the event loop: the longest block is the longest wait.- expect(delay.max / 1e6).toBeLessThan(1000);- });-});diff --git a/tests/identity-proxy.test.ts b/tests/identity-proxy.test.tsdeleted file mode 100644index bf517069..00000000--- a/tests/identity-proxy.test.ts+++ /dev/null@@ -1,177 +0,0 @@-/**- * The proxy after accounts (docs/research/accounts-8.md §7.1, §8): Just me on this computer, a password install,- * API tokens (valid, wrong, revoked), Better Auth's session cookie, refusal codes, share links, the client-IP- * header only a trusted proxy may set, session refresh on POST, and no-store on sign-in paths.- */-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { NextRequest } from "next/server";-import { afterAll, describe, expect, it, vi } from "vitest";--// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.-vi.setConfig({ testTimeout: 60_000 });--const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-proxy-"));-process.env.FUOBE_DATA_DIR = dir;-for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET", "FUOBE_TRUST_PROXY", "FUOBE_TRUSTED_PROXIES", "FUOBE_SITE_URL"]) delete process.env[k];--const { proxy } = await import("@/proxy");-const { db } = await import("@/server/db");-const { bootstrapIdentity } = await import("@/server/identity/bootstrap");-const tokens = await import("@/server/identity/tokens");-const shares = await import("@/server/shares");-const gens = await import("@/server/generations");-const { saveFile } = await import("@/server/storage");-const { setOwnerPassword, ownerCookie } = await import("./helpers/identity");-const { SHARE_VIEW_HEADER } = await import("@/lib/share");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));--await bootstrapIdentity();-const PASSWORD = "correct horse battery";--const req = (url: string, init: { method?: string; headers?: Record<string, string> } = {}) =>- new NextRequest(url, {- method: init.method ?? "GET",- headers: { host: new URL(url).host, ...(init.method && init.method !== "GET" && { origin: new URL(url).origin }), ...init.headers },- ...(init.method && init.method !== "GET" && init.method !== "HEAD" && { body: "{}" }),- });-const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";-const forwarded = (r: Response, name: string) => r.headers.get(`x-middleware-request-${name}`);--describe("Just me on this computer", () => {- it("lets every page and API through as the owner, with no sign-in", async () => {- expect(passed(await proxy(req("http://localhost:3000/library")))).toBe(true);- expect(passed(await proxy(req("http://localhost:3000/api/generations", { method: "POST" })))).toBe(true);- });-- it("ignores a wrong bearer token and accepts a right one", async () => {- expect(passed(await proxy(req("http://localhost:3000/api/generations", { headers: { authorization: "Bearer fuobe_wrong" } })))).toBe(true);- const { token } = tokens.createToken("u_owner", "CLI");- expect(passed(await proxy(req("http://localhost:3000/api/generations", { headers: { authorization: `Bearer ${token}` } })))).toBe(true);- });-- it("sends /login home: there is nothing to sign in to", async () => {- const r = await proxy(req("http://localhost:3000/login"));- expect(r.status).toBe(307);- expect(new URL(r.headers.get("location")!).pathname).toBe("/");- });-- it("keeps the DNS-rebinding and cross-site checks", async () => {- expect((await proxy(req("http://rebind.attacker.example/library"))).status).toBe(403);- expect((await proxy(req("http://localhost:3000/api/generations", { method: "POST", headers: { origin: "http://evil.example" } }))).status).toBe(403);- });-- it("answers 404 at /api/identity: Better Auth isn't mounted", async () => {- const route = await import("@/app/api/identity/[...all]/route");- expect((await route.GET(new Request("http://localhost:3000/api/identity/get-session", { headers: { host: "localhost:3000" } }))).status).toBe(404);- });-});--describe("the client address Better Auth sees", () => {- it("is never what the client wrote", async () => {- const r = await proxy(req("http://localhost:3000/api/generations", { headers: { "x-fuobe-client-ip": "6.6.6.6", "x-forwarded-for": "6.6.6.6" } }));- expect(passed(r)).toBe(true);- expect(forwarded(r, "x-fuobe-client-ip")).toBeNull();- expect(r.headers.get("x-middleware-override-headers") ?? "").not.toContain("x-fuobe-client-ip");- });-- it("comes from X-Forwarded-For only behind a trusted proxy (hops or ranges)", async () => {- vi.stubEnv("FUOBE_TRUST_PROXY", "1");- try {- const r = await proxy(req("http://localhost:3000/api/generations", { headers: { "x-fuobe-client-ip": "6.6.6.6", "x-forwarded-for": "6.6.6.6, 203.0.113.5" } }));- expect(forwarded(r, "x-fuobe-client-ip")).toBe("203.0.113.5");- } finally {- vi.unstubAllEnvs();- }- vi.stubEnv("FUOBE_TRUSTED_PROXIES", "10.0.0.0/8, 192.0.2.1");- try {- const r = await proxy(req("http://localhost:3000/api/generations", { headers: { "x-forwarded-for": "6.6.6.6, 198.51.100.7, 10.1.2.3, 192.0.2.1" } }));- expect(forwarded(r, "x-fuobe-client-ip")).toBe("198.51.100.7");- } finally {- vi.unstubAllEnvs();- }- });-});--describe("a password install", () => {- it("needs a session or a token for everything but sign-in", async () => {- await setOwnerPassword(PASSWORD);- const api = await proxy(req("http://localhost:3000/api/generations"));- expect(api.status).toBe(401);- expect(api.headers.get("www-authenticate")).toMatch(/Bearer/);- const page = await proxy(req("http://localhost:3000/cinema?tab=new"));- expect(page.status).toBe(307);- const to = new URL(page.headers.get("location")!);- expect(to.pathname).toBe("/login");- expect(to.searchParams.get("next")).toBe("/cinema?tab=new");- for (const open of ["/login", "/api/auth/login", "/api/identity/get-session"]) {- const r = await proxy(req(`http://localhost:3000${open}`, open === "/api/auth/login" ? { method: "POST" } : {}));- expect(passed(r), open).toBe(true);- expect(r.headers.get("cache-control"), open).toBe("no-store");- }- expect((await proxy(req("http://localhost:3000/library"))).headers.get("cache-control")).toBeNull();- });-- it("takes API tokens: a right one passes, a wrong or revoked one is 401 with a way forward", async () => {- const { token, info } = tokens.createToken("u_owner", "MCP");- expect(passed(await proxy(req("http://localhost:3000/api/mcp", { method: "POST", headers: { authorization: `Bearer ${token}` } })))).toBe(true);- const wrong = await proxy(req("http://localhost:3000/api/generations", { headers: { authorization: "Bearer fuobe_wrong" } }));- expect(wrong.status).toBe(401);- expect(((await wrong.json()) as { error: string }).error).toMatch(/isn't valid/);- tokens.revokeToken("u_owner", info.id);- expect((await proxy(req("http://localhost:3000/api/generations", { headers: { authorization: `Bearer ${token}` } }))).status).toBe(401);- });-- it("takes Better Auth's session cookie, until the session ends", async () => {- const cookie = await ownerCookie(PASSWORD);- expect(cookie).toMatch(/^fuobe\.session_token=/);- expect(passed(await proxy(req("http://localhost:3000/library", { headers: { cookie } })))).toBe(true);- const logout = await import("@/app/api/auth/logout/route");- const out = await logout.POST(new Request("http://localhost:3000/api/auth/logout", { method: "POST", headers: { cookie, host: "localhost:3000" } }));- expect(out.headers.getSetCookie().some((c) => /fuobe\.session_token=;/.test(c) && /Max-Age=0/i.test(c))).toBe(true);- expect((await proxy(req("http://localhost:3000/library", { headers: { cookie } }))).status).toBe(307);- });-- it("refuses a person who may not act with their code (API) or on the sign-in card (pages)", async () => {- const cookie = await ownerCookie(PASSWORD);- db().prepare("UPDATE users SET status = 'disabled' WHERE id = 'u_owner'").run();- try {- const api = await proxy(req("http://localhost:3000/api/generations", { headers: { cookie } }));- expect(api.status).toBe(403);- expect(await api.json()).toMatchObject({ code: "ACCOUNT_DISABLED", error: expect.stringMatching(/turned off/) });- const page = await proxy(req("http://localhost:3000/library", { headers: { cookie } }));- expect(new URL(page.headers.get("location")!).searchParams.get("code")).toBe("ACCOUNT_DISABLED");- } finally {- db().prepare("UPDATE users SET status = 'active' WHERE id = 'u_owner'").run();- }- });-- it("refreshes a session that is due, on a POST only", async () => {- const cookie = await ownerCookie(PASSWORD);- // Two days into a 30-day session: due for its daily refresh.- const token = decodeURIComponent(cookie.split("=")[1]).split(".")[0];- const due = new Date(Date.now() + 28 * 86_400_000);- db().prepare('UPDATE auth_session SET "expiresAt" = ? WHERE token = ?').run(due.toISOString(), token);- const get = await proxy(req("http://localhost:3000/library", { headers: { cookie } }));- expect(passed(get)).toBe(true);- expect(get.headers.getSetCookie()).toEqual([]);- const post = await proxy(req("http://localhost:3000/api/generations", { method: "POST", headers: { cookie } }));- expect(passed(post)).toBe(true);- expect(post.headers.getSetCookie().some((c) => c.startsWith("fuobe.session_token="))).toBe(true);- const after = db().prepare('SELECT "expiresAt" AS e FROM auth_session WHERE token = ?').get(token) as { e: string };- expect(new Date(after.e).getTime()).toBeGreaterThan(due.getTime() + 86_400_000);- });-- it("opens a live share link without a session, and the signed-in owner's own visit isn't a view", async () => {- const asset = saveFile({ data: Buffer.from("not really a png"), contentType: "image/png", source: "generation" });- const g = gens.recordLocalGeneration({ feature: "grade", modelId: "local-color-grade", op: "grade", prompt: "proxy pier", inputs: {}, output: { url: asset.url, kind: "image", contentType: "image/png" } });- const S = shares.createShare({ kind: "result", targetId: g.id });- const visitor = await proxy(req(`http://localhost:3000/s/${S.token}`, { headers: { "user-agent": "Mozilla/5.0 Chrome/141.0" } }));- expect(passed(visitor)).toBe(true);- expect(forwarded(visitor, SHARE_VIEW_HEADER)).toBe("1");- const cookie = await ownerCookie(PASSWORD);- const own = await proxy(req(`http://localhost:3000/s/${S.token}`, { headers: { "user-agent": "Mozilla/5.0 Chrome/141.0", cookie } }));- expect(forwarded(own, SHARE_VIEW_HEADER)).toBeNull();- });-});diff --git a/tests/identity-snapshot.test.ts b/tests/identity-snapshot.test.tsdeleted file mode 100644index c04ad877..00000000--- a/tests/identity-snapshot.test.ts+++ /dev/null@@ -1,86 +0,0 @@-/**- * Snapshots never carry live credentials (docs/research/accounts-8.md §7.16), and the security headers (§7.1).- */-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import Database from "better-sqlite3";-import { afterAll, describe, expect, it, vi } from "vitest";--// Real scrypt hashes (N=2^15) and fresh module loads per case: slow under a parallel run.-vi.setConfig({ testTimeout: 60_000 });--const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-snap-"));-process.env.FUOBE_DATA_DIR = dir;-for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET"]) delete process.env[k];--const { db } = await import("@/server/db");-const { bootstrapIdentity } = await import("@/server/identity/bootstrap");-const { snapshotDatabase, STRIPPED_TABLES } = await import("@/server/backup/snapshot");-const { setOwnerPassword, ownerCookie } = await import("./helpers/identity");-const nextConfig = (await import("../next.config")).default;-const { getPathMatch } = await import("next/dist/shared/lib/router/utils/path-match");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));--await bootstrapIdentity();--describe("database snapshots", () => {- it("strip sessions, verifications and step-up marks, even from free pages, and keep everything else", async () => {- await setOwnerPassword("correct horse battery");- const cookie = await ownerCookie("correct horse battery");- const token = decodeURIComponent(cookie.split("=")[1]).split(".")[0];- const now = new Date().toISOString();- db().prepare(`INSERT INTO auth_verification (id, identifier, value, "expiresAt", "createdAt", "updatedAt") VALUES ('v1', 'reset:owner', 'secret-reset-value', ?, ?, ?)`).run(now, now, now);- db().prepare("INSERT INTO session_step_up (session_id, user_id, confirmed_at, expires_at) VALUES ('s1', 'u_owner', 1, 2)").run();- expect((db().prepare("SELECT COUNT(*) AS n FROM auth_session").get() as { n: number }).n).toBe(1);-- const snap = snapshotDatabase({ kind: "manual" });- expect(path.dirname(snap.db)).toBe(path.join(dir, "backups"));- expect(fs.statSync(path.join(dir, "backups")).mode & 0o777).toBe(0o700);- for (const f of [snap.db, snap.secret!, snap.manifest]) expect(fs.statSync(f).mode & 0o777, f).toBe(0o600);- expect(fs.readFileSync(snap.secret!)).toEqual(fs.readFileSync(path.join(dir, "secret.key")));-- const copy = new Database(snap.db, { readonly: true });- for (const t of ["auth_session", "auth_verification", "session_step_up"]) expect((copy.prepare(`SELECT COUNT(*) AS n FROM "${t}"`).get() as { n: number }).n, t).toBe(0);- expect(copy.prepare("SELECT id FROM users").all()).toEqual([{ id: "u_owner" }]);- expect((copy.prepare("SELECT COUNT(*) AS n FROM auth_account").get() as { n: number }).n).toBe(1);- copy.close();- // Not even the bytes of a deleted row survive.- const bytes = fs.readFileSync(snap.db).toString("latin1");- expect(bytes).not.toContain(token);- expect(bytes).not.toContain("secret-reset-value");-- const manifest = JSON.parse(fs.readFileSync(snap.manifest, "utf8"));- expect(manifest).toMatchObject({ kind: "manual", database: path.basename(snap.db), stripped: ["auth_session", "auth_verification", "session_step_up"] });- expect(STRIPPED_TABLES).toEqual(expect.arrayContaining(["auth_session", "auth_verification", "session_step_up", "cli_connect_requests", "request_keys"]));- // The live database still has its session.- expect((db().prepare("SELECT COUNT(*) AS n FROM auth_session").get() as { n: number }).n).toBe(1);- });-- it("refuse an odd kind name", () => {- expect(() => snapshotDatabase({ kind: "../escape" })).toThrow(/kind/);- });-});--describe("security headers", () => {- const rules = async () => (await nextConfig.headers!()) as { source: string; headers: { key: string; value: string }[] }[];- const headersFor = async (pathname: string) => {- const out: Record<string, string> = {};- for (const r of await rules()) if (getPathMatch(r.source, { removeUnnamedParams: true, strict: true })(pathname)) for (const h of r.headers) out[h.key] = h.value;- return out;- };-- it("forbid framing everywhere but share pages", async () => {- for (const p of ["/", "/library", "/settings", "/login", "/api/files/outputs/a.png", "/s"]) {- expect(await headersFor(p), p).toMatchObject({ "X-Frame-Options": "DENY", "Content-Security-Policy": "frame-ancestors 'none'" });- }- for (const p of ["/s/abcdefabcdefabcdefabcdefabcdefabcdefabcdefab", "/s/abc/f/outputs/a.png"]) {- expect(await headersFor(p), p).not.toHaveProperty("X-Frame-Options");- }- });-- it("keep sign-in pages and their APIs out of every cache", async () => {- for (const p of ["/login", "/api/auth/login", "/api/auth/tokens", "/api/identity/get-session"]) expect((await headersFor(p))["Cache-Control"], p).toBe("no-store");- expect(await headersFor("/library")).not.toHaveProperty("Cache-Control");- });-});diff --git a/tests/licences.test.ts b/tests/licences.test.tsindex 94ab586c..374772cb 100644--- a/tests/licences.test.ts+++ b/tests/licences.test.ts@@ -84,16 +84,3 @@ describe("licences", () => {expect(without.notices.some((n) => n.text === "Built with DINOv3")).toBe(false);});});--describe("pinned libraries (accounts plan §5.2)", () => {- it("record a licence for each, at the exact version package.json pins", async () => {- const { PINNED_LIBRARIES } = await import("@/lib/licences");- const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8")) as { dependencies: Record<string, string> };- expect(PINNED_LIBRARIES.map((l) => l.name)).toEqual(expect.arrayContaining(["better-auth", "kysely"]));- for (const l of PINNED_LIBRARIES) {- expect(pkg.dependencies[l.name], l.name).toBe(l.version);- expect(l.licence.name, l.name).toBeTruthy();- expect(l.licence.note, l.name).toBeTruthy();- }- });-});diff --git a/tests/no-higgsfield.test.ts b/tests/no-higgsfield.test.tsindex f2a11282..05b94d49 100644--- a/tests/no-higgsfield.test.ts+++ b/tests/no-higgsfield.test.ts@@ -26,7 +26,7 @@ const { SOUL_LEGACY_IDS } = await import("@/lib/catalog/soul-looks.generated");const { PROVIDER_SETTINGS } = await import("@/lib/connections");const { PROVIDERS, provider, RETIRED_PROVIDER_ERROR } = await import("@/server/providers");const { SETTINGS, getSetting, setSetting } = await import("@/server/settings");-const { db, migrationIndexOf } = await import("@/server/db");+const { db } = await import("@/server/db");const { withCurrentModels } = await import("@/lib/catalog/canvas");const generationsRoute = await import("@/app/api/generations/route");const { currentRequest, ensureRunner, getGeneration, listGenerations, previewGeneration } = await import("@/server/generations");@@ -538,9 +538,7 @@ describe("stored ids resolve where they are read", () => {describe("the O7 migration", () => {it("deletes the retired key, resets the provider choice and marks the ads drawn whole as baked", () => {const d = db();- // The O7 migration by what it does (later packages append theirs after it).- const last = migrationIndexOf("DELETE FROM settings WHERE key = 'higgsfield.key'");- expect(last).toBeGreaterThan(0);+ const last = (d.prepare("SELECT MAX(id) AS id FROM _migrations").get() as { id: number }).id;// An install from before: rows the migration rewrites, then the migration runs again on the next open.d.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('higgsfield.key', 'id:secret'), ('cloud.provider', 'higgsfield')").run();d.prepare("INSERT INTO ad_batches (id, brand_id, engine, route, model_id, created_at) VALUES ('b1', 'br', 'cloud', 'higgsfield', 'ads-studio', 1), ('b2', 'br', 'cloud', 'fuobe', 'nano-banana-pro', 2)").run();diff --git a/tests/record-pages.test.ts b/tests/record-pages.test.tsindex 16deded0..73c2a184 100644--- a/tests/record-pages.test.ts+++ b/tests/record-pages.test.ts@@ -14,8 +14,8 @@ const { proxy } = await import("@/proxy");afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));/** Where the proxy sent a page request: its own path, or the not-found page (with the status). */-async function routed(pathname: string): Promise<{ status: number; to: string | null }> {- const res = await proxy(new NextRequest(`http://localhost:3000${pathname}`, { headers: { host: "localhost:3000" } }));+function routed(pathname: string): { status: number; to: string | null } {+ const res = proxy(new NextRequest(`http://localhost:3000${pathname}`, { headers: { host: "localhost:3000" } }));return { status: res.status, to: res.headers.get("x-middleware-rewrite") };}@@ -94,14 +94,14 @@ describe("record pages (real 404s)", () => {expect(recordExists({ kind: "explainer", ids: ["ep1"] })).toBe(true);});- it("answers unknown ids with a 404 before the page streams", async () => {- expect(await routed("/canvas/nope")).toEqual({ status: 404, to: "http://localhost:3000/_fuobe-not-found" });- expect((await routed("/faceless/ch1/nope")).status).toBe(404);- expect((await routed("/audio/nope")).status).toBe(404);- expect((await routed("/apps/nope")).status).toBe(404);+ it("answers unknown ids with a 404 before the page streams", () => {+ expect(routed("/canvas/nope")).toEqual({ status: 404, to: "http://localhost:3000/_fuobe-not-found" });+ expect(routed("/faceless/ch1/nope").status).toBe(404);+ expect(routed("/audio/nope").status).toBe(404);+ expect(routed("/apps/nope").status).toBe(404);// Stored records, real modes and other pages go through.for (const p of ["/canvas/cv1", "/faceless/ch1", "/faceless/ch1/new", "/faceless/ch1/ep1", "/audio/music", "/ads/multiplier", "/library"]) {- expect(await routed(p), p).toEqual({ status: 200, to: null });+ expect(routed(p), p).toEqual({ status: 200, to: null });}});});diff --git a/tests/runtime-auth.test.ts b/tests/runtime-auth.test.tsindex 2f27051b..6455d5cc 100644--- a/tests/runtime-auth.test.ts+++ b/tests/runtime-auth.test.ts@@ -9,7 +9,6 @@ process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;const auth = await import("@/server/auth");const { proxy, config } = await import("@/proxy");-const { setOwnerPassword } = await import("./helpers/identity");const { safeNext } = await import("@/lib/safe-redirect");afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));@@ -18,25 +17,25 @@ const post = (url: string, headers: Record<string, string> = {}) => new NextRequdescribe("cross-site requests (S8)", () => {it("blocks state changes from other websites, password or not", async () => {expect(auth.authEnabled()).toBe(false);- const evil = await proxy(post("http://localhost:3000/api/auth/password", { origin: "http://evil.example", "content-type": "text/plain" }));+ const evil = proxy(post("http://localhost:3000/api/auth/password", { origin: "http://evil.example", "content-type": "text/plain" }));expect(evil.status).toBe(403);expect((await evil.json()).error).toMatch(/another website/);- expect((await proxy(post("http://localhost:3000/api/generations", { origin: "null" }))).status).toBe(403);- expect((await proxy(post("http://localhost:3000/api/generations", { "sec-fetch-site": "cross-site" }))).status).toBe(403);+ expect(proxy(post("http://localhost:3000/api/generations", { origin: "null" })).status).toBe(403);+ expect(proxy(post("http://localhost:3000/api/generations", { "sec-fetch-site": "cross-site" })).status).toBe(403);// Another port on localhost is another origin.- expect((await proxy(post("http://localhost:3000/api/generations", { origin: "http://localhost:5173" }))).status).toBe(403);+ expect(proxy(post("http://localhost:3000/api/generations", { origin: "http://localhost:5173" })).status).toBe(403);});- it("lets the studio's own pages, non-browser clients and reads through", async () => {- const ok = async (r: Promise<Response>) => (await r).headers.get("x-middleware-next") === "1";- expect(await ok(proxy(post("http://localhost:3000/api/generations", { origin: "http://localhost:3000" })))).toBe(true);- expect(await ok(proxy(post("http://localhost:3000/api/mcp")))).toBe(true);- expect(await ok(proxy(new NextRequest("http://localhost:3000/api/generations", { headers: { origin: "http://evil.example" } })))).toBe(true);+ it("lets the studio's own pages, non-browser clients and reads through", () => {+ const ok = (r: Response) => r.headers.get("x-middleware-next") === "1";+ expect(ok(proxy(post("http://localhost:3000/api/generations", { origin: "http://localhost:3000" })))).toBe(true);+ expect(ok(proxy(post("http://localhost:3000/api/mcp")))).toBe(true);+ expect(ok(proxy(new NextRequest("http://localhost:3000/api/generations", { headers: { origin: "http://evil.example" } })))).toBe(true);// Behind a reverse proxy that forwards the public host.- expect(await ok(proxy(post("http://127.0.0.1:3000/api/generations", { origin: "https://fuobe.example.com", "x-forwarded-host": "fuobe.example.com" })))).toBe(true);+ expect(ok(proxy(post("http://127.0.0.1:3000/api/generations", { origin: "https://fuobe.example.com", "x-forwarded-host": "fuobe.example.com" })))).toBe(true);process.env.FUOBE_ALLOWED_ORIGINS = "https://studio.example.org";try {- expect(await ok(proxy(post("http://127.0.0.1:3000/api/generations", { origin: "https://studio.example.org" })))).toBe(true);+ expect(ok(proxy(post("http://127.0.0.1:3000/api/generations", { origin: "https://studio.example.org" })))).toBe(true);} finally {delete process.env.FUOBE_ALLOWED_ORIGINS;}@@ -44,44 +43,44 @@ describe("cross-site requests (S8)", () => {});describe("DNS rebinding", () => {- const ok = async (r: Promise<Response>) => (await r).headers.get("x-middleware-next") === "1";+ const ok = (r: Response) => r.headers.get("x-middleware-next") === "1";const at = (host: string, init: { method?: string; headers?: Record<string, string> } = {}) =>proxy(new NextRequest(`http://${host}/api/generations`, { method: init.method ?? "GET", headers: { host, ...init.headers }, ...(init.method === "POST" && { body: "{}" }) }));it("refuses a name that was re-pointed at this machine, reads included, while no password is set", async () => {expect(auth.authEnabled()).toBe(false);// The attacker's page and its requests share one origin, so the Origin check alone lets them through.- const read = await at("rebind.attacker.example:3000");+ const read = at("rebind.attacker.example:3000");expect(read.status).toBe(403);expect((await read.json()).error).toMatch(/FUOBE_ALLOWED_ORIGINS/);- expect((await at("rebind.attacker.example:3000", { method: "POST", headers: { origin: "http://rebind.attacker.example:3000" } })).status).toBe(403);+ expect(at("rebind.attacker.example:3000", { method: "POST", headers: { origin: "http://rebind.attacker.example:3000" } }).status).toBe(403);// A forwarded host is no way around it (the page can set that header itself).- expect((await at("rebind.attacker.example", { headers: { "x-forwarded-host": "localhost:3000" } })).status).toBe(403);+ expect(at("rebind.attacker.example", { headers: { "x-forwarded-host": "localhost:3000" } }).status).toBe(403);});- it("lets local addresses, LAN names, this machine and allow-listed names through", async () => {+ it("lets local addresses, LAN names, this machine and allow-listed names through", () => {for (const host of ["localhost:3000", "127.0.0.1:3000", "[::1]:3000", "192.168.1.5:3000", "studio.localhost", "nas:3000", "studio.local", "box.lan:3000", "fuobe.home.arpa", `${os.hostname()}:3000`]) {- expect(await ok(at(host)), host).toBe(true);+ expect(ok(at(host)), host).toBe(true);}process.env.FUOBE_ALLOWED_ORIGINS = "https://fuobe.example.com,studio.example.org:8443";try {- expect(await ok(at("fuobe.example.com"))).toBe(true);- expect(await ok(at("studio.example.org:8443"))).toBe(true);- expect((await at("studio.example.org:9999")).status).toBe(403);- expect((await at("rebind.attacker.example")).status).toBe(403);+ expect(ok(at("fuobe.example.com"))).toBe(true);+ expect(ok(at("studio.example.org:8443"))).toBe(true);+ expect(at("studio.example.org:9999").status).toBe(403);+ expect(at("rebind.attacker.example").status).toBe(403);} finally {delete process.env.FUOBE_ALLOWED_ORIGINS;}expect(auth.hostAllowed(null)).toBe(true);});- it("leaves it to the sign-in check once a password is set", async () => {- await setOwnerPassword("correct horse battery");+ it("leaves it to the sign-in check once a password is set", () => {+ auth.setPassword("correct horse battery");try {// Signed out: sent to sign in (the rebound page has no session cookie for its name).- expect((await at("fuobe.example.com")).status).toBe(401);+ expect(at("fuobe.example.com").status).toBe(401);} finally {- await setOwnerPassword(null);+ auth.setPassword(null);}});});diff --git a/tests/share-links.test.ts b/tests/share-links.test.tsindex 9510c3ce..99743a55 100644--- a/tests/share-links.test.ts+++ b/tests/share-links.test.ts@@ -34,7 +34,6 @@ const auth = await import("@/server/auth");const { saveFile } = await import("@/server/storage");const { db } = await import("@/server/db");const { proxy } = await import("@/proxy");-const { setOwnerPassword, ownerCookie } = await import("./helpers/identity");const fileRoute = await import("@/app/s/[token]/f/[...path]/route");const listRoute = await import("@/app/api/shares/route");const idRoute = await import("@/app/api/shares/[id]/route");@@ -485,108 +484,108 @@ describe("renewing", () => {});});-describe("the sign-in proxy", async () => {- it("lets exactly a live share's page and files through without a session, and nothing else", async () => {+describe("the sign-in proxy", () => {+ it("lets exactly a live share's page and files through without a session, and nothing else", () => {const { g, rel, input } = made("proxy pier");const S = shares.createShare({ kind: "result", targetId: g.id });- await setOwnerPassword("correct horse battery");+ auth.setPassword("correct horse battery");try {- const page = (await proxy(req(`http://localhost:3000/s/${S.token}`)));+ const page = proxy(req(`http://localhost:3000/s/${S.token}`));expect(passed(page)).toBe(true);expect(page.headers.get("x-robots-tag")).toMatch(/noindex/);expect(page.headers.get("referrer-policy")).toBe("no-referrer");- expect(passed((await proxy(req(`http://localhost:3000/s/${S.token}/f/${rel}`))))).toBe(true);- expect(passed((await proxy(req(`http://localhost:3000/s/${S.token}`, { method: "HEAD" }))))).toBe(true);+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}/f/${rel}`)))).toBe(true);+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`, { method: "HEAD" })))).toBe(true);// The files route itself decides which files (the proxy passes the shape; see "what a token serves").- expect(passed((await proxy(req(`http://localhost:3000/s/${S.token}/f/${input}`))))).toBe(true);+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}/f/${input}`)))).toBe(true);// Everything else still needs a session.- expect((await proxy(req(`http://localhost:3000/api/files/${rel}`))).status).toBe(401);- expect((await proxy(req("http://localhost:3000/api/shares"))).status).toBe(401);- expect((await proxy(req(`http://localhost:3000/api/shares/${S.share.id}`, { method: "POST", headers: { origin: "http://localhost:3000" } }))).status).toBe(401);+ expect(proxy(req(`http://localhost:3000/api/files/${rel}`)).status).toBe(401);+ expect(proxy(req("http://localhost:3000/api/shares")).status).toBe(401);+ expect(proxy(req(`http://localhost:3000/api/shares/${S.share.id}`, { method: "POST", headers: { origin: "http://localhost:3000" } })).status).toBe(401);for (const p of [`/s/${S.token}/other`, `/s/${S.token}/f/../../library`, "/s/gone", "/library", `/s/${S.token}x`]) {- const r = (await proxy(req(`http://localhost:3000${p}`)));+ const r = proxy(req(`http://localhost:3000${p}`));expect(r.status, p).toBe(307);expect(r.headers.get("location"), p).toMatch(/\/login/);}// A share path written to (a server action, a form post) is not opened.- expect(passed((await proxy(req(`http://localhost:3000/s/${S.token}`, { method: "POST", headers: { origin: "http://localhost:3000" } }))))).toBe(false);+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`, { method: "POST", headers: { origin: "http://localhost:3000" } })))).toBe(false);// Revoked or unknown: a real 404 (the "link unavailable" page), not a sign-in redirect.- expect(gone((await proxy(req(`http://localhost:3000/s/${"Q".repeat(44)}`))))).toBe(true);+ expect(gone(proxy(req(`http://localhost:3000/s/${"Q".repeat(44)}`)))).toBe(true);shares.revokeShare(S.share.id);- expect(gone((await proxy(req(`http://localhost:3000/s/${S.token}`))))).toBe(true);- expect(gone((await proxy(req(`http://localhost:3000/s/${S.token}/f/${rel}`))))).toBe(true);+ expect(gone(proxy(req(`http://localhost:3000/s/${S.token}`)))).toBe(true);+ expect(gone(proxy(req(`http://localhost:3000/s/${S.token}/f/${rel}`)))).toBe(true);} finally {- await setOwnerPassword(null);+ auth.setPassword(null);}});- it("keeps the host allowlist and the cross-site check when no password is set", async () => {+ it("keeps the host allowlist and the cross-site check when no password is set", () => {const { g } = made("rebound pier");const S = shares.createShare({ kind: "result", targetId: g.id });expect(auth.authEnabled()).toBe(false);- const rebound = (await proxy(new NextRequest(`http://rebind.attacker.example/s/${S.token}`, { headers: { host: "rebind.attacker.example" } })));+ const rebound = proxy(new NextRequest(`http://rebind.attacker.example/s/${S.token}`, { headers: { host: "rebind.attacker.example" } }));expect(rebound.status).toBe(403);- expect(passed((await proxy(req(`http://localhost:3000/s/${S.token}`))))).toBe(true);- expect((await proxy(req(`http://localhost:3000/s/${S.token}`, { method: "POST", headers: { origin: "http://evil.example" } }))).status).toBe(403);+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`)))).toBe(true);+ expect(proxy(req(`http://localhost:3000/s/${S.token}`, { method: "POST", headers: { origin: "http://evil.example" } })).status).toBe(403);});- it("rate-limits wrong tokens without ever blocking a live link, and never the signed-in owner", async () => {+ it("rate-limits wrong tokens without ever blocking a live link, and never the signed-in owner", () => {const { g } = made("guessed pier");const S = shares.createShare({ kind: "result", targetId: g.id });globalThis.__fuobeShareGuard = new access.ShareGuard({ perClient: 3, global: 5, windowMs: 60_000, lockMs: 60_000, maxClients: 100 });- await setOwnerPassword("correct horse battery");+ auth.setPassword("correct horse battery");try {- for (let i = 0; i < 5; i++) expect(gone((await proxy(req(`http://localhost:3000/s/${String(i).repeat(44)}`))))).toBe(true);+ for (let i = 0; i < 5; i++) expect(gone(proxy(req(`http://localhost:3000/s/${String(i).repeat(44)}`)))).toBe(true);// Past the global budget a wrong token answers 429…- const blocked = (await proxy(req(`http://localhost:3000/s/${"7".repeat(44)}`)));+ const blocked = proxy(req(`http://localhost:3000/s/${"7".repeat(44)}`));expect(blocked.status).toBe(429);expect(Number(blocked.headers.get("retry-after"))).toBeGreaterThan(0);// …but anyone else's misses never take a working link down.- expect(passed((await proxy(req(`http://localhost:3000/s/${S.token}`))))).toBe(true);- const cookie = await ownerCookie("correct horse battery");- expect(passed((await proxy(req(`http://localhost:3000/s/${S.token}`, { headers: { cookie } }))))).toBe(true);+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`)))).toBe(true);+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`, { headers: { cookie } })))).toBe(true);} finally {- await setOwnerPassword(null);+ auth.setPassword(null);}});- it("counts one miss per dead token, so a revoked page full of files doesn't trip the limit", async () => {+ it("counts one miss per dead token, so a revoked page full of files doesn't trip the limit", () => {const { g, rel } = made("revoked gallery pier");const S = shares.createShare({ kind: "result", targetId: g.id });const other = shares.createShare({ kind: "result", targetId: made("other live pier").g.id });globalThis.__fuobeShareGuard = new access.ShareGuard({ perClient: 3, global: 5, windowMs: 60_000, lockMs: 60_000, maxClients: 100 });shares.revokeShare(S.share.id);// A page left open after its link was revoked: the page and 120 lazy-loaded files.- for (let i = 0; i < 120; i++) expect(gone((await proxy(req(`http://localhost:3000/s/${S.token}${i ? `/f/${rel}` : ""}`))))).toBe(true);+ for (let i = 0; i < 120; i++) expect(gone(proxy(req(`http://localhost:3000/s/${S.token}${i ? `/f/${rel}` : ""}`)))).toBe(true);expect(globalThis.__fuobeShareGuard.saturated()).toBe(false);- expect(passed((await proxy(req(`http://localhost:3000/s/${other.token}`))))).toBe(true);+ expect(passed(proxy(req(`http://localhost:3000/s/${other.token}`)))).toBe(true);});- it("locks out a client it can tell apart (behind a trusted proxy), working links included, and nobody else", async () => {+ it("locks out a client it can tell apart (behind a trusted proxy), working links included, and nobody else", () => {const { g } = made("trusted proxy pier");const S = shares.createShare({ kind: "result", targetId: g.id });globalThis.__fuobeShareGuard = new access.ShareGuard({ perClient: 3, global: 50, windowMs: 60_000, lockMs: 60_000, maxClients: 100 });vi.stubEnv("FUOBE_TRUST_PROXY", "1");try {const from = (ip: string) => ({ headers: { "x-forwarded-for": ip } });- for (let i = 0; i < 3; i++) expect(gone((await proxy(req(`http://localhost:3000/s/${String(i).repeat(44)}`, from("203.0.113.9")))))).toBe(true);+ for (let i = 0; i < 3; i++) expect(gone(proxy(req(`http://localhost:3000/s/${String(i).repeat(44)}`, from("203.0.113.9"))))).toBe(true);// That client can't tell a hit from a miss for a minute…- expect((await proxy(req(`http://localhost:3000/s/${S.token}`, from("203.0.113.9")))).status).toBe(429);+ expect(proxy(req(`http://localhost:3000/s/${S.token}`, from("203.0.113.9"))).status).toBe(429);// …while everyone else opens the link.- expect(passed((await proxy(req(`http://localhost:3000/s/${S.token}`, from("198.51.100.4")))))).toBe(true);+ expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`, from("198.51.100.4"))))).toBe(true);} finally {vi.unstubAllEnvs();}});});-describe("views", async () => {+describe("views", () => {const CHROME = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";const viewHeader = (r: Response) => r.headers.get(`x-middleware-request-${share.SHARE_VIEW_HEADER}`);- it("counts a browser opening the page, not a HEAD, a prefetch, a script or a link-preview bot", async () => {+ it("counts a browser opening the page, not a HEAD, a prefetch, a script or a link-preview bot", () => {const h = (o: Record<string, string>) => new Headers(o);expect(share.countsAsView("GET", h({ "user-agent": CHROME, "sec-fetch-dest": "document" }))).toBe(true);expect(share.countsAsView("GET", h({ "user-agent": CHROME }))).toBe(true); // older browsers send no Sec-Fetch-*@@ -609,25 +608,25 @@ describe("views", async () => {}});- it("is told to the page by the proxy only, for a visitor's page request", async () => {+ it("is told to the page by the proxy only, for a visitor's page request", () => {const { g, rel } = made("viewed pier");const S = shares.createShare({ kind: "result", targetId: g.id });const page = `http://localhost:3000/s/${S.token}`;- expect(viewHeader((await proxy(req(page, { headers: { "user-agent": CHROME } }))))).toBe("1");- expect(viewHeader((await proxy(req(page, { method: "HEAD", headers: { "user-agent": CHROME } }))))).toBeNull();- expect(viewHeader((await proxy(req(`${page}/f/${rel}`, { headers: { "user-agent": CHROME } }))))).toBeNull();+ expect(viewHeader(proxy(req(page, { headers: { "user-agent": CHROME } })))).toBe("1");+ expect(viewHeader(proxy(req(page, { method: "HEAD", headers: { "user-agent": CHROME } })))).toBeNull();+ expect(viewHeader(proxy(req(`${page}/f/${rel}`, { headers: { "user-agent": CHROME } })))).toBeNull();// A visitor can't count views by sending the header themselves.- const forged = (await proxy(req(page, { headers: { "user-agent": "Slackbot 1.0", [share.SHARE_VIEW_HEADER]: "1" } })));+ const forged = proxy(req(page, { headers: { "user-agent": "Slackbot 1.0", [share.SHARE_VIEW_HEADER]: "1" } }));expect(viewHeader(forged)).toBeNull();expect(forged.headers.get("x-middleware-override-headers") ?? "").not.toContain(share.SHARE_VIEW_HEADER);// The signed-in owner checking their own link isn't a view.- await setOwnerPassword("correct horse battery");+ auth.setPassword("correct horse battery");try {- const cookie = await ownerCookie("correct horse battery");- expect(viewHeader((await proxy(req(page, { headers: { "user-agent": CHROME, cookie } }))))).toBeNull();- expect(viewHeader((await proxy(req(page, { headers: { "user-agent": CHROME } }))))).toBe("1");+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ expect(viewHeader(proxy(req(page, { headers: { "user-agent": CHROME, cookie } })))).toBeNull();+ expect(viewHeader(proxy(req(page, { headers: { "user-agent": CHROME } })))).toBe("1");} finally {- await setOwnerPassword(null);+ auth.setPassword(null);}});});