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
Accounts 1: Better Auth behind Fuobe, identity tables, principal and proxy
Claude155ca7703fe7
diff --git a/next.config.ts b/next.config.tsindex 60b44f74..4f45b4a8 100644--- a/next.config.ts+++ b/next.config.ts@@ -1,5 +1,21 @@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,@@ -8,6 +24,9 @@ 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 fc09910c..4bcd19a9 100644--- a/package.json+++ b/package.json@@ -35,10 +35,12 @@"@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 0e422101..89403649 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -23,6 +23,9 @@ 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@@ -35,6 +38,9 @@ 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])@@ -266,6 +272,82 @@ 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==}@@ -418,89 +500,105 @@ 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==}@@ -600,24 +698,28 @@ 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==}@@ -631,6 +733,14 @@ 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'}@@ -651,6 +761,10 @@ 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==}@@ -1385,36 +1499,42 @@ 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==}@@ -1454,6 +1574,9 @@ 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==}@@ -1495,24 +1618,28 @@ 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==}@@ -1746,51 +1873,61 @@ 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==}@@ -1991,6 +2128,73 @@ 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'}@@ -2289,6 +2493,9 @@ 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'}@@ -3124,6 +3331,10 @@ 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==}@@ -3203,48 +3414,56 @@ 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==}@@ -3531,6 +3750,10 @@ 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}@@ -3925,6 +4148,9 @@ 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'}@@ -3974,6 +4200,9 @@ 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'}@@ -4759,6 +4988,59 @@ 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]':@@ -5104,6 +5386,10 @@ snapshots:'@next/[email protected]':optional: true+ '@noble/[email protected]': {}++ '@noble/[email protected]': {}+'@nodelib/[email protected]':dependencies:'@nodelib/fs.stat': 2.0.5@@ -5120,6 +5406,8 @@ snapshots:'@opentelemetry/[email protected]': {}+ '@opentelemetry/[email protected]': {}+'@oxc-project/[email protected]': {}'@radix-ui/[email protected]': {}@@ -5957,6 +6245,8 @@ snapshots:'@stablelib/[email protected]': {}+ '@standard-schema/[email protected]': {}+'@swc/[email protected]':dependencies:tslib: 2.8.1@@ -6486,6 +6776,42 @@ 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@@ -6760,6 +7086,8 @@ snapshots:has-property-descriptors: 1.0.2object-keys: 1.1.1+ [email protected]: {}+@@ -7741,6 +8069,8 @@ snapshots:+ [email protected]: {}+@@ -8309,6 +8639,8 @@ snapshots:+ [email protected]: {}+@@ -8827,6 +9159,8 @@ snapshots:'@rolldown/binding-win32-arm64-msvc': 1.2.14'@rolldown/binding-win32-x64-msvc': 1.2.14+ [email protected]: {}+dependencies:debug: 4.4.3@@ -8897,6 +9231,8 @@ snapshots:+ [email protected]: {}+dependencies:define-data-property: 1.1.4diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsindex 99c7da90..0015aa23 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -1,6 +1,15 @@-import { cookies } from "next/headers";import { z } from "zod";-import { authEnabled, checkPassword, createSession, LoginGuard, SESSION_COOKIE } from "@/server/auth";+import { LoginGuard } from "@/server/auth";+import { appendAudit } from "@/server/identity/audit-log";+import { signInOwner, type SignInResult } from "@/server/identity/owner";+import { refusal } from "@/server/identity/refusals";+import { signInRequired } from "@/server/mode";++/**+ * 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(500) });@@ -9,32 +18,36 @@ declare global {}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 (!authEnabled()) return Response.json({ ok: true });+ if (!signInRequired()) 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_TRUST_PROXY=1 so each visitor gets their own limit." : "";+ const hint = key === LoginGuard.DIRECT ? " Behind a reverse proxy? Set FUOBE_TRUSTED_PROXIES=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));- if (!parsed.success || !checkPassword(parsed.data.password)) {+ 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 });+ }guard.fail(key);- return Response.json({ error: "Wrong password" }, { status: 401 });+ 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 });}guard.succeed(key);- 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 });+ 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 });}diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.tsindex 240babb1..e1fda938 100644--- a/src/app/api/auth/logout/route.ts+++ b/src/app/api/auth/logout/route.ts@@ -1,7 +1,14 @@-import { cookies } from "next/headers";-import { SESSION_COOKIE } from "@/server/auth";+import { appendAudit } from "@/server/identity/audit-log";+import { signOut } from "@/server/identity/owner";+import { resolvePrincipal } from "@/server/identity/principal";-export async function POST() {- (await cookies()).delete(SESSION_COOKIE);- return Response.json({ ok: true });+/** 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 });}diff --git a/src/app/api/auth/password/route.ts b/src/app/api/auth/password/route.tsindex 98f33be8..ab6bbbb9 100644--- a/src/app/api/auth/password/route.ts+++ b/src/app/api/auth/password/route.ts@@ -1,33 +1,50 @@-import { cookies } from "next/headers";import { connection } from "next/server";import { z } from "zod";-import { authEnabled, authStatus, checkPassword, createSession, SESSION_COOKIE, setPassword, validSession } from "@/server/auth";+import { checkOwnerPassword, changeOwnerPassword, ownerPasswordStatus, signInOwner } from "@/server/identity/owner";+import { resolvePrincipal } from "@/server/identity/principal";+import { listTokens } from "@/server/identity/tokens";+import { signInRequired } from "@/server/mode";++/**+ * 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() });-export async function GET() {+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) {await connection();- return Response.json(authStatus());+ return Response.json(await status(request));}-/** 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 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 });+ 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 });+ }try {- setPassword(password);+ await changeOwnerPassword(password, { actorId: actor.userId, via: actor.via });} catch (e) {return Response.json({ error: (e as Error).message }, { status: 400 });}+ const headers = new Headers({ "Cache-Control": "no-store" });if (password) {- 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);+ // 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);}- return Response.json(authStatus());+ headers.append("set-cookie", "fuobe_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax");+ return Response.json(await status(request), { headers });}diff --git a/src/app/api/auth/tokens/route.ts b/src/app/api/auth/tokens/route.tsindex f7916d18..8c7e6591 100644--- a/src/app/api/auth/tokens/route.ts+++ b/src/app/api/auth/tokens/route.ts@@ -1,35 +1,39 @@-import { cookies } from "next/headers";import { connection } from "next/server";import { z } from "zod";-import { authEnabled, authStatus, createToken, revokeToken, SESSION_COOKIE, validSession } from "@/server/auth";+import { resolvePrincipal, type Actor } from "@/server/identity/principal";+import { createToken, listTokens, revokeToken } from "@/server/identity/tokens";-/** 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;+/**+ * 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;return Response.json({ error: "Manage API tokens from a signed-in browser" }, { status: 403 });}-export async function GET() {+export async function GET(request: Request) {await connection();- const denied = await browserOnly();- if (denied) return denied;- return Response.json({ tokens: authStatus().tokens });+ const actor = await browserActor(request);+ if (actor instanceof Response) return actor;+ return Response.json({ tokens: listTokens(actor.userId) });}/** Create a token; the full value is in this response only. */export async function POST(request: Request) {- const denied = await browserOnly();- if (denied) return denied;+ const actor = await browserActor(request);+ if (actor instanceof Response) return actor;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(parsed.data.name), { status: 201 });+ return Response.json(createToken(actor.userId, parsed.data.name), { status: 201 });}export async function DELETE(request: Request) {- const denied = await browserOnly();- if (denied) return denied;+ const actor = await browserActor(request);+ if (actor instanceof Response) return actor;const id = new URL(request.url).searchParams.get("id");if (!id) return Response.json({ error: "Which token?" }, { status: 400 });- revokeToken(id);+ if (!revokeToken(actor.userId, id)) return Response.json({ error: "No such token" }, { status: 404 });return new Response(null, { status: 204 });}diff --git a/src/app/api/identity/[...all]/route.ts b/src/app/api/identity/[...all]/route.tsnew file mode 100644index 00000000..b853e61f--- /dev/null+++ b/src/app/api/identity/[...all]/route.ts@@ -0,0 +1,16 @@+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/instrumentation.ts b/src/instrumentation.tsindex 1471ecf0..9b3a36de 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -1,11 +1,23 @@/**- * Runs once when the server starts: start the generation runner right away, so jobs that were in+ * 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* 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 { bootstrapIdentity, StartupError } = await import("./server/identity/bootstrap");+ 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.");+ } catch (e) {+ console.error(e instanceof StartupError ? `Fuobe can't start: ${e.message}` : e);+ process.exit(1);+ }const { ensureRunner } = await import("./server/generations");ensureRunner();const { ensureTrashPurge } = await import("./server/library");diff --git a/src/lib/sign-in-refusals.ts b/src/lib/sign-in-refusals.tsnew file mode 100644index 00000000..4f3f5f6c--- /dev/null+++ b/src/lib/sign-in-refusals.ts@@ -0,0 +1,27 @@+/**+ * 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 570a4570..dba67ef8 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -2,12 +2,57 @@ 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 { authEnabled, crossSite, hostAllowed, LoginGuard, SESSION_COOKIE, validSession, validToken } from "@/server/auth";+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 { recordExists } from "@/server/records";import { findShare, shareGuard, shareTargetExists } from "@/server/share-access";-/** Paths that work signed out: the login page and its API (and share links: openShare). */-const OPEN = new Set(["/login", "/api/auth/login"]);+/**+ * 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());const APP_IDS = new Set(APPS.map((a) => a.id));@@ -18,13 +63,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): NextResponse {+function pass(request: NextRequest, headers: Headers | null): 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 NextResponse.next();+ return next(headers);}const notFound = (request: NextRequest) => NextResponse.rewrite(new URL("/_fuobe-not-found", request.url), { status: 404 });@@ -32,8 +77,6 @@ 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) } });@@ -46,8 +89,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.*/-function openShare(request: NextRequest, token: string, file: boolean): NextResponse {- const owner = authEnabled() && signedIn(request);+async function openShare(request: NextRequest, token: string, file: boolean): Promise<NextResponse> {+ const owner = signInRequired() && !!(await resolvePrincipal(request)).actor;const guard = shareGuard();const key = LoginGuard.clientKey(request.headers);if (!owner) {@@ -65,7 +108,7 @@ function openShare(request: NextRequest, token: string, file: boolean): NextRespres = 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 = new Headers(request.headers);+ const headers = forwardHeaders(request) ?? 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 } });@@ -82,35 +125,61 @@ function safeDecode(s: string): string {}}-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;+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)) {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 (crossSite(request, request.nextUrl.host)) {+ if (!crossSiteExempt(pathname) && 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);- if (!authEnabled()) return pass(request);- if (OPEN.has(pathname)) return NextResponse.next();- if (signedIn(request)) return pass(request);+ 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 (pathname.startsWith("/api/")) {- return NextResponse.json({ error: "Sign in, or send an API token as Authorization: Bearer fuobe_…" }, { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="fuobe"' } });+ 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"' } });}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 7909fda6..6469ac98 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -1,128 +1,47 @@/**- * 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_…`).+ * 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.*- * 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.)+ * 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.*/-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");-export const SESSION_COOKIE = "fuobe_session";-const SESSION_DAYS = 30;--export interface ApiToken {+/** An API token as auth.json kept it. */+export interface LegacyToken {id: string;name: string;- /** sha256 of the token; the token itself is shown once. */+ /** sha256 of the token, hex. */hash: string;prefix: string;createdAt: number;lastUsedAt?: number;}-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 {+/** 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 {try {- 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;+ 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 };} catch {- 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);+ return null;}- const exp = Date.now() + SESSION_DAYS * 86_400_000;- return { value: `${exp}.${sign(d.secret, String(exp))}`, maxAge: SESSION_DAYS * 86_400 };}-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)));-}+/** Whether every page and API call needs a session or a token (Personal with sign-in, Studio, Platform). */+export const authEnabled = (): boolean => signInRequired();// ---------------------------------------------------------------------------// Cross-site requests@@ -205,7 +124,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_TRUST_PROXY=1; the proxy's own entry is the last one): such a client is locked+ * you trust (FUOBE_TRUSTED_PROXIES or FUOBE_TRUST_PROXY=1, see clientIp): 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@@ -220,11 +139,10 @@ 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 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;+ /** 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;}/** Milliseconds until this client may try again (0 = now). */@@ -265,36 +183,49 @@ export class LoginGuard {}// ----------------------------------------------------------------------------// API tokens+// The client's address behind a trusted reverse proxy-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) };-}--export function revokeToken(id: string): void {- const d = read();- write({ ...d, tokens: d.tokens.filter((t) => t.id !== id) });+/**+ * 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 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)) });+/** 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];}- return true;+ return null;}diff --git a/src/server/backup/snapshot.ts b/src/server/backup/snapshot.tsnew file mode 100644index 00000000..ff6b5ae8--- /dev/null+++ b/src/server/backup/snapshot.ts@@ -0,0 +1,95 @@+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 95c2a105..2b226203 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -564,8 +564,163 @@ 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 migration that creates the identity tables: the bootstrap snapshots an existing database before it runs (src/server/identity/bootstrap.ts). */+export const IDENTITY_MIGRATION = MIGRATIONS.findIndex((sql) => sql.includes("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 0f339ba1..c9786566 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -326,6 +326,8 @@ 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" },];/**@@ -356,6 +358,7 @@ 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.tsnew file mode 100644index 00000000..12998515--- /dev/null+++ b/src/server/identity/admin-ops.ts@@ -0,0 +1,119 @@+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.tsnew file mode 100644index 00000000..98622d9f--- /dev/null+++ b/src/server/identity/audit-log.ts@@ -0,0 +1,80 @@+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.tsnew file mode 100644index 00000000..8891a0f8--- /dev/null+++ b/src/server/identity/auth.ts@@ -0,0 +1,364 @@+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, verifyPassword } from "./password";+import { refusal } from "./refusals";+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.+ */++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. Packages add theirs (invite, sso, scim, admin). */+export const CREATE_INTENTS = new Set<string>(["claim-owner", "bootstrap-import"]);++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 }),+];++/** 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)!;+}++/** 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_user" },+ account: {+ modelName: "auth_account",+ accountLinking: { trustedProviders: [] as string[], allowDifferentEmails: false },+ },+ session: {+ modelName: "auth_session",+ expiresIn: 30 * 86_400,+ updateAge: 86_400,+ deferSessionRefresh: true,+ freshAge: 600,+ cookieCache: { enabled: false },+ },+ verification: { modelName: "auth_verification", storeIdentifier: "hashed" as const },+ rateLimit: { enabled: true, storage: "database" as const, modelName: "auth_rate_limit" },+ emailAndPassword: {+ enabled: true,+ minPasswordLength: PASSWORD_MIN,+ maxPasswordLength: PASSWORD_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();+ if (installValue(INSTALL.multiUser) === "1") return;+ if (!intent || !CREATE_INTENTS.has(intent)) {+ 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: {+ // The router allowlist: only browser traffic carries ctx.request; Fuobe's auth.api calls pass.+ before: createAuthMiddleware(async (ctx) => {+ 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.tsnew file mode 100644index 00000000..e09249e1--- /dev/null+++ b/src/server/identity/bootstrap.ts@@ -0,0 +1,135 @@+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, INSTALL, installValue, legacyPasswordSet, setInstallValue } from "../mode";+import * as ops from "./admin-ops";+import { appendAudit } from "./audit-log";+import { ensureOwnerAuthUser, ownerAuthUserId } from "./owner";+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.+ */++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.");+ }+}++function checkSecret(): void {+ resetSecretCache();+ const fingerprint = secretFingerprint();+ 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();+ 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");+ }++ report.signin = installValue(INSTALL.signin) === "on" ? "on" : "off";+ return report;+}diff --git a/src/server/identity/owner.ts b/src/server/identity/owner.tsnew file mode 100644index 00000000..6ad8ba48--- /dev/null+++ b/src/server/identity/owner.ts@@ -0,0 +1,104 @@+import "server-only";+import { isAPIError } from "better-auth/api";+import { db } from "../db";+import { bumpIdentityConfig, envOwnerPassword, 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)) {+ const code = (e.body as { code?: string } | undefined)?.code;+ if (code && code !== "INVALID_EMAIL_OR_PASSWORD") 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: whether a password is required, and whether the server sets it. */+export function ownerPasswordStatus(): { fromEnv: boolean } {+ return { fromEnv: !!envOwnerPassword() };+}++/**+ * 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 FUOBE_PASSWORD on the server");+ 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.tsnew file mode 100644index 00000000..1affb92e--- /dev/null+++ b/src/server/identity/password.ts@@ -0,0 +1,73 @@+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;+export const PASSWORD_MAX = 128;++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.tsnew file mode 100644index 00000000..2557a5ad--- /dev/null+++ b/src/server/identity/principal.ts@@ -0,0 +1,142 @@+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.tsnew file mode 100644index 00000000..d0366350--- /dev/null+++ b/src/server/identity/refusals.ts@@ -0,0 +1,33 @@+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/secret.ts b/src/server/identity/secret.tsnew file mode 100644index 00000000..073df16f--- /dev/null+++ b/src/server/identity/secret.ts@@ -0,0 +1,72 @@+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.tsnew file mode 100644index 00000000..9d532ae8--- /dev/null+++ b/src/server/identity/tokens.ts@@ -0,0 +1,129 @@+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.tsnew file mode 100644index 00000000..e3bf5f2c--- /dev/null+++ b/src/server/mode.ts@@ -0,0 +1,171 @@+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 || "";+}++/** 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 137d9557..687adcf2 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 = proxy(new NextRequest("http://localhost:3000/apps/does-not-exist"));+ const unknown = await 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 = proxy(new NextRequest("http://localhost:3000/apps/app-packshot"));+ const known = await proxy(new NextRequest("http://localhost:3000/apps/app-packshot"));expect(known.status).toBe(200);expect(known.headers.get("x-middleware-rewrite")).toBeNull();- expect(proxy(new NextRequest("http://localhost:3000/apps")).headers.get("x-middleware-rewrite")).toBeNull();+ expect((await proxy(new NextRequest("http://localhost:3000/apps"))).headers.get("x-middleware-rewrite")).toBeNull();// A malformed escape doesn't crash the proxy.- expect(proxy(new NextRequest("http://localhost:3000/apps/%E0%A4%A")).status).toBe(404);+ expect((await 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 13c39f13..65872c69 100644--- a/tests/auth.test.ts+++ b/tests/auth.test.ts@@ -1,3 +1,8 @@+/**+ * 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";@@ -5,55 +10,130 @@ import { afterAll, describe, expect, it } from "vitest";const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-auth-"));process.env.FUOBE_DATA_DIR = dir;-delete process.env.FUOBE_PASSWORD;+for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET"]) delete process.env[k];+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 }));-describe("auth", () => {- it("is off until a password is set", () => {+/** 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 () => {expect(auth.authEnabled()).toBe(false);- expect(auth.checkPassword("anything")).toBe(false);+ expect(await owner.checkOwnerPassword("anything")).toBe(false);});- it("hashes the password, checks it and rejects short ones", () => {- expect(() => auth.setPassword("short")).toThrow(/8 characters/);- auth.setPassword("correct horse");+ 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");expect(auth.authEnabled()).toBe(true);- 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", () => {+ 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 () => {process.env.FUOBE_PASSWORD = "from the env";- 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);+ 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.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/helpers/identity.ts b/tests/helpers/identity.tsnew file mode 100644index 00000000..edbb6686--- /dev/null+++ b/tests/helpers/identity.ts@@ -0,0 +1,27 @@+/**+ * 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.tsnew file mode 100644index 00000000..a1be4225--- /dev/null+++ b/tests/identity-better-auth.test.ts@@ -0,0 +1,171 @@+/**+ * 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 fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";++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();+ // The owner is already linked, so the new user 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.+ await expect(+ identity.withCreateIntent("claim-owner", () => identity.getAuth().api.signUpEmail({ body: { email: "[email protected]", password: "another long password", name: "Scope" } })),+ ).rejects.toMatchObject({ body: { code: "ACCOUNT_PENDING" } });+ 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 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");+ }+ });+});diff --git a/tests/record-pages.test.ts b/tests/record-pages.test.tsindex 73c2a184..16deded0 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). */-function routed(pathname: string): { status: number; to: string | null } {- const res = proxy(new NextRequest(`http://localhost:3000${pathname}`, { headers: { host: "localhost:3000" } }));+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" } }));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", () => {- 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);+ 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);// 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(routed(p), p).toEqual({ status: 200, to: null });+ expect(await routed(p), p).toEqual({ status: 200, to: null });}});});diff --git a/tests/runtime-auth.test.ts b/tests/runtime-auth.test.tsindex 6455d5cc..2f27051b 100644--- a/tests/runtime-auth.test.ts+++ b/tests/runtime-auth.test.ts@@ -9,6 +9,7 @@ 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 }));@@ -17,25 +18,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 = proxy(post("http://localhost:3000/api/auth/password", { origin: "http://evil.example", "content-type": "text/plain" }));+ const evil = await 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(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);+ 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);// Another port on localhost is another origin.- expect(proxy(post("http://localhost:3000/api/generations", { origin: "http://localhost:5173" })).status).toBe(403);+ expect((await 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", () => {- 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);+ 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);// Behind a reverse proxy that forwards the public host.- 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);+ 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);process.env.FUOBE_ALLOWED_ORIGINS = "https://studio.example.org";try {- expect(ok(proxy(post("http://127.0.0.1:3000/api/generations", { origin: "https://studio.example.org" })))).toBe(true);+ expect(await 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;}@@ -43,44 +44,44 @@ describe("cross-site requests (S8)", () => {});describe("DNS rebinding", () => {- const ok = (r: Response) => r.headers.get("x-middleware-next") === "1";+ const ok = async (r: Promise<Response>) => (await 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 = at("rebind.attacker.example:3000");+ const read = await at("rebind.attacker.example:3000");expect(read.status).toBe(403);expect((await read.json()).error).toMatch(/FUOBE_ALLOWED_ORIGINS/);- expect(at("rebind.attacker.example:3000", { method: "POST", headers: { origin: "http://rebind.attacker.example:3000" } }).status).toBe(403);+ expect((await 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(at("rebind.attacker.example", { headers: { "x-forwarded-host": "localhost:3000" } }).status).toBe(403);+ expect((await 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", () => {+ it("lets local addresses, LAN names, this machine and allow-listed names through", async () => {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(ok(at(host)), host).toBe(true);+ expect(await ok(at(host)), host).toBe(true);}process.env.FUOBE_ALLOWED_ORIGINS = "https://fuobe.example.com,studio.example.org:8443";try {- 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);+ 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);} 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", () => {- auth.setPassword("correct horse battery");+ it("leaves it to the sign-in check once a password is set", async () => {+ await setOwnerPassword("correct horse battery");try {// Signed out: sent to sign in (the rebound page has no session cookie for its name).- expect(at("fuobe.example.com").status).toBe(401);+ expect((await at("fuobe.example.com")).status).toBe(401);} finally {- auth.setPassword(null);+ await setOwnerPassword(null);}});});diff --git a/tests/share-links.test.ts b/tests/share-links.test.tsindex 99743a55..9510c3ce 100644--- a/tests/share-links.test.ts+++ b/tests/share-links.test.ts@@ -34,6 +34,7 @@ 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");@@ -484,108 +485,108 @@ describe("renewing", () => {});});-describe("the sign-in proxy", () => {- it("lets exactly a live share's page and files through without a session, and nothing else", () => {+describe("the sign-in proxy", async () => {+ it("lets exactly a live share's page and files through without a session, and nothing else", async () => {const { g, rel, input } = made("proxy pier");const S = shares.createShare({ kind: "result", targetId: g.id });- auth.setPassword("correct horse battery");+ await setOwnerPassword("correct horse battery");try {- const page = proxy(req(`http://localhost:3000/s/${S.token}`));+ const page = (await 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(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);+ 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);// The files route itself decides which files (the proxy passes the shape; see "what a token serves").- expect(passed(proxy(req(`http://localhost:3000/s/${S.token}/f/${input}`)))).toBe(true);+ expect(passed((await proxy(req(`http://localhost:3000/s/${S.token}/f/${input}`))))).toBe(true);// Everything else still needs a session.- 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);+ 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);for (const p of [`/s/${S.token}/other`, `/s/${S.token}/f/../../library`, "/s/gone", "/library", `/s/${S.token}x`]) {- const r = proxy(req(`http://localhost:3000${p}`));+ const r = (await 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(proxy(req(`http://localhost:3000/s/${S.token}`, { method: "POST", headers: { origin: "http://localhost:3000" } })))).toBe(false);+ expect(passed((await 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(proxy(req(`http://localhost:3000/s/${"Q".repeat(44)}`)))).toBe(true);+ expect(gone((await proxy(req(`http://localhost:3000/s/${"Q".repeat(44)}`))))).toBe(true);shares.revokeShare(S.share.id);- 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);+ 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);} finally {- auth.setPassword(null);+ await setOwnerPassword(null);}});- it("keeps the host allowlist and the cross-site check when no password is set", () => {+ it("keeps the host allowlist and the cross-site check when no password is set", async () => {const { g } = made("rebound pier");const S = shares.createShare({ kind: "result", targetId: g.id });expect(auth.authEnabled()).toBe(false);- const rebound = proxy(new NextRequest(`http://rebind.attacker.example/s/${S.token}`, { headers: { host: "rebind.attacker.example" } }));+ const rebound = (await proxy(new NextRequest(`http://rebind.attacker.example/s/${S.token}`, { headers: { host: "rebind.attacker.example" } })));expect(rebound.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);+ 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);});- it("rate-limits wrong tokens without ever blocking a live link, and never the signed-in owner", () => {+ it("rate-limits wrong tokens without ever blocking a live link, and never the signed-in owner", async () => {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 });- auth.setPassword("correct horse battery");+ await setOwnerPassword("correct horse battery");try {- for (let i = 0; i < 5; i++) expect(gone(proxy(req(`http://localhost:3000/s/${String(i).repeat(44)}`)))).toBe(true);+ for (let i = 0; i < 5; i++) expect(gone((await proxy(req(`http://localhost:3000/s/${String(i).repeat(44)}`))))).toBe(true);// Past the global budget a wrong token answers 429…- const blocked = proxy(req(`http://localhost:3000/s/${"7".repeat(44)}`));+ const blocked = (await 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(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);+ 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);} finally {- auth.setPassword(null);+ await setOwnerPassword(null);}});- it("counts one miss per dead token, so a revoked page full of files doesn't trip the limit", () => {+ it("counts one miss per dead token, so a revoked page full of files doesn't trip the limit", async () => {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(proxy(req(`http://localhost:3000/s/${S.token}${i ? `/f/${rel}` : ""}`)))).toBe(true);+ for (let i = 0; i < 120; i++) expect(gone((await proxy(req(`http://localhost:3000/s/${S.token}${i ? `/f/${rel}` : ""}`))))).toBe(true);expect(globalThis.__fuobeShareGuard.saturated()).toBe(false);- expect(passed(proxy(req(`http://localhost:3000/s/${other.token}`)))).toBe(true);+ expect(passed((await 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", () => {+ it("locks out a client it can tell apart (behind a trusted proxy), working links included, and nobody else", async () => {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(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((await 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(proxy(req(`http://localhost:3000/s/${S.token}`, from("203.0.113.9"))).status).toBe(429);+ expect((await proxy(req(`http://localhost:3000/s/${S.token}`, from("203.0.113.9")))).status).toBe(429);// …while everyone else opens the link.- expect(passed(proxy(req(`http://localhost:3000/s/${S.token}`, from("198.51.100.4"))))).toBe(true);+ expect(passed((await proxy(req(`http://localhost:3000/s/${S.token}`, from("198.51.100.4")))))).toBe(true);} finally {vi.unstubAllEnvs();}});});-describe("views", () => {+describe("views", async () => {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", () => {+ it("counts a browser opening the page, not a HEAD, a prefetch, a script or a link-preview bot", async () => {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-*@@ -608,25 +609,25 @@ describe("views", () => {}});- it("is told to the page by the proxy only, for a visitor's page request", () => {+ it("is told to the page by the proxy only, for a visitor's page request", async () => {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(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();+ 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();// A visitor can't count views by sending the header themselves.- const forged = proxy(req(page, { headers: { "user-agent": "Slackbot 1.0", [share.SHARE_VIEW_HEADER]: "1" } }));+ const forged = (await 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.- auth.setPassword("correct horse battery");+ await setOwnerPassword("correct horse battery");try {- 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");+ 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");} finally {- auth.setPassword(null);+ await setOwnerPassword(null);}});});