auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

commit e1cabeb4ba1fcdfdf94b5dad05ad8a06b00e2ea8
parent 7545111f059c60da1d602735468001ef1da7702e
Author: finwo <finwo@pm.me>
Date:   Wed, 21 Oct 2026 21:37:01 +0200

Split login, admin and account into standalone SPAs with built-in OIDC clients

Diffstat:
M.gitignore | 3++-
Aapp/account/config.example.json | 3+++
Aapp/account/esbuild.cjs | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/account/package-lock.json | 506+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/account/package.json | 14++++++++++++++
Aapp/account/src/assets/account.css | 255+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/account/src/main.ts | 17+++++++++++++++++
Aapp/account/src/screen/account.tsx | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/account/src/util/api.ts | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/account/src/util/auth.ts | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/config.example.json | 3+++
Aapp/admin/esbuild.cjs | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/package-lock.json | 506+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/package.json | 14++++++++++++++
Aapp/admin/src/assets/admin.css | 466+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/src/main.ts | 17+++++++++++++++++
Aapp/admin/src/screen/admin.tsx | 256+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/src/util/api.ts | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/src/util/auth.ts | 170+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/login/esbuild.cjs | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/login/package-lock.json | 506+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/login/package.json | 15+++++++++++++++
Aapp/login/scripts/generate-hex-grid.js | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Rserver/web/src/assets/hex-grid-dark.svg -> app/login/src/assets/hex-grid-dark.svg | 0
Rserver/web/src/assets/hex-grid-light.svg -> app/login/src/assets/hex-grid-light.svg | 0
Aapp/login/src/assets/login.css | 258+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/login/src/main.ts | 16++++++++++++++++
Aapp/login/src/screen/login.tsx | 381+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/login/src/util/api.ts | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/auth.example.yaml | 4++++
Aserver/migrations/sqlite/system/006_system_oidc.sql | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/package-lock.json | 1053-------------------------------------------------------------------------------
Mserver/package.json | 9---------
Dserver/scripts/generate-hex-grid.js | 89-------------------------------------------------------------------------------
Mserver/scripts/seed-demo.js | 2+-
Aserver/src/controller/app/account.js | 28++++++++++++++++++++++++++++
Aserver/src/controller/app/admin.js | 31+++++++++++++++++++++++++++++++
Mserver/src/controller/login/password.js | 60++++++++++++++++++++++++++++++++++++------------------------
Mserver/src/controller/login/resolve.js | 15++++++++++-----
Mserver/src/controller/oidc.js | 575++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------
Mserver/src/controller/session/select.js | 30++++++++++++++++++------------
Mserver/src/controller/session/show.js | 2+-
Mserver/src/index.js | 43+++++++++++++++++++------------------------
Mserver/src/lib/admin-auth.js | 18++++++++----------
Aserver/src/lib/apps.js | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/lib/config.js | 21++++++++++++++++++++-
Mserver/src/lib/host-context.js | 16++++++++++++----
Mserver/src/lib/oidc/clients.js | 33+++++++++++++++++++--------------
Mserver/src/lib/oidc/context.js | 32+++++++++++++-------------------
Mserver/src/lib/oidc/keys.js | 46+++++++++++++++++++++++++++++++++-------------
Mserver/src/lib/oidc/requests.js | 22++++++++++++++--------
Mserver/src/lib/policy.js | 5-----
Mserver/src/lib/realm.js | 4++++
Aserver/src/lib/refresh-tokens.js | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/lib/session.js | 15+++++++++++++++
Aserver/src/lib/system-clients.js | 32++++++++++++++++++++++++++++++++
Mserver/test/config.test.js | 16++++++++++++++++
Mserver/test/http.test.js | 274+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Mserver/test/policy.test.js | 43+++++++------------------------------------
Mserver/test/realm.test.js | 2++
Dserver/web/esbuild.cjs | 103-------------------------------------------------------------------------------
Dserver/web/src/assets/global.css | 258-------------------------------------------------------------------------------
Dserver/web/src/main.ts | 24------------------------
Dserver/web/src/screen/admin.tsx | 79-------------------------------------------------------------------------------
Dserver/web/src/screen/login.tsx | 394-------------------------------------------------------------------------------
Dserver/web/src/util/api.ts | 174-------------------------------------------------------------------------------
66 files changed, 5968 insertions(+), 2641 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -1,3 +1,4 @@ node_modules/ -server/web/dist/ +app/*/node_modules/ +app/*/dist/ server/data/ diff --git a/app/account/config.example.json b/app/account/config.example.json @@ -0,0 +1,3 @@ +{ + "auth_url": "https://auth.example.com" +} diff --git a/app/account/esbuild.cjs b/app/account/esbuild.cjs @@ -0,0 +1,101 @@ +#!/usr/bin/env node + +// require('dotenv').config(); +const fs = require('node:fs'); +const esbuild = require('esbuild'); +// const { nodeModulesPolyfillPlugin } = require('esbuild-plugins-node-modules-polyfill'); + +// const __dirname = dirname(fileURLToPath(import.meta.url)); + +const entryPoints = { + 'main': __dirname + '/src/main.ts', +}; + +const config = { + format: 'iife', // immediately invoked function expression + platform: 'browser', + target: ['chrome108','firefox107'], + mainFields: ['browser','module','main'], + bundle: true, + outdir: __dirname + '/dist', + entryPoints: [ + ...Object.values(entryPoints), + // __dirname+'/src/service-worker.ts', + ], + minify: false, + // define, + + jsxFactory : 'm', + jsxFragment : '"["', + + loader: { + '.eot' : 'dataurl', + '.html' : 'text', + '.wasm' : 'dataurl', + '.png' : 'dataurl', + '.svg' : 'dataurl', + '.ttf' : 'dataurl', + '.woff' : 'dataurl', + '.woff2': 'dataurl', + }, + + // Kept for when a Buffer is needed. + // plugins: [ + // nodeModulesPolyfillPlugin({ + // globals: { + // Buffer: true + // } + // }) + // ], + +}; + +const buildList = []; +const styles = []; + +esbuild + .build(config) + .then(async () => { + + // Already rendered at every size by util/icon.js, so only copied here. + for(const name of Object.keys(entryPoints)) { + buildList.push(`${name}.js`); + try { + fs.statSync(config.outdir + `/${name}.css`); + styles.push(`${name}.css`); + } catch(e) { + // Intentionally empty + } + } + + fs.writeFileSync(config.outdir + `/index.html`, `<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0"> + <title>auth</title> + ${styles.map(name => `<style>/* ${name} */ ${fs.readFileSync(`${config.outdir}/${name}`, 'utf8')}</style>`).join('\n ')} + </head> + <body> + Loading... + ${buildList.map(name => `<script>/* ${name} */ ${fs.readFileSync(`${config.outdir}/${name}`, 'utf8')}</script>`).join('\n ')} + </body> +</html> +`); + + // const files = await new Promise(done => { + // exec(`find ${config.outdir} -type f`, (err,stdout, stderr) => { + // done(stdout + // .split('\n') + // .map(file => file.slice(config.outdir.length)) + // .filter(file => file) + // ); + // }); + // }); + // let sw = fs.readFileSync(`${config.outdir}/service-worker.js`, 'utf-8') + // .split('"--FILES--"').join(JSON.stringify(['/',...files])); + // fs.writeFileSync(`${config.outdir}/service-worker.js`, sw); + }) + // Without this a failed build still exits 0, and the image ships empty. + .catch(e => { console.error(e); process.exit(1); }); + diff --git a/app/account/package-lock.json b/app/account/package-lock.json @@ -0,0 +1,506 @@ +{ + "name": "auth-account", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "auth-account", + "dependencies": { + "mithril": "^2.3.8" + }, + "devDependencies": { + "esbuild": "^0.28.2" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/mithril": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/mithril/-/mithril-2.3.8.tgz", + "integrity": "sha512-za/Yo7qXEckjm5syrSfaaI9Utf4tCUT3T1IOIYqH6Lrj7G0OZuYYLAY9SV4ygoaAf0+CNqU92MBt+7pmo53JVQ==", + "license": "MIT" + } + } +} diff --git a/app/account/package.json b/app/account/package.json @@ -0,0 +1,14 @@ +{ + "name": "auth-account", + "private": true, + "type": "module", + "scripts": { + "build": "node esbuild.cjs" + }, + "dependencies": { + "mithril": "^2.3.8" + }, + "devDependencies": { + "esbuild": "^0.28.2" + } +} diff --git a/app/account/src/assets/account.css b/app/account/src/assets/account.css @@ -0,0 +1,255 @@ +.account-app, +.account-status-page { + --account-canvas: #ededed; + --account-surface: #ffffff; + --account-topbar: #151515; + --account-border: #d2d2d2; + --account-text: #151515; + --account-muted: #6a6e73; + --account-accent: #2255aa; + --account-danger: #c9190b; + font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html, +body { + margin: 0; + padding: 0; +} + +.account-app { + min-height: 100vh; + background: var(--account-canvas); + color: var(--account-text); + font-size: 1rem; +} + +.account-topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + min-height: 3.5rem; + padding: 0 2rem; + background: var(--account-topbar); + color: #fff; +} + +.account-brand { + color: #fff; + font-size: 0.9375rem; + text-decoration: none; +} + +.account-signout { + padding: 0.5rem 0.75rem; + border: 1pt solid rgba(255, 255, 255, 0.42); + border-radius: 0; + background: transparent; + color: #fff; + font: inherit; + font-size: 0.875rem; + cursor: pointer; +} + +.account-signout:hover { + border-color: #fff; +} + +.account-signout:disabled { + opacity: 0.5; + cursor: default; +} + +.account-page-header { + padding: 1.25rem 2rem; + border-bottom: 1pt solid var(--account-border); + background: var(--account-surface); +} + +.account-page-header h1 { + margin: 0; + font-size: 1.5rem; + font-weight: 400; + line-height: 1.3; +} + +.account-page-header p { + margin: 0.25rem 0 0; + color: var(--account-muted); + font-size: 0.875rem; + line-height: 1.5; +} + +.account-content { + max-width: 72rem; + padding: 1.5rem 2rem 3rem; +} + +.account-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1.5rem; +} + +.account-card { + min-width: 0; + padding: 1.5rem; + border: 1pt solid var(--account-border); + background: var(--account-surface); + box-shadow: 0 1pt 2pt rgba(0, 0, 0, 0.06); +} + +.account-card-wide { + grid-column: 1 / -1; +} + +.account-card h2 { + margin: 0 0 1rem; + font-size: 1.25rem; + font-weight: 400; + line-height: 1.3; +} + +.account-definition { + margin: 0; +} + +.account-definition > div { + display: grid; + grid-template-columns: 9rem minmax(0, 1fr); + gap: 1rem; + padding: 0.75rem 0; + border-bottom: 1pt solid var(--account-border); +} + +.account-definition > div:last-child { + border-bottom: 0; + padding-bottom: 0; +} + +.account-definition dt { + color: var(--account-muted); + font-size: 0.875rem; + line-height: 1.5; +} + +.account-definition dd { + margin: 0; + overflow-wrap: anywhere; + font-size: 0.9375rem; + line-height: 1.5; +} + +.account-note { + margin: 0; + color: var(--account-muted); + font-size: 0.875rem; + line-height: 1.5; +} + +.account-alert { + margin: 0 0 1.5rem; + padding: 0.75rem 1rem; + border: 1pt solid var(--account-border); + border-left: 3pt solid var(--account-danger); + background: var(--account-surface); + font-size: 0.875rem; + line-height: 1.5; +} + +.account-loading { + padding: 1rem 0; + color: var(--account-muted); + font-size: 0.875rem; +} + +.account-status-page { + display: grid; + place-items: center; + min-height: 100vh; + padding: 2rem; + background: var(--account-canvas); + color: var(--account-text); +} + +.account-status-panel { + width: 30rem; + max-width: calc(100vw - 2rem); + padding: 2rem; + border: 1pt solid var(--account-border); + border-left: 3pt solid var(--account-accent); + background: var(--account-surface); +} + +.account-status-panel h1 { + margin: 0 0 1rem; + font-size: 1.5rem; + font-weight: 400; +} + +.account-link { + display: inline-block; + margin-top: 1rem; + color: var(--account-accent); + font-size: 0.875rem; +} + +.account-link:hover { + text-decoration: none; +} + +.account-app a:focus-visible, +.account-app button:focus-visible, +.account-status-page a:focus-visible { + outline: 2pt solid var(--account-accent); + outline-offset: 2pt; +} + +@media (max-width: 60em) { + .account-content { + padding: 1rem 1rem 2rem; + } + + .account-page-header, + .account-topbar { + padding-left: 1rem; + padding-right: 1rem; + } + + .account-grid { + grid-template-columns: minmax(0, 1fr); + gap: 1rem; + } +} + +@media (max-width: 30em) { + .account-definition > div { + grid-template-columns: minmax(0, 1fr); + gap: 0.25rem; + } +} + +@media (prefers-color-scheme: dark) { + .account-app, + .account-status-page { + --account-canvas: #1b1d1f; + --account-surface: #242628; + --account-topbar: #111315; + --account-border: #3a3d40; + --account-text: #e7e7e7; + --account-muted: #a0a4a8; + --account-accent: #7cc0ff; + --account-danger: #f28b82; + } + + .account-app { + color-scheme: dark; + } +} diff --git a/app/account/src/main.ts b/app/account/src/main.ts @@ -0,0 +1,17 @@ +import m from 'mithril'; +import { Account, AccountCallback } from './screen/account'; +import { getBasePath } from './util/api'; + +import './assets/account.css'; + +const routes: m.RouteDefs = { + '/': { + render: () => m(Account, {}), + }, + '/callback': { + render: () => m(AccountCallback, {}), + }, +}; + +m.route.prefix = getBasePath(); +m.route(document.body, '/', routes); diff --git a/app/account/src/screen/account.tsx b/app/account/src/screen/account.tsx @@ -0,0 +1,232 @@ +import m from 'mithril'; +import { + appUrl, + getClientSession, + getDiscovery, + type SessionInfo, + type UserInfo, +} from '../util/api'; +import { + accountSignOut, + completeAccountLogin, + getAccountTokens, + loadAccountUser, + startAccountLogin, +} from '../util/auth'; + +type Mode = 'oidc' | 'client'; + +function formatTime(value: number | null | undefined) { + if (!value) return 'Unknown'; + return new Intl.DateTimeFormat(undefined, { + dateStyle: 'medium', + timeStyle: 'short', + }).format(new Date(value)); +} + +function PageHeader(title: string, subtitle: string) { + return ( + <div class="account-page-header"> + <h1>{title}</h1> + <p>{subtitle}</p> + </div> + ); +} + +export const Account: m.Component = { + mode: null as Mode | null, + user: null as UserInfo | null, + session: null as SessionInfo | null, + error: null as Error | null, + pending: false, + + oninit(this: any) { + this.load(); + }, + + async load(this: any) { + try { + const discovery = await getDiscovery(); + if (!discovery) { + this.mode = 'client'; + this.session = await getClientSession(); + document.title = 'Account'; + } else if (!getAccountTokens()) { + await startAccountLogin(); + return; + } else { + this.mode = 'oidc'; + this.user = await loadAccountUser(); + document.title = 'Account'; + } + } catch (e) { + const error = e as any; + if (this.mode === 'oidc' && (error?.status === 401 || error?.status === 400)) { + try { + await startAccountLogin(); + return; + } catch (loginError) { + this.error = loginError as Error; + } + } else { + this.error = error as Error; + } + } + m.redraw(); + }, + + async signOut(this: any) { + this.pending = true; + this.error = null; + if (this.mode === 'client') { + try { + await fetch('/api/v1/logout', { + method: 'POST', + credentials: 'same-origin', + }); + this.session = null; + this.pending = false; + m.redraw(); + } catch (e) { + this.error = e as Error; + this.pending = false; + m.redraw(); + } + return; + } + await accountSignOut(); + }, + + view(this: any) { + const tokens = getAccountTokens(); + const user = this.user; + const session = this.session; + const name = user?.name || session?.user.display_name || session?.user.username; + + return ( + <div class="account-app"> + <header class="account-topbar"> + <a class="account-brand" href={appUrl('/')}> + Account + </a> + <button + class="account-signout" + type="button" + disabled={this.pending || (!user && !session)} + onclick={() => this.signOut()} + > + {this.pending ? 'Signing out' : 'Sign out'} + </button> + </header> + + {PageHeader('Account', 'Identity and access settings')} + + <main class="account-content"> + {this.error ? ( + <div class="account-alert" role="alert"> + {this.error.message} + </div> + ) : null} + + {!name ? ( + <div class="account-loading">Loading account</div> + ) : ( + <div class="account-grid"> + <section class="account-card"> + <h2>Identity</h2> + <dl class="account-definition"> + <div> + <dt>Name</dt> + <dd>{name}</dd> + </div> + <div> + <dt>Username</dt> + <dd>{user?.preferred_username || session?.user.username}</dd> + </div> + <div> + <dt>Email</dt> + <dd>{user?.email || 'Not set'}</dd> + </div> + <div> + <dt>Session</dt> + <dd>{session ? session.scope.type : 'account client'}</dd> + </div> + </dl> + </section> + + <section class="account-card"> + <h2>Access</h2> + <dl class="account-definition"> + <div> + <dt>Client</dt> + <dd>{session?.scope.client_id || 'account'}</dd> + </div> + <div> + <dt>Realm</dt> + <dd>{session?.realm?.display_name || 'Global'}</dd> + </div> + <div> + <dt>Expires</dt> + <dd>{formatTime(session?.expires_at || tokens?.expires_at)}</dd> + </div> + <div> + <dt>Permissions</dt> + <dd>{session ? 'Current client' : 'Full account'}</dd> + </div> + </dl> + </section> + + <section class="account-card account-card-wide"> + <h2>Permissions</h2> + <p class="account-note"> + App permissions and consent management arrive in the next account slice. + </p> + </section> + </div> + )} + </main> + </div> + ); + }, +}; + +export const AccountCallback: m.Component = { + error: null as Error | null, + + oninit(this: any) { + this.complete(); + }, + + async complete(this: any) { + const query = (m.route.get() || '').split('?')[1] || ''; + try { + await completeAccountLogin(query); + m.route.set('/'); + } catch (e) { + this.error = e as Error; + m.redraw(); + } + }, + + view(this: any) { + return ( + <div class="account-status-page"> + <div class="account-status-panel"> + <h1>{this.error ? 'Sign-in failed' : 'Completing sign-in'}</h1> + {this.error ? ( + <p class="account-alert" role="alert"> + {this.error.message} + </p> + ) : ( + <p class="account-note">Establishing the account session.</p> + )} + {this.error ? ( + <a class="account-link" href={appUrl('/')}> + Return to account + </a> + ) : null} + </div> + </div> + ); + }, +}; diff --git a/app/account/src/util/api.ts b/app/account/src/util/api.ts @@ -0,0 +1,219 @@ +export interface AccountConfig { + auth_url: string; +} + +export interface Discovery { + issuer: string; + client_id: string; + realm: string | null; + display_name: string; + branding: Record<string, string>; + authorization_endpoint: string; + token_endpoint: string; + userinfo_endpoint: string; + end_session_endpoint: string; + system_client: boolean; +} + +export interface TokenResponse { + access_token: string; + token_type: string; + expires_in: number; + id_token?: string; + refresh_token?: string; + scope: string; +} + +export interface UserInfo { + sub: string; + name: string; + preferred_username: string; + email?: string; + email_verified: boolean; + roles: string[]; + is_system_admin: boolean; +} + +export interface SessionInfo { + scope: { + type: 'global' | 'realm' | 'client'; + host: string; + realm_id: string | null; + client_id: string | null; + }; + realm: { + slug: string; + display_name: string; + branding: Record<string, string>; + } | null; + user: { + id: string; + username: string; + display_name: string | null; + }; + roles: string[]; + is_system_admin: boolean; + expires_at: number; + accounts: unknown[]; +} + +export interface ApiError extends Error { + code?: string; + status?: number; +} + +let configPromise: Promise<AccountConfig> | null = null; +let discoveryPromise: Promise<Discovery | null> | null = null; + +export function getBasePath() { + const path = window.location.pathname; + if (path === '/app/account' || path.startsWith('/app/account/')) return '/app/account'; + return ''; +} + +export function appUrl(path = '') { + return `${window.location.origin}${getBasePath()}${path}`; +} + +async function loadConfig(): Promise<AccountConfig> { + if (!configPromise) { + configPromise = (async () => { + try { + const response = await fetch(`${getBasePath()}/config.json`, { + credentials: 'same-origin', + }); + if (response.ok) { + const value = await response.json(); + if (typeof value?.auth_url === 'string' && value.auth_url) { + return { auth_url: value.auth_url.replace(/\/+$/, '') }; + } + } + } catch { + // Server-hosted apps fall back to the current origin. + } + return { auth_url: window.location.origin }; + })(); + } + return configPromise; +} + +export async function getAuthUrl() { + return (await loadConfig()).auth_url; +} + +export function getDiscovery(): Promise<Discovery | null> { + if (!discoveryPromise) { + discoveryPromise = (async () => { + const authUrl = await getAuthUrl(); + const response = await fetch(`${authUrl}/oidc/account/openid-configuration`, { + credentials: 'omit', + }); + if (response.status === 404) return null; + if (!response.ok) throw new Error('Account discovery is unavailable'); + return response.json(); + })().catch((error) => { + discoveryPromise = null; + throw error; + }); + } + return discoveryPromise; +} + +async function formRequest<T>(url: string, values: Record<string, string>): Promise<T> { + const response = await fetch(url, { + method: 'POST', + credentials: 'omit', + headers: { + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams(values).toString(), + }); + let payload: any = null; + try { + payload = await response.json(); + } catch { + payload = null; + } + if (!response.ok) { + const error = new Error( + payload?.error_description || payload?.error?.message || response.statusText + ) as ApiError; + error.code = payload?.error?.code || payload?.error; + error.status = response.status; + throw error; + } + return payload as T; +} + +export async function exchangeCode( + code: string, + redirectUri: string, + verifier: string +): Promise<TokenResponse> { + const discovery = await getDiscovery(); + if (!discovery) throw new Error('This host does not offer the account client'); + return formRequest<TokenResponse>(discovery.token_endpoint, { + grant_type: 'authorization_code', + client_id: 'account', + code, + redirect_uri: redirectUri, + code_verifier: verifier, + }); +} + +export async function refreshAccessToken(refreshToken: string): Promise<TokenResponse> { + const discovery = await getDiscovery(); + if (!discovery) throw new Error('This host does not offer the account client'); + return formRequest<TokenResponse>(discovery.token_endpoint, { + grant_type: 'refresh_token', + client_id: 'account', + refresh_token: refreshToken, + }); +} + +export async function getUserInfo(accessToken: string): Promise<UserInfo> { + const discovery = await getDiscovery(); + if (!discovery) throw new Error('This host does not offer the account client'); + const response = await fetch(discovery.userinfo_endpoint, { + credentials: 'omit', + headers: { + authorization: `Bearer ${accessToken}`, + }, + }); + let payload: any = null; + try { + payload = await response.json(); + } catch { + payload = null; + } + if (!response.ok) { + const error = new Error( + payload?.error_description || payload?.error?.message || response.statusText + ) as ApiError; + error.code = payload?.error?.code || payload?.error; + error.status = response.status; + throw error; + } + return payload as UserInfo; +} + +export async function getClientSession(): Promise<SessionInfo> { + const response = await fetch('/api/v1/session', { + credentials: 'same-origin', + }); + let payload: any = null; + try { + payload = await response.json(); + } catch { + payload = null; + } + if (!response.ok) { + const error = new Error( + payload?.error?.message || response.statusText + ) as ApiError; + error.code = payload?.error?.code; + error.status = response.status; + throw error; + } + return payload as SessionInfo; +} diff --git a/app/account/src/util/auth.ts b/app/account/src/util/auth.ts @@ -0,0 +1,172 @@ +import { + appUrl, + exchangeCode, + getDiscovery, + getUserInfo, + refreshAccessToken, + type TokenResponse, + type UserInfo, +} from './api'; + +const TOKEN_KEY = 'account_tokens'; +const FLOW_KEY = 'account_oidc_flow'; + +export interface AccountTokens { + access_token: string; + refresh_token: string; + id_token?: string; + expires_at: number; + scope: string; +} + +interface LoginFlow { + state: string; + verifier: string; + redirectUri: string; +} + +let refreshPending: Promise<AccountTokens> | null = null; + +function base64url(bytes: Uint8Array) { + let value = ''; + for (const byte of bytes) value += String.fromCharCode(byte); + return btoa(value).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +function randomValue(size = 32) { + return base64url(crypto.getRandomValues(new Uint8Array(size))); +} + +async function codeChallenge(verifier: string) { + const digest = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(verifier) + ); + return base64url(new Uint8Array(digest)); +} + +function saveTokens(response: TokenResponse): AccountTokens { + const tokens: AccountTokens = { + access_token: response.access_token, + refresh_token: response.refresh_token || '', + id_token: response.id_token, + expires_at: Date.now() + response.expires_in * 1000, + scope: response.scope, + }; + sessionStorage.setItem(TOKEN_KEY, JSON.stringify(tokens)); + return tokens; +} + +export function getAccountTokens(): AccountTokens | null { + try { + const value = sessionStorage.getItem(TOKEN_KEY); + return value ? (JSON.parse(value) as AccountTokens) : null; + } catch { + return null; + } +} + +export function clearAccountTokens() { + sessionStorage.removeItem(TOKEN_KEY); + sessionStorage.removeItem(FLOW_KEY); +} + +export async function startAccountLogin() { + const discovery = await getDiscovery(); + if (!discovery) throw new Error('This host does not offer the account client'); + const state = randomValue(); + const verifier = randomValue(48); + const challenge = await codeChallenge(verifier); + const flow: LoginFlow = { + state, + verifier, + redirectUri: appUrl('/callback'), + }; + sessionStorage.setItem(FLOW_KEY, JSON.stringify(flow)); + + const authorizationUrl = new URL(discovery.authorization_endpoint); + authorizationUrl.searchParams.set('response_type', 'code'); + authorizationUrl.searchParams.set('client_id', 'account'); + authorizationUrl.searchParams.set('redirect_uri', flow.redirectUri); + authorizationUrl.searchParams.set('scope', 'openid profile email'); + authorizationUrl.searchParams.set('state', state); + authorizationUrl.searchParams.set('code_challenge', challenge); + authorizationUrl.searchParams.set('code_challenge_method', 'S256'); + window.location.assign(authorizationUrl.toString()); +} + +export async function completeAccountLogin(search: string) { + const params = new URLSearchParams(search); + const error = params.get('error'); + if (error) { + throw new Error(params.get('error_description') || 'Account sign-in was denied'); + } + + const code = params.get('code'); + const state = params.get('state'); + if (!code || !state) throw new Error('The sign-in response is incomplete'); + + let flow: LoginFlow | null = null; + try { + const value = sessionStorage.getItem(FLOW_KEY); + flow = value ? (JSON.parse(value) as LoginFlow) : null; + } catch { + flow = null; + } + if (!flow || flow.state !== state) throw new Error('The sign-in state is invalid'); + + const response = await exchangeCode(code, flow.redirectUri, flow.verifier); + sessionStorage.removeItem(FLOW_KEY); + saveTokens(response); +} + +async function performRefresh(tokens: AccountTokens) { + if (!tokens.refresh_token) throw new Error('The account session has expired'); + return saveTokens(await refreshAccessToken(tokens.refresh_token)); +} + +export function refreshAccountTokens() { + if (!refreshPending) { + const tokens = getAccountTokens(); + refreshPending = tokens + ? performRefresh(tokens) + .catch((error) => { + clearAccountTokens(); + throw error; + }) + .finally(() => { + refreshPending = null; + }) + : Promise.reject(new Error('The account session has expired')); + } + return refreshPending; +} + +export async function ensureAccountAccessToken() { + const tokens = getAccountTokens(); + if (!tokens) throw new Error('The account session has expired'); + if (tokens.expires_at > Date.now() + 30_000) return tokens.access_token; + return (await refreshAccountTokens()).access_token; +} + +export async function loadAccountUser(): Promise<UserInfo> { + let accessToken = await ensureAccountAccessToken(); + try { + return await getUserInfo(accessToken); + } catch (error: any) { + if (error?.status !== 401) throw error; + accessToken = (await refreshAccountTokens()).access_token; + return getUserInfo(accessToken); + } +} + +export async function accountSignOut() { + const tokens = getAccountTokens(); + clearAccountTokens(); + const discovery = await getDiscovery(); + if (!discovery) throw new Error('This host does not offer the account client'); + const logoutUrl = new URL(discovery.end_session_endpoint); + logoutUrl.searchParams.set('post_logout_redirect_uri', appUrl('/')); + if (tokens?.id_token) logoutUrl.searchParams.set('id_token_hint', tokens.id_token); + window.location.assign(logoutUrl.toString()); +} diff --git a/app/admin/config.example.json b/app/admin/config.example.json @@ -0,0 +1,3 @@ +{ + "auth_url": "https://auth.example.com" +} diff --git a/app/admin/esbuild.cjs b/app/admin/esbuild.cjs @@ -0,0 +1,101 @@ +#!/usr/bin/env node + +// require('dotenv').config(); +const fs = require('node:fs'); +const esbuild = require('esbuild'); +// const { nodeModulesPolyfillPlugin } = require('esbuild-plugins-node-modules-polyfill'); + +// const __dirname = dirname(fileURLToPath(import.meta.url)); + +const entryPoints = { + 'main': __dirname + '/src/main.ts', +}; + +const config = { + format: 'iife', // immediately invoked function expression + platform: 'browser', + target: ['chrome108','firefox107'], + mainFields: ['browser','module','main'], + bundle: true, + outdir: __dirname + '/dist', + entryPoints: [ + ...Object.values(entryPoints), + // __dirname+'/src/service-worker.ts', + ], + minify: false, + // define, + + jsxFactory : 'm', + jsxFragment : '"["', + + loader: { + '.eot' : 'dataurl', + '.html' : 'text', + '.wasm' : 'dataurl', + '.png' : 'dataurl', + '.svg' : 'dataurl', + '.ttf' : 'dataurl', + '.woff' : 'dataurl', + '.woff2': 'dataurl', + }, + + // Kept for when a Buffer is needed. + // plugins: [ + // nodeModulesPolyfillPlugin({ + // globals: { + // Buffer: true + // } + // }) + // ], + +}; + +const buildList = []; +const styles = []; + +esbuild + .build(config) + .then(async () => { + + // Already rendered at every size by util/icon.js, so only copied here. + for(const name of Object.keys(entryPoints)) { + buildList.push(`${name}.js`); + try { + fs.statSync(config.outdir + `/${name}.css`); + styles.push(`${name}.css`); + } catch(e) { + // Intentionally empty + } + } + + fs.writeFileSync(config.outdir + `/index.html`, `<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0"> + <title>auth</title> + ${styles.map(name => `<style>/* ${name} */ ${fs.readFileSync(`${config.outdir}/${name}`, 'utf8')}</style>`).join('\n ')} + </head> + <body> + Loading... + ${buildList.map(name => `<script>/* ${name} */ ${fs.readFileSync(`${config.outdir}/${name}`, 'utf8')}</script>`).join('\n ')} + </body> +</html> +`); + + // const files = await new Promise(done => { + // exec(`find ${config.outdir} -type f`, (err,stdout, stderr) => { + // done(stdout + // .split('\n') + // .map(file => file.slice(config.outdir.length)) + // .filter(file => file) + // ); + // }); + // }); + // let sw = fs.readFileSync(`${config.outdir}/service-worker.js`, 'utf-8') + // .split('"--FILES--"').join(JSON.stringify(['/',...files])); + // fs.writeFileSync(`${config.outdir}/service-worker.js`, sw); + }) + // Without this a failed build still exits 0, and the image ships empty. + .catch(e => { console.error(e); process.exit(1); }); + diff --git a/app/admin/package-lock.json b/app/admin/package-lock.json @@ -0,0 +1,506 @@ +{ + "name": "auth-admin", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "auth-admin", + "dependencies": { + "mithril": "^2.3.8" + }, + "devDependencies": { + "esbuild": "^0.28.2" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/mithril": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/mithril/-/mithril-2.3.8.tgz", + "integrity": "sha512-za/Yo7qXEckjm5syrSfaaI9Utf4tCUT3T1IOIYqH6Lrj7G0OZuYYLAY9SV4ygoaAf0+CNqU92MBt+7pmo53JVQ==", + "license": "MIT" + } + } +} diff --git a/app/admin/package.json b/app/admin/package.json @@ -0,0 +1,14 @@ +{ + "name": "auth-admin", + "private": true, + "type": "module", + "scripts": { + "build": "node esbuild.cjs" + }, + "dependencies": { + "mithril": "^2.3.8" + }, + "devDependencies": { + "esbuild": "^0.28.2" + } +} diff --git a/app/admin/src/assets/admin.css b/app/admin/src/assets/admin.css @@ -0,0 +1,466 @@ +.admin-app, +.admin-status-page { + --admin-canvas: #ededed; + --admin-surface: #ffffff; + --admin-sidebar: #292e34; + --admin-sidebar-active: #3c4149; + --admin-topbar: #151515; + --admin-border: #d2d2d2; + --admin-text: #151515; + --admin-muted: #6a6e73; + --admin-accent: #2255aa; + --admin-danger: #c9190b; + font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html, +body { + margin: 0; + padding: 0; +} + +.admin-app { + display: grid; + grid-template-columns: 15rem minmax(0, 1fr); + min-height: 100vh; + background: var(--admin-canvas); + color: var(--admin-text); + font-size: 1rem; +} + +.admin-sidebar { + display: flex; + flex-direction: column; + min-height: 100vh; + background: var(--admin-sidebar); + color: #fff; +} + +.admin-sidebar-user { + display: grid; + gap: 0.25rem; + padding: 1.25rem 1.5rem; + border-bottom: 1pt solid rgba(255, 255, 255, 0.14); +} + +.admin-sidebar-name { + font-size: 1rem; + line-height: 1.4; +} + +.admin-sidebar-meta { + overflow: hidden; + color: rgba(255, 255, 255, 0.62); + font-size: 0.8125rem; + line-height: 1.4; + text-overflow: ellipsis; + white-space: nowrap; +} + +.admin-nav { + flex: 1; + padding: 1rem 0.75rem; +} + +.admin-nav-section { + padding: 0.75rem 0.75rem 0.375rem; + color: rgba(255, 255, 255, 0.52); + font-size: 0.6875rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.admin-nav-item { + display: block; + padding: 0.625rem 0.75rem; + border-left: 3pt solid transparent; + color: rgba(255, 255, 255, 0.88); + font-size: 0.9375rem; + line-height: 1.5; + text-decoration: none; +} + +.admin-nav-item:hover { + background: var(--admin-sidebar-active); +} + +.admin-nav-item.is-active { + border-left-color: #6cb2ff; + background: var(--admin-sidebar-active); + color: #fff; +} + +.admin-sidebar-footer { + padding: 1rem 1.5rem; + border-top: 1pt solid rgba(255, 255, 255, 0.14); + color: rgba(255, 255, 255, 0.62); + font-size: 0.8125rem; + line-height: 1.5; +} + +.admin-main { + display: flex; + flex-direction: column; + min-width: 0; + background: var(--admin-canvas); +} + +.admin-topbar { + display: flex; + align-items: center; + gap: 1rem; + min-height: 3.5rem; + padding: 0 1.5rem; + background: var(--admin-topbar); + color: #fff; +} + +.admin-topbar-context { + flex: 1; + color: rgba(255, 255, 255, 0.78); + font-size: 0.875rem; + letter-spacing: 0.02em; +} + +.admin-menu-button { + display: none; + padding: 0.375rem 0.75rem; + border: 1pt solid rgba(255, 255, 255, 0.36); + border-radius: 0; + background: transparent; + color: #fff; + font: inherit; + font-size: 0.875rem; + cursor: pointer; +} + +.admin-session-menu { + position: relative; +} + +.admin-session-menu summary { + padding: 0.5rem 0.75rem; + border: 1pt solid transparent; + color: #fff; + font-size: 0.875rem; + line-height: 1.5; + list-style: none; + cursor: pointer; +} + +.admin-session-menu summary::-webkit-details-marker { + display: none; +} + +.admin-session-menu summary::marker { + content: ''; +} + +.admin-session-menu summary:hover, +.admin-session-menu[open] summary { + border-color: rgba(255, 255, 255, 0.38); +} + +.admin-session-panel { + position: absolute; + top: 2.75rem; + right: 0; + z-index: 10; + display: grid; + gap: 0.5rem; + min-width: 16rem; + padding: 1rem; + border: 1pt solid var(--admin-border); + background: var(--admin-surface); + color: var(--admin-text); + box-shadow: 0 2pt 6pt rgba(0, 0, 0, 0.18); +} + +.admin-session-label { + font-size: 0.875rem; + line-height: 1.5; +} + +.admin-session-detail { + color: var(--admin-muted); + font-size: 0.8125rem; + line-height: 1.5; +} + +.admin-session-panel button { + padding: 0.5rem 0.75rem; + border: 1pt solid var(--admin-accent); + border-radius: 0; + background: transparent; + color: var(--admin-accent); + font: inherit; + font-size: 0.875rem; + text-align: left; + cursor: pointer; +} + +.admin-session-panel button:hover { + background: var(--admin-accent); + color: #fff; +} + +.admin-page-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1.5rem; + padding: 1.25rem 2rem; + border-bottom: 1pt solid var(--admin-border); + background: var(--admin-surface); +} + +.admin-page-header h1 { + margin: 0; + font-size: 1.5rem; + font-weight: 400; + line-height: 1.3; +} + +.admin-page-header p { + margin: 0.25rem 0 0; + color: var(--admin-muted); + font-size: 0.875rem; + line-height: 1.5; +} + +.admin-content { + flex: 1; + padding: 1.5rem 2rem 3rem; +} + +.admin-card-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1.5rem; +} + +.admin-card { + min-width: 0; + padding: 1.5rem; + border: 1pt solid var(--admin-border); + background: var(--admin-surface); + box-shadow: 0 1pt 2pt rgba(0, 0, 0, 0.06); +} + +.admin-card-wide { + grid-column: 1 / -1; +} + +.admin-card h2 { + margin: 0 0 1rem; + font-size: 1.25rem; + font-weight: 400; + line-height: 1.3; +} + +.admin-card-note { + margin: 0; + color: var(--admin-muted); + font-size: 0.875rem; + line-height: 1.5; +} + +.admin-definition { + margin: 0; +} + +.admin-definition > div { + display: grid; + grid-template-columns: 10rem minmax(0, 1fr); + gap: 1rem; + padding: 0.75rem 0; + border-bottom: 1pt solid var(--admin-border); +} + +.admin-definition > div:last-child { + border-bottom: 0; + padding-bottom: 0; +} + +.admin-definition dt { + color: var(--admin-muted); + font-size: 0.875rem; + line-height: 1.5; +} + +.admin-definition dd { + margin: 0; + overflow-wrap: anywhere; + font-size: 0.9375rem; + line-height: 1.5; +} + +.admin-alert { + margin: 0 0 1.5rem; + padding: 0.75rem 1rem; + border: 1pt solid var(--admin-border); + border-left: 3pt solid var(--admin-danger); + background: var(--admin-surface); + font-size: 0.875rem; + line-height: 1.5; +} + +.admin-loading { + padding: 1rem 0; + color: var(--admin-muted); + font-size: 0.875rem; +} + +.admin-status-page { + display: grid; + place-items: center; + min-height: 100vh; + padding: 2rem; + background: var(--admin-canvas); + color: var(--admin-text); +} + +.admin-status-panel { + width: 30rem; + max-width: calc(100vw - 2rem); + padding: 2rem; + border: 1pt solid var(--admin-border); + border-left: 3pt solid var(--admin-accent); + background: var(--admin-surface); +} + +.admin-status-panel h1 { + margin: 0 0 1rem; + font-size: 1.5rem; + font-weight: 400; +} + +.admin-status-note { + margin: 0; + color: var(--admin-muted); + font-size: 0.875rem; +} + +.admin-text-link { + display: inline-block; + margin-top: 1rem; + color: var(--admin-accent); + font-size: 0.875rem; +} + +.admin-text-link:hover { + text-decoration: none; +} + +.admin-backdrop { + display: none; +} + +.admin-app a:focus-visible, +.admin-app button:focus-visible, +.admin-app summary:focus-visible, +.admin-status-page a:focus-visible { + outline: 2pt solid var(--admin-accent); + outline-offset: 2pt; +} + +@media (max-width: 60em) { + .admin-app { + grid-template-columns: minmax(0, 1fr); + } + + .admin-sidebar { + position: fixed; + top: 0; + left: 0; + z-index: 20; + width: 15rem; + transform: translateX(-15rem); + transition: transform 0.15s ease; + } + + .admin-sidebar.is-open { + transform: translateX(0); + box-shadow: 2pt 0 8pt rgba(0, 0, 0, 0.28); + } + + .admin-menu-button { + display: inline-flex; + } + + .admin-backdrop { + position: fixed; + inset: 0; + z-index: 15; + display: block; + border: 0; + background: rgba(0, 0, 0, 0.44); + } + + .admin-page-header { + padding: 1rem; + } + + .admin-content { + padding: 1rem 1rem 2rem; + } + + .admin-card-grid { + grid-template-columns: minmax(0, 1fr); + gap: 1rem; + } + + .admin-topbar { + padding: 0 1rem; + } +} + +@media (max-width: 30em) { + .admin-definition > div { + grid-template-columns: minmax(0, 1fr); + gap: 0.25rem; + } + + .admin-topbar-context { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +@media (prefers-color-scheme: dark) { + .admin-app, + .admin-status-page { + --admin-canvas: #1b1d1f; + --admin-surface: #242628; + --admin-sidebar: #151719; + --admin-sidebar-active: #2c3034; + --admin-topbar: #111315; + --admin-border: #3a3d40; + --admin-text: #e7e7e7; + --admin-muted: #a0a4a8; + --admin-accent: #7cc0ff; + --admin-danger: #f28b82; + } + + .admin-app { + color-scheme: dark; + } + + .admin-session-panel button:hover { + background: #2f6fbf; + border-color: #2f6fbf; + color: #fff; + } + + .admin-nav-item.is-active { + border-left-color: #7cc0ff; + } +} diff --git a/app/admin/src/main.ts b/app/admin/src/main.ts @@ -0,0 +1,17 @@ +import m from 'mithril'; +import { Admin, AdminCallback } from './screen/admin'; +import { getBasePath } from './util/api'; + +import './assets/admin.css'; + +const routes: m.RouteDefs = { + '/': { + render: () => m(Admin, {}), + }, + '/callback': { + render: () => m(AdminCallback, {}), + }, +}; + +m.route.prefix = getBasePath(); +m.route(document.body, '/', routes); diff --git a/app/admin/src/screen/admin.tsx b/app/admin/src/screen/admin.tsx @@ -0,0 +1,256 @@ +import m from 'mithril'; +import { + adminSignOut, + completeAdminLogin, + getAdminTokens, + loadAdminUser, + startAdminLogin, +} from '../util/auth'; +import { appUrl, type UserInfo } from '../util/api'; + +function formatTime(value: number | null | undefined) { + if (!value) return 'Unknown'; + return new Intl.DateTimeFormat(undefined, { + dateStyle: 'medium', + timeStyle: 'short', + }).format(new Date(value)); +} + +function roleLabel(user: UserInfo) { + return user.is_system_admin ? 'System administrator' : 'Realm administrator'; +} + +function Sidebar(user: UserInfo | null, page: any) { + return ( + <aside class={page.sidebarOpen ? 'admin-sidebar is-open' : 'admin-sidebar'}> + <div class="admin-sidebar-user"> + <span class="admin-sidebar-name">{user?.name || 'Administrator'}</span> + <span class="admin-sidebar-meta"> + {user?.email || user?.preferred_username || 'Identity provider'} + </span> + </div> + <nav class="admin-nav" aria-label="Administration"> + <div class="admin-nav-section">Administration</div> + <a + class="admin-nav-item is-active" + href={appUrl('/')} + aria-current="page" + onclick={(event: Event) => { + event.preventDefault(); + page.sidebarOpen = false; + m.route.set('/'); + }} + > + Overview + </a> + </nav> + <div class="admin-sidebar-footer"> + <span>{user ? roleLabel(user) : 'Administrative access'}</span> + </div> + </aside> + ); +} + +export const Admin: m.Component = { + user: null as UserInfo | null, + error: null as Error | null, + pending: false, + sidebarOpen: false, + + oninit(this: any) { + this.load(); + }, + + async load(this: any) { + if (!getAdminTokens()) { + try { + await startAdminLogin(); + } catch (e) { + this.error = e as Error; + m.redraw(); + } + return; + } + + try { + this.user = await loadAdminUser(); + document.title = 'Administration'; + } catch (e) { + const error = e as any; + if (error?.status === 401 || error?.status === 400 || !getAdminTokens()) { + try { + await startAdminLogin(); + return; + } catch (loginError) { + this.error = loginError as Error; + } + } else { + this.error = error as Error; + } + } + m.redraw(); + }, + + view(this: any) { + const tokens = getAdminTokens(); + const user = this.user; + + return ( + <div class="admin-app"> + {Sidebar(user, this)} + {this.sidebarOpen ? ( + <button + class="admin-backdrop" + type="button" + aria-label="Close navigation" + onclick={() => { + this.sidebarOpen = false; + }} + /> + ) : null} + <div class="admin-main"> + <header class="admin-topbar"> + <button + class="admin-menu-button" + type="button" + aria-expanded={this.sidebarOpen} + onclick={() => { + this.sidebarOpen = !this.sidebarOpen; + }} + > + Menu + </button> + <span class="admin-topbar-context">Administrative access</span> + <details class="admin-session-menu"> + <summary>Session</summary> + <div class="admin-session-panel"> + <span class="admin-session-label"> + {user ? roleLabel(user) : 'Signing in'} + </span> + <span class="admin-session-detail"> + Access expires {formatTime(tokens?.expires_at)} + </span> + <button type="button" onclick={() => adminSignOut()}> + Sign out + </button> + </div> + </details> + </header> + + <div class="admin-page-header"> + <div> + <h1>Overview</h1> + <p>Identity provider control plane</p> + </div> + </div> + + <main class="admin-content"> + {this.error ? ( + <div class="admin-alert" role="alert"> + {this.error.message} + </div> + ) : null} + + {!user ? ( + <div class="admin-loading">Loading session</div> + ) : ( + <div class="admin-card-grid"> + <section class="admin-card"> + <h2>Session</h2> + <dl class="admin-definition"> + <div> + <dt>User</dt> + <dd>{user.name}</dd> + </div> + <div> + <dt>Email</dt> + <dd>{user.email || 'Not set'}</dd> + </div> + <div> + <dt>Username</dt> + <dd>{user.preferred_username}</dd> + </div> + <div> + <dt>Access token</dt> + <dd>{formatTime(tokens?.expires_at)}</dd> + </div> + </dl> + </section> + + <section class="admin-card"> + <h2>Access</h2> + <dl class="admin-definition"> + <div> + <dt>Role</dt> + <dd>{roleLabel(user)}</dd> + </div> + <div> + <dt>Client</dt> + <dd>admin</dd> + </div> + <div> + <dt>Refresh</dt> + <dd>Automatic</dd> + </div> + <div> + <dt>Scope</dt> + <dd>{tokens?.scope || 'openid'}</dd> + </div> + </dl> + </section> + + <section class="admin-card admin-card-wide"> + <h2>Administration</h2> + <p class="admin-card-note"> + Realm and session management arrive in the next admin slice. + </p> + </section> + </div> + )} + </main> + </div> + </div> + ); + }, +}; + +export const AdminCallback: m.Component = { + error: null as Error | null, + + oninit(this: any) { + this.complete(); + }, + + async complete(this: any) { + const query = (m.route.get() || '').split('?')[1] || ''; + try { + await completeAdminLogin(query); + m.route.set('/'); + } catch (e) { + this.error = e as Error; + m.redraw(); + } + }, + + view(this: any) { + return ( + <div class="admin-status-page"> + <div class="admin-status-panel"> + <h1>{this.error ? 'Sign-in failed' : 'Completing sign-in'}</h1> + {this.error ? ( + <p class="admin-alert" role="alert"> + {this.error.message} + </p> + ) : ( + <p class="admin-status-note">Establishing the administrative session.</p> + )} + {this.error ? ( + <a class="admin-text-link" href={appUrl('/')}> + Return to administration + </a> + ) : null} + </div> + </div> + ); + }, +}; diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts @@ -0,0 +1,182 @@ +export interface AdminConfig { + auth_url: string; +} + +export interface Discovery { + issuer: string; + client_id: string; + realm: string | null; + display_name: string; + branding: Record<string, string>; + authorization_endpoint: string; + token_endpoint: string; + userinfo_endpoint: string; + end_session_endpoint: string; + system_client: boolean; +} + +export interface TokenResponse { + access_token: string; + token_type: string; + expires_in: number; + id_token?: string; + refresh_token?: string; + scope: string; +} + +export interface UserInfo { + sub: string; + name: string; + preferred_username: string; + email?: string; + email_verified: boolean; + roles: string[]; + is_system_admin: boolean; +} + +export interface ApiError extends Error { + code?: string; + status?: number; +} + +let configPromise: Promise<AdminConfig> | null = null; +let discoveryPromise: Promise<Discovery> | null = null; + +export function getBasePath() { + const path = window.location.pathname; + if (path === '/app/admin' || path.startsWith('/app/admin/')) return '/app/admin'; + return ''; +} + +export function appUrl(path = '') { + return `${window.location.origin}${getBasePath()}${path}`; +} + +async function loadConfig(): Promise<AdminConfig> { + if (!configPromise) { + configPromise = (async () => { + try { + const response = await fetch(`${getBasePath()}/config.json`, { + credentials: 'same-origin', + }); + if (response.ok) { + const value = await response.json(); + if (typeof value?.auth_url === 'string' && value.auth_url) { + return { auth_url: value.auth_url.replace(/\/+$/, '') }; + } + } + } catch { + // Server-hosted apps fall back to the current origin. + } + return { auth_url: window.location.origin }; + })(); + } + return configPromise; +} + +export async function getAuthUrl() { + return (await loadConfig()).auth_url; +} + +export function getDiscovery(): Promise<Discovery> { + if (!discoveryPromise) { + discoveryPromise = (async () => { + const authUrl = await getAuthUrl(); + const response = await fetch(`${authUrl}/oidc/admin/openid-configuration`, { + credentials: 'omit', + }); + if (!response.ok) throw new Error('Admin discovery is unavailable'); + return response.json(); + })().catch((error) => { + discoveryPromise = null; + throw error; + }); + } + return discoveryPromise; +} + +async function formRequest<T>(url: string, values: Record<string, string>): Promise<T> { + const response = await fetch(url, { + method: 'POST', + credentials: 'omit', + headers: { + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams(values).toString(), + }); + let payload: any = null; + try { + payload = await response.json(); + } catch { + payload = null; + } + if (!response.ok) { + const error = new Error( + payload?.error_description || payload?.error?.message || response.statusText + ) as ApiError; + error.code = payload?.error?.code || payload?.error; + error.status = response.status; + throw error; + } + return payload as T; +} + +export async function exchangeCode( + code: string, + redirectUri: string, + verifier: string +): Promise<TokenResponse> { + const discovery = await getDiscovery(); + return formRequest<TokenResponse>(discovery.token_endpoint, { + grant_type: 'authorization_code', + client_id: 'admin', + code, + redirect_uri: redirectUri, + code_verifier: verifier, + }); +} + +export async function refreshAccessToken(refreshToken: string): Promise<TokenResponse> { + const discovery = await getDiscovery(); + return formRequest<TokenResponse>(discovery.token_endpoint, { + grant_type: 'refresh_token', + client_id: 'admin', + refresh_token: refreshToken, + }); +} + +export async function getUserInfo(accessToken: string): Promise<UserInfo> { + const discovery = await getDiscovery(); + const response = await fetch(discovery.userinfo_endpoint, { + credentials: 'omit', + headers: { + authorization: `Bearer ${accessToken}`, + }, + }); + let payload: any = null; + try { + payload = await response.json(); + } catch { + payload = null; + } + if (!response.ok) { + const error = new Error( + payload?.error_description || payload?.error?.message || response.statusText + ) as ApiError; + error.code = payload?.error?.code || payload?.error; + error.status = response.status; + throw error; + } + return payload as UserInfo; +} + +export async function adminApi(path: string, accessToken: string, init: RequestInit = {}) { + const authUrl = await getAuthUrl(); + const headers = new Headers(init.headers); + headers.set('authorization', `Bearer ${accessToken}`); + return fetch(`${authUrl}${path}`, { + ...init, + credentials: 'omit', + headers, + }); +} diff --git a/app/admin/src/util/auth.ts b/app/admin/src/util/auth.ts @@ -0,0 +1,170 @@ +import { + appUrl, + exchangeCode, + getDiscovery, + getUserInfo, + refreshAccessToken, + type TokenResponse, + type UserInfo, +} from './api'; + +const TOKEN_KEY = 'admin_tokens'; +const FLOW_KEY = 'admin_oidc_flow'; + +export interface AdminTokens { + access_token: string; + refresh_token: string; + id_token?: string; + expires_at: number; + scope: string; +} + +interface LoginFlow { + state: string; + verifier: string; + redirectUri: string; +} + +let refreshPending: Promise<AdminTokens> | null = null; + +function base64url(bytes: Uint8Array) { + let value = ''; + for (const byte of bytes) value += String.fromCharCode(byte); + return btoa(value).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +function randomValue(size = 32) { + return base64url(crypto.getRandomValues(new Uint8Array(size))); +} + +async function codeChallenge(verifier: string) { + const digest = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(verifier) + ); + return base64url(new Uint8Array(digest)); +} + +function saveTokens(response: TokenResponse): AdminTokens { + const tokens: AdminTokens = { + access_token: response.access_token, + refresh_token: response.refresh_token || '', + id_token: response.id_token, + expires_at: Date.now() + response.expires_in * 1000, + scope: response.scope, + }; + sessionStorage.setItem(TOKEN_KEY, JSON.stringify(tokens)); + return tokens; +} + +export function getAdminTokens(): AdminTokens | null { + try { + const value = sessionStorage.getItem(TOKEN_KEY); + return value ? (JSON.parse(value) as AdminTokens) : null; + } catch { + return null; + } +} + +export function clearAdminTokens() { + sessionStorage.removeItem(TOKEN_KEY); + sessionStorage.removeItem(FLOW_KEY); +} + +export async function startAdminLogin() { + const discovery = await getDiscovery(); + const state = randomValue(); + const verifier = randomValue(48); + const challenge = await codeChallenge(verifier); + const flow: LoginFlow = { + state, + verifier, + redirectUri: appUrl('/callback'), + }; + sessionStorage.setItem(FLOW_KEY, JSON.stringify(flow)); + + const authorizationUrl = new URL(discovery.authorization_endpoint); + authorizationUrl.searchParams.set('response_type', 'code'); + authorizationUrl.searchParams.set('client_id', 'admin'); + authorizationUrl.searchParams.set('redirect_uri', flow.redirectUri); + authorizationUrl.searchParams.set('scope', 'openid profile email'); + authorizationUrl.searchParams.set('state', state); + authorizationUrl.searchParams.set('code_challenge', challenge); + authorizationUrl.searchParams.set('code_challenge_method', 'S256'); + window.location.assign(authorizationUrl.toString()); +} + +export async function completeAdminLogin(search: string) { + const params = new URLSearchParams(search); + const error = params.get('error'); + if (error) { + throw new Error(params.get('error_description') || 'Admin sign-in was denied'); + } + + const code = params.get('code'); + const state = params.get('state'); + if (!code || !state) throw new Error('The sign-in response is incomplete'); + + let flow: LoginFlow | null = null; + try { + const value = sessionStorage.getItem(FLOW_KEY); + flow = value ? (JSON.parse(value) as LoginFlow) : null; + } catch { + flow = null; + } + if (!flow || flow.state !== state) throw new Error('The sign-in state is invalid'); + + const response = await exchangeCode(code, flow.redirectUri, flow.verifier); + sessionStorage.removeItem(FLOW_KEY); + saveTokens(response); +} + +async function performRefresh(tokens: AdminTokens) { + if (!tokens.refresh_token) throw new Error('The admin session has expired'); + return saveTokens(await refreshAccessToken(tokens.refresh_token)); +} + +export function refreshAdminTokens() { + if (!refreshPending) { + const tokens = getAdminTokens(); + refreshPending = tokens + ? performRefresh(tokens) + .catch((error) => { + clearAdminTokens(); + throw error; + }) + .finally(() => { + refreshPending = null; + }) + : Promise.reject(new Error('The admin session has expired')); + } + return refreshPending; +} + +export async function ensureAdminAccessToken() { + const tokens = getAdminTokens(); + if (!tokens) throw new Error('The admin session has expired'); + if (tokens.expires_at > Date.now() + 30_000) return tokens.access_token; + return (await refreshAdminTokens()).access_token; +} + +export async function loadAdminUser(): Promise<UserInfo> { + let accessToken = await ensureAdminAccessToken(); + try { + return await getUserInfo(accessToken); + } catch (error: any) { + if (error?.status !== 401) throw error; + accessToken = (await refreshAdminTokens()).access_token; + return getUserInfo(accessToken); + } +} + +export async function adminSignOut() { + const tokens = getAdminTokens(); + clearAdminTokens(); + const discovery = await getDiscovery(); + const logoutUrl = new URL(discovery.end_session_endpoint); + logoutUrl.searchParams.set('post_logout_redirect_uri', appUrl('/')); + if (tokens?.id_token) logoutUrl.searchParams.set('id_token_hint', tokens.id_token); + window.location.assign(logoutUrl.toString()); +} diff --git a/app/login/esbuild.cjs b/app/login/esbuild.cjs @@ -0,0 +1,101 @@ +#!/usr/bin/env node + +// require('dotenv').config(); +const fs = require('node:fs'); +const esbuild = require('esbuild'); +// const { nodeModulesPolyfillPlugin } = require('esbuild-plugins-node-modules-polyfill'); + +// const __dirname = dirname(fileURLToPath(import.meta.url)); + +const entryPoints = { + 'main': __dirname + '/src/main.ts', +}; + +const config = { + format: 'iife', // immediately invoked function expression + platform: 'browser', + target: ['chrome108','firefox107'], + mainFields: ['browser','module','main'], + bundle: true, + outdir: __dirname + '/dist', + entryPoints: [ + ...Object.values(entryPoints), + // __dirname+'/src/service-worker.ts', + ], + minify: false, + // define, + + jsxFactory : 'm', + jsxFragment : '"["', + + loader: { + '.eot' : 'dataurl', + '.html' : 'text', + '.wasm' : 'dataurl', + '.png' : 'dataurl', + '.svg' : 'dataurl', + '.ttf' : 'dataurl', + '.woff' : 'dataurl', + '.woff2': 'dataurl', + }, + + // Kept for when a Buffer is needed. + // plugins: [ + // nodeModulesPolyfillPlugin({ + // globals: { + // Buffer: true + // } + // }) + // ], + +}; + +const buildList = []; +const styles = []; + +esbuild + .build(config) + .then(async () => { + + // Already rendered at every size by util/icon.js, so only copied here. + for(const name of Object.keys(entryPoints)) { + buildList.push(`${name}.js`); + try { + fs.statSync(config.outdir + `/${name}.css`); + styles.push(`${name}.css`); + } catch(e) { + // Intentionally empty + } + } + + fs.writeFileSync(config.outdir + `/index.html`, `<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0"> + <title>auth</title> + ${styles.map(name => `<style>/* ${name} */ ${fs.readFileSync(`${config.outdir}/${name}`, 'utf8')}</style>`).join('\n ')} + </head> + <body> + Loading... + ${buildList.map(name => `<script>/* ${name} */ ${fs.readFileSync(`${config.outdir}/${name}`, 'utf8')}</script>`).join('\n ')} + </body> +</html> +`); + + // const files = await new Promise(done => { + // exec(`find ${config.outdir} -type f`, (err,stdout, stderr) => { + // done(stdout + // .split('\n') + // .map(file => file.slice(config.outdir.length)) + // .filter(file => file) + // ); + // }); + // }); + // let sw = fs.readFileSync(`${config.outdir}/service-worker.js`, 'utf-8') + // .split('"--FILES--"').join(JSON.stringify(['/',...files])); + // fs.writeFileSync(`${config.outdir}/service-worker.js`, sw); + }) + // Without this a failed build still exits 0, and the image ships empty. + .catch(e => { console.error(e); process.exit(1); }); + diff --git a/app/login/package-lock.json b/app/login/package-lock.json @@ -0,0 +1,506 @@ +{ + "name": "auth-login", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "auth-login", + "dependencies": { + "mithril": "^2.3.8" + }, + "devDependencies": { + "esbuild": "^0.28.2" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/mithril": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/mithril/-/mithril-2.3.8.tgz", + "integrity": "sha512-za/Yo7qXEckjm5syrSfaaI9Utf4tCUT3T1IOIYqH6Lrj7G0OZuYYLAY9SV4ygoaAf0+CNqU92MBt+7pmo53JVQ==", + "license": "MIT" + } + } +} diff --git a/app/login/package.json b/app/login/package.json @@ -0,0 +1,15 @@ +{ + "name": "auth-login", + "private": true, + "type": "module", + "scripts": { + "build": "node esbuild.cjs", + "assets:hex": "node scripts/generate-hex-grid.js" + }, + "dependencies": { + "mithril": "^2.3.8" + }, + "devDependencies": { + "esbuild": "^0.28.2" + } +} diff --git a/app/login/scripts/generate-hex-grid.js b/app/login/scripts/generate-hex-grid.js @@ -0,0 +1,89 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const SETTINGS = { + width: 1024, + height: 576, + amount: 20, + density: 1, + strokeWidth: 0.5, + baseWidth: 512, + randomFillOpacity: true, + light: { + back: '#FFF', + front: '#DDD', + }, + dark: { + back: '#000', + front: '#222', + }, +}; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const assets = path.resolve(here, '../src/assets'); + +function randomAt(column, row) { + let value = Math.imul(column + 1000, 374761393) + Math.imul(row + 1000, 668265263); + value = Math.imul(value ^ (value >>> 13), 1274126177); + return ((value ^ (value >>> 16)) >>> 0) / 4294967295; +} + +function hexPath(cx, cy, radius, halfWidth) { + const halfHeight = radius / 2; + const points = [ + [cx, cy - radius], + [cx + halfWidth, cy - halfHeight], + [cx + halfWidth, cy + halfHeight], + [cx, cy + radius], + [cx - halfWidth, cy + halfHeight], + [cx - halfWidth, cy - halfHeight], + ].map(([x, y]) => `${Number(x.toFixed(3))} ${Number(y.toFixed(3))}`); + return `M ${points[0]} L ${points[1]} L ${points[2]} L ${points[3]} L ${points[4]} L ${points[5]} Z`; +} + +function buildSvg({ front, back }) { + const { width, height, amount, density, strokeWidth, baseWidth } = SETTINGS; + const spacing = width / amount; + const radius = (spacing / Math.sqrt(3)) * density; + const verticalSpacing = 1.5 * radius; + const stroke = strokeWidth * (width / baseWidth); + const rows = Math.ceil(height / verticalSpacing) + 1; + + const paths = []; + for (let row = -1; row <= rows; row += 1) { + const parity = ((row % 2) + 2) % 2; + const cy = radius + verticalSpacing * row; + for (let column = 0; column <= amount; column += 1) { + const cx = parity * (spacing / 2) + spacing * column; + const random = randomAt(column, row); + const opacity = !SETTINGS.randomFillOpacity + ? 1 + : random >= 0.45 + ? Number((random ** 2).toFixed(2)) + : 0; + const fill = opacity > 0 ? ` fill="${front}" fill-opacity="${opacity}"` : ' fill="none"'; + paths.push( + `<path stroke="${front}" stroke-width="${Number(stroke.toFixed(4))}"${fill} d="${hexPath( + cx, + cy, + radius, + spacing / 2 + )}"/>` + ); + } + } + + return [ + `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`, + `<rect width="100%" height="100%" fill="${back}"/>`, + ...paths, + '</svg>', + '', + ].join('\n'); +} + +fs.writeFileSync(path.join(assets, 'hex-grid-light.svg'), buildSvg(SETTINGS.light)); +fs.writeFileSync(path.join(assets, 'hex-grid-dark.svg'), buildSvg(SETTINGS.dark)); + +console.log('wrote hex-grid-light.svg and hex-grid-dark.svg'); diff --git a/server/web/src/assets/hex-grid-dark.svg b/app/login/src/assets/hex-grid-dark.svg diff --git a/server/web/src/assets/hex-grid-light.svg b/app/login/src/assets/hex-grid-light.svg diff --git a/app/login/src/assets/login.css b/app/login/src/assets/login.css @@ -0,0 +1,258 @@ +:root { + font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; + --realm-primary: #25A; +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html, +body { + margin: 0; + padding: 0; +} + +.auth-page { + min-height: 100vh; + display: flex; + justify-content: center; + align-items: flex-start; + padding: 12vh 1.5rem 3rem; + background: #fff; +} + +.auth-card { + width: min(24rem, 100%); + padding: 2rem; + background: #fff; + border-radius: 0; +} + +.auth-logo { + max-width: 8rem; + margin-bottom: 1rem; +} + +.auth-card h1 { + margin: 0 0 1.5rem; + font-size: 1.5rem; + font-weight: 400; +} + +.auth-field { + position: relative; + padding-top: 1rem; +} + +.auth-input { + width: 100%; + padding: 0.5rem 0; + border: 0; + border-bottom: 1pt solid rgba(0, 0, 0, 0.42); + border-radius: 0; + background: transparent; + color: inherit; + font: inherit; + font-size: 1rem; + line-height: 1.5; + outline: none; +} + +.auth-input:focus { + border-bottom-color: var(--realm-primary); +} + +.auth-field label { + position: absolute; + top: 1.5em; + left: 0; + font-size: 1rem; + line-height: 1.5; + color: rgba(0, 0, 0, 0.6); + pointer-events: none; + transform-origin: left top; + transition: top 0.15s ease, font-size 0.15s ease, color 0.15s ease, opacity 0.15s ease; +} + +.auth-input:focus + label, +.auth-input:not(:placeholder-shown) + label { + top: 0; + font-size: 0.85em; + font-weight: 500; + color: inherit; + opacity: 0.8; +} + +.auth-identifier { + margin: 0 0 0.5rem; + color: rgba(0, 0, 0, 0.6); + font-size: 0.875rem; +} + +.auth-note { + margin: 0 0 1rem; + color: rgba(0, 0, 0, 0.6); + font-size: 0.875rem; + line-height: 1.5; +} + +.auth-choice { + display: flex; + align-items: center; + gap: 0.5rem; + margin-top: 1rem; + font-size: 0.875rem; + line-height: 1.5; + cursor: pointer; +} + +.auth-choice input { + width: 1rem; + height: 1rem; + accent-color: var(--realm-primary); +} + +.auth-accounts { + display: grid; + gap: 0.5rem; + margin-top: 1rem; +} + +.auth-account { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.125rem; + width: 100%; + padding: 0.75rem 0; + border: 0; + border-bottom: 1pt solid rgba(0, 0, 0, 0.16); + border-radius: 0; + background: none; + color: inherit; + font: inherit; + text-align: left; + cursor: pointer; +} + +.auth-account:hover, +.auth-account:focus-visible { + border-bottom-color: var(--realm-primary); +} + +.auth-account:disabled { + opacity: 0.5; + cursor: default; +} + +.auth-account-name { + font-size: 1rem; + line-height: 1.5; +} + +.auth-account-username { + color: rgba(0, 0, 0, 0.6); + font-size: 0.875rem; + line-height: 1.5; +} + +.auth-error { + margin: 1rem 0 0; + color: #d93025; + font-size: 0.875rem; + line-height: 1.5; +} + +.auth-actions { + display: flex; + justify-content: flex-end; + align-items: center; + gap: 1rem; + margin-top: 1.5rem; +} + +.auth-button { + padding: 0.75rem 1.5rem; + border: 0; + border-radius: 0; + background: var(--realm-primary); + color: #fff; + font: inherit; + font-size: 0.875rem; + letter-spacing: 0.05em; + text-transform: uppercase; + cursor: pointer; +} + +.auth-button:disabled { + opacity: 0.5; + cursor: default; +} + +.auth-link { + padding: 0.5rem 0; + border: 0; + background: none; + color: var(--realm-primary); + font: inherit; + font-size: 0.875rem; + cursor: pointer; +} + +@media (prefers-color-scheme: dark) { + .auth-page { + background-color: #222; + } + + .auth-card { + background-color: #222; + color: #fff; + } + + .auth-input { + border-bottom-color: rgba(255, 255, 255, 0.42); + color: #fff; + } + + .auth-field label, + .auth-identifier, + .auth-note, + .auth-account-username { + color: rgba(255, 255, 255, 0.6); + } + + .auth-account { + border-bottom-color: rgba(255, 255, 255, 0.16); + } + + .auth-error { + color: #f28b82; + } +} + +@media (min-width: 35em) { + .auth-page { + background-color: #fff; + background-image: url('./hex-grid-light.svg'); + background-position: center; + background-repeat: no-repeat; + background-size: cover; + } + + .auth-card { + box-shadow: 0 0.25em 0.5em #0008; + } +} + +@media (min-width: 35em) and (prefers-color-scheme: dark) { + .auth-page { + background-color: #222; + background-image: url('./hex-grid-dark.svg'); + background-position: center; + background-repeat: no-repeat; + background-size: cover; + } +} diff --git a/app/login/src/main.ts b/app/login/src/main.ts @@ -0,0 +1,16 @@ +import m from 'mithril'; +import { Login } from './screen/login'; + +import './assets/login.css'; + +const routes: m.RouteDefs = { + '/oidc/:clientId/login': { + render: (vnode) => m(Login, { clientId: (vnode.attrs as any).clientId }), + }, + '/oidc/login': { + render: () => m(Login, {}), + }, +}; + +m.route.prefix = ''; +m.route(document.body, '/oidc/login', routes); diff --git a/app/login/src/screen/login.tsx b/app/login/src/screen/login.tsx @@ -0,0 +1,381 @@ +import m from 'mithril'; +import { + getClientDiscovery, + getSession, + resolveLogin, + selectSession, + signInPassword, + type ClientDiscovery, + type LoginResolution, + type PasswordLoginResult, + type SessionAccount, +} from '../util/api'; + +type Step = 'accounts' | 'identifier' | 'password' | 'oidc' | 'done'; + +interface TextFieldAttrs { + id: string; + label: string; + type?: string; + value: string; + autocomplete?: string; + autofocus?: boolean; + disabled?: boolean; + oninput: (value: string) => void; +} + +function queryParam(name: string) { + const query = (m.route.get() || '').split('?')[1] || ''; + return new URLSearchParams(query).get(name); +} + +function authorizeRoute() { + const path = (m.route.get() || '').split('?')[0]; + return path.replace(/\/login$/, '/authorize'); +} + +const TextField: m.Component<TextFieldAttrs> = { + view({ attrs }) { + return ( + <div class="auth-field"> + <input + class="auth-input" + id={attrs.id} + type={attrs.type || 'text'} + value={attrs.value} + placeholder=" " + autocomplete={attrs.autocomplete} + disabled={attrs.disabled} + oninput={(e: Event) => attrs.oninput((e.target as HTMLInputElement).value)} + oncreate={attrs.autofocus ? ({ dom }: any) => dom.focus() : undefined} + /> + <label for={attrs.id}>{attrs.label}</label> + </div> + ); + }, +}; + +export const Login: m.Component<{ clientId?: string }> = { + clientId: null as string | null, + discovery: null as ClientDiscovery | null, + step: 'identifier' as Step, + accounts: [] as SessionAccount[], + identifier: '', + password: '', + longSession: false, + provider: null as LoginResolution['provider'] | null, + signedIn: null as PasswordLoginResult['user'] | null, + error: null as Error | null, + pending: false, + reauth: false, + + oninit(this: any, vnode: any) { + this.clientId = vnode.attrs.clientId ?? null; + this.reauth = queryParam('reauth') === '1'; + this.loadClient(); + }, + + async loadClient(this: any) { + this.error = null; + try { + const discovery = await getClientDiscovery(this.clientId); + this.discovery = discovery; + this.clientId = discovery.client_id; + document.title = discovery.display_name; + await this.loadAccounts(); + } catch (e) { + this.error = e as Error; + } + m.redraw(); + }, + + async loadAccounts(this: any) { + if (this.reauth) { + this.accounts = []; + return; + } + try { + const session = await getSession(); + if (session.accounts.length >= 2) { + this.accounts = session.accounts; + this.step = 'accounts'; + } + } catch { + this.accounts = []; + } + }, + + async submitIdentifier(this: any) { + this.pending = true; + this.error = null; + try { + const result = await resolveLogin(this.clientId, this.identifier); + if (result.next === 'oidc' && result.provider) { + this.provider = result.provider; + this.step = 'oidc'; + } else { + this.step = 'password'; + } + } catch (e) { + this.error = e as Error; + } + this.pending = false; + m.redraw(); + }, + + async submitPassword(this: any) { + this.pending = true; + this.error = null; + try { + const result = await signInPassword( + this.clientId, + this.identifier, + this.password, + this.longSession + ); + + if (result.pending_auth_request) { + m.route.set(authorizeRoute()); + return; + } + + this.signedIn = result.user; + this.step = 'done'; + this.pending = false; + m.redraw(); + } catch (e) { + this.error = e as Error; + this.pending = false; + m.redraw(); + } + }, + + async selectAccount(this: any, account: SessionAccount) { + this.pending = true; + this.error = null; + try { + const result = await selectSession(account.public_id, this.clientId); + if (result.pending_auth_request) { + m.route.set(authorizeRoute()); + return; + } + + this.signedIn = result.user; + this.step = 'done'; + } catch (e) { + this.error = e as Error; + } + this.pending = false; + m.redraw(); + }, + + differentAccount(this: any) { + this.step = 'identifier'; + this.identifier = ''; + this.password = ''; + this.longSession = false; + this.provider = null; + this.error = null; + m.redraw(); + }, + + back(this: any) { + this.step = 'identifier'; + this.password = ''; + this.longSession = false; + this.provider = null; + this.error = null; + m.redraw(); + }, + + backToAccounts(this: any) { + this.step = 'accounts'; + this.error = null; + m.redraw(); + }, + + view(this: any) { + const branding = this.discovery?.branding || {}; + const primary = typeof branding.primary_color === 'string' ? branding.primary_color : '#25A'; + const style = { '--realm-primary': primary } as any; + + if (!this.discovery && this.error) { + return ( + <div class="auth-page" style={style}> + <div class="auth-card"> + <h1>Sign in</h1> + <p class="auth-error">{this.error.message}</p> + </div> + </div> + ); + } + + const title = this.discovery?.display_name || 'Sign in'; + + return ( + <div class="auth-page" style={style}> + <div class="auth-card"> + {typeof branding.logo_url === 'string' && branding.logo_url ? ( + <img class="auth-logo" src={branding.logo_url} alt={title} /> + ) : null} + <h1>{title}</h1> + + {this.step === 'accounts' ? this.renderAccounts() : null} + {this.step === 'identifier' ? this.renderIdentifier() : null} + {this.step === 'password' ? this.renderPassword() : null} + {this.step === 'oidc' ? this.renderProvider() : null} + {this.step === 'done' ? this.renderDone() : null} + </div> + </div> + ); + }, + + renderAccounts(this: any) { + return ( + <div> + <p class="auth-note">Choose an account to continue.</p> + <div class="auth-accounts"> + {this.accounts.map((account: SessionAccount) => { + const name = account.user.display_name || account.user.username; + const secondary = + account.user.display_name && account.user.display_name !== account.user.username + ? account.user.username + : null; + return ( + <button + class="auth-account" + type="button" + disabled={this.pending} + onclick={() => this.selectAccount(account)} + > + <span class="auth-account-name">{name}</span> + {secondary ? <span class="auth-account-username">{secondary}</span> : null} + </button> + ); + })} + </div> + {this.error ? <p class="auth-error">{this.error.message}</p> : null} + <div class="auth-actions"> + <button class="auth-link" type="button" onclick={() => this.differentAccount()}> + Different account + </button> + </div> + </div> + ); + }, + + renderIdentifier(this: any) { + return ( + <form + onsubmit={(e: Event) => { + e.preventDefault(); + if (!this.pending && this.identifier.trim()) this.submitIdentifier(); + }} + > + {this.reauth ? ( + <p class="auth-note">Confirm your password to continue.</p> + ) : null} + <TextField + id="identifier" + label="Email or username" + value={this.identifier} + autocomplete="username" + autofocus + disabled={this.pending} + oninput={(value: string) => { + this.identifier = value; + }} + /> + {this.error ? <p class="auth-error">{this.error.message}</p> : null} + <div class="auth-actions"> + {!this.reauth && this.accounts.length >= 2 ? ( + <button class="auth-link" type="button" onclick={() => this.backToAccounts()}> + Back to accounts + </button> + ) : null} + <button class="auth-button" type="submit" disabled={this.pending || !this.identifier.trim()}> + {this.pending ? 'Checking' : 'Next'} + </button> + </div> + </form> + ); + }, + + renderPassword(this: any) { + return ( + <form + onsubmit={(e: Event) => { + e.preventDefault(); + if (!this.pending) this.submitPassword(); + }} + > + <p class="auth-identifier">{this.identifier}</p> + <TextField + id="password" + label="Password" + type="password" + value={this.password} + autocomplete="current-password" + autofocus + disabled={this.pending} + oninput={(value: string) => { + this.password = value; + }} + /> + {this.discovery?.allow_session_duration_choice !== false ? ( + <label class="auth-choice"> + <input + type="checkbox" + checked={this.longSession} + disabled={this.pending} + onchange={(e: Event) => { + this.longSession = (e.target as HTMLInputElement).checked; + }} + /> + <span>Keep me signed in</span> + </label> + ) : null} + {this.error ? <p class="auth-error">{this.error.message}</p> : null} + <div class="auth-actions"> + <button class="auth-link" type="button" onclick={() => this.back()}> + Back + </button> + <button class="auth-button" type="submit" disabled={this.pending || !this.password}> + {this.pending ? 'Signing in' : 'Sign in'} + </button> + </div> + </form> + ); + }, + + renderProvider(this: any) { + const provider = this.provider; + return ( + <div> + <p class="auth-identifier">{this.identifier}</p> + <p class="auth-note"> + {provider + ? `This account signs in with ${provider.display_name}.` + : 'This account signs in with an identity provider.'} + </p> + <div class="auth-actions"> + <button class="auth-link" type="button" onclick={() => this.back()}> + Back + </button> + <button class="auth-button" type="button" disabled> + Continue + </button> + </div> + </div> + ); + }, + + renderDone(this: any) { + const user = this.signedIn; + return ( + <div> + <p class="auth-note">Signed in as {user?.display_name || user?.username}</p> + </div> + ); + }, +}; diff --git a/app/login/src/util/api.ts b/app/login/src/util/api.ts @@ -0,0 +1,174 @@ +export interface RealmInfo { + slug: string; + display_name: string; + branding: Record<string, string>; + allow_session_duration_choice: boolean; +} + +export interface ClientDiscovery { + issuer: string; + client_id: string; + client_name: string; + realm: string | null; + display_name: string; + branding: Record<string, string>; + access_mode: string; + system_client: boolean; + require_pkce: boolean; + allow_session_duration_choice: boolean; +} + +export interface LoginResolution { + realm: RealmInfo | null; + next: 'password' | 'oidc'; + provider?: { + slug: string; + display_name: string; + }; +} + +export interface PasswordLoginResult { + realm: RealmInfo | null; + user: { + id: string; + username: string; + display_name: string | null; + }; + expires_at: number; + pending_auth_request: boolean; +} + +export interface SessionScope { + type: 'global' | 'realm' | 'client'; + host: string; + realm_id: string | null; + client_id: string | null; +} + +export interface SessionAccount { + public_id: string; + active: boolean; + user: { + id: string; + username: string; + display_name: string | null; + }; + created_at: number; + expires_at: number; +} + +export interface SessionInfo { + scope: SessionScope; + realm: RealmInfo | null; + user: { + id: string; + username: string; + display_name: string | null; + }; + roles: string[]; + is_system_admin: boolean; + expires_at: number; + accounts: SessionAccount[]; +} + +export interface SelectSessionResult { + ok: boolean; + user: { + id: string; + username: string; + display_name: string | null; + }; + expires_at: number; + pending_auth_request: boolean; +} + +export interface ApiError extends Error { + code?: string; + status?: number; +} + +async function request<T>(path: string, options: RequestInit = {}): Promise<T> { + const response = await fetch(path, { + credentials: 'same-origin', + headers: { + 'content-type': 'application/json', + }, + ...options, + }); + + let payload: any = null; + try { + payload = await response.json(); + } catch { + payload = null; + } + + if (!response.ok) { + const error = new Error(payload?.error?.message || response.statusText) as ApiError; + error.code = payload?.error?.code; + error.status = response.status; + throw error; + } + + return payload as T; +} + +export function getRealm(realm?: string | null): Promise<RealmInfo> { + const query = realm ? `?realm=${encodeURIComponent(realm)}` : ''; + return request<RealmInfo>(`/api/v1/realm${query}`); +} + +export function getClientDiscovery(clientId?: string | null): Promise<ClientDiscovery> { + if (clientId) { + return request<ClientDiscovery>(`/oidc/${encodeURIComponent(clientId)}/openid-configuration`); + } + return request<ClientDiscovery>('/oidc/openid-configuration'); +} + +export function resolveLogin( + clientId: string, + identifier: string +): Promise<LoginResolution> { + return request<LoginResolution>('/api/v1/login/resolve', { + method: 'POST', + body: JSON.stringify({ client_id: clientId, identifier }), + }); +} + +export function signInPassword( + clientId: string, + identifier: string, + password: string, + longSession: boolean +): Promise<PasswordLoginResult> { + return request<PasswordLoginResult>('/api/v1/login/password', { + method: 'POST', + body: JSON.stringify({ + client_id: clientId, + identifier, + password, + long_session: longSession, + }), + }); +} + +export function getSession(): Promise<SessionInfo> { + return request<SessionInfo>('/api/v1/session'); +} + +export function selectSession( + publicId: string, + clientId?: string | null +): Promise<SelectSessionResult> { + return request<SelectSessionResult>('/api/v1/session/select', { + method: 'POST', + body: JSON.stringify({ + public_id: publicId, + client_id: clientId || undefined, + }), + }); +} + +export function signOut(): Promise<{ ok: boolean }> { + return request('/api/v1/logout', { method: 'POST' }); +} diff --git a/server/auth.example.yaml b/server/auth.example.yaml @@ -7,3 +7,7 @@ database: dialect: sqlite path: ./data/system.sqlite realms: ./data/realms + +apps: + admin: null + account: null diff --git a/server/migrations/sqlite/system/006_system_oidc.sql b/server/migrations/sqlite/system/006_system_oidc.sql @@ -0,0 +1,68 @@ +CREATE TABLE system_signing_keys ( + id TEXT PRIMARY KEY, + alg TEXT NOT NULL, + private_jwk TEXT NOT NULL, + public_jwk TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'retired')), + created_at INTEGER NOT NULL, + retired_at INTEGER +); + +CREATE INDEX system_signing_keys_status ON system_signing_keys(status); + +CREATE TABLE auth_requests ( + id TEXT PRIMARY KEY, + client_id TEXT NOT NULL, + redirect_uri TEXT NOT NULL, + scope TEXT NOT NULL, + state TEXT, + nonce TEXT, + code_challenge TEXT, + code_challenge_method TEXT, + session_id TEXT, + user_id TEXT, + auth_time INTEGER, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + completed_at INTEGER +); + +CREATE INDEX auth_requests_expires ON auth_requests(expires_at); + +CREATE TABLE authorization_codes ( + id TEXT PRIMARY KEY, + auth_request_id TEXT NOT NULL UNIQUE, + client_id TEXT NOT NULL, + user_id TEXT NOT NULL, + redirect_uri TEXT NOT NULL, + scope TEXT NOT NULL, + nonce TEXT, + code_challenge TEXT, + code_challenge_method TEXT, + session_id TEXT, + auth_time INTEGER NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + consumed_at INTEGER +); + +CREATE INDEX authorization_codes_expires ON authorization_codes(expires_at); + +CREATE TABLE refresh_tokens ( + id TEXT PRIMARY KEY, + family_id TEXT NOT NULL, + session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, + user_id TEXT NOT NULL, + realm_id TEXT REFERENCES realms(id) ON DELETE CASCADE, + client_id TEXT NOT NULL, + scopes TEXT NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + consumed_at INTEGER, + replaced_by TEXT, + revoked_at INTEGER +); + +CREATE INDEX refresh_tokens_family ON refresh_tokens(family_id); +CREATE INDEX refresh_tokens_session ON refresh_tokens(session_id); +CREATE INDEX refresh_tokens_user ON refresh_tokens(user_id); diff --git a/server/package-lock.json b/server/package-lock.json @@ -10,457 +10,9 @@ "cookie": "^2.0.1", "cors": "^2.8.6", "jose": "^6.2.13", - "mithril": "^2.3.8", "morgan": "^1.12.1", "router": "^2.2.0", - "serve-static": "^2.2.1", "yaml": "^2.9.1" - }, - "devDependencies": { - "cpy": "^13.2.3", - "esbuild": "^0.28.2" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", - "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", - "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", - "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", - "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", - "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", - "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", - "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", - "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", - "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", - "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", - "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", - "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", - "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", - "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", - "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", - "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", - "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", - "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", - "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", - "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", - "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", - "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", - "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", - "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", - "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", - "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" } }, "node_modules/@finwo/scandir": { @@ -479,57 +31,6 @@ ], "license": "MIT" }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@sindresorhus/merge-streams": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-4.0.0.tgz", - "integrity": "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/basic-auth": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz", @@ -589,19 +90,6 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -666,23 +154,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/copy-file": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/copy-file/-/copy-file-11.1.0.tgz", - "integrity": "sha512-X8XDzyvYaA6msMyAM575CUoygY5b44QzLcGRKsK3MFmXcOvQa518dNPLsKYwkYsn72g3EiW+LE0ytd/FlqWmyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.11", - "p-event": "^6.0.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/cors": { "version": "2.8.6", "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", @@ -700,27 +171,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/cpy": { - "version": "13.2.3", - "resolved": "https://registry.npmjs.org/cpy/-/cpy-13.2.3.tgz", - "integrity": "sha512-N+jPR8ODTJIzAKmCtUglRSCQzMuDkB/saH1ZJfY1MDfXYMZbfsuih3GhpUEYeuTCDQLBr4GvKyHDwV0Y2Sd0gQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "copy-file": "^11.1.0", - "globby": "^16.1.0", - "junk": "^4.0.1", - "micromatch": "^4.0.8", - "p-filter": "^4.1.0", - "p-map": "^7.0.4" - }, - "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", @@ -759,15 +209,6 @@ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", "license": "MIT" }, - "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -798,112 +239,6 @@ "node": ">= 0.4" } }, - "node_modules/esbuild": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", - "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.28.2", - "@esbuild/android-arm": "0.28.2", - "@esbuild/android-arm64": "0.28.2", - "@esbuild/android-x64": "0.28.2", - "@esbuild/darwin-arm64": "0.28.2", - "@esbuild/darwin-x64": "0.28.2", - "@esbuild/freebsd-arm64": "0.28.2", - "@esbuild/freebsd-x64": "0.28.2", - "@esbuild/linux-arm": "0.28.2", - "@esbuild/linux-arm64": "0.28.2", - "@esbuild/linux-ia32": "0.28.2", - "@esbuild/linux-loong64": "0.28.2", - "@esbuild/linux-mips64el": "0.28.2", - "@esbuild/linux-ppc64": "0.28.2", - "@esbuild/linux-riscv64": "0.28.2", - "@esbuild/linux-s390x": "0.28.2", - "@esbuild/linux-x64": "0.28.2", - "@esbuild/netbsd-arm64": "0.28.2", - "@esbuild/netbsd-x64": "0.28.2", - "@esbuild/openbsd-arm64": "0.28.2", - "@esbuild/openbsd-x64": "0.28.2", - "@esbuild/openharmony-arm64": "0.28.2", - "@esbuild/sunos-x64": "0.28.2", - "@esbuild/win32-arm64": "0.28.2", - "@esbuild/win32-ia32": "0.28.2", - "@esbuild/win32-x64": "0.28.2" - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT" - }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fastq": { - "version": "1.20.3", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", - "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", - "dev": true, - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/fresh": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", - "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", @@ -950,41 +285,6 @@ "node": ">= 0.4" } }, - "node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/globby": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/globby/-/globby-16.2.4.tgz", - "integrity": "sha512-c8B/VNLmxRcmqqenRA9t+9IyOjf9+V6lTxPaUJLqOCONdQkWZ0ETYgX0qbtJqPsgCNusT9MZ5Jeidw8Eb9tn2g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@sindresorhus/merge-streams": "^4.0.0", - "fast-glob": "^3.3.3", - "ignore": "^7.0.5", - "is-path-inside": "^4.0.0", - "micromatch": "^4.0.8", - "slash": "^5.1.0", - "unicorn-magic": "^0.4.0" - }, - "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -997,13 +297,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true, - "license": "ISC" - }, "node_modules/has-symbols": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", @@ -1064,68 +357,12 @@ "url": "https://opencollective.com/express" } }, - "node_modules/ignore": { - "version": "7.0.13", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.13.tgz", - "integrity": "sha512-2E8Q6rh+1RRSq/YdaGsNfXsEZy9FVqv6BSSrkmZJP7BnaoPnRfKL+YaofPvP+5rzdk144qSm6i4+hvPgUcbV4Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-path-inside": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-4.0.0.tgz", - "integrity": "sha512-lJJV/5dYS+RcL8uQdBDW9c9uWFLLBNRyFhnAKXw5tVqLlKZ4RMGZKv+YQ/IA3OhD+RpbJa1LLFM1FQPGyIXvOA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", @@ -1141,19 +378,6 @@ "url": "https://github.com/sponsors/panva" } }, - "node_modules/junk": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/junk/-/junk-4.0.1.tgz", - "integrity": "sha512-Qush0uP+G8ZScpGMZvHUiRfI0YBWuB3gVBYlI0v0vvOJt5FLicco+IkP0a50LqTTQhmts/m6tP5SWE+USyIvcQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -1176,30 +400,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, "node_modules/mime-db": { "version": "1.54.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", @@ -1225,12 +425,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/mithril": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/mithril/-/mithril-2.3.8.tgz", - "integrity": "sha512-za/Yo7qXEckjm5syrSfaaI9Utf4tCUT3T1IOIYqH6Lrj7G0OZuYYLAY9SV4ygoaAf0+CNqU92MBt+7pmo53JVQ==", - "license": "MIT" - }, "node_modules/morgan": { "version": "1.12.1", "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.12.1.tgz", @@ -1299,64 +493,6 @@ "node": ">= 0.8" } }, - "node_modules/p-event": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/p-event/-/p-event-6.0.1.tgz", - "integrity": "sha512-Q6Bekk5wpzW5qIyUP4gdMEujObYstZl6DMMOSenwBvV0BlE5LkDwkjs5yHbZmdCEq2o4RJx4tE1vwxFVf2FG1w==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-timeout": "^6.1.2" - }, - "engines": { - "node": ">=16.17" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-filter": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-filter/-/p-filter-4.1.0.tgz", - "integrity": "sha512-37/tPdZ3oJwHaS3gNJdenCDB3Tz26i9sjhnguBtvN0vYlRIiDNnvTWkuh+0hETV9rLPdJ3rlL3yVOYPIAnM8rw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-map": "^7.0.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-map": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.1.1.tgz", - "integrity": "sha512-6Lh3jQPLthYujSrlw6ccWXBGZTkoTCz27Hd92g79LH/kjAbgoEu0t442cCCNbegPSJsA0lwDX8z0bcKtkpA32g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-timeout": { - "version": "6.1.4", - "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-6.1.4.tgz", - "integrity": "sha512-MyIV3ZA/PmyBN/ud8vV9XzwTrNtR4jFrObymZYnZqMmW0zA8Z17vnT0rBgFE/TlohB+YCHqXMgZzb3Csp49vqg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -1376,19 +512,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/picomatch": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", - "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/qs": { "version": "6.16.1", "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz", @@ -1405,40 +528,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/range-parser": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", - "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/raw-body": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", @@ -1454,17 +543,6 @@ "node": ">= 0.10" } }, - "node_modules/reusify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", - "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, "node_modules/router": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", @@ -1504,30 +582,6 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, "node_modules/safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", @@ -1540,74 +594,6 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "license": "MIT" }, - "node_modules/send": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", - "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", - "license": "MIT", - "dependencies": { - "debug": "^4.4.3", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "fresh": "^2.0.0", - "http-errors": "^2.0.1", - "mime-types": "^3.0.2", - "ms": "^2.1.3", - "on-finished": "^2.4.1", - "range-parser": "^1.2.1", - "statuses": "^2.0.2" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/send/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/send/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/serve-static": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", - "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", - "license": "MIT", - "dependencies": { - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "parseurl": "^1.3.3", - "send": "^1.2.0" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -1686,19 +672,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/slash": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz", - "integrity": "sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -1708,19 +681,6 @@ "node": ">= 0.8" } }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, "node_modules/toidentifier": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", @@ -1748,19 +708,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/unicorn-magic": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.4.1.tgz", - "integrity": "sha512-lzlXPoVB0Uy/FvTaUgX39RbixYiSKoc3JSoSf01+0c2B6FR3qdYIPN7Qjo/AV7n6sqLCk0509cT3LRj1oSZ1+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", diff --git a/server/package.json b/server/package.json @@ -1,9 +1,6 @@ { "type": "module", "scripts": { - "build": "web/esbuild.cjs", - "assets:hex": "node scripts/generate-hex-grid.js", - "prestart": "npm run build", "start": "node src/index.js", "seed:demo": "node scripts/seed-demo.js", "test": "node --test \"test/**/*.test.js\"" @@ -14,14 +11,8 @@ "cookie": "^2.0.1", "cors": "^2.8.6", "jose": "^6.2.13", - "mithril": "^2.3.8", "morgan": "^1.12.1", "router": "^2.2.0", - "serve-static": "^2.2.1", "yaml": "^2.9.1" - }, - "devDependencies": { - "cpy": "^13.2.3", - "esbuild": "^0.28.2" } } diff --git a/server/scripts/generate-hex-grid.js b/server/scripts/generate-hex-grid.js @@ -1,89 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const SETTINGS = { - width: 1024, - height: 576, - amount: 20, - density: 1, - strokeWidth: 0.5, - baseWidth: 512, - randomFillOpacity: true, - light: { - back: '#FFF', - front: '#DDD', - }, - dark: { - back: '#000', - front: '#222', - }, -}; - -const here = path.dirname(fileURLToPath(import.meta.url)); -const assets = path.resolve(here, '../web/src/assets'); - -function randomAt(column, row) { - let value = Math.imul(column + 1000, 374761393) + Math.imul(row + 1000, 668265263); - value = Math.imul(value ^ (value >>> 13), 1274126177); - return ((value ^ (value >>> 16)) >>> 0) / 4294967295; -} - -function hexPath(cx, cy, radius, halfWidth) { - const halfHeight = radius / 2; - const points = [ - [cx, cy - radius], - [cx + halfWidth, cy - halfHeight], - [cx + halfWidth, cy + halfHeight], - [cx, cy + radius], - [cx - halfWidth, cy + halfHeight], - [cx - halfWidth, cy - halfHeight], - ].map(([x, y]) => `${Number(x.toFixed(3))} ${Number(y.toFixed(3))}`); - return `M ${points[0]} L ${points[1]} L ${points[2]} L ${points[3]} L ${points[4]} L ${points[5]} Z`; -} - -function buildSvg({ front, back }) { - const { width, height, amount, density, strokeWidth, baseWidth } = SETTINGS; - const spacing = width / amount; - const radius = (spacing / Math.sqrt(3)) * density; - const verticalSpacing = 1.5 * radius; - const stroke = strokeWidth * (width / baseWidth); - const rows = Math.ceil(height / verticalSpacing) + 1; - - const paths = []; - for (let row = -1; row <= rows; row += 1) { - const parity = ((row % 2) + 2) % 2; - const cy = radius + verticalSpacing * row; - for (let column = 0; column <= amount; column += 1) { - const cx = parity * (spacing / 2) + spacing * column; - const random = randomAt(column, row); - const opacity = !SETTINGS.randomFillOpacity - ? 1 - : random >= 0.45 - ? Number((random ** 2).toFixed(2)) - : 0; - const fill = opacity > 0 ? ` fill="${front}" fill-opacity="${opacity}"` : ' fill="none"'; - paths.push( - `<path stroke="${front}" stroke-width="${Number(stroke.toFixed(4))}"${fill} d="${hexPath( - cx, - cy, - radius, - spacing / 2 - )}"/>` - ); - } - } - - return [ - `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`, - `<rect width="100%" height="100%" fill="${back}"/>`, - ...paths, - '</svg>', - '', - ].join('\n'); -} - -fs.writeFileSync(path.join(assets, 'hex-grid-light.svg'), buildSvg(SETTINGS.light)); -fs.writeFileSync(path.join(assets, 'hex-grid-dark.svg'), buildSvg(SETTINGS.dark)); - -console.log('wrote hex-grid-light.svg and hex-grid-dark.svg'); diff --git a/server/scripts/seed-demo.js b/server/scripts/seed-demo.js @@ -309,6 +309,6 @@ console.log( 'globex-members-app, globex-public-app' ); console.log('client host: app.acme.localhost -> acme/internal-app'); -console.log('virtual clients: admin, account'); +console.log('built-in system clients: admin, account'); await closeRealms(); diff --git a/server/src/controller/app/account.js b/server/src/controller/app/account.js @@ -0,0 +1,28 @@ +import { app } from '../../app.js'; +import { serveAppDocument } from '../../lib/apps.js'; +import { resolveHostContext } from '../../lib/host-context.js'; +import { HttpError } from '../../lib/http/http-error.js'; + +export default { + mount: '/app/account', + name: 'app.account', + async handler(req, res) { + try { + await resolveHostContext(req, { + publicUrl: app.config.server.public_url, + }); + serveAppDocument(res, 'account'); + } catch (e) { + if (res.headersSent) { + res.end(); + return; + } + if (e instanceof HttpError) { + e.toResponse().send(res); + return; + } + console.error(e); + new HttpError(500, 'internal_error', 'Internal server error').toResponse().send(res); + } + }, +}; diff --git a/server/src/controller/app/admin.js b/server/src/controller/app/admin.js @@ -0,0 +1,31 @@ +import { app } from '../../app.js'; +import { serveAppDocument } from '../../lib/apps.js'; +import { resolveHostContext } from '../../lib/host-context.js'; +import { HttpError } from '../../lib/http/http-error.js'; + +export default { + mount: '/app/admin', + name: 'app.admin', + async handler(req, res) { + try { + const hostContext = await resolveHostContext(req, { + publicUrl: app.config.server.public_url, + }); + if (hostContext.mode !== 'canonical') { + throw new HttpError(404, 'not_found', 'Not found'); + } + serveAppDocument(res, 'admin'); + } catch (e) { + if (res.headersSent) { + res.end(); + return; + } + if (e instanceof HttpError) { + e.toResponse().send(res); + return; + } + console.error(e); + new HttpError(500, 'internal_error', 'Internal server error').toResponse().send(res); + } + }, +}; diff --git a/server/src/controller/login/password.js b/server/src/controller/login/password.js @@ -2,7 +2,7 @@ import { app } from '../../app.js'; import { resolveClientForHost, resolveHostContext } from '../../lib/host-context.js'; import { HttpError } from '../../lib/http/http-error.js'; import { findManagedProviderForUser, resolveLogin } from '../../lib/login.js'; -import { getClient } from '../../lib/oidc/clients.js'; +import { getClient, getSystemClient } from '../../lib/oidc/clients.js'; import { getAuthRequest, readAuthRequestId, @@ -21,6 +21,7 @@ import { requestToken, setSessionCookie, } from '../../lib/session.js'; +import { canUseSystemClient } from '../../lib/system-clients.js'; import { findUserByIdentifier, getMembership, @@ -54,11 +55,14 @@ export default { const hostContext = await resolveHostContext(req, { publicUrl: app.config.server.public_url, }); - const { realm, clientId } = await resolveClientForHost(hostContext, body.client_id); - const metadata = await realmMetadata(realm); - const realmDb = await openRealmDatabase(realm); + const target = await resolveClientForHost(hostContext, body.client_id); + const { realm, clientId, systemClient } = target; + const metadata = realm ? await realmMetadata(realm) : null; + const realmDb = realm ? await openRealmDatabase(realm) : null; const systemDb = getSystemDatabase(); - const client = await getClient(realmDb, clientId); + const client = systemClient + ? getSystemClient(clientId) + : await getClient(realmDb, clientId); if (!client || !client.enabled) { throw new HttpError(404, 'unknown_client', 'Unknown client'); } @@ -72,10 +76,11 @@ export default { const user = await findUserByIdentifier(systemDb, body.identifier); const credential = user ? await getPasswordCredential(systemDb, user.id) : null; - const membership = user ? await getMembership(realmDb, user.id) : null; - const roles = user ? await getUserRoles(realmDb, user.id) : []; - const pendingId = readAuthRequestId(req, realm); - const pending = pendingId ? await getAuthRequest(realmDb, pendingId) : null; + const membership = user && realmDb ? await getMembership(realmDb, user.id) : null; + const roles = user && realmDb ? await getUserRoles(realmDb, user.id) : []; + const store = systemClient ? systemDb : realmDb; + const pendingId = readAuthRequestId(req, target); + const pending = pendingId ? await getAuthRequest(store, pendingId) : null; const pendingClient = pending && !pending.completed_at && pending.client_id === client.client_id; if (!credential) { @@ -92,18 +97,23 @@ export default { throw new HttpError(401, 'invalid_credentials', 'Invalid credentials'); } - const allowedByPolicy = canUseClient({ - user, - membership, - roles, - client, - realm, - }); - const member = membership && membership.status === 'active'; - const publicNonMember = client.access_mode === 'public' && !client.virtual && pendingClient; - const allowed = - allowedByPolicy && - (member || client.virtual || publicNonMember || user.is_system_admin); + let allowed; + if (systemClient) { + allowed = await canUseSystemClient(systemDb, { user, client }); + } else { + const allowedByPolicy = canUseClient({ + user, + membership, + roles, + client, + realm, + }); + const member = membership && membership.status === 'active'; + const publicNonMember = client.access_mode === 'public' && pendingClient; + allowed = + allowedByPolicy && + (member || publicNonMember || user.is_system_admin); + } if (!allowed) { throw new HttpError(401, 'invalid_credentials', 'Invalid credentials'); @@ -119,7 +129,9 @@ export default { } } - const longSession = body.long_session === true && metadata.allow_session_duration_choice; + const longSession = + body.long_session === true && + (metadata?.allow_session_duration_choice ?? true); const ttl = longSession ? LONG_SESSION_TTL : SHORT_SESSION_TTL; await purgeExpiredSessions(systemDb); @@ -133,11 +145,11 @@ export default { }); const authTime = await reauthenticateSession(systemDb, { sessionId: session.id, - realmId: realm.id, + realmId: realm?.id ?? null, }); setSessionCookie(res, req, token, session.ttl); if (pendingClient && pending) { - await selectAuthRequestAccount(realmDb, pending.id, { + await selectAuthRequestAccount(store, pending.id, { userId: user.id, sessionId: session.id, authTime, diff --git a/server/src/controller/login/resolve.js b/server/src/controller/login/resolve.js @@ -1,7 +1,7 @@ import { app } from '../../app.js'; import { resolveClientForHost, resolveHostContext } from '../../lib/host-context.js'; import { resolveLogin } from '../../lib/login.js'; -import { getClient } from '../../lib/oidc/clients.js'; +import { getClient, getSystemClient } from '../../lib/oidc/clients.js'; import { HttpError } from '../../lib/http/http-error.js'; import { openRealmDatabase, realmMetadata } from '../../lib/realm.js'; @@ -21,14 +21,19 @@ export default { const hostContext = await resolveHostContext(req, { publicUrl: app.config.server.public_url, }); - const { realm, clientId } = await resolveClientForHost(hostContext, body.client_id); - const realmDb = await openRealmDatabase(realm); - const client = await getClient(realmDb, clientId); + const { realm, clientId, systemClient } = await resolveClientForHost( + hostContext, + body.client_id + ); + const realmDb = realm ? await openRealmDatabase(realm) : null; + const client = systemClient + ? getSystemClient(clientId) + : await getClient(realmDb, clientId); if (!client || !client.enabled) { throw new HttpError(404, 'unknown_client', 'Unknown client'); } - const metadata = await realmMetadata(realm); + const metadata = realm ? await realmMetadata(realm) : null; const result = await resolveLogin({ identifier: body.identifier }); return new app.HttpOk({ diff --git a/server/src/controller/oidc.js b/server/src/controller/oidc.js @@ -1,9 +1,15 @@ import crypto from 'node:crypto'; import { app } from '../app.js'; +import { + serveAppDocument, + systemClientPostLogoutUris, + systemClientRedirectUris, +} from '../lib/apps.js'; import { HttpError } from '../lib/http/http-error.js'; import { authenticateClient, getClient, + getSystemClient, postLogoutRedirectAllowed, redirectUriAllowed, } from '../lib/oidc/clients.js'; @@ -12,6 +18,7 @@ import { endpointBase, endpointUrls, resolveOidcContext, + systemIssuer, } from '../lib/oidc/context.js'; import { getJwks, signToken, verifyToken } from '../lib/oidc/keys.js'; import { @@ -27,20 +34,20 @@ import { setAuthRequestCookie, } from '../lib/oidc/requests.js'; import { canUseClient } from '../lib/policy.js'; -import { - getSystemDatabase, - openRealmDatabase, - realmMetadata, -} from '../lib/realm.js'; +import { getSystemDatabase, openRealmDatabase, realmMetadata } from '../lib/realm.js'; +import { issueRefreshToken, rotateRefreshToken } from '../lib/refresh-tokens.js'; import { authenticateRequest, bindSessionRealm, clearSessionCookie, destroySession, + findActiveSessionById, getSessionRealmBinding, listSessionAccounts, requestToken, + sessionMatchesContext, } from '../lib/session.js'; +import { canUseSystemClient } from '../lib/system-clients.js'; import { findUserById, getMembership, @@ -48,6 +55,8 @@ import { getUserRoles, } from '../lib/users.js'; +const ACCESS_TOKEN_TTL = 300; + function oidcError(status, error, description, headers = {}) { return new app.HttpResponse( status, @@ -86,33 +95,54 @@ function accessDenied(res, redirectUri, state) { ); } +function tokenStore(context, systemDb, realmDb) { + if (context.systemClient) { + return { db: systemDb, table: 'system_signing_keys' }; + } + return { db: realmDb, table: 'signing_keys' }; +} + +function tokenIssuer(context) { + return context.systemClient + ? systemIssuer(app.config.server.public_url) + : canonicalIssuer(app.config.server.public_url, context.realm.slug); +} + +function systemCallbacks(context, client) { + return client.system_client ? systemClientRedirectUris(context, client.client_id) : []; +} + async function discovery(context, client) { - const realm = await realmMetadata(context.realm); - const publicUrl = app.config.server.public_url; + const realm = context.realm ? await realmMetadata(context.realm) : null; const urls = endpointUrls(context); - const branding = Object.keys(client.branding || {}).length > 0 ? client.branding : realm.branding; + const branding = + Object.keys(client.branding || {}).length > 0 + ? client.branding + : realm?.branding || {}; const scopes = String(client.scopes || 'openid profile email') .split(/\s+/) .filter(Boolean); return new app.HttpOk( { - issuer: canonicalIssuer(publicUrl, context.realm.slug), + issuer: tokenIssuer(context), client_id: client.client_id, client_name: client.name, - realm: context.realm.slug, + realm: context.realm?.slug ?? null, display_name: client.name, branding, access_mode: client.access_mode, - virtual: Boolean(client.virtual), - allow_session_duration_choice: realm.allow_session_duration_choice, + system_client: Boolean(client.system_client), + allow_session_duration_choice: realm?.allow_session_duration_choice ?? true, authorization_endpoint: urls.authorize, token_endpoint: urls.token, userinfo_endpoint: urls.userinfo, jwks_uri: urls.jwks, end_session_endpoint: urls.logout, response_types_supported: ['code'], - grant_types_supported: ['authorization_code'], + grant_types_supported: client.system_client + ? ['authorization_code', 'refresh_token'] + : ['authorization_code'], subject_types_supported: ['public'], id_token_signing_alg_values_supported: ['ES256'], scopes_supported: scopes, @@ -141,104 +171,135 @@ async function discovery(context, client) { async function authorize(context, client, req, res) { const url = new URL(req.url, context.origin); const params = url.searchParams; - const redirectUri = params.get('redirect_uri'); - const state = params.get('state'); - const scope = params.get('scope') || 'openid'; - const clientId = params.get('client_id') || context.clientId; - const virtualCallbacks = [ - `${endpointBase(context)}/callback`, - `${context.origin}/app/${client.client_id}/callback`, - ]; - - if (!redirectUri) { - return oidcError(400, 'invalid_request', 'redirect_uri is required'); - } - if (!redirectUriAllowed(client, redirectUri, virtualCallbacks)) { - return oidcError(400, 'invalid_request', 'redirect_uri is not registered'); + const systemDb = getSystemDatabase(); + const realmDb = context.realm ? await openRealmDatabase(context.realm) : null; + const store = context.systemClient ? systemDb : realmDb; + await purgeExpired(store); + + const pendingId = readAuthRequestId(req, context); + let pending = await getAuthRequest(store, pendingId); + if (pending && (pending.completed_at || pending.client_id !== client.client_id)) { + await deleteAuthRequest(store, pending.id); + clearAuthRequestCookie(res, req, context); + pending = null; } - const fail = (error, description) => - redirect(res, withQuery(redirectUri, { error, error_description: description, state })); - - if (params.get('response_type') !== 'code') { - return fail('unsupported_response_type', 'Only response_type=code is supported'); - } - if (clientId !== client.client_id) { - return fail('invalid_request', 'client_id does not match the requested client'); - } - if (!scope.split(/\s+/).includes('openid')) { - return fail('invalid_scope', 'The openid scope is required'); - } + const callbacks = systemCallbacks(context, client); + let redirectUri = params.get('redirect_uri'); + let state = params.get('state'); + let scope = params.get('scope'); + let nonce = params.get('nonce'); + let codeChallenge = params.get('code_challenge'); + let codeChallengeMethod = params.get('code_challenge_method'); + const requestedClientId = params.get('client_id'); + + const fail = (error, description) => { + const target = pending?.redirect_uri || redirectUri; + if (!target) return oidcError(400, error, description); + return redirect( + res, + withQuery(target, { + error, + error_description: description, + state: pending?.state || state, + }) + ); + }; - const codeChallenge = params.get('code_challenge'); - const codeChallengeMethod = params.get('code_challenge_method'); - if (client.require_pkce && (!codeChallenge || codeChallengeMethod !== 'S256')) { - return fail('invalid_request', 'PKCE with S256 is required'); - } + if (pending) { + const mismatch = + (redirectUri && redirectUri !== pending.redirect_uri) || + (requestedClientId && requestedClientId !== pending.client_id) || + (params.has('response_type') && params.get('response_type') !== 'code') || + (scope && scope !== pending.scope) || + (params.has('state') && state !== pending.state) || + (params.has('nonce') && nonce !== pending.nonce) || + (codeChallenge && codeChallenge !== pending.code_challenge) || + (codeChallengeMethod && codeChallengeMethod !== pending.code_challenge_method); + + if (mismatch) { + await deleteAuthRequest(store, pending.id); + clearAuthRequestCookie(res, req, context); + return fail('invalid_request', 'The authorization request changed during login'); + } - const db = await openRealmDatabase(context.realm); - const systemDb = getSystemDatabase(); - await purgeExpired(db); - - const pendingId = readAuthRequestId(req, context.realm); - let pending = await getAuthRequest(db, pendingId); - if ( - pending && - (pending.client_id !== client.client_id || - pending.redirect_uri !== redirectUri || - pending.completed_at) - ) { - await deleteAuthRequest(db, pending.id); - pending = null; + redirectUri = pending.redirect_uri; + state = pending.state; + scope = pending.scope; + nonce = pending.nonce; + codeChallenge = pending.code_challenge; + codeChallengeMethod = pending.code_challenge_method; + } else { + if (!redirectUri) { + return oidcError(400, 'invalid_request', 'redirect_uri is required'); + } + if (!redirectUriAllowed(client, redirectUri, callbacks)) { + return oidcError(400, 'invalid_request', 'redirect_uri is not registered'); + } + if (params.get('response_type') !== 'code') { + return fail('unsupported_response_type', 'Only response_type=code is supported'); + } + if ((requestedClientId || context.clientId) !== client.client_id) { + return fail('invalid_request', 'client_id does not match the requested client'); + } + if (!scope) scope = 'openid'; + if (!scope.split(/\s+/).includes('openid')) { + return fail('invalid_scope', 'The openid scope is required'); + } + if (client.require_pkce && (!codeChallenge || codeChallengeMethod !== 'S256')) { + return fail('invalid_request', 'PKCE with S256 is required'); + } } const auth = await authenticateRequest({ systemDb, - realmDb: db, + realmDb, req, res, context, }); const allowed = auth - ? canUseClient({ - user: auth.user, - membership: auth.membership, - roles: auth.roles, - client, - realm: context.realm, - }) + ? client.system_client + ? await canUseSystemClient(systemDb, { user: auth.user, client }) + : canUseClient({ + user: auth.user, + membership: auth.membership, + roles: auth.roles, + client, + realm: context.realm, + }) : false; if (auth && !allowed) { if (pending) { - await deleteAuthRequest(db, pending.id); - clearAuthRequestCookie(res, req, context.realm); + await deleteAuthRequest(store, pending.id); + clearAuthRequestCookie(res, req, context); } return accessDenied(res, redirectUri, state); } if (!pending) { pending = { - id: await createAuthRequest(db, { + id: await createAuthRequest(store, { clientId: client.client_id, redirectUri, scope, state, - nonce: params.get('nonce'), + nonce, codeChallenge, codeChallengeMethod, }), }; if (!auth) { - setAuthRequestCookie(res, req, context.realm, pending.id); + setAuthRequestCookie(res, req, context, pending.id); return redirect(res, endpointUrls(context).login); } } if (!auth) { - setAuthRequestCookie(res, req, context.realm, pending.id); + setAuthRequestCookie(res, req, context, pending.id); return redirect(res, endpointUrls(context).login); } @@ -250,37 +311,39 @@ async function authorize(context, client, req, res) { pending.user_id === auth.user.id ); if ((pending.user_id || pending.session_id) && !selected) { - await clearAuthRequestSelection(db, pending.id); + await clearAuthRequestSelection(store, pending.id); } if (!selected && accounts.length >= 2) { - setAuthRequestCookie(res, req, context.realm, pending.id); + setAuthRequestCookie(res, req, context, pending.id); return redirect(res, endpointUrls(context).login); } - const binding = await getSessionRealmBinding( - systemDb, - auth.session.id, - context.realm.id - ); - if (binding?.revoked_at) { - await clearAuthRequestSelection(db, pending.id); - setAuthRequestCookie(res, req, context.realm, pending.id); - const login = new URL(endpointUrls(context).login); - login.searchParams.set('reauth', '1'); - return redirect(res, login.toString()); + if (context.realm) { + const binding = await getSessionRealmBinding( + systemDb, + auth.session.id, + context.realm.id + ); + if (binding?.revoked_at) { + await clearAuthRequestSelection(store, pending.id); + setAuthRequestCookie(res, req, context, pending.id); + const login = new URL(endpointUrls(context).login); + login.searchParams.set('reauth', '1'); + return redirect(res, login.toString()); + } + await bindSessionRealm(systemDb, auth.session.id, context.realm.id); } - await bindSessionRealm(systemDb, auth.session.id, context.realm.id); - await completeAuthRequest(db, pending.id, { + await completeAuthRequest(store, pending.id, { userId: auth.user.id, sessionId: auth.session.id, authTime: auth.session.auth_time, }); - const request = await getAuthRequest(db, pending.id); - const code = await createAuthorizationCode(db, request); - await deleteAuthRequest(db, pending.id); - clearAuthRequestCookie(res, req, context.realm); + const request = await getAuthRequest(store, pending.id); + const code = await createAuthorizationCode(store, request); + await deleteAuthRequest(store, pending.id); + clearAuthRequestCookie(res, req, context); return redirect(res, withQuery(redirectUri, { code, state })); } @@ -293,6 +356,67 @@ function verifyPkce(codeVerifier, challenge) { return left.length === right.length && crypto.timingSafeEqual(left, right); } +async function accessTokenResponse({ + systemDb, + realmDb, + context, + client, + user, + scope, + sessionId, + authTime, + nonce, + includeIdToken = true, +}) { + const store = tokenStore(context, systemDb, realmDb); + const issuer = tokenIssuer(context); + const email = await getPrimaryEmail(systemDb, user.id); + const roles = context.systemClient ? [] : await getUserRoles(realmDb, user.id); + + const accessClaims = { + sub: user.id, + client_id: client.client_id, + scope, + roles, + sid: sessionId || undefined, + }; + const accessToken = await signToken(store.db, accessClaims, { + issuer, + audience: client.client_id, + expiresIn: ACCESS_TOKEN_TTL, + table: store.table, + }); + + const response = { + access_token: accessToken, + token_type: 'Bearer', + expires_in: ACCESS_TOKEN_TTL, + scope, + }; + + if (includeIdToken) { + const idClaims = { + sub: user.id, + email: email?.email, + email_verified: Boolean(email?.verified), + name: user.display_name || user.username, + preferred_username: user.username, + roles, + auth_time: authTime, + sid: sessionId || undefined, + nonce: nonce || undefined, + }; + response.id_token = await signToken(store.db, idClaims, { + issuer, + audience: client.client_id, + expiresIn: ACCESS_TOKEN_TTL, + table: store.table, + }); + } + + return response; +} + async function token(context, client, req) { if (req.method !== 'POST') { return oidcError(405, 'invalid_request', 'POST is required'); @@ -304,105 +428,149 @@ async function token(context, client, req) { 'www-authenticate': 'Basic realm="oidc"', }); } - if (body.grant_type !== 'authorization_code') { - return oidcError(400, 'unsupported_grant_type', 'Only authorization_code is supported'); - } - const db = await openRealmDatabase(context.realm); const systemDb = getSystemDatabase(); - const code = await db.get( - `SELECT id, auth_request_id, client_id, user_id, redirect_uri, scope, nonce, - code_challenge, code_challenge_method, session_id, auth_time, - expires_at, consumed_at - FROM authorization_codes - WHERE id = {id}`, - { id: crypto.createHash('sha256').update(String(body.code || '')).digest('hex') } - ); + const realmDb = context.realm ? await openRealmDatabase(context.realm) : null; + const store = tokenStore(context, systemDb, realmDb); + + if (body.grant_type === 'authorization_code') { + const code = await store.db.get( + `SELECT id, auth_request_id, client_id, user_id, redirect_uri, scope, nonce, + code_challenge, code_challenge_method, session_id, auth_time, + expires_at, consumed_at + FROM authorization_codes + WHERE id = {id}`, + { id: crypto.createHash('sha256').update(String(body.code || '')).digest('hex') } + ); - if ( - !code || - code.consumed_at || - code.expires_at <= Date.now() || - code.client_id !== client.client_id - ) { - return oidcError(400, 'invalid_grant', 'The authorization code is invalid'); - } - if (body.redirect_uri !== code.redirect_uri) { - return oidcError(400, 'invalid_grant', 'redirect_uri does not match'); - } - if (code.code_challenge) { if ( - code.code_challenge_method !== 'S256' || - !verifyPkce(body.code_verifier, code.code_challenge) + !code || + code.consumed_at || + code.expires_at <= Date.now() || + code.client_id !== client.client_id ) { - return oidcError(400, 'invalid_grant', 'PKCE verification failed'); + return oidcError(400, 'invalid_grant', 'The authorization code is invalid'); + } + if (body.redirect_uri !== code.redirect_uri) { + return oidcError(400, 'invalid_grant', 'redirect_uri does not match'); + } + if (code.code_challenge) { + if ( + code.code_challenge_method !== 'S256' || + !verifyPkce(body.code_verifier, code.code_challenge) + ) { + return oidcError(400, 'invalid_grant', 'PKCE verification failed'); + } + } else if (client.require_pkce) { + return oidcError(400, 'invalid_grant', 'PKCE is required'); } - } else if (client.require_pkce) { - return oidcError(400, 'invalid_grant', 'PKCE is required'); - } - await db.run('UPDATE authorization_codes SET consumed_at = {now} WHERE id = {id}', { - now: Date.now(), - id: code.id, - }); + await store.db.run('UPDATE authorization_codes SET consumed_at = {now} WHERE id = {id}', { + now: Date.now(), + id: code.id, + }); - const user = await findUserById(systemDb, code.user_id); - if (!user || user.status !== 'active') { - return oidcError(400, 'invalid_grant', 'The user is not available'); - } + const user = await findUserById(systemDb, code.user_id); + if (!user || user.status !== 'active') { + return oidcError(400, 'invalid_grant', 'The user is not available'); + } - const membership = await getMembership(db, user.id); - const roles = await getUserRoles(db, user.id); - if ( - !canUseClient({ - user, - membership, - roles, + if (client.system_client) { + if (!(await canUseSystemClient(systemDb, { user, client }))) { + return oidcError(400, 'invalid_grant', 'The user no longer has access to this client'); + } + } else { + const membership = await getMembership(realmDb, user.id); + const roles = await getUserRoles(realmDb, user.id); + if ( + !canUseClient({ + user, + membership, + roles, + client, + realm: context.realm, + }) + ) { + return oidcError(400, 'invalid_grant', 'The user no longer has access to this client'); + } + } + + const response = await accessTokenResponse({ + systemDb, + realmDb, + context, client, - realm: context.realm, - }) - ) { - return oidcError(400, 'invalid_grant', 'The user no longer has access to this client'); + user, + scope: code.scope, + sessionId: code.session_id, + authTime: code.auth_time, + nonce: code.nonce, + }); + + if (client.system_client && code.session_id) { + const refresh = await issueRefreshToken(systemDb, { + sessionId: code.session_id, + userId: user.id, + realmId: context.realm?.id ?? null, + clientId: client.client_id, + scopes: code.scope, + }); + response.refresh_token = refresh.token; + } + + return new app.HttpOk(response, { 'cache-control': 'no-store' }); } - const email = await getPrimaryEmail(systemDb, user.id); - const issuer = canonicalIssuer(app.config.server.public_url, context.realm.slug); - const audience = client.client_id; - const expiresIn = 300; + if (body.grant_type === 'refresh_token') { + if (!client.system_client) { + return oidcError(400, 'unsupported_grant_type', 'Only authorization_code is supported'); + } - const idClaims = { - sub: user.id, - email: email?.email, - email_verified: Boolean(email?.verified), - name: user.display_name || user.username, - preferred_username: user.username, - roles, - auth_time: code.auth_time, - sid: code.session_id || undefined, - nonce: code.nonce || undefined, - }; + const rotated = await rotateRefreshToken(systemDb, body.refresh_token, { + async validate(row, tx) { + if (row.client_id !== client.client_id) return false; + if (row.realm_id !== (context.realm?.id ?? null)) return false; + + const session = await findActiveSessionById(tx, row.session_id); + if (!session || session.user_id !== row.user_id) return false; + if (!sessionMatchesContext(session, context)) return false; + + const user = await findUserById(tx, row.user_id); + if (!user || user.status !== 'active') return false; + if (!(await canUseSystemClient(tx, { user, client }))) return false; + + if (row.realm_id) { + const binding = await getSessionRealmBinding(tx, row.session_id, row.realm_id); + if (!binding || binding.revoked_at) return false; + } + return true; + }, + }); - const accessClaims = { - sub: user.id, - client_id: client.client_id, - scope: code.scope, - roles, - sid: code.session_id || undefined, - }; + if (rotated.status !== 'ok') { + return oidcError(400, 'invalid_grant', 'The refresh token is invalid'); + } - const idToken = await signToken(db, idClaims, { issuer, audience, expiresIn }); - const accessToken = await signToken(db, accessClaims, { issuer, audience, expiresIn }); + const user = await findUserById(systemDb, rotated.row.user_id); + if (!user || user.status !== 'active') { + return oidcError(400, 'invalid_grant', 'The user is not available'); + } - return new app.HttpOk( - { - access_token: accessToken, - token_type: 'Bearer', - expires_in: expiresIn, - id_token: idToken, - scope: code.scope, - }, - { 'cache-control': 'no-store' } - ); + const response = await accessTokenResponse({ + systemDb, + realmDb, + context, + client, + user, + scope: rotated.row.scopes, + sessionId: rotated.row.session_id, + includeIdToken: false, + }); + response.refresh_token = rotated.token; + return new app.HttpOk(response, { 'cache-control': 'no-store' }); + } + + return oidcError(400, 'unsupported_grant_type', 'Only authorization_code is supported'); } async function userinfo(context, client, req) { @@ -413,13 +581,15 @@ async function userinfo(context, client, req) { }); } - const db = await openRealmDatabase(context.realm); - const issuer = canonicalIssuer(app.config.server.public_url, context.realm.slug); + const systemDb = getSystemDatabase(); + const realmDb = context.realm ? await openRealmDatabase(context.realm) : null; + const store = tokenStore(context, systemDb, realmDb); let payload; try { - payload = await verifyToken(db, tokenValue, { - issuer, + payload = await verifyToken(store.db, tokenValue, { + issuer: tokenIssuer(context), audience: client.client_id, + table: store.table, }); } catch { return oidcError(401, 'invalid_token', 'The access token is invalid', { @@ -433,14 +603,16 @@ async function userinfo(context, client, req) { }); } - const systemDb = getSystemDatabase(); const user = await findUserById(systemDb, payload.sub); if (!user || user.status !== 'active') { return oidcError(401, 'invalid_token', 'The user is not available'); } + if (client.system_client && !(await canUseSystemClient(systemDb, { user, client }))) { + return oidcError(401, 'invalid_token', 'The user no longer has access to this client'); + } const email = await getPrimaryEmail(systemDb, user.id); - const roles = await getUserRoles(db, user.id); + const roles = client.system_client ? [] : await getUserRoles(realmDb, user.id); return new app.HttpOk({ sub: user.id, @@ -449,6 +621,7 @@ async function userinfo(context, client, req) { email: email?.email, email_verified: Boolean(email?.verified), roles, + is_system_admin: Boolean(user.is_system_admin), }); } @@ -456,31 +629,33 @@ async function logout(context, client, req, res) { const url = new URL(req.url, context.origin); const postLogoutUri = url.searchParams.get('post_logout_redirect_uri'); const state = url.searchParams.get('state'); - const virtualCallbacks = [ - `${endpointBase(context)}/callback`, - `${context.origin}/app/${client.client_id}/callback`, - ]; + const callbacks = client.system_client + ? systemClientPostLogoutUris(context, client.client_id) + : []; - if (!postLogoutRedirectAllowed(client, postLogoutUri, virtualCallbacks)) { + if (!postLogoutRedirectAllowed(client, postLogoutUri, callbacks)) { return oidcError(400, 'invalid_request', 'post_logout_redirect_uri is not registered'); } - const db = await openRealmDatabase(context.realm); + const systemDb = getSystemDatabase(); + const realmDb = context.realm ? await openRealmDatabase(context.realm) : null; + const store = tokenStore(context, systemDb, realmDb); const idTokenHint = url.searchParams.get('id_token_hint'); if (idTokenHint) { try { - await verifyToken(db, idTokenHint, { - issuer: canonicalIssuer(app.config.server.public_url, context.realm.slug), + await verifyToken(store.db, idTokenHint, { + issuer: tokenIssuer(context), audience: client.client_id, + table: store.table, }); } catch { return oidcError(400, 'invalid_request', 'id_token_hint is invalid'); } } - const result = await destroySession(getSystemDatabase(), requestToken(req)); + const result = await destroySession(systemDb, requestToken(req)); if (result.groupDeleted) clearSessionCookie(res, req); - clearAuthRequestCookie(res, req, context.realm); + clearAuthRequestCookie(res, req, context); if (postLogoutUri) { return redirect(res, withQuery(postLogoutUri, { state })); @@ -491,18 +666,24 @@ async function logout(context, client, req, res) { export default { mount: '/oidc', name: 'oidc', - async handler(req, res, next) { + async handler(req, res) { try { const context = await resolveOidcContext(req, { publicUrl: app.config.server.public_url, }); - if (context.action === 'login' || context.action === 'callback') { - next(); + if (context.action === 'login') { + serveAppDocument(res, 'login'); return; } + if (context.action === 'callback') { + throw new HttpError(404, 'not_found', 'Not found'); + } - const db = await openRealmDatabase(context.realm); - const client = await getClient(db, context.clientId); + const systemDb = getSystemDatabase(); + const realmDb = context.realm ? await openRealmDatabase(context.realm) : null; + const client = context.systemClient + ? getSystemClient(context.clientId) + : await getClient(realmDb, context.clientId); if (!client || !client.enabled) { throw new HttpError(404, 'unknown_client', 'Unknown client'); } @@ -513,7 +694,9 @@ export default { result = await discovery(context, client); break; case 'jwks': - result = new app.HttpOk(await getJwks(db)); + result = context.systemClient + ? new app.HttpOk(await getJwks(systemDb, { table: 'system_signing_keys' })) + : new app.HttpOk(await getJwks(realmDb)); break; case 'authorize': result = await authorize(context, client, req, res); diff --git a/server/src/controller/session/select.js b/server/src/controller/session/select.js @@ -25,15 +25,17 @@ export default { const hostContext = await resolveHostContext(req, { publicUrl: app.config.server.public_url, }); - let realm = hostContext.realm || null; - let clientId = body.client_id || hostContext.clientId || null; - if (body.client_id && hostContext.mode !== 'client') { - const resolved = await resolveClientForHost(hostContext, body.client_id); - realm = resolved.realm; - clientId = resolved.clientId; + const systemDb = getSystemDatabase(); + let target = { + realm: hostContext.realm || null, + clientId: hostContext.clientId || null, + systemClient: false, + }; + if (body.client_id) { + target = await resolveClientForHost(hostContext, body.client_id); } - const selected = await selectSessionAccount(getSystemDatabase(), { + const selected = await selectSessionAccount(systemDb, { token: requestToken(req), context: hostContext, publicId: body.public_id, @@ -43,15 +45,19 @@ export default { } let pendingAuthRequest = false; - if (realm) { - const realmDb = await openRealmDatabase(realm); - const pending = await getAuthRequest(realmDb, readAuthRequestId(req, realm)); + const store = target.systemClient + ? systemDb + : target.realm + ? await openRealmDatabase(target.realm) + : null; + if (store) { + const pending = await getAuthRequest(store, readAuthRequestId(req, target)); if ( pending && !pending.completed_at && - (!clientId || pending.client_id === clientId) + (!target.clientId || pending.client_id === target.clientId) ) { - await selectAuthRequestAccount(realmDb, pending.id, { + await selectAuthRequestAccount(store, pending.id, { userId: selected.user.id, sessionId: selected.session.id, authTime: selected.session.auth_time, diff --git a/server/src/controller/session/show.js b/server/src/controller/session/show.js @@ -27,7 +27,7 @@ export default { throw new HttpError(401, 'not_authenticated', 'Not signed in'); } if ( - hostContext.mode !== 'canonical' && + hostContext.mode === 'realm' && !isSystemAdmin(auth.user) && (!auth.membership || auth.membership.status !== 'active') ) { diff --git a/server/src/index.js b/server/src/index.js @@ -1,19 +1,16 @@ import bodyParser from 'body-parser'; import cors from 'cors'; -import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import morgan from 'morgan'; import scandir from '@finwo/scandir'; -import serveStatic from 'serve-static'; import { app } from './app.js'; import { loadConfig } from './lib/config.js'; import { closeRealms, initRealms } from './lib/realm.js'; const here = path.dirname(fileURLToPath(import.meta.url)); -const dist = path.join(here, '..', 'web', 'dist'); const cfg = loadConfig(); app.config = cfg; @@ -33,8 +30,20 @@ for (const mod of await loadModules(path.join(here, 'lib', 'http'))) { Object.assign(app, mod); } +const browserOrigins = new Set( + [cfg.server.public_url, cfg.apps?.admin, cfg.apps?.account] + .filter(Boolean) + .map((value) => new URL(value).origin) +); + app.use(morgan('tiny')); -app.use(cors()); +app.use( + cors({ + origin(origin, callback) { + callback(null, !origin || browserOrigins.has(origin)); + }, + }) +); app.use(bodyParser.json({ limit: '16kb' })); app.use(bodyParser.urlencoded({ extended: false, limit: '16kb' })); @@ -89,17 +98,6 @@ for (const route of routes) { }); } -const serve = serveStatic(dist, { - index: ['index.htm', 'index.html'], -}); - -let indexContent = null; -try { - indexContent = fs.readFileSync(path.join(dist, 'index.html')); -} catch { - indexContent = null; -} - await initRealms(cfg); const server = http.createServer((req, res) => { @@ -112,15 +110,12 @@ const server = http.createServer((req, res) => { return; } - serve(req, res, () => { - if (!indexContent) { - res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); - res.end('frontend build missing'); - return; - } - res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); - res.end(indexContent); - }); + if (res.headersSent) { + res.end(); + return; + } + res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); + res.end('Not found'); }); }); diff --git a/server/src/lib/admin-auth.js b/server/src/lib/admin-auth.js @@ -1,7 +1,7 @@ import { app } from '../app.js'; import { HttpError } from './http/http-error.js'; import { resolveHostContext } from './host-context.js'; -import { canonicalIssuer } from './oidc/context.js'; +import { systemIssuer } from './oidc/context.js'; import { verifyToken } from './oidc/keys.js'; import { isRealmAdmin, isSystemAdmin } from './policy.js'; import { getSystemDatabase, openRealmDatabase, resolveRealm } from './realm.js'; @@ -16,25 +16,22 @@ export async function authenticateAdminRequest(req, { realmSlug }) { const hostContext = await resolveHostContext(req, { publicUrl: app.config.server.public_url, }); - if (hostContext.mode === 'client') { + if (hostContext.mode !== 'canonical') { throw new HttpError(404, 'not_found', 'Not found'); } - const realm = await resolveRealm({ - host: hostContext.host, - slug: realmSlug, - }); - const realmDb = await openRealmDatabase(realm); const token = bearerToken(req); if (!token) { throw new HttpError(401, 'invalid_token', 'A bearer token is required'); } + const systemDb = getSystemDatabase(); let payload; try { - payload = await verifyToken(realmDb, token, { - issuer: canonicalIssuer(app.config.server.public_url, realm.slug), + payload = await verifyToken(systemDb, token, { + issuer: systemIssuer(app.config.server.public_url), audience: 'admin', + table: 'system_signing_keys', }); } catch { throw new HttpError(401, 'invalid_token', 'The access token is invalid'); @@ -44,7 +41,6 @@ export async function authenticateAdminRequest(req, { realmSlug }) { throw new HttpError(401, 'invalid_token', 'The access token is invalid'); } - const systemDb = getSystemDatabase(); const user = await findUserById(systemDb, payload.sub); if (!user || user.status !== 'active') { throw new HttpError(401, 'invalid_token', 'The user is not available'); @@ -60,6 +56,8 @@ export async function authenticateAdminRequest(req, { realmSlug }) { throw new HttpError(401, 'invalid_token', 'The admin session is not active'); } + const realm = await resolveRealm({ slug: realmSlug }); + const realmDb = await openRealmDatabase(realm); const membership = await getMembership(realmDb, user.id); const roles = await getUserRoles(realmDb, user.id); if ( diff --git a/server/src/lib/apps.js b/server/src/lib/apps.js @@ -0,0 +1,82 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { app } from '../app.js'; +import { canonicalBaseUrl } from './oidc/context.js'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repoRoot = path.resolve(here, '../../..'); +const appNames = ['login', 'account', 'admin']; +const cache = new Map(); + +function appDist(name) { + if (!appNames.includes(name)) throw new Error(`unknown app: ${name}`); + return path.join(repoRoot, 'app', name, 'dist'); +} + +export function appIndex(name) { + if (!cache.has(name)) { + const file = path.join(appDist(name), 'index.html'); + try { + cache.set(name, fs.readFileSync(file)); + } catch { + cache.set(name, null); + } + } + return cache.get(name); +} + +export function serveAppDocument(res, name) { + const content = appIndex(name); + if (!content) { + res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' }); + res.end(`${name} app build missing`); + return; + } + res.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': 'no-cache', + }); + res.end(content); +} + +function addOriginUrl(urls, base, pathname) { + if (!base) return; + urls.add(`${String(base).replace(/\/+$/, '')}${pathname}`); +} + +export function systemClientRedirectUris(context, clientId) { + const urls = new Set(); + const publicBase = canonicalBaseUrl(app.config.server.public_url); + + if (clientId === 'admin') { + addOriginUrl(urls, publicBase, '/app/admin/callback'); + } else if (clientId === 'account') { + addOriginUrl(urls, publicBase, '/app/account/callback'); + if (context.mode === 'realm') { + addOriginUrl(urls, context.origin, '/app/account/callback'); + } + } + + const staticOrigin = app.config.apps?.[clientId]; + addOriginUrl(urls, staticOrigin, '/callback'); + return [...urls]; +} + +export function systemClientPostLogoutUris(context, clientId) { + const urls = new Set(); + const publicBase = canonicalBaseUrl(app.config.server.public_url); + + if (clientId === 'admin') { + addOriginUrl(urls, publicBase, '/app/admin/'); + } else if (clientId === 'account') { + addOriginUrl(urls, publicBase, '/app/account/'); + if (context.mode === 'realm') { + addOriginUrl(urls, context.origin, '/app/account/'); + } + } + + const staticOrigin = app.config.apps?.[clientId]; + addOriginUrl(urls, staticOrigin, '/'); + return [...urls]; +} diff --git a/server/src/lib/config.js b/server/src/lib/config.js @@ -21,6 +21,10 @@ const DEFAULTS = { path: './data/system.sqlite', realms: './data/realms', }, + apps: { + admin: null, + account: null, + }, }; // [environment variable, dotted config path, parser] @@ -31,6 +35,8 @@ const ENV_MAP = [ ['AUTH_DATABASE_DIALECT', 'database.dialect', lower], ['AUTH_DATABASE_PATH', 'database.path', String], ['AUTH_REALMS_PATH', 'database.realms', String], + ['AUTH_ADMIN_APP_URL', 'apps.admin', String], + ['AUTH_ACCOUNT_APP_URL', 'apps.account', String], ]; function lower(v) { @@ -106,7 +112,20 @@ function validate(cfg) { } } - + for (const [name, value] of Object.entries(cfg.apps || {})) { + if (!value) continue; + try { + const url = new URL(value); + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + errors.push(`apps.${name} must use http or https`); + } + if (url.pathname !== '/' || url.search || url.hash) { + errors.push(`apps.${name} must be an origin without a path`); + } + } catch { + errors.push(`apps.${name} must be an absolute URL`); + } + } if (errors.length > 0) { throw new Error(`invalid configuration:\n - ${errors.join('\n - ')}`); diff --git a/server/src/lib/host-context.js b/server/src/lib/host-context.js @@ -1,5 +1,5 @@ import { HttpError } from './http/http-error.js'; -import { isVirtualClient } from './oidc/clients.js'; +import { isSystemClient } from './oidc/clients.js'; import { findClientRealm, findOidcClientHost, findRealmHost, normalizeHost } from './realm.js'; export async function resolveHostContext(req, { publicUrl } = {}) { @@ -41,11 +41,18 @@ export async function resolveClientForHost(context, clientId) { if (value !== context.clientId) { throw new HttpError(404, 'unknown_client', 'Unknown client'); } - return { realm: context.realm, clientId: context.clientId }; + return { realm: context.realm, clientId: context.clientId, systemClient: false }; } - if (context.mode === 'realm' && isVirtualClient(value)) { - return { realm: context.realm, clientId: value }; + if (isSystemClient(value)) { + if (value === 'admin' && context.mode !== 'canonical') { + throw new HttpError(404, 'unknown_client', 'Unknown client'); + } + return { + realm: context.mode === 'realm' ? context.realm : null, + clientId: value, + systemClient: true, + }; } const mapping = await findClientRealm(value); @@ -64,5 +71,6 @@ export async function resolveClientForHost(context, clientId) { owner_user_id: mapping.owner_user_id, }, clientId: value, + systemClient: false, }; } diff --git a/server/src/lib/oidc/clients.js b/server/src/lib/oidc/clients.js @@ -1,8 +1,8 @@ import crypto from 'node:crypto'; -const VIRTUAL_CLIENTS = { +const SYSTEM_CLIENTS = { admin: { - id: 'virtual:admin', + id: 'system:admin', client_id: 'admin', name: 'Admin', access_mode: 'admin', @@ -13,10 +13,10 @@ const VIRTUAL_CLIENTS = { post_logout_redirect_uris: [], branding: {}, required_roles: [], - virtual: true, + system_client: true, }, account: { - id: 'virtual:account', + id: 'system:account', client_id: 'account', name: 'Account', access_mode: 'public', @@ -27,7 +27,7 @@ const VIRTUAL_CLIENTS = { post_logout_redirect_uris: [], branding: {}, required_roles: [], - virtual: true, + system_client: true, }, }; @@ -43,13 +43,18 @@ export function hashClientSecret(secret) { return crypto.createHash('sha256').update(secret).digest('hex'); } -export function isVirtualClient(clientId) { - return Object.hasOwn(VIRTUAL_CLIENTS, clientId); +export function isSystemClient(clientId) { + return Object.hasOwn(SYSTEM_CLIENTS, clientId); +} + +export function getSystemClient(clientId) { + const client = SYSTEM_CLIENTS[clientId]; + return client ? { ...client } : null; } export async function getClient(db, clientId) { - const virtual = VIRTUAL_CLIENTS[clientId]; - if (virtual) return { ...virtual }; + const system = SYSTEM_CLIENTS[clientId]; + if (system) return { ...system }; const row = await db.get( `SELECT id, client_id, name, redirect_uris, scopes, access_mode, enabled, @@ -77,18 +82,18 @@ export async function getClient(db, clientId) { post_logout_redirect_uris: parseJson(row.post_logout_redirect_uris, []), branding: parseJson(row.branding, {}), required_roles: roles.map((role) => role.slug), - virtual: false, + system_client: false, }; } -export function redirectUriAllowed(client, redirectUri, virtualCallbacks = []) { - if (client.virtual) return virtualCallbacks.includes(redirectUri); +export function redirectUriAllowed(client, redirectUri, systemCallbacks = []) { + if (client.system_client) return systemCallbacks.includes(redirectUri); return client.redirect_uris.includes(redirectUri); } -export function postLogoutRedirectAllowed(client, redirectUri, virtualCallbacks = []) { +export function postLogoutRedirectAllowed(client, redirectUri, systemCallbacks = []) { if (!redirectUri) return true; - if (client.virtual) return virtualCallbacks.includes(redirectUri); + if (client.system_client) return systemCallbacks.includes(redirectUri); return client.post_logout_redirect_uris.includes(redirectUri); } diff --git a/server/src/lib/oidc/context.js b/server/src/lib/oidc/context.js @@ -1,6 +1,5 @@ import { HttpError } from '../http/http-error.js'; import { resolveClientForHost, resolveHostContext } from '../host-context.js'; -import { isVirtualClient } from './clients.js'; export function requestOrigin(req) { const forwarded = String(req.headers['x-forwarded-proto'] || '') @@ -10,9 +9,16 @@ export function requestOrigin(req) { return `${proto}://${req.headers.host}`; } +export function canonicalBaseUrl(publicUrl) { + return String(publicUrl || '').replace(/\/+$/, ''); +} + export function canonicalIssuer(publicUrl, realmSlug) { - const base = String(publicUrl || '').replace(/\/+$/, ''); - return `${base}/oidc/${encodeURIComponent(realmSlug)}`; + return `${canonicalBaseUrl(publicUrl)}/oidc/${encodeURIComponent(realmSlug)}`; +} + +export function systemIssuer(publicUrl) { + return canonicalBaseUrl(publicUrl); } function pathSegments(req) { @@ -36,6 +42,7 @@ export async function resolveOidcContext(req, { publicUrl } = {}) { origin, realm: hostContext.realm, clientId: hostContext.clientId, + systemClient: false, action: segments[0], }; } @@ -43,28 +50,15 @@ export async function resolveOidcContext(req, { publicUrl } = {}) { if (segments.length !== 2) throw new HttpError(404, 'not_found', 'Not found'); const clientId = segments[0]; const action = segments[1]; - - if (hostContext.mode === 'realm') { - const resolved = isVirtualClient(clientId) - ? { realm: hostContext.realm, clientId } - : await resolveClientForHost(hostContext, clientId); - return { - mode: 'realm', - host: hostContext.host, - origin, - realm: resolved.realm, - clientId: resolved.clientId, - action, - }; - } - const resolved = await resolveClientForHost(hostContext, clientId); + return { - mode: 'canonical', + mode: hostContext.mode, host: hostContext.host, origin, realm: resolved.realm, clientId: resolved.clientId, + systemClient: resolved.systemClient, action, }; } diff --git a/server/src/lib/oidc/keys.js b/server/src/lib/oidc/keys.js @@ -8,11 +8,17 @@ import { } from 'jose'; const pending = new WeakMap(); +const SIGNING_KEY_TABLES = new Set(['signing_keys', 'system_signing_keys']); -async function loadSigningKey(db) { +function signingKeyTable(name) { + if (!SIGNING_KEY_TABLES.has(name)) throw new Error(`unknown signing key table: ${name}`); + return name; +} + +async function loadSigningKey(db, table) { const row = await db.get( `SELECT id, alg, private_jwk, public_jwk - FROM signing_keys + FROM ${table} WHERE status = 'active' ORDER BY created_at DESC LIMIT 1` @@ -39,7 +45,7 @@ async function loadSigningKey(db) { publicJwk.use = 'sig'; await db.run( - `INSERT INTO signing_keys (id, alg, private_jwk, public_jwk, status, created_at) + `INSERT INTO ${table} (id, alg, private_jwk, public_jwk, status, created_at) VALUES ({id}, 'ES256', {privateJwk}, {publicJwk}, 'active', {createdAt})`, { id, @@ -52,22 +58,32 @@ async function loadSigningKey(db) { return { id, alg: 'ES256', privateJwk, publicJwk }; } -export function ensureSigningKey(db) { - let promise = pending.get(db); +export function ensureSigningKey(db, tableName = 'signing_keys') { + const table = signingKeyTable(tableName); + let tables = pending.get(db); + if (!tables) { + tables = new Map(); + pending.set(db, tables); + } + let promise = tables.get(table); if (!promise) { - promise = loadSigningKey(db); - pending.set(db, promise); + promise = loadSigningKey(db, table); + tables.set(table, promise); } return promise; } -export async function getJwks(db) { - const key = await ensureSigningKey(db); +export async function getJwks(db, { table = 'signing_keys' } = {}) { + const key = await ensureSigningKey(db, table); return { keys: [key.publicJwk] }; } -export async function signToken(db, claims, { issuer, audience, expiresIn }) { - const key = await ensureSigningKey(db); +export async function signToken( + db, + claims, + { issuer, audience, expiresIn, table = 'signing_keys' } +) { + const key = await ensureSigningKey(db, table); const privateKey = await importJWK(key.privateJwk, key.alg); const now = Math.floor(Date.now() / 1000); @@ -80,8 +96,12 @@ export async function signToken(db, claims, { issuer, audience, expiresIn }) { .sign(privateKey); } -export async function verifyToken(db, token, { issuer, audience }) { - const key = await ensureSigningKey(db); +export async function verifyToken( + db, + token, + { issuer, audience, table = 'signing_keys' } +) { + const key = await ensureSigningKey(db, table); const publicKey = await importJWK(key.publicJwk, key.alg); const { payload } = await jwtVerify(token, publicKey, { issuer, audience }); return payload; diff --git a/server/src/lib/oidc/requests.js b/server/src/lib/oidc/requests.js @@ -4,8 +4,14 @@ import { parseCookie, stringifySetCookie } from 'cookie'; const AUTH_REQUEST_TTL = 10 * 60; const CODE_TTL = 60; -export function authRequestCookieName(realm) { - return `auth_request_${realm.slug}`; +function authRequestScopeName(scope) { + if (scope.systemClient) return `system_${scope.clientId}`; + if (!scope.realm?.slug) throw new Error('auth request scope requires a realm'); + return scope.realm.slug; +} + +export function authRequestCookieName(scope) { + return `auth_request_${authRequestScopeName(scope)}`; } function secureRequest(req) { @@ -24,11 +30,11 @@ function appendSetCookie(res, value) { res.setHeader('Set-Cookie', [...values, value]); } -export function setAuthRequestCookie(res, req, realm, id, ttl = AUTH_REQUEST_TTL) { +export function setAuthRequestCookie(res, req, scope, id, ttl = AUTH_REQUEST_TTL) { appendSetCookie( res, stringifySetCookie({ - name: authRequestCookieName(realm), + name: authRequestCookieName(scope), value: id, httpOnly: true, sameSite: 'lax', @@ -39,11 +45,11 @@ export function setAuthRequestCookie(res, req, realm, id, ttl = AUTH_REQUEST_TTL ); } -export function clearAuthRequestCookie(res, req, realm) { +export function clearAuthRequestCookie(res, req, scope) { appendSetCookie( res, stringifySetCookie({ - name: authRequestCookieName(realm), + name: authRequestCookieName(scope), value: '', httpOnly: true, sameSite: 'lax', @@ -54,9 +60,9 @@ export function clearAuthRequestCookie(res, req, realm) { ); } -export function readAuthRequestId(req, realm) { +export function readAuthRequestId(req, scope) { const cookies = parseCookie(req.headers.cookie || ''); - return cookies[authRequestCookieName(realm)] || null; + return cookies[authRequestCookieName(scope)] || null; } export async function purgeExpired(db, now = Date.now()) { diff --git a/server/src/lib/policy.js b/server/src/lib/policy.js @@ -13,11 +13,6 @@ export function canUseClient({ user, membership, roles, client, realm }) { const requiredRoles = Array.isArray(client.required_roles) ? client.required_roles : []; const roleOk = requiredRoles.length === 0 || requiredRoles.some((role) => roles.includes(role)); - if (client.virtual && client.client_id === 'admin') { - if (isSystemAdmin(user)) return true; - return Boolean(membership && membership.status === 'active' && roles.includes('realm-admin')); - } - if (client.access_mode === 'public') return true; if (!membership || membership.status !== 'active') return false; diff --git a/server/src/lib/realm.js b/server/src/lib/realm.js @@ -4,6 +4,7 @@ import crypto from 'node:crypto'; import { openDatabase, runMigrations } from './db/index.js'; import { MIGRATIONS_ROOT } from './db/migrate.js'; import { HttpError } from './http/http-error.js'; +import { isSystemClient } from './oidc/clients.js'; let systemDb = null; let dialect = 'sqlite'; @@ -287,6 +288,9 @@ export async function addClientRealm(clientId, realmId) { if (!/^[a-z0-9][a-z0-9-]*$/.test(value)) { throw new Error(`invalid client id: ${JSON.stringify(clientId)}`); } + if (isSystemClient(value)) { + throw new Error(`client id is reserved: ${value}`); + } const existing = await findClientRealm(value); if (existing) { if (existing.realm_id === realmId) return existing; diff --git a/server/src/lib/refresh-tokens.js b/server/src/lib/refresh-tokens.js @@ -0,0 +1,130 @@ +import crypto from 'node:crypto'; + +export const REFRESH_TOKEN_TTL = 7 * 24 * 60 * 60; + +function hashToken(token) { + return crypto.createHash('sha256').update(String(token || '')).digest('hex'); +} + +function nextToken() { + return crypto.randomBytes(32).toString('base64url'); +} + +async function insertRefreshToken(tx, { + token, + familyId, + sessionId, + userId, + realmId, + clientId, + scopes, + now, +}) { + const id = hashToken(token); + const expiresAt = now + REFRESH_TOKEN_TTL * 1000; + await tx.run( + `INSERT INTO refresh_tokens + (id, family_id, session_id, user_id, realm_id, client_id, scopes, + created_at, expires_at, consumed_at, replaced_by, revoked_at) + VALUES + ({id}, {familyId}, {sessionId}, {userId}, {realmId}, {clientId}, {scopes}, + {now}, {expiresAt}, NULL, NULL, NULL)`, + { + id, + familyId, + sessionId, + userId, + realmId, + clientId, + scopes, + now, + expiresAt, + } + ); + return { id, token, expiresAt }; +} + +export async function issueRefreshToken( + systemDb, + { sessionId, userId, realmId = null, clientId, scopes, now = Date.now() } +) { + const familyId = crypto.randomUUID(); + const token = nextToken(); + return systemDb.transaction((tx) => + insertRefreshToken(tx, { + token, + familyId, + sessionId, + userId, + realmId, + clientId, + scopes, + now, + }) + ); +} + +async function revokeFamily(tx, familyId, now) { + await tx.run( + `UPDATE refresh_tokens + SET revoked_at = {now} + WHERE family_id = {familyId} AND revoked_at IS NULL`, + { familyId, now } + ); +} + +export async function rotateRefreshToken( + systemDb, + token, + { validate, now = Date.now() } = {} +) { + if (!token) return { status: 'invalid' }; + + return systemDb.transaction(async (tx) => { + const row = await tx.get( + `SELECT id, family_id, session_id, user_id, realm_id, client_id, scopes, + created_at, expires_at, consumed_at, replaced_by, revoked_at + FROM refresh_tokens + WHERE id = {id}`, + { id: hashToken(token) } + ); + if (!row || row.revoked_at) return { status: 'invalid' }; + if (row.consumed_at) { + await revokeFamily(tx, row.family_id, now); + return { status: 'reuse' }; + } + if (row.expires_at <= now) return { status: 'expired' }; + + if (validate && !(await validate(row, tx))) { + await revokeFamily(tx, row.family_id, now); + return { status: 'denied' }; + } + + const next = nextToken(); + const nextId = hashToken(next); + const expiresAt = now + REFRESH_TOKEN_TTL * 1000; + await tx.run( + `UPDATE refresh_tokens + SET consumed_at = {now}, replaced_by = {nextId} + WHERE id = {id}`, + { now, nextId, id: row.id } + ); + await insertRefreshToken(tx, { + token: next, + familyId: row.family_id, + sessionId: row.session_id, + userId: row.user_id, + realmId: row.realm_id, + clientId: row.client_id, + scopes: row.scopes, + now, + }); + + return { + status: 'ok', + token: next, + expiresAt, + row, + }; + }); +} diff --git a/server/src/lib/session.js b/server/src/lib/session.js @@ -96,6 +96,21 @@ function scopeMatches(session, context) { ); } +export function sessionMatchesContext(session, context) { + return scopeMatches(session, context); +} + +export async function findActiveSessionById(systemDb, sessionId, now = Date.now()) { + return systemDb.get( + `SELECT id, public_id, group_id, user_id, scope_type, scope_host, realm_id, + client_id, ttl, auth_time, created_at, expires_at, last_seen_at, + user_agent, ip + FROM sessions + WHERE id = {id} AND expires_at > {now}`, + { id: sessionId, now } + ); +} + async function findGroupByToken(systemDb, token) { if (!token) return null; return systemDb.get( diff --git a/server/src/lib/system-clients.js b/server/src/lib/system-clients.js @@ -0,0 +1,32 @@ +import { isSystemAdmin } from './policy.js'; +import { openRealmDatabase } from './realm.js'; +import { getMembership, getUserRoles } from './users.js'; + +export async function listAdminRealms(systemDb, user) { + const realms = await systemDb.all( + 'SELECT id, slug, db_file, owner_user_id FROM realms ORDER BY slug ASC' + ); + if (isSystemAdmin(user)) return realms; + + const accessible = []; + for (const realm of realms) { + try { + const db = await openRealmDatabase(realm); + const membership = await getMembership(db, user.id); + if (membership?.status !== 'active') continue; + const roles = await getUserRoles(db, user.id); + if (roles.includes('realm-admin')) accessible.push(realm); + } catch { + continue; + } + } + return accessible; +} + +export async function canUseSystemClient(systemDb, { user, client }) { + if (!user || user.status !== 'active' || !client?.enabled) return false; + if (client.client_id === 'account') return true; + if (client.client_id !== 'admin') return false; + if (isSystemAdmin(user)) return true; + return (await listAdminRealms(systemDb, user)).length > 0; +} diff --git a/server/test/config.test.js b/server/test/config.test.js @@ -107,6 +107,22 @@ test('a non-integer port names the environment variable', async () => { ); }); +test('static app origins are origins without paths', async () => { + await inTempDir(() => + withEnv( + { + AUTH_DATABASE_PATH: './data/system.sqlite', + AUTH_REALMS_PATH: './data/realms', + AUTH_ADMIN_APP_URL: 'https://admin.example.com', + AUTH_ACCOUNT_APP_URL: 'https://account.example.com/app', + }, + () => { + assert.throws(() => loadConfig(), /apps\.account/); + } + ) + ); +}); + test('environment variables override the YAML file', async () => { await inTempDir(async () => { await fs.writeFile( diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -230,6 +230,8 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { AUTH_REALMS_PATH: path.join(dir, 'realms'), AUTH_PORT: String(port), AUTH_PUBLIC_URL: publicUrl, + AUTH_ADMIN_APP_URL: `http://admin.test:${port}`, + AUTH_ACCOUNT_APP_URL: `http://account.test:${port}`, }; const origin = (host) => `http://${host}:${port}`; @@ -267,7 +269,10 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(login.status, 200); jar = mergeCookies(jar, login); - const second = await requester({ path: authorizePath, cookie: jar }); + const second = await requester({ + path: authorizePath.split('?')[0], + cookie: jar, + }); assert.equal(second.status, 302); const code = locationQuery(second).searchParams.get('code'); assert.ok(code); @@ -284,7 +289,19 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }, }); assert.equal(tokenResponse.status, 200); - return { access_token: tokenResponse.json.access_token, cookie: jar }; + return { + access_token: tokenResponse.json.access_token, + refresh_token: tokenResponse.json.refresh_token, + cookie: jar, + }; + } + + async function adminToken(identifier = 'admin@system.test') { + return accessToken(identity, { + clientId: 'admin', + identifier, + redirectUri: `${origin('identity.test')}/app/admin/callback`, + }); } await t.test('realm metadata is served for a realm hostname', async () => { @@ -355,16 +372,24 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(otherRealm.json.issuer, `${publicUrl}/oidc/globex`); }); - await t.test('virtual clients are discoverable', async () => { - const admin = await acme({ path: '/oidc/admin/openid-configuration' }); + await t.test('system clients are discoverable on their allowed hosts', async () => { + const admin = await identity({ path: '/oidc/admin/openid-configuration' }); assert.equal(admin.status, 200); - assert.equal(admin.json.virtual, true); + assert.equal(admin.json.system_client, true); assert.equal(admin.json.access_mode, 'admin'); + assert.equal(admin.json.issuer, publicUrl); - const account = await acme({ path: '/oidc/account/openid-configuration' }); + const adminRealm = await acme({ path: '/oidc/admin/openid-configuration' }); + assert.equal(adminRealm.status, 404); + + const account = await identity({ path: '/oidc/account/openid-configuration' }); assert.equal(account.status, 200); - assert.equal(account.json.virtual, true); + assert.equal(account.json.system_client, true); assert.equal(account.json.access_mode, 'public'); + + const accountRealm = await acme({ path: '/oidc/account/openid-configuration' }); + assert.equal(accountRealm.status, 200); + assert.equal(accountRealm.json.system_client, true); }); await t.test('identifier resolution selects password or upstream OIDC', async () => { @@ -1016,48 +1041,151 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(tokenResponse.status, 200); }); - await t.test('system admins can use the admin virtual client', async () => { - const redirectUri = `${origin('acme.localhost')}/oidc/admin/callback`; - const { verifier, challenge } = pkce(); - const authorizePath = - `/oidc/admin/authorize?response_type=code&client_id=admin` + - `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20profile` + - `&state=state-3&code_challenge=${challenge}&code_challenge_method=S256`; + await t.test('system admins can use the admin client on the canonical host', async () => { + const admin = await adminToken(); + assert.ok(admin.access_token); + assert.ok(admin.refresh_token); - const first = await acme({ path: authorizePath }); - assert.equal(first.status, 302); - let jar = mergeCookies('', first); + const discovery = await identity({ path: '/oidc/admin/openid-configuration' }); + assert.equal(discovery.status, 200); + assert.equal(discovery.json.issuer, publicUrl); + assert.ok(discovery.json.grant_types_supported.includes('refresh_token')); - const login = await acme({ + const userinfo = await identity({ + path: '/oidc/admin/userinfo', + bearer: admin.access_token, + }); + assert.equal(userinfo.status, 200); + assert.equal(userinfo.json.preferred_username, 'admin'); + assert.equal(userinfo.json.is_system_admin, true); + + const refreshed = await identity({ method: 'POST', - path: '/api/v1/login/password', - body: { client_id: 'admin', identifier: 'admin@system.test', password: 'demo' }, - cookie: jar, + path: '/oidc/admin/token', + form: { + grant_type: 'refresh_token', + client_id: 'admin', + refresh_token: admin.refresh_token, + }, }); - assert.equal(login.status, 200); - jar = mergeCookies(jar, login); + assert.equal(refreshed.status, 200); + assert.ok(refreshed.json.access_token); + assert.ok(refreshed.json.refresh_token); + assert.notEqual(refreshed.json.refresh_token, admin.refresh_token); - const second = await acme({ path: authorizePath, cookie: jar }); - assert.equal(second.status, 302); - const code = locationQuery(second).searchParams.get('code'); - assert.ok(code); + const reused = await identity({ + method: 'POST', + path: '/oidc/admin/token', + form: { + grant_type: 'refresh_token', + client_id: 'admin', + refresh_token: admin.refresh_token, + }, + }); + assert.equal(reused.status, 400); + assert.equal(reused.json.error, 'invalid_grant'); - const tokenResponse = await acme({ + const revoked = await identity({ method: 'POST', path: '/oidc/admin/token', form: { - grant_type: 'authorization_code', - code, - redirect_uri: redirectUri, + grant_type: 'refresh_token', client_id: 'admin', - code_verifier: verifier, + refresh_token: refreshed.json.refresh_token, }, }); - assert.equal(tokenResponse.status, 200); + assert.equal(revoked.status, 400); + }); + + await t.test('configured static app callbacks are accepted', async () => { + const admin = await accessToken(identity, { + clientId: 'admin', + identifier: 'admin@system.test', + redirectUri: `http://admin.test:${port}/callback`, + }); + assert.ok(admin.access_token); + + const account = await accessToken(identity, { + clientId: 'account', + identifier: 'guest@personal.test', + redirectUri: `http://account.test:${port}/callback`, + }); + assert.ok(account.access_token); + }); + + await t.test('split apps are served on their allowed hosts', async (t) => { + const admin = await identity({ path: '/app/admin' }); + if (admin.status === 503) { + t.skip('app builds are not available'); + return; + } + assert.equal(admin.status, 200); + assert.match(admin.headers['content-type'], /text\/html/); + assert.match(admin.text, /admin-app/); + + const adminRealm = await acme({ path: '/app/admin' }); + assert.equal(adminRealm.status, 404); + + const accountCanonical = await identity({ path: '/app/account' }); + assert.equal(accountCanonical.status, 200); + assert.match(accountCanonical.text, /account-app/); + + const accountRealm = await acme({ path: '/app/account' }); + assert.equal(accountRealm.status, 200); + + const accountClient = await app({ path: '/app/account' }); + assert.equal(accountClient.status, 200); + + const login = await identity({ path: '/oidc/admin/login' }); + assert.equal(login.status, 200); + assert.match(login.text, /auth-page/); + + const loginRealm = await acme({ path: '/oidc/admin/login' }); + assert.equal(loginRealm.status, 404); + }); + + await t.test('account clients work for guests on canonical and realm hosts', async (t) => { + const canonical = await identity({ path: '/oidc/account/openid-configuration' }); + assert.equal(canonical.status, 200); + assert.equal(canonical.json.issuer, publicUrl); + + const realmHost = await acme({ path: '/oidc/account/openid-configuration' }); + assert.equal(realmHost.status, 200); + assert.equal(realmHost.json.issuer, publicUrl); + + const clientHost = await app({ path: '/oidc/account/openid-configuration' }); + assert.equal(clientHost.status, 404); + + const account = await accessToken(acme, { + clientId: 'account', + identifier: 'guest@personal.test', + redirectUri: `${origin('acme.localhost')}/app/account/callback`, + }); + assert.ok(account.access_token); + assert.ok(account.refresh_token); + + const userinfo = await acme({ + path: '/oidc/account/userinfo', + bearer: account.access_token, + }); + assert.equal(userinfo.status, 200); + assert.equal(userinfo.json.preferred_username, 'guest'); + + const refreshed = await acme({ + method: 'POST', + path: '/oidc/account/token', + form: { + grant_type: 'refresh_token', + client_id: 'account', + refresh_token: account.refresh_token, + }, + }); + assert.equal(refreshed.status, 200); + assert.ok(refreshed.json.refresh_token); }); await t.test('admin session APIs require an active admin token', async () => { - const missing = await acme({ path: '/api/v1/admin/realms/acme/sessions' }); + const missing = await identity({ path: '/api/v1/admin/realms/acme/sessions' }); assert.equal(missing.status, 401); assert.equal(missing.json.error.code, 'invalid_token'); @@ -1066,7 +1194,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { identifier: 'alice@acme.test', redirectUri: `${origin('app.acme.localhost')}/callback`, }); - const wrongAudience = await acme({ + const wrongAudience = await identity({ path: '/api/v1/admin/realms/acme/sessions', bearer: alice.access_token, }); @@ -1098,12 +1226,8 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); const contractorPublicId = activeSessionPublicId(env, contractor.cookie); - const admin = await accessToken(acme, { - clientId: 'admin', - identifier: 'it@acme.test', - redirectUri: `${origin('acme.localhost')}/oidc/admin/callback`, - }); - const response = await acme({ + const admin = await adminToken('it@acme.test'); + const response = await identity({ path: '/api/v1/admin/realms/acme/sessions', bearer: admin.access_token, }); @@ -1133,11 +1257,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); await t.test('guest realm admins can revoke realm access but not terminate', async () => { - const admin = await accessToken(globex, { - clientId: 'admin', - identifier: 'contractor@personal.test', - redirectUri: `${origin('globex.localhost')}/oidc/admin/callback`, - }); + const admin = await adminToken('contractor@personal.test'); const alice = await accessToken(globex, { clientId: 'globex-members-app', identifier: 'alice@acme.test', @@ -1145,7 +1265,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); const alicePublicId = activeSessionPublicId(env, alice.cookie); - const list = await globex({ + const list = await identity({ path: '/api/v1/admin/realms/globex/sessions', bearer: admin.access_token, }); @@ -1156,7 +1276,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { false ); - const revoked = await globex({ + const revoked = await identity({ method: 'DELETE', path: `/api/v1/admin/realms/globex/sessions/${alicePublicId}/realm`, bearer: admin.access_token, @@ -1199,7 +1319,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(reauthLocation.pathname, '/oidc/globex-members-app/login'); assert.equal(reauthLocation.searchParams.get('reauth'), '1'); - const terminate = await globex({ + const terminate = await identity({ method: 'DELETE', path: `/api/v1/admin/realms/globex/sessions/${alicePublicId}`, bearer: admin.access_token, @@ -1215,11 +1335,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); await t.test('home realm admins terminate only the selected session', async () => { - const admin = await accessToken(acme, { - clientId: 'admin', - identifier: 'it@acme.test', - redirectUri: `${origin('acme.localhost')}/oidc/admin/callback`, - }); + const admin = await adminToken('it@acme.test'); const aliceAcme = await acme({ method: 'POST', @@ -1235,7 +1351,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { redirectUri: `${origin('members.localhost')}/callback`, }); - const terminated = await acme({ + const terminated = await identity({ method: 'DELETE', path: `/api/v1/admin/realms/acme/sessions/${aliceAcmePublicId}`, bearer: admin.access_token, @@ -1283,12 +1399,8 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { (account) => account.user.username === 'alice' ); - const admin = await accessToken(acme, { - clientId: 'admin', - identifier: 'it@acme.test', - redirectUri: `${origin('acme.localhost')}/oidc/admin/callback`, - }); - const terminated = await acme({ + const admin = await adminToken('it@acme.test'); + const terminated = await identity({ method: 'DELETE', path: `/api/v1/admin/realms/acme/sessions/${aliceAccount.public_id}`, bearer: admin.access_token, @@ -1305,11 +1417,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); await t.test('system admins can terminate guest sessions', async () => { - const admin = await accessToken(globex, { - clientId: 'admin', - identifier: 'admin@system.test', - redirectUri: `${origin('globex.localhost')}/oidc/admin/callback`, - }); + const admin = await adminToken(); const alice = await accessToken(globex, { clientId: 'globex-members-app', identifier: 'alice@acme.test', @@ -1317,7 +1425,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); const alicePublicId = activeSessionPublicId(env, alice.cookie); - const list = await globex({ + const list = await identity({ path: '/api/v1/admin/realms/globex/sessions', bearer: admin.access_token, }); @@ -1328,7 +1436,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { true ); - const terminated = await globex({ + const terminated = await identity({ method: 'DELETE', path: `/api/v1/admin/realms/globex/sessions/${alicePublicId}`, bearer: admin.access_token, @@ -1343,19 +1451,21 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); await t.test('admin token sessions and realms are enforced', async () => { - const admin = await accessToken(acme, { - clientId: 'admin', - identifier: 'it@acme.test', - redirectUri: `${origin('acme.localhost')}/oidc/admin/callback`, - }); + const admin = await adminToken('it@acme.test'); const adminPublicId = activeSessionPublicId(env, admin.cookie); - const otherRealm = await acme({ + const otherRealm = await identity({ path: '/api/v1/admin/realms/globex/sessions', bearer: admin.access_token, }); - assert.equal(otherRealm.status, 404); - assert.equal(otherRealm.json.error.code, 'unknown_realm'); + assert.equal(otherRealm.status, 403); + assert.equal(otherRealm.json.error.code, 'forbidden'); + + const realmHost = await acme({ + path: '/api/v1/admin/realms/acme/sessions', + bearer: admin.access_token, + }); + assert.equal(realmHost.status, 404); const clientHost = await app({ path: '/api/v1/admin/realms/acme/sessions', @@ -1369,14 +1479,14 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); assert.equal(canonical.status, 200); - const terminated = await acme({ + const terminated = await identity({ method: 'DELETE', path: `/api/v1/admin/realms/acme/sessions/${adminPublicId}`, bearer: admin.access_token, }); assert.equal(terminated.status, 200); - const deadToken = await acme({ + const deadToken = await identity({ path: '/api/v1/admin/realms/acme/sessions', bearer: admin.access_token, }); @@ -1385,11 +1495,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); await t.test('admin access is re-read from the realm database', async () => { - const admin = await accessToken(acme, { - clientId: 'admin', - identifier: 'it@acme.test', - redirectUri: `${origin('acme.localhost')}/oidc/admin/callback`, - }); + const admin = await adminToken('it@acme.test'); const actor = withSystemDatabase(env, (database) => database.prepare('SELECT id FROM users WHERE username = ?').get('acme-it') ); @@ -1404,7 +1510,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }); try { - const response = await acme({ + const response = await identity({ path: '/api/v1/admin/realms/acme/sessions', bearer: admin.access_token, }); diff --git a/server/test/policy.test.js b/server/test/policy.test.js @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { canManageUser, canUseClient, isRealmAdmin, isSystemAdmin } from '../src/lib/policy.js'; +import { getSystemClient, isSystemClient } from '../src/lib/oidc/clients.js'; const realm = { id: 'realm-a' }; const user = { id: 'u1', status: 'active', home_realm_id: 'realm-a' }; @@ -60,42 +61,12 @@ test('disabled users and clients are denied', () => { ); }); -test('virtual admin clients accept system admins and realm admins', () => { - const adminClient = { ...client('admin'), virtual: true, client_id: 'admin' }; - const systemAdmin = { ...guest, is_system_admin: 1 }; - - assert.equal( - canUseClient({ user: systemAdmin, membership: null, roles: [], client: adminClient, realm }), - true - ); - assert.equal( - canUseClient({ - user: guest, - membership: activeMembership, - roles: ['realm-admin'], - client: adminClient, - realm, - }), - true - ); - assert.equal( - canUseClient({ - user: guest, - membership: activeMembership, - roles: [], - client: adminClient, - realm, - }), - false - ); -}); - -test('virtual account clients accept every active user', () => { - const accountClient = { ...client('public'), virtual: true, client_id: 'account' }; - assert.equal( - canUseClient({ user: guest, membership: null, roles: [], client: accountClient, realm }), - true - ); +test('admin and account are built-in system clients', () => { + assert.equal(isSystemClient('admin'), true); + assert.equal(isSystemClient('account'), true); + assert.equal(isSystemClient('internal-app'), false); + assert.equal(getSystemClient('admin').system_client, true); + assert.equal(getSystemClient('missing'), null); assert.equal(isSystemAdmin({ is_system_admin: 1 }), true); assert.equal(isSystemAdmin({ is_system_admin: 0 }), false); }); diff --git a/server/test/realm.test.js b/server/test/realm.test.js @@ -86,6 +86,8 @@ test('client IDs are globally unique and client hosts resolve through mappings', /already assigned/ ); await assert.rejects(() => addClientRealm('Bad App', acme.id), /invalid client id/); + await assert.rejects(() => addClientRealm('admin', acme.id), /reserved/); + await assert.rejects(() => addClientRealm('account', acme.id), /reserved/); await addOidcClientHost('shared-app', 'app.acme.localhost'); const clientHost = await findOidcClientHost('app.acme.localhost:3000'); diff --git a/server/web/esbuild.cjs b/server/web/esbuild.cjs @@ -1,103 +0,0 @@ -#!/usr/bin/env node - -// require('dotenv').config(); -const cpy = require('cpy').default; -const fs = require('node:fs'); -const esbuild = require('esbuild'); -// const { nodeModulesPolyfillPlugin } = require('esbuild-plugins-node-modules-polyfill'); - -// const __dirname = dirname(fileURLToPath(import.meta.url)); - -const entryPoints = { - 'main': __dirname + '/src/main.ts', -}; - -const config = { - format: 'iife', // immediately invoked function expression - platform: 'browser', - target: ['chrome108','firefox107'], - mainFields: ['browser','module','main'], - bundle: true, - outdir: __dirname + '/dist', - entryPoints: [ - ...Object.values(entryPoints), - // __dirname+'/src/service-worker.ts', - ], - minify: false, - // define, - - jsxFactory : 'm', - jsxFragment : '"["', - - loader: { - '.eot' : 'dataurl', - '.html' : 'text', - '.wasm' : 'dataurl', - '.png' : 'dataurl', - '.svg' : 'dataurl', - '.ttf' : 'dataurl', - '.woff' : 'dataurl', - '.woff2': 'dataurl', - }, - - // Kept for when a Buffer is needed. - // plugins: [ - // nodeModulesPolyfillPlugin({ - // globals: { - // Buffer: true - // } - // }) - // ], - -}; - -const buildList = []; -const styles = ['assets/global.css']; - -esbuild - .build(config) - .then(async () => { - - try { fs.mkdirSync('./dist/assets'); } catch { /* empty */ } - // Already rendered at every size by util/icon.js, so only copied here. - await cpy(__dirname + '/src/assets/**/*', __dirname + '/dist/assets'); - for(const name of Object.keys(entryPoints)) { - buildList.push(`${name}.js`); - try { - fs.statSync(config.outdir + `/${name}.css`); - styles.push(`${name}.css`); - } catch(e) { - // Intentionally empty - } - } - - fs.writeFileSync(config.outdir + `/index.html`, `<!DOCTYPE html> -<html> - <head> - <meta charset="utf-8"> - <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0"> - <title>auth</title> - ${styles.map(name => `<link rel="stylesheet" href="/${name}"/>`).join('\n ')} - </head> - <body> - ${buildList.map(name => `<script src="/${name}" defer></script>`).join('\n ')} - </body> -</html> -`); - - // const files = await new Promise(done => { - // exec(`find ${config.outdir} -type f`, (err,stdout, stderr) => { - // done(stdout - // .split('\n') - // .map(file => file.slice(config.outdir.length)) - // .filter(file => file) - // ); - // }); - // }); - // let sw = fs.readFileSync(`${config.outdir}/service-worker.js`, 'utf-8') - // .split('"--FILES--"').join(JSON.stringify(['/',...files])); - // fs.writeFileSync(`${config.outdir}/service-worker.js`, sw); - }) - // Without this a failed build still exits 0, and the image ships empty. - .catch(e => { console.error(e); process.exit(1); }); - diff --git a/server/web/src/assets/global.css b/server/web/src/assets/global.css @@ -1,258 +0,0 @@ -:root { - font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; - --realm-primary: #25A; -} - -*, -*::before, -*::after { - box-sizing: border-box; -} - -html, -body { - margin: 0; - padding: 0; -} - -.auth-page { - min-height: 100vh; - display: flex; - justify-content: center; - align-items: flex-start; - padding: 12vh 1.5rem 3rem; - background: #fff; -} - -.auth-card { - width: min(24rem, 100%); - padding: 2rem; - background: #fff; - border-radius: 0; -} - -.auth-logo { - max-width: 8rem; - margin-bottom: 1rem; -} - -.auth-card h1 { - margin: 0 0 1.5rem; - font-size: 1.5rem; - font-weight: 400; -} - -.auth-field { - position: relative; - padding-top: 1rem; -} - -.auth-input { - width: 100%; - padding: 0.5rem 0; - border: 0; - border-bottom: 1pt solid rgba(0, 0, 0, 0.42); - border-radius: 0; - background: transparent; - color: inherit; - font: inherit; - font-size: 1rem; - line-height: 1.5; - outline: none; -} - -.auth-input:focus { - border-bottom-color: var(--realm-primary); -} - -.auth-field label { - position: absolute; - top: 1.5em; - left: 0; - font-size: 1rem; - line-height: 1.5; - color: rgba(0, 0, 0, 0.6); - pointer-events: none; - transform-origin: left top; - transition: top 0.15s ease, font-size 0.15s ease, color 0.15s ease, opacity 0.15s ease; -} - -.auth-input:focus + label, -.auth-input:not(:placeholder-shown) + label { - top: 0; - font-size: 0.85em; - font-weight: 500; - color: inherit; - opacity: 0.8; -} - -.auth-identifier { - margin: 0 0 0.5rem; - color: rgba(0, 0, 0, 0.6); - font-size: 0.875rem; -} - -.auth-note { - margin: 0 0 1rem; - color: rgba(0, 0, 0, 0.6); - font-size: 0.875rem; - line-height: 1.5; -} - -.auth-choice { - display: flex; - align-items: center; - gap: 0.5rem; - margin-top: 1rem; - font-size: 0.875rem; - line-height: 1.5; - cursor: pointer; -} - -.auth-choice input { - width: 1rem; - height: 1rem; - accent-color: var(--realm-primary); -} - -.auth-accounts { - display: grid; - gap: 0.5rem; - margin-top: 1rem; -} - -.auth-account { - display: flex; - flex-direction: column; - align-items: flex-start; - gap: 0.125rem; - width: 100%; - padding: 0.75rem 0; - border: 0; - border-bottom: 1pt solid rgba(0, 0, 0, 0.16); - border-radius: 0; - background: none; - color: inherit; - font: inherit; - text-align: left; - cursor: pointer; -} - -.auth-account:hover, -.auth-account:focus-visible { - border-bottom-color: var(--realm-primary); -} - -.auth-account:disabled { - opacity: 0.5; - cursor: default; -} - -.auth-account-name { - font-size: 1rem; - line-height: 1.5; -} - -.auth-account-username { - color: rgba(0, 0, 0, 0.6); - font-size: 0.875rem; - line-height: 1.5; -} - -.auth-error { - margin: 1rem 0 0; - color: #d93025; - font-size: 0.875rem; - line-height: 1.5; -} - -.auth-actions { - display: flex; - justify-content: flex-end; - align-items: center; - gap: 1rem; - margin-top: 1.5rem; -} - -.auth-button { - padding: 0.75rem 1.5rem; - border: 0; - border-radius: 0; - background: var(--realm-primary); - color: #fff; - font: inherit; - font-size: 0.875rem; - letter-spacing: 0.05em; - text-transform: uppercase; - cursor: pointer; -} - -.auth-button:disabled { - opacity: 0.5; - cursor: default; -} - -.auth-link { - padding: 0.5rem 0; - border: 0; - background: none; - color: var(--realm-primary); - font: inherit; - font-size: 0.875rem; - cursor: pointer; -} - -@media (prefers-color-scheme: dark) { - .auth-page { - background-color: #222; - } - - .auth-card { - background-color: #222; - color: #fff; - } - - .auth-input { - border-bottom-color: rgba(255, 255, 255, 0.42); - color: #fff; - } - - .auth-field label, - .auth-identifier, - .auth-note, - .auth-account-username { - color: rgba(255, 255, 255, 0.6); - } - - .auth-account { - border-bottom-color: rgba(255, 255, 255, 0.16); - } - - .auth-error { - color: #f28b82; - } -} - -@media (min-width: 35em) { - .auth-page { - background-color: #fff; - background-image: url('/assets/hex-grid-light.svg'); - background-position: center; - background-repeat: no-repeat; - background-size: cover; - } - - .auth-card { - box-shadow: 0 0.25em 0.5em #0008; - } -} - -@media (min-width: 35em) and (prefers-color-scheme: dark) { - .auth-page { - background-color: #222; - background-image: url('/assets/hex-grid-dark.svg'); - background-position: center; - background-repeat: no-repeat; - background-size: cover; - } -} diff --git a/server/web/src/main.ts b/server/web/src/main.ts @@ -1,24 +0,0 @@ -import m from 'mithril'; -import { Admin } from './screen/admin'; -import { Login } from './screen/login'; - -const routes: m.RouteDefs = { - '/oidc/:clientId/login': { - render: (vnode) => m(Login, { clientId: (vnode.attrs as any).clientId }), - }, - '/oidc/login': { - render: () => m(Login, {}), - }, - '/realms/:realm/admin': { - render: (vnode) => m(Admin, { realm: (vnode.attrs as any).realm }), - }, - '/admin': { - render: () => m(Admin, {}), - }, - '/': { - onmatch: () => m.route.set('/oidc/login'), - }, -}; - -m.route.prefix = ''; -m.route(document.body, '/oidc/login', routes); diff --git a/server/web/src/screen/admin.tsx b/server/web/src/screen/admin.tsx @@ -1,79 +0,0 @@ -import m from 'mithril'; -import { getSession, signOut, type ApiError, type SessionInfo } from '../util/api'; - -export const Admin: m.Component = { - session: null as SessionInfo | null, - error: null as Error | null, - pending: false, - - oninit(this: any) { - this.load(); - }, - - async load(this: any) { - try { - this.session = await getSession(); - document.title = this.session.realm?.display_name || 'Identity'; - } catch (e) { - const error = e as ApiError; - if (error.status === 401) { - m.route.set('/oidc/admin/login'); - return; - } - this.error = error; - } - m.redraw(); - }, - - async signOut(this: any) { - this.pending = true; - this.error = null; - try { - await signOut(); - m.route.set('/oidc/admin/login'); - } catch (e) { - this.error = e as Error; - this.pending = false; - m.redraw(); - } - }, - - view(this: any) { - const session = this.session; - const branding = session?.realm?.branding || {}; - const primary = typeof branding.primary_color === 'string' ? branding.primary_color : '#25A'; - const style = { '--realm-primary': primary } as any; - - if (!session) { - return ( - <div class="auth-page" style={style}> - <div class="auth-card"> - <h1>Admin</h1> - {this.error ? <p class="auth-error">{this.error.message}</p> : <p class="auth-note">Loading</p>} - </div> - </div> - ); - } - - return ( - <div class="auth-page" style={style}> - <div class="auth-card"> - <h1>{session.realm?.display_name || 'Identity'}</h1> - <p class="auth-identifier"> - Signed in as {session.user.display_name || session.user.username} - </p> - <p class="auth-note">{session.user.username}</p> - <p class="auth-note"> - {session.roles.length > 0 ? `Roles: ${session.roles.join(', ')}` : 'No realm roles'} - </p> - {this.error ? <p class="auth-error">{this.error.message}</p> : null} - <div class="auth-actions"> - <button class="auth-button" type="button" disabled={this.pending} onclick={() => this.signOut()}> - {this.pending ? 'Signing out' : 'Sign out'} - </button> - </div> - </div> - </div> - ); - }, -}; diff --git a/server/web/src/screen/login.tsx b/server/web/src/screen/login.tsx @@ -1,394 +0,0 @@ -import m from 'mithril'; -import { - getClientDiscovery, - getSession, - resolveLogin, - selectSession, - signInPassword, - type ClientDiscovery, - type LoginResolution, - type PasswordLoginResult, - type SessionAccount, -} from '../util/api'; - -type Step = 'accounts' | 'identifier' | 'password' | 'oidc' | 'done'; - -interface TextFieldAttrs { - id: string; - label: string; - type?: string; - value: string; - autocomplete?: string; - autofocus?: boolean; - disabled?: boolean; - oninput: (value: string) => void; -} - -function queryParam(name: string) { - const query = (m.route.get() || '').split('?')[1] || ''; - return new URLSearchParams(query).get(name); -} - -function authorizeRoute() { - const path = (m.route.get() || '').split('?')[0]; - return path.replace(/\/login$/, '/authorize'); -} - -const TextField: m.Component<TextFieldAttrs> = { - view({ attrs }) { - return ( - <div class="auth-field"> - <input - class="auth-input" - id={attrs.id} - type={attrs.type || 'text'} - value={attrs.value} - placeholder=" " - autocomplete={attrs.autocomplete} - disabled={attrs.disabled} - oninput={(e: Event) => attrs.oninput((e.target as HTMLInputElement).value)} - oncreate={attrs.autofocus ? ({ dom }: any) => dom.focus() : undefined} - /> - <label for={attrs.id}>{attrs.label}</label> - </div> - ); - }, -}; - -export const Login: m.Component<{ realm?: string; clientId?: string }> = { - realmSlug: null as string | null, - clientId: null as string | null, - discovery: null as ClientDiscovery | null, - step: 'identifier' as Step, - accounts: [] as SessionAccount[], - identifier: '', - password: '', - longSession: false, - provider: null as LoginResolution['provider'] | null, - signedIn: null as PasswordLoginResult['user'] | null, - error: null as Error | null, - pending: false, - reauth: false, - - oninit(this: any, vnode: any) { - this.realmSlug = vnode.attrs.realm ?? null; - this.clientId = vnode.attrs.clientId ?? null; - this.reauth = queryParam('reauth') === '1'; - this.loadClient(); - }, - - async loadClient(this: any) { - this.error = null; - try { - const discovery = await getClientDiscovery(this.clientId); - this.discovery = discovery; - this.realmSlug = discovery.realm; - this.clientId = discovery.client_id; - document.title = discovery.display_name; - await this.loadAccounts(); - } catch (e) { - this.error = e as Error; - } - m.redraw(); - }, - - async loadAccounts(this: any) { - if (this.reauth) { - this.accounts = []; - return; - } - try { - const session = await getSession(); - if (session.accounts.length >= 2) { - this.accounts = session.accounts; - this.step = 'accounts'; - } - } catch { - this.accounts = []; - } - }, - - async submitIdentifier(this: any) { - this.pending = true; - this.error = null; - try { - const result = await resolveLogin(this.clientId, this.identifier); - if (result.next === 'oidc' && result.provider) { - this.provider = result.provider; - this.step = 'oidc'; - } else { - this.step = 'password'; - } - } catch (e) { - this.error = e as Error; - } - this.pending = false; - m.redraw(); - }, - - async submitPassword(this: any) { - this.pending = true; - this.error = null; - try { - const result = await signInPassword( - this.clientId, - this.identifier, - this.password, - this.longSession - ); - - if (result.pending_auth_request) { - m.route.set(authorizeRoute()); - return; - } - - if (this.clientId === 'admin') { - m.route.set(this.realmSlug ? `/realms/${this.realmSlug}/admin` : '/admin'); - return; - } - - this.signedIn = result.user; - this.step = 'done'; - this.pending = false; - m.redraw(); - } catch (e) { - this.error = e as Error; - this.pending = false; - m.redraw(); - } - }, - - async selectAccount(this: any, account: SessionAccount) { - this.pending = true; - this.error = null; - try { - const result = await selectSession(account.public_id, this.clientId); - if (result.pending_auth_request) { - m.route.set(authorizeRoute()); - return; - } - - if (this.clientId === 'admin') { - m.route.set(this.realmSlug ? `/realms/${this.realmSlug}/admin` : '/admin'); - return; - } - - this.signedIn = result.user; - this.step = 'done'; - } catch (e) { - this.error = e as Error; - } - this.pending = false; - m.redraw(); - }, - - differentAccount(this: any) { - this.step = 'identifier'; - this.identifier = ''; - this.password = ''; - this.longSession = false; - this.provider = null; - this.error = null; - m.redraw(); - }, - - back(this: any) { - this.step = 'identifier'; - this.password = ''; - this.longSession = false; - this.provider = null; - this.error = null; - m.redraw(); - }, - - backToAccounts(this: any) { - this.step = 'accounts'; - this.error = null; - m.redraw(); - }, - - view(this: any) { - const branding = this.discovery?.branding || {}; - const primary = typeof branding.primary_color === 'string' ? branding.primary_color : '#25A'; - const style = { '--realm-primary': primary } as any; - - if (!this.discovery && this.error) { - return ( - <div class="auth-page" style={style}> - <div class="auth-card"> - <h1>Sign in</h1> - <p class="auth-error">{this.error.message}</p> - </div> - </div> - ); - } - - const title = this.discovery?.display_name || 'Sign in'; - - return ( - <div class="auth-page" style={style}> - <div class="auth-card"> - {typeof branding.logo_url === 'string' && branding.logo_url ? ( - <img class="auth-logo" src={branding.logo_url} alt={title} /> - ) : null} - <h1>{title}</h1> - - {this.step === 'accounts' ? this.renderAccounts() : null} - {this.step === 'identifier' ? this.renderIdentifier() : null} - {this.step === 'password' ? this.renderPassword() : null} - {this.step === 'oidc' ? this.renderProvider() : null} - {this.step === 'done' ? this.renderDone() : null} - </div> - </div> - ); - }, - - renderAccounts(this: any) { - return ( - <div> - <p class="auth-note">Choose an account to continue.</p> - <div class="auth-accounts"> - {this.accounts.map((account: SessionAccount) => { - const name = account.user.display_name || account.user.username; - const secondary = - account.user.display_name && account.user.display_name !== account.user.username - ? account.user.username - : null; - return ( - <button - class="auth-account" - type="button" - disabled={this.pending} - onclick={() => this.selectAccount(account)} - > - <span class="auth-account-name">{name}</span> - {secondary ? <span class="auth-account-username">{secondary}</span> : null} - </button> - ); - })} - </div> - {this.error ? <p class="auth-error">{this.error.message}</p> : null} - <div class="auth-actions"> - <button class="auth-link" type="button" onclick={() => this.differentAccount()}> - Different account - </button> - </div> - </div> - ); - }, - - renderIdentifier(this: any) { - return ( - <form - onsubmit={(e: Event) => { - e.preventDefault(); - if (!this.pending && this.identifier.trim()) this.submitIdentifier(); - }} - > - {this.reauth ? ( - <p class="auth-note">Confirm your password to continue.</p> - ) : null} - <TextField - id="identifier" - label="Email or username" - value={this.identifier} - autocomplete="username" - autofocus - disabled={this.pending} - oninput={(value: string) => { - this.identifier = value; - }} - /> - {this.error ? <p class="auth-error">{this.error.message}</p> : null} - <div class="auth-actions"> - {!this.reauth && this.accounts.length >= 2 ? ( - <button class="auth-link" type="button" onclick={() => this.backToAccounts()}> - Back to accounts - </button> - ) : null} - <button class="auth-button" type="submit" disabled={this.pending || !this.identifier.trim()}> - {this.pending ? 'Checking' : 'Next'} - </button> - </div> - </form> - ); - }, - - renderPassword(this: any) { - return ( - <form - onsubmit={(e: Event) => { - e.preventDefault(); - if (!this.pending) this.submitPassword(); - }} - > - <p class="auth-identifier">{this.identifier}</p> - <TextField - id="password" - label="Password" - type="password" - value={this.password} - autocomplete="current-password" - autofocus - disabled={this.pending} - oninput={(value: string) => { - this.password = value; - }} - /> - {this.discovery?.allow_session_duration_choice !== false ? ( - <label class="auth-choice"> - <input - type="checkbox" - checked={this.longSession} - disabled={this.pending} - onchange={(e: Event) => { - this.longSession = (e.target as HTMLInputElement).checked; - }} - /> - <span>Keep me signed in</span> - </label> - ) : null} - {this.error ? <p class="auth-error">{this.error.message}</p> : null} - <div class="auth-actions"> - <button class="auth-link" type="button" onclick={() => this.back()}> - Back - </button> - <button class="auth-button" type="submit" disabled={this.pending || !this.password}> - {this.pending ? 'Signing in' : 'Sign in'} - </button> - </div> - </form> - ); - }, - - renderProvider(this: any) { - const provider = this.provider; - return ( - <div> - <p class="auth-identifier">{this.identifier}</p> - <p class="auth-note"> - {provider - ? `This account signs in with ${provider.display_name}.` - : 'This account signs in with an identity provider.'} - </p> - <div class="auth-actions"> - <button class="auth-link" type="button" onclick={() => this.back()}> - Back - </button> - <button class="auth-button" type="button" disabled> - Continue - </button> - </div> - </div> - ); - }, - - renderDone(this: any) { - const user = this.signedIn; - return ( - <div> - <p class="auth-note">Signed in as {user?.display_name || user?.username}</p> - </div> - ); - }, -}; diff --git a/server/web/src/util/api.ts b/server/web/src/util/api.ts @@ -1,174 +0,0 @@ -export interface RealmInfo { - slug: string; - display_name: string; - branding: Record<string, string>; - allow_session_duration_choice: boolean; -} - -export interface ClientDiscovery { - issuer: string; - client_id: string; - client_name: string; - realm: string; - display_name: string; - branding: Record<string, string>; - access_mode: string; - virtual: boolean; - require_pkce: boolean; - allow_session_duration_choice: boolean; -} - -export interface LoginResolution { - realm: RealmInfo; - next: 'password' | 'oidc'; - provider?: { - slug: string; - display_name: string; - }; -} - -export interface PasswordLoginResult { - realm: RealmInfo; - user: { - id: string; - username: string; - display_name: string | null; - }; - expires_at: number; - pending_auth_request: boolean; -} - -export interface SessionScope { - type: 'global' | 'realm' | 'client'; - host: string; - realm_id: string | null; - client_id: string | null; -} - -export interface SessionAccount { - public_id: string; - active: boolean; - user: { - id: string; - username: string; - display_name: string | null; - }; - created_at: number; - expires_at: number; -} - -export interface SessionInfo { - scope: SessionScope; - realm: RealmInfo | null; - user: { - id: string; - username: string; - display_name: string | null; - }; - roles: string[]; - is_system_admin: boolean; - expires_at: number; - accounts: SessionAccount[]; -} - -export interface SelectSessionResult { - ok: boolean; - user: { - id: string; - username: string; - display_name: string | null; - }; - expires_at: number; - pending_auth_request: boolean; -} - -export interface ApiError extends Error { - code?: string; - status?: number; -} - -async function request<T>(path: string, options: RequestInit = {}): Promise<T> { - const response = await fetch(path, { - credentials: 'same-origin', - headers: { - 'content-type': 'application/json', - }, - ...options, - }); - - let payload: any = null; - try { - payload = await response.json(); - } catch { - payload = null; - } - - if (!response.ok) { - const error = new Error(payload?.error?.message || response.statusText) as ApiError; - error.code = payload?.error?.code; - error.status = response.status; - throw error; - } - - return payload as T; -} - -export function getRealm(realm?: string | null): Promise<RealmInfo> { - const query = realm ? `?realm=${encodeURIComponent(realm)}` : ''; - return request<RealmInfo>(`/api/v1/realm${query}`); -} - -export function getClientDiscovery(clientId?: string | null): Promise<ClientDiscovery> { - if (clientId) { - return request<ClientDiscovery>(`/oidc/${encodeURIComponent(clientId)}/openid-configuration`); - } - return request<ClientDiscovery>('/oidc/openid-configuration'); -} - -export function resolveLogin( - clientId: string, - identifier: string -): Promise<LoginResolution> { - return request<LoginResolution>('/api/v1/login/resolve', { - method: 'POST', - body: JSON.stringify({ client_id: clientId, identifier }), - }); -} - -export function signInPassword( - clientId: string, - identifier: string, - password: string, - longSession: boolean -): Promise<PasswordLoginResult> { - return request<PasswordLoginResult>('/api/v1/login/password', { - method: 'POST', - body: JSON.stringify({ - client_id: clientId, - identifier, - password, - long_session: longSession, - }), - }); -} - -export function getSession(): Promise<SessionInfo> { - return request<SessionInfo>('/api/v1/session'); -} - -export function selectSession( - publicId: string, - clientId?: string | null -): Promise<SelectSessionResult> { - return request<SelectSessionResult>('/api/v1/session/select', { - method: 'POST', - body: JSON.stringify({ - public_id: publicId, - client_id: clientId || undefined, - }), - }); -} - -export function signOut(): Promise<{ ok: boolean }> { - return request('/api/v1/logout', { method: 'POST' }); -}