diff --git a/client/fork/auth/loginUrl.js b/client/fork/auth/loginUrl.js new file mode 100644 index 00000000..94d93a99 --- /dev/null +++ b/client/fork/auth/loginUrl.js @@ -0,0 +1,33 @@ +// Login-/Logout-Helfer für den Client (ADR 0001 §6). Konfiguration kommt aus configuration.auth (Server). +const NATURALCRIT_LOGIN = 'https://www.naturalcrit.com/login'; + +const authConfig = ()=>(typeof global !== 'undefined' && global.config?.auth) || null; + +export const oidcEnabled = ()=>!!authConfig()?.providers?.includes('oidc'); +export const naturalcritEnabled = ()=>{ + const providers = authConfig()?.providers; + return !providers || providers.includes('naturalcrit'); +}; + +export const getOidcLabel = ()=>authConfig()?.oidcLabel || 'Anmelden'; + +// redirect: Pfad (mit Query) oder absolute URL; bei OIDC wird nur der Pfad verwendet +export const getLoginUrl = (redirect = '/')=>{ + const cfg = authConfig(); + if(cfg?.loginUrl) { + let path = redirect; + try { + const u = new URL(redirect, typeof window !== 'undefined' ? window.location.href : 'http://localhost'); + path = `${u.pathname}${u.search}${u.hash}`; + } catch { path = '/'; } + return `${cfg.loginUrl}?redirect=${encodeURIComponent(path)}`; + } + if(!redirect || redirect === '/') return NATURALCRIT_LOGIN; + const base = redirect.startsWith('/') ? (global.config?.baseUrl || global.config?.publicUrl || '') : ''; + return `${NATURALCRIT_LOGIN}?redirect=${base}${redirect}`; +}; + +export const getLogoutUrl = ()=>authConfig()?.logoutUrl || '/auth/logout'; + +// true, wenn der Client den Logout dem Server überlassen muss (httpOnly-Cookie) +export const logoutViaServer = (account = typeof global !== 'undefined' ? global.account : undefined)=>account?.provider === 'oidc'; diff --git a/client/homebrew/navbar/account.navitem.jsx b/client/homebrew/navbar/account.navitem.jsx index 0be06c47..2061b88c 100644 --- a/client/homebrew/navbar/account.navitem.jsx +++ b/client/homebrew/navbar/account.navitem.jsx @@ -2,6 +2,7 @@ import React from 'react'; import createReactClass from 'create-react-class'; import request from 'superagent'; import Nav from './nav.jsx'; +import { getLoginUrl, getLogoutUrl, getOidcLabel, logoutViaServer, oidcEnabled, naturalcritEnabled } from '../../fork/auth/loginUrl.js'; const Account = createReactClass({ displayName : 'AccountNavItem', @@ -23,6 +24,7 @@ const Account = createReactClass({ if(confirm('Are you sure you want to log out?')) { // Reset divider position window.localStorage.removeItem('naturalcrit-pane-split'); + if(logoutViaServer()) { window.location = getLogoutUrl(); return; } // Clear login cookie let domain = ''; if(window.location?.hostname) { @@ -97,7 +99,7 @@ const Account = createReactClass({ // Logged out // LOCAL ONLY - if(global.config?.local) { + if(global.config?.local && !oidcEnabled() && naturalcritEnabled()) { return login ; @@ -105,8 +107,8 @@ const Account = createReactClass({ // Logged out // Production site - return - login + return + {oidcEnabled() ? getOidcLabel() : 'login'} ; } }); diff --git a/client/homebrew/pages/errorPage/errors/errorIndex.js b/client/homebrew/pages/errorPage/errors/errorIndex.js index 06551246..5dba512c 100644 --- a/client/homebrew/pages/errorPage/errors/errorIndex.js +++ b/client/homebrew/pages/errorPage/errors/errorIndex.js @@ -1,6 +1,5 @@ import dedent from 'dedent'; - -const loginUrl = 'https://www.naturalcrit.com/login'; +import { getLoginUrl } from '../../../../fork/auth/loginUrl.js'; // Prevent parsing text (e.g. document titles) as markdown const escape = (text = '')=>{ @@ -105,7 +104,7 @@ const errorIndex = (props)=>{ ## Sign-in required to edit this brew. You must be logged in to one of the accounts listed as an author of this brew. - User is not logged in. Please log in [here](${loginUrl}). + User is not logged in. Please log in [here](${getLoginUrl()}). : @@ -208,7 +207,7 @@ const errorIndex = (props)=>{ You are trying to access the account page, but are not signed in to an account. - Please login or signup at our [login page](https://www.naturalcrit.com/login?redirect=https://homebrewery.naturalcrit.com/account).`, + Please login or signup at our [login page](${getLoginUrl('/account')}).`, // Brew locked by Administrators error '51' : dedent` diff --git a/package-lock.json b/package-lock.json index 6504bb85..60253fdd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -46,6 +46,7 @@ "hash-wasm": "^4.12.0", "idb-keyval": "^6.2.5", "js-yaml": "^5.5.0", + "jsonwebtoken": "^9.0.3", "jwt-simple": "^0.6.1", "less": "^4.9.1", "lodash": "^4.18.1", @@ -56,6 +57,7 @@ "nanoid": "6.0.2", "nconf": "^0.13.0", "node": "^26.13.0", + "openid-client": "^6.9.1", "prettier": "^3.9.10", "react": "^19.3.1", "react-dom": "^19.3.1", @@ -76,6 +78,7 @@ "jest-expect-message": "^1.1.3", "jsdom": "^30.1.3", "jsdom-global": "^3.0.2", + "oidc-provider": "^9.15.1", "postcss-less": "^6.0.0", "stylelint": "^17.16.0", "stylelint-config-recess-order": "^7.9.0", @@ -6446,6 +6449,20 @@ "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==", "license": "MIT" }, + "node_modules/cookies": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/cookies/-/cookies-0.9.2.tgz", + "integrity": "sha512-8BIbcC6tPZMv2/PD4PrB3CtKks7LmAWhA7FRZK/6/b/WJ2RUz00KCga7gq50S4/RhZ22kxefRFGgsuts0v3eoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "keygrip": "~1.1.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/copy-anything": { "version": "3.0.5", "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-3.0.5.tgz", @@ -6736,6 +6753,13 @@ } } }, + "node_modules/deep-equal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", + "integrity": "sha512-bHtC0iYvWhyaTzvV3CZgPeZQqCOBGyGsVV7v4eevpdkLHfiSrXUdBG+qAuSz4RI70sszvjQ1QSZ98An1yNwpSw==", + "dev": true, + "license": "MIT" + }, "node_modules/deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", @@ -6795,6 +6819,13 @@ "node": ">=0.4.0" } }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", + "dev": true, + "license": "MIT" + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -6804,6 +6835,17 @@ "node": ">= 0.8" } }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -8606,6 +8648,57 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/http-assert": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/http-assert/-/http-assert-1.5.0.tgz", + "integrity": "sha512-uPpH7OKX4H25hBmU6G1jWNaqJGpTXxey+YOUizJUAgu0AjLUeC8D73hTrhvDS5D+GJN1DN1+hhc/eF/wpxtp0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-equal": "~1.0.1", + "http-errors": "~1.8.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-assert/node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-assert/node_modules/http-errors": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", + "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-assert/node_modules/statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -10851,6 +10944,15 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, + "node_modules/jose": { + "version": "6.2.18", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.18.tgz", + "integrity": "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-tokens": { "version": "10.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", @@ -11015,6 +11117,28 @@ "graceful-fs": "^4.1.6" } }, + "node_modules/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", + "license": "MIT", + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, "node_modules/jsx-ast-utils": { "version": "3.3.5", "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", @@ -11070,6 +11194,19 @@ "node": ">=18.0.0" } }, + "node_modules/keygrip": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz", + "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tsscmp": "1.0.6" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/keyv": { "version": "4.5.4", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", @@ -11089,6 +11226,124 @@ "node": ">=0.10.0" } }, + "node_modules/koa": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/koa/-/koa-3.3.0.tgz", + "integrity": "sha512-NdsWJYxVzUuYt718DtEQRhUXqqsAPA4VlaUGrlidjh/T2TP/4OQXqQg4ouUHfHD9f+tgmwLZWPm+JQLgqM9YbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "accepts": "^1.3.8", + "content-disposition": "~1.0.1", + "content-type": "^1.0.5", + "cookies": "~0.9.1", + "delegates": "^1.0.0", + "destroy": "^1.2.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "fresh": "~0.5.2", + "http-assert": "^1.5.0", + "http-errors": "^2.0.0", + "koa-compose": "^4.1.0", + "mime-types": "^3.0.1", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/koa-compose": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/koa-compose/-/koa-compose-4.1.0.tgz", + "integrity": "sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw==", + "dev": true, + "license": "MIT" + }, + "node_modules/koa/node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa/node_modules/accepts/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa/node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/koa/node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa/node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa/node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/less": { "version": "4.9.1", "resolved": "https://registry.npmjs.org/less/-/less-4.9.1.tgz", @@ -11443,12 +11698,54 @@ "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", "license": "MIT" }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", "license": "MIT" }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, "node_modules/lodash.truncate": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", @@ -12271,6 +12568,15 @@ "node": ">=8" } }, + "node_modules/oauth4webapi": { + "version": "3.8.9", + "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.9.tgz", + "integrity": "sha512-gyn4jpaxyYFm1epl3mwqc1sFShLjT9eq/63JW+Nvk286Lz6FC72pVv/SyhJHxo+sQiHEcjIHs4TtFKX/+Md07A==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -12385,6 +12691,21 @@ "node": ">=12.20.0" } }, + "node_modules/oidc-provider": { + "version": "9.15.1", + "resolved": "https://registry.npmjs.org/oidc-provider/-/oidc-provider-9.15.1.tgz", + "integrity": "sha512-27bW0bbGdw+kC36uISUohDBgvQ0CjTbbZyyvP9JtLpSR22+YYjc5gqxG0RVWqK5tgVfodLO0nxtXTMhTIiLkdw==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "jose": "^6.2.17", + "koa": "^3.3.0" + }, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/on-finished": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", @@ -12422,6 +12743,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/openid-client": { + "version": "6.9.1", + "resolved": "https://registry.npmjs.org/openid-client/-/openid-client-6.9.1.tgz", + "integrity": "sha512-wysSRjtNRRpu1S/HCVaQ7LRPSNc42lhS1szB1SihVTcA2kAarpzKyvAd+sjFX41ky7iDblGerORC8ASwpt3zqA==", + "license": "MIT", + "dependencies": { + "jose": "^6.2.18", + "oauth4webapi": "^3.8.9" + }, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -14744,6 +15078,16 @@ "devOptional": true, "license": "0BSD" }, + "node_modules/tsscmp": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", + "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6.x" + } + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", diff --git a/package.json b/package.json index 72cb02cc..fe099ecb 100644 --- a/package.json +++ b/package.json @@ -61,7 +61,7 @@ "server" ], "transformIgnorePatterns": [ - "node_modules/(?!(nanoid|@exodus/bytes|parse5|@asamuzakjp|@csstools|entities)/)" + "node_modules/(?!(nanoid|@exodus/bytes|parse5|@asamuzakjp|@csstools|entities|openid-client|oauth4webapi|jose|oidc-provider)/)" ], "transform": { "^.+\\.[jt]s$": "babel-jest", @@ -125,6 +125,7 @@ "hash-wasm": "^4.12.0", "idb-keyval": "^6.2.5", "js-yaml": "^5.5.0", + "jsonwebtoken": "^9.0.3", "jwt-simple": "^0.6.1", "less": "^4.9.1", "lodash": "^4.18.1", @@ -135,6 +136,7 @@ "nanoid": "6.0.2", "nconf": "^0.13.0", "node": "^26.13.0", + "openid-client": "^6.9.1", "prettier": "^3.9.10", "react": "^19.3.1", "react-dom": "^19.3.1", @@ -155,6 +157,7 @@ "jest-expect-message": "^1.1.3", "jsdom": "^30.1.3", "jsdom-global": "^3.0.2", + "oidc-provider": "^9.15.1", "postcss-less": "^6.0.0", "stylelint": "^17.16.0", "stylelint-config-recess-order": "^7.9.0", diff --git a/server.js b/server.js index a9da7c2c..535c55b8 100644 --- a/server.js +++ b/server.js @@ -1,4 +1,4 @@ -import DB from './server/db.js'; +import storage from './server/storage/index.js'; import createApp from './server/app.js'; import config from './server/config.js'; import { createServer as createViteServer } from 'vite'; @@ -15,7 +15,7 @@ async function start() { }); } - await DB.connect(config).catch((err)=>{ + await storage.connect(config).catch((err)=>{ console.error('Database connection failed:', err); process.exit(1); }); diff --git a/server/app.js b/server/app.js index dde6b6c2..04993e41 100644 --- a/server/app.js +++ b/server/app.js @@ -35,6 +35,9 @@ import forceSSL from './forcessl.mw.js'; import dbCheck from './middleware/dbCheck.js'; +import { readAuthConfig, accountMiddleware, createAuthRouter, clientConfig as authClientConfig } from './fork/auth/index.js'; +import { getStorage } from './storage/index.js'; + import cors from 'cors'; export default async function createApp(vite) { @@ -112,6 +115,14 @@ export default async function createApp(vite) { return next(); }); + // Fork: OIDC-Login (ADR 0001); ersetzt req.account nach der Upstream-Middleware + const authConfig = readAuthConfig(); + app.use(accountMiddleware(authConfig)); + app.use(createAuthRouter(authConfig, { + getUsers : ()=>getStorage().users, + brewAuthorExists : async (name)=>!!(await HomebrewModel.exists({ authors: name })) + })); + app.use(homebrewApi); app.use(adminApi(vite)); app.use(vaultApi); @@ -231,7 +242,8 @@ export default async function createApp(vite) { baseUrl : `${req.protocol}://${req.get('host')}`, environment : nodeEnv, deployment : config.get('heroku_app_name') ?? '', - developmentStyle : config.get('development_style') + developmentStyle : config.get('development_style'), + auth : authClientConfig(authConfig) }; const props = { version : version, diff --git a/server/fork/auth/accountMapping.js b/server/fork/auth/accountMapping.js new file mode 100644 index 00000000..8fb9863c --- /dev/null +++ b/server/fork/auth/accountMapping.js @@ -0,0 +1,75 @@ +// (iss, sub) -> Benutzer, nach ADR 0001 §4. +const USERNAME_RE = /^[A-Za-z0-9._-]{2,40}$/; + +export const sanitizeUsername = (raw)=>{ + let name = String(raw ?? '').trim(); + if(name.includes('@')) name = name.split('@')[0]; // Benutzernamen dürfen keine E-Mail-Adresse sein + name = name.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 40); + if(name.length < 2) name = (`${name}user`).slice(0, 40); + return USERNAME_RE.test(name) ? name : 'user'; +}; + +export const baseUsername = (claims, usernameClaim)=>{ + const candidate = claims[usernameClaim] + || (typeof claims.email === 'string' && claims.email.split('@')[0]) + || 'user'; + return sanitizeUsername(candidate); +}; + +const uniqueUsername = async (base, { users, brewAuthorExists })=>{ + for (let i = 1; i < 10000; i++) { + const suffix = i === 1 ? '' : `-${i}`; + const name = `${base.slice(0, 40 - suffix.length)}${suffix}`; + if(await users.usernameExists(name)) continue; + if(await brewAuthorExists(name)) continue; + return name; + } + throw new Error('Kein freier Benutzername gefunden'); +}; + +const profile = (claims)=>({ + email : claims.email ? String(claims.email).toLowerCase() : undefined, + emailVerified : claims.email_verified === true, + displayName : claims.name || undefined +}); + +/** + * @param {{iss:string, sub:string, claims:object}} identity + * @param {{users:object, brewAuthorExists:(name:string)=>Promise, usernameClaim:string, linkByEmail:boolean, logger?:object}} deps + */ +export const mapAccount = async ({ iss, sub, claims }, deps)=>{ + const { users, usernameClaim, linkByEmail, logger = console } = deps; + const now = new Date(); + const p = profile(claims); + + // 1. Primärschlüssel (iss, sub) + const existing = await users.findByOidc(iss, sub); + if(existing) { + return users.update(existing.id, { ...p, lastLoginAt: now }); + } + + // 2. Verknüpfung per verifizierter E-Mail mit vorab angelegtem Benutzer + if(linkByEmail && p.email && p.emailVerified) { + const candidates = await users.findUnlinkedByEmail(p.email); + if(candidates.length === 1) { + return users.update(candidates[0].id, { ...p, oidcIssuer: iss, oidcSub: sub, lastLoginAt: now }); + } + if(candidates.length > 1) { + logger.error(`OIDC: ${candidates.length} vorab angelegte Benutzer mit E-Mail ${p.email}, keine Verknüpfung.`); + } + } + + // 3. Neuanlage + const base = baseUsername(claims, usernameClaim); + for (let attempt = 0; attempt < 5; attempt++) { + const username = await uniqueUsername(base, deps); + try { + return await users.create({ username, oidcIssuer: iss, oidcSub: sub, ...p }); + } catch (err) { + // Race (gleichzeitiger Login): (iss, sub) inzwischen vorhanden? + const raced = await users.findByOidc(iss, sub); + if(raced) return raced; + if(attempt === 4) throw err; + } + } +}; diff --git a/server/fork/auth/accountMapping.spec.js b/server/fork/auth/accountMapping.spec.js new file mode 100644 index 00000000..52ca1a0f --- /dev/null +++ b/server/fork/auth/accountMapping.spec.js @@ -0,0 +1,108 @@ +import { mapAccount, sanitizeUsername } from './accountMapping.js'; +import { createMemoryUsers } from './testUsers.js'; + +const ISS = 'https://idp'; +const identity = (sub, claims = {})=>({ iss: ISS, sub, claims }); +let users; let authors; +const deps = (extra = {})=>({ + users, usernameClaim : 'preferred_username', linkByEmail : false, logger : { error: jest.fn() }, + brewAuthorExists : async (n)=>authors.has(n), ...extra +}); +beforeEach(()=>{ users = createMemoryUsers(); authors = new Set(); }); + +describe('sanitizeUsername', ()=>{ + test.each([ + ['alice', 'alice'], ['Alice Smith', 'Alice-Smith'], ['a@b.test', 'a-user'.length ? 'a' + 'user' : ''], + ['müller', 'm-ller'], ['x', 'xuser'], ['', 'user'], ['..bob..', 'bob'], ['a'.repeat(60), 'a'.repeat(40)] + ])('%j -> %j', (i, o)=>expect(sanitizeUsername(i)).toBe(o)); + test('E-Mail wird nie als Benutzername übernommen', ()=>{ + expect(sanitizeUsername('carol@example.test')).toBe('carol'); + }); +}); + +describe('mapAccount', ()=>{ + test('Neuanlage aus preferred_username', async ()=>{ + const u = await mapAccount(identity('s1', { preferred_username: 'alice', email: 'A@x.test', email_verified: true, name: 'Alice' }), deps()); + expect(u).toMatchObject({ username: 'alice', oidcIssuer: ISS, oidcSub: 's1', email: 'a@x.test', emailVerified: true, displayName: 'Alice' }); + }); + + test('Fallback: E-Mail-Teil, dann "user"', async ()=>{ + expect((await mapAccount(identity('s1', { email: 'bob@x.test' }), deps())).username).toBe('bob'); + expect((await mapAccount(identity('s2', {}), deps())).username).toBe('user'); + }); + + test('eigener Username-Claim', async ()=>{ + const u = await mapAccount(identity('s1', { upn: 'dora', preferred_username: 'ignored' }), deps({ usernameClaim: 'upn' })); + expect(u.username).toBe('dora'); + }); + + test('zweiter Login: gleicher Benutzer, username unverändert, Profil aktualisiert', async ()=>{ + const a = await mapAccount(identity('s1', { preferred_username: 'alice', email: 'a@x.test' }), deps()); + const b = await mapAccount(identity('s1', { preferred_username: 'alice-neu', email: 'neu@x.test', email_verified: true }), deps()); + expect(b.id).toBe(a.id); + expect(b.username).toBe('alice'); + expect(b.email).toBe('neu@x.test'); + expect(b.lastLoginAt).toBeInstanceOf(Date); + expect(users.rows).toHaveLength(1); + }); + + test('gleicher sub bei anderem Issuer ist ein anderer Benutzer', async ()=>{ + await mapAccount(identity('s1', { preferred_username: 'alice' }), deps()); + const other = await mapAccount({ iss: 'https://other', sub: 's1', claims: { preferred_username: 'alice' } }, deps()); + expect(other.username).toBe('alice-2'); + }); + + test('Namenskollision mit Benutzer und mit Brew-Autor: Suffix', async ()=>{ + await users.create({ username: 'alice' }); + authors.add('alice-2'); + const u = await mapAccount(identity('s9', { preferred_username: 'alice' }), deps()); + expect(u.username).toBe('alice-3'); + }); + + test('Suffix hält die Maximallänge ein', async ()=>{ + const long = 'a'.repeat(40); + await users.create({ username: long }); + const u = await mapAccount(identity('s1', { preferred_username: long }), deps()); + expect(u.username).toHaveLength(40); + expect(u.username.endsWith('-2')).toBe(true); + }); + + describe('E-Mail-Verknüpfung', ()=>{ + const claims = { preferred_username: 'neuer-name', email: 'carol@x.test', email_verified: true }; + + test('aus (Standard): keine Verknüpfung, Neuanlage', async ()=>{ + const pre = await users.create({ username: 'carol', email: 'carol@x.test' }); + const u = await mapAccount(identity('s1', claims), deps()); + expect(u.id).not.toBe(pre.id); + expect(u.username).toBe('neuer-name'); + }); + + test('an + verifiziert: bindet vorab angelegten Benutzer, Name bleibt', async ()=>{ + const pre = await users.create({ username: 'carol', email: 'carol@x.test' }); + const u = await mapAccount(identity('s1', claims), deps({ linkByEmail: true })); + expect(u).toMatchObject({ id: pre.id, username: 'carol', oidcSub: 's1', oidcIssuer: ISS }); + }); + + test('an, aber E-Mail nicht verifiziert: keine Verknüpfung', async ()=>{ + const pre = await users.create({ username: 'carol', email: 'carol@x.test' }); + const u = await mapAccount(identity('s1', { ...claims, email_verified: false }), deps({ linkByEmail: true })); + expect(u.id).not.toBe(pre.id); + }); + + test('an, Benutzer hat schon OIDC-Bindung: keine Übernahme', async ()=>{ + const pre = await users.create({ username: 'carol', email: 'carol@x.test', oidcIssuer: ISS, oidcSub: 'andere' }); + const u = await mapAccount(identity('s1', claims), deps({ linkByEmail: true })); + expect(u.id).not.toBe(pre.id); + expect((await users.findById(pre.id)).oidcSub).toBe('andere'); + }); + + test('an, mehrere Treffer: keine Verknüpfung, Fehler wird geloggt', async ()=>{ + await users.create({ username: 'carol1', email: 'carol@x.test' }); + await users.create({ username: 'carol2', email: 'carol@x.test' }); + const d = deps({ linkByEmail: true }); + const u = await mapAccount(identity('s1', claims), d); + expect(u.username).toBe('neuer-name'); + expect(d.logger.error).toHaveBeenCalled(); + }); + }); +}); diff --git a/server/fork/auth/auth.api.spec.js b/server/fork/auth/auth.api.spec.js new file mode 100644 index 00000000..d259bcc2 --- /dev/null +++ b/server/fork/auth/auth.api.spec.js @@ -0,0 +1,390 @@ +import http from 'http'; +import express from 'express'; +import cookieParser from 'cookie-parser'; +import jwt from 'jsonwebtoken'; +import { startIdp, loginAtIdp, CLIENT } from './testIdp.js'; +import { createMemoryUsers } from './testUsers.js'; +import { readAuthConfig, accountMiddleware, createAuthRouter } from './index.js'; +import { openTx, sealTx, SESSION_COOKIE, TX_COOKIE } from './session.js'; + +const SECRET = 's'.repeat(40); +const ACCOUNTS = { + alice : { preferred_username: 'alice', email: 'alice@example.test', email_verified: true, name: 'Alice A.' }, + bob : { preferred_username: 'bob', email: 'bob@example.test', email_verified: false } +}; + +let appServer; let idp; let appUrl; let delegate; let users; let authors; let renameCalled; + +const buildApp = (envOverrides = {}, depsOverrides = {})=>{ + const config = readAuthConfig({ + HB_PUBLIC_URL : appUrl, HB_OIDC_ISSUER : idp.issuer, HB_OIDC_CLIENT_ID : CLIENT.client_id, + HB_OIDC_CLIENT_SECRET : CLIENT.client_secret, HB_SESSION_SECRET : SECRET, ...envOverrides + }); + const app = express(); + app.use(cookieParser()); + // Stand-in für die Upstream-Account-Middleware: nc_session-Cookie == Benutzername + app.use((req, res, next)=>{ if(req.cookies.nc_session) req.account = { username: req.cookies.nc_session }; next(); }); + app.use(accountMiddleware(config)); + app.use(createAuthRouter(config, { getUsers: ()=>users, brewAuthorExists: async (n)=>authors.has(n), ...depsOverrides })); + app.get('/whoami', (req, res)=>res.json(req.account ?? null)); + app.put('/api/user/rename', (req, res)=>{ renameCalled = true; res.json({ upstream: true }); }); + app.post('/local/login', (req, res)=>res.json('upstream-token')); + app.get('/', (req, res)=>res.send('home')); + delegate = app; + return config; +}; + +// Mini-Browser mit Cookie-Jar +const browser = ()=>{ + const jar = {}; + const store = (res)=>{ + for (const c of res.headers.getSetCookie()) { + const [kv, ...attrs] = c.split(';'); + const i = kv.indexOf('='); + const name = kv.slice(0, i); const value = kv.slice(i + 1); + if(!value || attrs.some((a)=>/expires=Thu, 01 Jan 1970/i.test(a))) delete jar[name]; else jar[name] = value; + } + }; + const req = async (path, init = {})=>{ + const res = await fetch(path.startsWith('http') ? path : `${appUrl}${path}`, { + redirect : 'manual', ...init, + headers : { cookie: Object.entries(jar).map(([k, v])=>`${k}=${v}`).join('; '), ...(init.headers || {}) } + }); + store(res); + return res; + }; + return { jar, req }; +}; + +// Vollständiger Login; gibt { b, res (Callback-Antwort), authUrl } +const login = async (sub, redirect = '/brews', b = browser())=>{ + const start = await b.req(`/auth/oidc/login?redirect=${encodeURIComponent(redirect)}`); + const authUrl = start.headers.get('location'); + const { callbackUrl } = await loginAtIdp(authUrl, { login: sub }); + const res = await b.req(callbackUrl); + return { b, res, authUrl, callbackUrl }; +}; + +beforeAll(async ()=>{ + jest.spyOn(console, 'warn').mockImplementation(()=>{}); + jest.spyOn(console, 'error').mockImplementation(()=>{}); + appServer = http.createServer((req, res)=>delegate(req, res)); + await new Promise((r)=>appServer.listen(0, '127.0.0.1', r)); + appUrl = `http://127.0.0.1:${appServer.address().port}`; + idp = await startIdp({ accounts: ACCOUNTS, redirectUri: `${appUrl}/auth/oidc/callback` }); +}); +afterAll(async ()=>{ + await idp.close(); + await new Promise((r)=>{ appServer.closeAllConnections?.(); appServer.close(r); }); + jest.restoreAllMocks(); +}); +beforeEach(()=>{ + users = createMemoryUsers(); authors = new Set(); renameCalled = false; + buildApp(); +}); + +describe('OIDC-Login (Authorization Code + PKCE) gegen Mock-IdP', ()=>{ + test('Login-Redirect enthält PKCE S256, state, nonce, Scopes und setzt das Tx-Cookie', async ()=>{ + const b = browser(); + const res = await b.req('/auth/oidc/login'); + expect(res.status).toBe(302); + const u = new URL(res.headers.get('location')); + expect(u.origin).toBe(idp.issuer); + expect(u.searchParams.get('code_challenge_method')).toBe('S256'); + expect(u.searchParams.get('code_challenge')).toMatch(/^[\w-]{43}$/); + expect(u.searchParams.get('state')).toHaveLength(43); + expect(u.searchParams.get('nonce')).toHaveLength(43); + expect(u.searchParams.get('scope')).toBe('openid profile email'); + expect(u.searchParams.get('redirect_uri')).toBe(`${appUrl}/auth/oidc/callback`); + const setCookie = res.headers.getSetCookie().find((c)=>c.startsWith(TX_COOKIE)); + expect(setCookie).toMatch(/HttpOnly/i); + expect(setCookie).toMatch(/SameSite=Lax/i); + expect(setCookie).toMatch(/Path=\/auth\/oidc/); + expect(setCookie).toMatch(/Max-Age=600/); + expect(setCookie).not.toMatch(/Secure/i); // http-Testumgebung + }); + + test('Erfolg: Konto angelegt, Session-Cookie, Weiterleitung, req.account gesetzt', async ()=>{ + const { b, res } = await login('alice', '/edit/xyz?a=1'); + expect(res.status).toBe(302); + expect(res.headers.get('location')).toBe('/edit/xyz?a=1'); + const sessionCookie = res.headers.getSetCookie().find((c)=>c.startsWith(SESSION_COOKIE)); + expect(sessionCookie).toMatch(/HttpOnly/i); + expect(sessionCookie).toMatch(/Path=\//); + expect(b.jar[TX_COOKIE]).toBeUndefined(); // Transaktion verbraucht + + expect(users.rows).toHaveLength(1); + expect(users.rows[0]).toMatchObject({ username: 'alice', oidcIssuer: idp.issuer, oidcSub: 'alice', email: 'alice@example.test', emailVerified: true, displayName: 'Alice A.' }); + + const who = await (await b.req('/whoami')).json(); + expect(who).toEqual({ username: 'alice', uid: users.rows[0].id, provider: 'oidc' }); + + const claims = jwt.verify(b.jar[SESSION_COOKIE], SECRET, { algorithms: ['HS256'] }); + expect(claims).toMatchObject({ v: 1, username: 'alice', iss: idp.issuer, sub: 'alice' }); + expect(claims.exp - claims.iat).toBe(7 * 24 * 3600); + }); + + test('erneuter Login erzeugt kein zweites Konto', async ()=>{ + await login('alice'); + await login('alice'); + expect(users.rows).toHaveLength(1); + expect(users.rows[0].lastLoginAt).toBeInstanceOf(Date); + }); + + test('Namenskollision mit Brew-Autor: neues Konto bekommt Suffix', async ()=>{ + authors.add('alice'); + await login('alice'); + expect(users.rows[0].username).toBe('alice-2'); + }); + + test('E-Mail-Verknüpfung nur bei HB_OIDC_LINK_BY_EMAIL=true und verifizierter E-Mail', async ()=>{ + const pre = await users.create({ username: 'legacy-alice', email: 'alice@example.test' }); + await login('alice'); + expect(users.rows.map((r)=>r.username).sort()).toEqual(['alice', 'legacy-alice']); + + users = createMemoryUsers(); + const pre2 = await users.create({ username: 'legacy-alice', email: 'alice@example.test' }); + buildApp({ HB_OIDC_LINK_BY_EMAIL: 'true' }); + await login('alice'); + expect(users.rows).toHaveLength(1); + expect(users.rows[0]).toMatchObject({ id: pre2.id, username: 'legacy-alice', oidcSub: 'alice' }); + expect(pre.id).not.toBe(pre2.id); + + users = createMemoryUsers(); + await users.create({ username: 'legacy-bob', email: 'bob@example.test' }); + await login('bob'); // E-Mail nicht verifiziert + expect(users.rows.find((r)=>r.username === 'legacy-bob').oidcSub).toBeNull(); + }); + + test('eigener Anzeigename und Scopes über Umgebung', async ()=>{ + buildApp({ HB_OIDC_SCOPES: 'openid email', HB_OIDC_USERNAME_CLAIM: 'email' }); + const res = await browser().req('/auth/oidc/login'); + expect(new URL(res.headers.get('location')).searchParams.get('scope')).toBe('openid email'); + }); + + describe('Fehlerfälle im Callback', ()=>{ + const expectErrorPage = async (res, status)=>{ + expect(res.status).toBe(status); + expect(res.headers.get('content-type')).toMatch(/html/); + expect(await res.text()).toMatch(/Erneut anmelden/); + }; + + test('ohne Transaktion → 400', async ()=>{ + const res = await browser().req('/auth/oidc/callback?code=abc&state=xyz'); + await expectErrorPage(res, 400); + }); + + test('falscher state → 400, kein Konto, keine Session', async ()=>{ + const b = browser(); + const start = await b.req('/auth/oidc/login'); + const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' }); + const u = new URL(callbackUrl); + u.searchParams.set('state', 'manipuliert'); + const res = await b.req(u.href); + await expectErrorPage(res, 400); + expect(users.rows).toHaveLength(0); + expect(b.jar[SESSION_COOKIE]).toBeUndefined(); + expect(b.jar[TX_COOKIE]).toBeUndefined(); + }); + + test('Transaktion nur einmal verwendbar (Replay)', async ()=>{ + const b = browser(); + const start = await b.req('/auth/oidc/login'); + const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' }); + const txCookie = b.jar[TX_COOKIE]; + expect((await b.req(callbackUrl)).status).toBe(302); + b.jar[TX_COOKIE] = txCookie; // Angreifer spielt Cookie + Code erneut ein + const res = await b.req(callbackUrl); + await expectErrorPage(res, 400); // Code ist beim IdP verbraucht + expect(users.rows).toHaveLength(1); + }); + + test('abgelaufene Transaktion → 400', async ()=>{ + const b = browser(); + const start = await b.req('/auth/oidc/login'); + const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' }); + const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }); + const tx = openTx(config, b.jar[TX_COOKIE]); + b.jar[TX_COOKIE] = sealTx(config, { ...tx, createdAt: Date.now() - 11 * 60 * 1000 }); + await expectErrorPage(await b.req(callbackUrl), 400); + expect(users.rows).toHaveLength(0); + }); + + test('manipuliertes Tx-Cookie → 400', async ()=>{ + const b = browser(); + const start = await b.req('/auth/oidc/login'); + const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' }); + b.jar[TX_COOKIE] = `${b.jar[TX_COOKIE].slice(0, -3)}AAA`; + await expectErrorPage(await b.req(callbackUrl), 400); + }); + + test('falscher nonce (ID-Token passt nicht zur Transaktion) → 400', async ()=>{ + const b = browser(); + const start = await b.req('/auth/oidc/login'); + const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' }); + const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }); + const tx = openTx(config, b.jar[TX_COOKIE]); + b.jar[TX_COOKIE] = sealTx(config, { ...tx, nonce: 'anderer-nonce' }); + await expectErrorPage(await b.req(callbackUrl), 400); + expect(users.rows).toHaveLength(0); + expect(b.jar[SESSION_COOKIE]).toBeUndefined(); + }); + + test('falscher PKCE-Verifier → 400', async ()=>{ + const b = browser(); + const start = await b.req('/auth/oidc/login'); + const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' }); + const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }); + const tx = openTx(config, b.jar[TX_COOKIE]); + b.jar[TX_COOKIE] = sealTx(config, { ...tx, codeVerifier: 'A'.repeat(43) }); + await expectErrorPage(await b.req(callbackUrl), 400); + expect(users.rows).toHaveLength(0); + }); + + test('IdP meldet error=access_denied → 400 mit Hinweis', async ()=>{ + const b = browser(); + const start = await b.req('/auth/oidc/login'); + const state = new URL(start.headers.get('location')).searchParams.get('state'); + const res = await b.req(`/auth/oidc/callback?error=access_denied&state=${state}&iss=${encodeURIComponent(idp.issuer)}`); + await expectErrorPage(res, 400); + expect(users.rows).toHaveLength(0); + }); + + test('Code ungültig → 400', async ()=>{ + const b = browser(); + const start = await b.req('/auth/oidc/login'); + const state = new URL(start.headers.get('location')).searchParams.get('state'); + const res = await b.req(`/auth/oidc/callback?code=falsch&state=${state}&iss=${encodeURIComponent(idp.issuer)}`); + await expectErrorPage(res, 400); + }); + + test('Fehler im Konto-Mapping → 500 ohne Session', async ()=>{ + buildApp({}, { getUsers: ()=>({ findByOidc: async ()=>{ throw new Error('db down'); } }) }); + const { b, res } = await login('alice'); + await expectErrorPage(res, 500); + expect(b.jar[SESSION_COOKIE]).toBeUndefined(); + }); + + test('IdP nicht erreichbar → 502, späterer Versuch klappt (Discovery nicht dauerhaft gecacht)', async ()=>{ + buildApp({ HB_OIDC_ISSUER: 'http://127.0.0.1:9' }); + const res = await browser().req('/auth/oidc/login'); + await expectErrorPage(res, 502); + // anderer Router mit funktionierendem IdP + buildApp(); + expect((await browser().req('/auth/oidc/login')).status).toBe(302); + }); + }); + + describe('offene Weiterleitung', ()=>{ + test.each(['//evil.example', 'https://evil.example/x', '/\\evil.example', 'javascript:alert(1)'])('redirect=%s → /', async (redirect)=>{ + const { res } = await login('alice', redirect); + expect(res.headers.get('location')).toBe('/'); + }); + }); + + describe('Logout', ()=>{ + test('löscht das Session-Cookie und leitet auf / um', async ()=>{ + const { b } = await login('alice'); + const res = await b.req('/auth/logout'); + expect(res.status).toBe(302); + expect(res.headers.get('location')).toBe('/'); + expect(b.jar[SESSION_COOKIE]).toBeUndefined(); + expect(await (await b.req('/whoami')).json()).toBeNull(); + }); + + test('mit HB_OIDC_END_SESSION=true Redirect zum end_session_endpoint des IdP', async ()=>{ + buildApp({ HB_OIDC_END_SESSION: 'true' }); + const { b } = await login('alice'); + const res = await b.req('/auth/logout'); + const loc = new URL(res.headers.get('location')); + expect(loc.origin).toBe(idp.issuer); + expect(loc.pathname).toBe('/session/end'); + expect(loc.searchParams.get('client_id')).toBe(CLIENT.client_id); + expect(loc.searchParams.get('post_logout_redirect_uri')).toBe(`${appUrl}/`); + expect(b.jar[SESSION_COOKIE]).toBeUndefined(); + }); + }); +}); + +describe('Session-Gültigkeit', ()=>{ + test('abgelaufene und fremd signierte Sessions liefern kein Konto', async ()=>{ + const b = browser(); + const claims = { v: 1, uid: 'u', username: 'mallory', iss: 'i', sub: 's' }; + b.jar[SESSION_COOKIE] = jwt.sign(claims, SECRET, { expiresIn: -5 }); + expect(await (await b.req('/whoami')).json()).toBeNull(); + b.jar[SESSION_COOKIE] = jwt.sign(claims, 'x'.repeat(40), { expiresIn: 60 }); + expect(await (await b.req('/whoami')).json()).toBeNull(); + b.jar[SESSION_COOKIE] = jwt.sign(claims, SECRET, { expiresIn: 60 }); + expect((await (await b.req('/whoami')).json()).username).toBe('mallory'); + }); +}); + +describe('PUT /api/user/rename', ()=>{ + test('OIDC-Session → 403 A01, Upstream-Route wird nicht erreicht', async ()=>{ + const { b } = await login('alice'); + const res = await b.req('/api/user/rename', { + method : 'PUT', headers : { 'content-type': 'application/json' }, + body : JSON.stringify({ username: 'victim', newUsername: 'alice' }) + }); + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ HBErrorCode: 'A01' }); + expect(renameCalled).toBe(false); + }); + + test('naturalcrit-Session → Upstream-Verhalten', async ()=>{ + const b = browser(); + b.jar.nc_session = 'carol'; + const res = await b.req('/api/user/rename', { method: 'PUT' }); + expect(await res.json()).toEqual({ upstream: true }); + expect(renameCalled).toBe(true); + }); +}); + +describe('Alt-Logins abschaltbar (HB_AUTH_PROVIDERS)', ()=>{ + test('beide aktiv: nc_session gilt (mit provider), Auswahlseite, /local/login erreichbar', async ()=>{ + buildApp({ HB_AUTH_PROVIDERS: 'oidc,naturalcrit' }); + const b = browser(); + b.jar.nc_session = 'carol'; + expect(await (await b.req('/whoami')).json()).toEqual({ username: 'carol', provider: 'naturalcrit' }); + const chooser = await b.req('/auth/login?redirect=%2Fbrews'); + const html = await chooser.text(); + expect(html).toMatch(/\/auth\/oidc\/login\?redirect=%2Fbrews/); + expect(html).toMatch(/naturalcrit\.com\/login/); + expect((await b.req('/local/login', { method: 'POST' })).status).toBe(200); + }); + + test('nur oidc: nc_session wird ignoriert, /local/login 404, /auth/login leitet direkt zum IdP-Login', async ()=>{ + buildApp({ HB_AUTH_PROVIDERS: 'oidc' }); + const b = browser(); + b.jar.nc_session = 'carol'; + expect(await (await b.req('/whoami')).json()).toBeNull(); + expect((await b.req('/local/login', { method: 'POST' })).status).toBe(404); + const res = await b.req('/auth/login?redirect=%2Fx'); + expect(res.status).toBe(302); + expect(res.headers.get('location')).toBe('/auth/oidc/login?redirect=%2Fx'); + // OIDC-Login funktioniert weiter + const { b: b2 } = await login('alice'); + expect((await (await b2.req('/whoami')).json()).provider).toBe('oidc'); + }); + + test('nur naturalcrit: OIDC-Endpunkte gesperrt, hb_session wird ignoriert', async ()=>{ + buildApp({ HB_AUTH_PROVIDERS: 'naturalcrit' }); + const b = browser(); + expect((await b.req('/auth/oidc/login')).status).toBe(404); + expect((await b.req('/auth/oidc/callback?code=x&state=y')).status).toBe(404); + expect((await b.req('/auth/login')).status).toBe(404); + b.jar[SESSION_COOKIE] = jwt.sign({ v: 1, uid: 'u', username: 'mallory', iss: 'i', sub: 's' }, SECRET, { expiresIn: 60 }); + b.jar.nc_session = 'carol'; + expect(await (await b.req('/whoami')).json()).toEqual({ username: 'carol', provider: 'naturalcrit' }); + expect((await b.req('/local/login', { method: 'POST' })).status).toBe(200); + }); + + test('nur oidc: PUT /api/user/rename ohne OIDC-Session erreicht die Upstream-Route (dort greift die Kontoprüfung)', async ()=>{ + buildApp({ HB_AUTH_PROVIDERS: 'oidc' }); + const b = browser(); + b.jar.nc_session = 'carol'; + const res = await b.req('/api/user/rename', { method: 'PUT' }); + expect(renameCalled).toBe(true); + expect(res.status).toBe(200); + }); +}); diff --git a/server/fork/auth/config.js b/server/fork/auth/config.js new file mode 100644 index 00000000..c2f0c274 --- /dev/null +++ b/server/fork/auth/config.js @@ -0,0 +1,85 @@ +// Auth-Konfiguration ausschließlich aus Umgebungsvariablen (ADR 0001, "Konfiguration"). +const VALID_PROVIDERS = ['oidc', 'naturalcrit']; +const MIN_SECRET_BYTES = 32; + +const bool = (v, def = false)=>{ + if(v === undefined || v === null || v === '') return def; + return ['1', 'true', 'yes', 'on'].includes(String(v).trim().toLowerCase()); +}; + +// "7d", "12h", "30m", "90s", "604800" (Sekunden) -> Sekunden +export const parseTtl = (value, def = 7 * 24 * 3600)=>{ + if(value === undefined || value === '') return def; + const m = /^(\d+)\s*([smhdw]?)$/i.exec(String(value).trim()); + if(!m) throw new Error(`HB_SESSION_TTL ungültig: "${value}" (erwartet z. B. 7d, 12h, 3600)`); + const mult = { '': 1, s: 1, m: 60, h: 3600, d: 86400, w: 604800 }[m[2].toLowerCase()]; + const seconds = Number(m[1]) * mult; + if(seconds <= 0) throw new Error('HB_SESSION_TTL muss größer als 0 sein'); + return seconds; +}; + +export const readAuthConfig = (env = process.env)=>{ + const issuer = env.HB_OIDC_ISSUER || undefined; + + let providers; + if(env.HB_AUTH_PROVIDERS && env.HB_AUTH_PROVIDERS.trim()) { + providers = [...new Set(env.HB_AUTH_PROVIDERS.split(',').map((p)=>p.trim().toLowerCase()).filter(Boolean))]; + const unknown = providers.filter((p)=>!VALID_PROVIDERS.includes(p)); + if(unknown.length) throw new Error(`HB_AUTH_PROVIDERS: unbekannte Werte ${unknown.join(', ')} (erlaubt: ${VALID_PROVIDERS.join(', ')})`); + } else { + providers = issuer ? ['oidc', 'naturalcrit'] : ['naturalcrit']; + } + + const publicUrl = (env.HB_PUBLIC_URL || '').replace(/\/+$/, ''); + const config = { + providers, + publicUrl, + secureCookies : publicUrl.startsWith('https://'), + sessionSecret : env.HB_SESSION_SECRET || undefined, + sessionTtl : parseTtl(env.HB_SESSION_TTL), + oidc : { + issuer, + clientId : env.HB_OIDC_CLIENT_ID || undefined, + clientSecret : env.HB_OIDC_CLIENT_SECRET || undefined, + scopes : (env.HB_OIDC_SCOPES || 'openid profile email').trim(), + usernameClaim : env.HB_OIDC_USERNAME_CLAIM || 'preferred_username', + linkByEmail : bool(env.HB_OIDC_LINK_BY_EMAIL), + endSession : bool(env.HB_OIDC_END_SESSION), + label : env.HB_OIDC_LABEL || 'Anmelden' + } + }; + + if(providers.includes('oidc')) { + const required = { + HB_OIDC_ISSUER : config.oidc.issuer, + HB_OIDC_CLIENT_ID : config.oidc.clientId, + HB_OIDC_CLIENT_SECRET : config.oidc.clientSecret, + HB_PUBLIC_URL : config.publicUrl, + HB_SESSION_SECRET : config.sessionSecret + }; + const missing = Object.entries(required).filter(([, v])=>!v).map(([k])=>k); + if(missing.length) throw new Error(`Auth-Provider "oidc" ist aktiv, aber es fehlen: ${missing.join(', ')}`); + if(Buffer.byteLength(config.sessionSecret) < MIN_SECRET_BYTES) { + throw new Error(`HB_SESSION_SECRET muss mindestens ${MIN_SECRET_BYTES} Byte lang sein`); + } + if(!/^https?:\/\//.test(config.publicUrl)) throw new Error('HB_PUBLIC_URL muss mit http:// oder https:// beginnen'); + try { new URL(config.oidc.issuer); } catch { throw new Error('HB_OIDC_ISSUER ist keine gültige URL'); } + } + + return config; +}; + +export const hasProvider = (config, name)=>config.providers.includes(name); + +// Nur das, was der Client wissen darf (kein Secret) +const loginUrlFor = (providers)=>{ + if(!providers.includes('oidc')) return null; + return providers.includes('naturalcrit') ? '/auth/login' : '/auth/oidc/login'; +}; + +export const clientConfig = (config)=>({ + providers : config.providers, + loginUrl : loginUrlFor(config.providers), + logoutUrl : '/auth/logout', + oidcLabel : config.oidc.label +}); diff --git a/server/fork/auth/config.spec.js b/server/fork/auth/config.spec.js new file mode 100644 index 00000000..6663374d --- /dev/null +++ b/server/fork/auth/config.spec.js @@ -0,0 +1,55 @@ +import { readAuthConfig, parseTtl, clientConfig } from './config.js'; + +const base = { + HB_PUBLIC_URL : 'https://brew.example.org/', HB_OIDC_ISSUER : 'https://idp.example/realms/x', + HB_OIDC_CLIENT_ID : 'id', HB_OIDC_CLIENT_SECRET : 's', HB_SESSION_SECRET : 'x'.repeat(32) +}; + +describe('Auth-Konfiguration', ()=>{ + test('Standard ohne Angaben: nur naturalcrit (Upstream-Verhalten)', ()=>{ + const c = readAuthConfig({}); + expect(c.providers).toEqual(['naturalcrit']); + expect(clientConfig(c).loginUrl).toBeNull(); + }); + + test('Issuer gesetzt, Provider leer: oidc,naturalcrit mit Auswahlseite', ()=>{ + const c = readAuthConfig(base); + expect(c.providers).toEqual(['oidc', 'naturalcrit']); + expect(c.publicUrl).toBe('https://brew.example.org'); + expect(c.secureCookies).toBe(true); + expect(clientConfig(c).loginUrl).toBe('/auth/login'); + expect(c.oidc).toMatchObject({ scopes: 'openid profile email', usernameClaim: 'preferred_username', linkByEmail: false, endSession: false, label: 'Anmelden' }); + }); + + test('nur oidc: direkter Login-Link', ()=>{ + const c = readAuthConfig({ ...base, HB_AUTH_PROVIDERS: 'oidc' }); + expect(c.providers).toEqual(['oidc']); + expect(clientConfig(c).loginUrl).toBe('/auth/oidc/login'); + }); + + test('Startprüfung nennt fehlende Variablen', ()=>{ + expect(()=>readAuthConfig({ HB_AUTH_PROVIDERS: 'oidc' })).toThrow(/HB_OIDC_ISSUER.*HB_OIDC_CLIENT_ID.*HB_OIDC_CLIENT_SECRET.*HB_PUBLIC_URL.*HB_SESSION_SECRET/); + }); + + test('zu kurzes Session-Secret und unbekannter Provider brechen ab', ()=>{ + expect(()=>readAuthConfig({ ...base, HB_SESSION_SECRET: 'kurz' })).toThrow(/32 Byte/); + expect(()=>readAuthConfig({ HB_AUTH_PROVIDERS: 'ldap' })).toThrow(/unbekannte/); + }); + + test('http-URL: Cookies nicht Secure', ()=>{ + expect(readAuthConfig({ ...base, HB_PUBLIC_URL: 'http://localhost:8000' }).secureCookies).toBe(false); + }); + + test('TTL-Formate', ()=>{ + expect(parseTtl('7d')).toBe(604800); + expect(parseTtl('12h')).toBe(43200); + expect(parseTtl('3600')).toBe(3600); + expect(parseTtl(undefined)).toBe(604800); + expect(()=>parseTtl('bald')).toThrow(); + expect(()=>parseTtl('0')).toThrow(); + }); + + test('Secret taucht nicht in der Client-Konfiguration auf', ()=>{ + expect(JSON.stringify(clientConfig(readAuthConfig(base)))).not.toMatch(/secret|"s"/i); + }); +}); diff --git a/server/fork/auth/index.js b/server/fork/auth/index.js new file mode 100644 index 00000000..ea8dddb9 --- /dev/null +++ b/server/fork/auth/index.js @@ -0,0 +1,129 @@ +import express from 'express'; +import cookieParser from 'cookie-parser'; +import { readAuthConfig, hasProvider, clientConfig } from './config.js'; +import { createOidcClient, OidcCallbackError } from './oidc.js'; +import { issueSession, readSession, clearSession, setTx, takeTx, safeRedirect } from './session.js'; +import { mapAccount } from './accountMapping.js'; + +export { readAuthConfig, clientConfig }; + +const esc = (s)=>String(s).replace(/[&<>"']/g, (c)=>({ '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''' }[c])); + +const page = (title, body)=>`${esc(title)}` + + `` + + `` + + `

${esc(title)}

${body}`; + +const errorPage = (res, status, message, retryUrl = '/auth/oidc/login')=>{ + res.status(status).type('html').send(page('Anmeldung fehlgeschlagen', + `

${esc(message)}

Erneut anmelden

`)); +}; + +// Account-Middleware: läuft direkt nach der Upstream-Middleware und setzt req.account neu (ADR 0001 §3) +export const accountMiddleware = (config)=>(req, res, next)=>{ + const session = hasProvider(config, 'oidc') ? readSession(req, config) : null; + if(session) { + req.account = { username: session.username, uid: session.uid, provider: 'oidc' }; + } else if(hasProvider(config, 'naturalcrit')) { + if(req.account) req.account = { ...req.account, provider: 'naturalcrit' }; + } else { + req.account = undefined; + } + next(); +}; + +/** + * @param {object} config Ergebnis von readAuthConfig() + * @param {{ getUsers: ()=>object, brewAuthorExists: (name:string)=>Promise, oidcClient?: object }} deps + */ +export const createAuthRouter = (config, deps = {})=>{ + const router = express.Router(); + const oidcEnabled = hasProvider(config, 'oidc'); + const naturalcritEnabled = hasProvider(config, 'naturalcrit'); + const parseCookies = cookieParser(); + router.use((req, res, next)=>req.cookies ? next() : parseCookies(req, res, next)); + + // Upstream-Route sperren/umleiten, bevor sie greift + router.put('/api/user/rename', (req, res, next)=>{ + if(req.account?.provider === 'oidc') { + return res.status(403).json({ + error : 'Benutzernamen von OIDC-Konten sind unveränderlich.', + HBErrorCode : 'A01' + }); + } + next(); + }); + + if(!naturalcritEnabled) { + router.post('/local/login', (req, res)=>res.status(404).json({ error: 'Not found' })); + } + + router.get('/auth/logout', async (req, res)=>{ + const wasOidc = req.account?.provider === 'oidc'; + clearSession(res, config); + if(wasOidc && oidcEnabled) { + try { + const url = await (deps.oidcClient ?? (deps.oidcClient = createOidcClient(config))).buildEndSessionUrl(); + if(url) return res.redirect(url); + } catch (err) { + console.warn('OIDC end_session nicht möglich:', err?.message); + } + } + res.redirect('/'); + }); + + if(!oidcEnabled) { + // Abgeschaltete Methode: Endpunkte gesperrt + router.all('/auth/oidc/*splat', (req, res)=>res.status(404).json({ error: 'OIDC-Login ist deaktiviert.' })); + router.get('/auth/login', (req, res)=>res.status(404).json({ error: 'Not found' })); + return router; + } + + const oidc = deps.oidcClient ?? (deps.oidcClient = createOidcClient(config)); + + // Auswahlseite, wenn beide Provider aktiv sind + router.get('/auth/login', (req, res)=>{ + const redirect = safeRedirect(req.query.redirect); + if(!naturalcritEnabled) return res.redirect(`/auth/oidc/login?redirect=${encodeURIComponent(redirect)}`); + const ncUrl = `https://www.naturalcrit.com/login?redirect=${encodeURIComponent(`${config.publicUrl}${redirect}`)}`; + res.type('html').send(page('Anmelden', + `${esc(config.oidc.label)}` + + `NaturalCrit-Konto (Benutzername/Passwort, Google)`)); + }); + + router.get('/auth/oidc/login', async (req, res)=>{ + try { + const { url, tx } = await oidc.buildLogin(req.query.redirect); + setTx(res, config, tx); + res.redirect(url); + } catch (err) { + console.error('OIDC login:', err); + errorPage(res, err.status ?? 502, err.message ?? 'Anmeldung nicht möglich.'); + } + }); + + router.get('/auth/oidc/callback', async (req, res)=>{ + const tx = takeTx(req, res, config); + if(!tx) return errorPage(res, 400, 'Die Anmeldung ist abgelaufen oder wurde nicht von dieser Seite gestartet.'); + if(req.query.state !== tx.state) return errorPage(res, 400, 'Ungültiger Anmeldezustand (state).'); + + try { + const identity = await oidc.handleCallback(tx, `${config.publicUrl}${req.originalUrl}`); + const users = deps.getUsers(); + const user = await mapAccount(identity, { + users, + brewAuthorExists : deps.brewAuthorExists, + usernameClaim : config.oidc.usernameClaim, + linkByEmail : config.oidc.linkByEmail + }); + issueSession(res, config, user, identity); + res.redirect(safeRedirect(tx.redirect)); + } catch (err) { + console.error('OIDC callback:', err?.cause ?? err); + if(err instanceof OidcCallbackError) return errorPage(res, err.status, err.message); + errorPage(res, 500, 'Die Anmeldung ist fehlgeschlagen.'); + } + }); + + return router; +}; diff --git a/server/fork/auth/oidc.js b/server/fork/auth/oidc.js new file mode 100644 index 00000000..e71013ea --- /dev/null +++ b/server/fork/auth/oidc.js @@ -0,0 +1,102 @@ +import * as client from 'openid-client'; +import { randomToken, safeRedirect } from './session.js'; + +export class OidcCallbackError extends Error { + constructor(message, { status = 400, cause } = {}) { + super(message, { cause }); + this.name = 'OidcCallbackError'; + this.status = status; + } +} + +// Discovery gecacht; bei Fehler wird beim nächsten Login neu versucht (kein Start-Abbruch) +export const createOidcClient = (config, { clientLib = client } = {})=>{ + let cached; + const { oidc } = config; + const redirectUri = `${config.publicUrl}/auth/oidc/callback`; + + const getConfiguration = async ()=>{ + if(cached) return cached; + const issuerUrl = new URL(oidc.issuer); + const options = issuerUrl.protocol === 'http:' ? { execute: [clientLib.allowInsecureRequests] } : undefined; + try { + cached = await clientLib.discovery( + issuerUrl, + oidc.clientId, + { client_secret: oidc.clientSecret }, + clientLib.ClientSecretBasic(oidc.clientSecret), + options + ); + } catch (err) { + throw new OidcCallbackError('Der Identity Provider ist nicht erreichbar.', { status: 502, cause: err }); + } + return cached; + }; + + return { + redirectUri, + + async buildLogin(redirect) { + const cfg = await getConfiguration(); + const codeVerifier = clientLib.randomPKCECodeVerifier(); + const state = randomToken(); + const nonce = randomToken(); + const url = clientLib.buildAuthorizationUrl(cfg, { + redirect_uri : redirectUri, + scope : oidc.scopes, + code_challenge : await clientLib.calculatePKCECodeChallenge(codeVerifier), + code_challenge_method : 'S256', + state, + nonce + }); + return { url: url.href, tx: { codeVerifier, state, nonce, redirect: safeRedirect(redirect), createdAt: Date.now() } }; + }, + + // Gibt { iss, sub, claims } zurück oder wirft OidcCallbackError + async handleCallback(tx, callbackUrl) { + const cfg = await getConfiguration(); + let tokens; + try { + tokens = await clientLib.authorizationCodeGrant(cfg, new URL(callbackUrl), { + pkceCodeVerifier : tx.codeVerifier, + expectedState : tx.state, + expectedNonce : tx.nonce, + idTokenExpected : true + }); + } catch (err) { + if(err?.code === 'OAUTH_RESPONSE_BODY_ERROR' || err instanceof clientLib.AuthorizationResponseError) { + throw new OidcCallbackError(`Anmeldung abgelehnt (${err.error ?? 'Fehler'}).`, { status: 400, cause: err }); + } + throw new OidcCallbackError('Die Antwort des Identity Providers konnte nicht verifiziert werden.', { status: 400, cause: err }); + } + + const claims = tokens.claims(); + if(!claims?.sub) throw new OidcCallbackError('ID-Token ohne "sub".'); + let merged = { ...claims }; + // E-Mail (und Username-Claim) bei Bedarf vom userinfo_endpoint ergänzen + const needsUserinfo = !claims.email || (oidc.usernameClaim && claims[oidc.usernameClaim] === undefined); + if(needsUserinfo && cfg.serverMetadata().userinfo_endpoint && tokens.access_token) { + try { + const info = await clientLib.fetchUserInfo(cfg, tokens.access_token, claims.sub); + merged = { ...info, ...claims, ...(claims.email ? {} : { email: info.email, email_verified: info.email_verified }) }; + if(claims[oidc.usernameClaim] === undefined && info[oidc.usernameClaim] !== undefined) { + merged[oidc.usernameClaim] = info[oidc.usernameClaim]; + } + } catch (err) { + console.warn('OIDC userinfo fehlgeschlagen:', err?.message); + } + } + return { iss: claims.iss, sub: claims.sub, claims: merged }; + }, + + async buildEndSessionUrl() { + if(!oidc.endSession) return null; + const cfg = await getConfiguration(); + if(!cfg.serverMetadata().end_session_endpoint) return null; + return clientLib.buildEndSessionUrl(cfg, { + client_id : oidc.clientId, + post_logout_redirect_uri : `${config.publicUrl}/` + }).href; + } + }; +}; diff --git a/server/fork/auth/session.js b/server/fork/auth/session.js new file mode 100644 index 00000000..ac9ba716 --- /dev/null +++ b/server/fork/auth/session.js @@ -0,0 +1,81 @@ +import crypto from 'crypto'; +import jwt from 'jsonwebtoken'; + +export const SESSION_COOKIE = 'hb_session'; +export const TX_COOKIE = 'hb_oidc_tx'; +const TX_MAX_AGE = 600; // Sekunden + +const cookieBase = (config)=>({ httpOnly: true, secure: config.secureCookies, sameSite: 'lax' }); + +// ---- hb_session: JWT HS256, feste Laufzeit ---- +export const issueSession = (res, config, user, { iss, sub })=>{ + const token = jwt.sign( + { v: 1, uid: user.id, username: user.username, iss, sub }, + config.sessionSecret, + { algorithm: 'HS256', expiresIn: config.sessionTtl } + ); + res.cookie(SESSION_COOKIE, token, { ...cookieBase(config), path: '/', maxAge: config.sessionTtl * 1000 }); + return token; +}; + +export const readSession = (req, config)=>{ + const token = req.cookies?.[SESSION_COOKIE]; + if(!token || !config.sessionSecret) return null; + try { + const p = jwt.verify(token, config.sessionSecret, { algorithms: ['HS256'] }); + if(p.v !== 1 || !p.username || !p.uid) return null; + return p; + } catch { + return null; + } +}; + +export const clearSession = (res, config)=>{ + res.clearCookie(SESSION_COOKIE, { ...cookieBase(config), path: '/' }); +}; + +// ---- hb_oidc_tx: AES-256-GCM, Schlüssel per HKDF aus HB_SESSION_SECRET ---- +const txKey = (config)=>Buffer.from(crypto.hkdfSync('sha256', config.sessionSecret, '', 'oidc-tx', 32)); + +export const sealTx = (config, payload)=>{ + const iv = crypto.randomBytes(12); + const cipher = crypto.createCipheriv('aes-256-gcm', txKey(config), iv); + const enc = Buffer.concat([cipher.update(JSON.stringify(payload), 'utf8'), cipher.final()]); + return Buffer.concat([iv, cipher.getAuthTag(), enc]).toString('base64url'); +}; + +export const openTx = (config, value)=>{ + try { + const buf = Buffer.from(value, 'base64url'); + if(buf.length < 29) return null; + const decipher = crypto.createDecipheriv('aes-256-gcm', txKey(config), buf.subarray(0, 12)); + decipher.setAuthTag(buf.subarray(12, 28)); + const dec = Buffer.concat([decipher.update(buf.subarray(28)), decipher.final()]); + return JSON.parse(dec.toString('utf8')); + } catch { + return null; + } +}; + +export const setTx = (res, config, tx)=>{ + res.cookie(TX_COOKIE, sealTx(config, tx), { ...cookieBase(config), path: '/auth/oidc', maxAge: TX_MAX_AGE * 1000 }); +}; + +// Liest und löscht die Transaktion; null bei fehlend/manipuliert/abgelaufen +export const takeTx = (req, res, config, now = Date.now())=>{ + const raw = req.cookies?.[TX_COOKIE]; + res.clearCookie(TX_COOKIE, { ...cookieBase(config), path: '/auth/oidc' }); + if(!raw) return null; + const tx = openTx(config, raw); + if(!tx || typeof tx.createdAt !== 'number' || now - tx.createdAt > TX_MAX_AGE * 1000) return null; + return tx; +}; + +export const randomToken = ()=>crypto.randomBytes(32).toString('base64url'); + +// Nur relative Pfade zulassen (kein "//", kein "\") +export const safeRedirect = (value)=>{ + if(typeof value !== 'string' || !value.startsWith('/')) return '/'; + if(value.startsWith('//') || value.includes('\\') || /[\u0000-\u001f]/.test(value)) return '/'; + return value; +}; diff --git a/server/fork/auth/session.spec.js b/server/fork/auth/session.spec.js new file mode 100644 index 00000000..1124d7ee --- /dev/null +++ b/server/fork/auth/session.spec.js @@ -0,0 +1,48 @@ +import jwt from 'jsonwebtoken'; +import { readAuthConfig } from './config.js'; +import { readSession, sealTx, openTx, safeRedirect, SESSION_COOKIE } from './session.js'; + +const config = readAuthConfig({ + HB_PUBLIC_URL : 'http://localhost:8000', HB_OIDC_ISSUER : 'http://idp', HB_OIDC_CLIENT_ID : 'id', + HB_OIDC_CLIENT_SECRET : 's', HB_SESSION_SECRET : 'a'.repeat(32) +}); +const req = (token)=>({ cookies: { [SESSION_COOKIE]: token } }); +const payload = { v: 1, uid: 'u', username: 'bob', iss: 'i', sub: 's' }; + +describe('Session-Cookie', ()=>{ + test('gültiges Token', ()=>{ + expect(readSession(req(jwt.sign(payload, config.sessionSecret, { expiresIn: 60 })), config)).toMatchObject({ username: 'bob' }); + }); + test('abgelaufen, falsches Secret, alg none und Müll werden abgelehnt', ()=>{ + expect(readSession(req(jwt.sign(payload, config.sessionSecret, { expiresIn: -10 })), config)).toBeNull(); + expect(readSession(req(jwt.sign(payload, 'b'.repeat(32), { expiresIn: 60 })), config)).toBeNull(); + expect(readSession(req(jwt.sign(payload, '', { algorithm: 'none' })), config)).toBeNull(); + expect(readSession(req(jwt.sign(payload, config.sessionSecret, { algorithm: 'HS512', expiresIn: 60 })), config)).toBeNull(); + expect(readSession(req('müll'), config)).toBeNull(); + expect(readSession({ cookies: {} }, config)).toBeNull(); + }); + test('Upstream-JWT (nc_session-Format ohne v/uid) wird nicht als Session akzeptiert', ()=>{ + expect(readSession(req(jwt.sign({ username: 'bob' }, config.sessionSecret, { expiresIn: 60 })), config)).toBeNull(); + }); +}); + +describe('Transaktions-Cookie', ()=>{ + test('Roundtrip und Manipulationsschutz', ()=>{ + const sealed = sealTx(config, { a: 1 }); + expect(openTx(config, sealed)).toEqual({ a: 1 }); + const broken = sealed.slice(0, -2) + (sealed.endsWith('AA') ? 'BB' : 'AA'); + expect(openTx(config, broken)).toBeNull(); + expect(openTx({ ...config, sessionSecret: 'c'.repeat(32) }, sealed)).toBeNull(); + expect(openTx(config, 'kurz')).toBeNull(); + }); +}); + +describe('safeRedirect', ()=>{ + test.each([ + ['/brews', '/brews'], ['/edit/abc?x=1#y', '/edit/abc?x=1#y'], ['/', '/'], + ['//evil.com', '/'], ['https://evil.com', '/'], ['/\\evil.com', '/'], ['javascript:alert(1)', '/'], + ['/a\r\nSet-Cookie: x=y', '/'], [undefined, '/'], [['/a'], '/'] + ])('%j -> %j', (input, expected)=>{ + expect(safeRedirect(input)).toBe(expected); + }); +}); diff --git a/server/fork/auth/testIdp.js b/server/fork/auth/testIdp.js new file mode 100644 index 00000000..f039e5b1 --- /dev/null +++ b/server/fork/auth/testIdp.js @@ -0,0 +1,82 @@ +// In-Process-Mock-IdP (oidc-provider von panva) für die Auth-Tests. Nur Test-Hilfe. +import http from 'http'; +import Provider from 'oidc-provider'; + +export const CLIENT = { client_id: 'hb-test', client_secret: 'hb-test-secret' }; + +export const startIdp = async ({ accounts, redirectUri })=>{ + let handler = (req, res)=>{ res.statusCode = 503; res.end(); }; + const server = http.createServer((req, res)=>handler(req, res)); + await new Promise((r)=>server.listen(0, '127.0.0.1', r)); + const issuer = `http://127.0.0.1:${server.address().port}`; + const provider = new Provider(issuer, { + clients : [{ + ...CLIENT, + redirect_uris : [redirectUri], + post_logout_redirect_uris : [`${new URL(redirectUri).origin}/`], + grant_types : ['authorization_code'], + response_types : ['code'], + token_endpoint_auth_method : 'client_secret_basic' + }], + pkce : { required: ()=>true }, + scopes : ['openid', 'profile', 'email'], + claims : { openid: ['sub'], profile: ['name', 'preferred_username'], email: ['email', 'email_verified'] }, + findAccount : async (ctx, id)=>accounts[id] && { + accountId : id, + claims : async ()=>({ sub: id, ...accounts[id] }) + }, + features : { devInteractions: { enabled: true }, rpInitiatedLogout: { enabled: true, logoutSource: async (ctx, form)=>{ ctx.body = `${form}`; } } }, + cookies : { keys: ['test-key'] }, + ttl : { AuthorizationCode: 60, IdToken: 60, AccessToken: 60, Session: 60, Interaction: 60, Grant: 60 } + }); + provider.proxy = true; + handler = provider.callback(); + return { issuer, provider, close: ()=>new Promise((r)=>{ server.closeAllConnections?.(); server.close(r); }) }; +}; + +// Fährt den Login-Flow wie ein Browser (Cookie-Jar) bis zum Redirect auf die App und gibt die Callback-URL zurück +export const loginAtIdp = async (authUrl, { login })=>{ + const jar = {}; + const setCookies = (res)=>{ + for (const c of res.headers.getSetCookie()) { + const [kv] = c.split(';'); + const i = kv.indexOf('='); + jar[kv.slice(0, i)] = kv.slice(i + 1); + } + }; + const cookieHeader = ()=>Object.entries(jar).map(([k, v])=>`${k}=${v}`).join('; '); + const step = async (url, init = {})=>{ + const res = await fetch(url, { redirect: 'manual', ...init, headers: { cookie: cookieHeader(), ...(init.headers || {}) } }); + setCookies(res); + return res; + }; + const origin = new URL(authUrl).origin; + let res = await step(authUrl); + let guard = 0; + while (guard++ < 15) { + const loc = res.headers.get('location'); + if(!loc) throw new Error(`IdP-Flow ohne Redirect bei ${res.url}: ${res.status} ${(await res.text()).slice(0, 400)}`); + const next = new URL(loc, origin); + if(next.origin !== origin) return { callbackUrl: next.href }; + if(/^\/interaction\/[^/]+$/.test(next.pathname)) { + const page = await (await step(next.href)).text(); + const form = /]*action="([^"]+)"[\s\S]*?<\/form>/.exec(page); + if(!form) throw new Error(`Interaktion ohne Formular: ${page.slice(0, 300)}`); + const body = new URLSearchParams(); + for (const m of form[0].matchAll(/]*>/g)) { + const name = /name="([^"]+)"/.exec(m[0])?.[1]; + const value = /value="([^"]*)"/.exec(m[0])?.[1] ?? ''; + if(name) body.set(name, value); + } + if(body.has('login')) { body.set('login', login); body.set('password', 'x'); } + res = await step(new URL(form[1], origin).href, { + method : 'POST', + headers : { 'content-type': 'application/x-www-form-urlencoded' }, + body + }); + continue; + } + res = await step(next.href); + } + throw new Error('Zu viele Redirects im IdP-Flow'); +}; diff --git a/server/fork/auth/testUsers.js b/server/fork/auth/testUsers.js new file mode 100644 index 00000000..44951f10 --- /dev/null +++ b/server/fork/auth/testUsers.js @@ -0,0 +1,39 @@ +// In-Memory-UserRepository mit demselben Vertrag wie server/storage/mongo/users.js (Test-Hilfe) +import { randomUUID } from 'crypto'; + +export const createMemoryUsers = ()=>{ + const rows = []; + const plain = (u)=>u && ({ ...u }); + return { + rows, + async create(u) { + if(rows.some((r)=>r.username === u.username)) throw new Error('duplicate username'); + if(u.oidcSub && rows.some((r)=>r.oidcIssuer === u.oidcIssuer && r.oidcSub === u.oidcSub)) throw new Error('duplicate oidc'); + const row = { + id : randomUUID(), username : u.username, oidcIssuer : u.oidcIssuer ?? null, oidcSub : u.oidcSub ?? null, + email : u.email ? u.email.toLowerCase() : null, emailVerified : !!u.emailVerified, displayName : u.displayName ?? null, + createdAt : new Date(), lastLoginAt : null + }; + rows.push(row); + return plain(row); + }, + async findById(id) { return plain(rows.find((r)=>r.id === id)) ?? null; }, + async findByUsername(n) { return plain(rows.find((r)=>r.username === n)) ?? null; }, + async usernameExists(n) { return rows.some((r)=>r.username === n); }, + async findByOidc(i, s) { return plain(rows.find((r)=>r.oidcIssuer === i && r.oidcSub === s)) ?? null; }, + async findUnlinkedByEmail(e) { return rows.filter((r)=>r.email === e.toLowerCase() && !r.oidcSub).map(plain); }, + async update(id, patch) { + const row = rows.find((r)=>r.id === id); + if(!row) return null; + const { id: _i, username: _u, ...rest } = patch; + Object.entries(rest).forEach(([k, v])=>{ if(v !== undefined) row[k] = k === 'email' ? v.toLowerCase() : v; }); + return plain(row); + }, + async delete(id) { + const i = rows.findIndex((r)=>r.id === id); + if(i < 0) return false; + rows.splice(i, 1); + return true; + } + }; +}; diff --git a/server/fork/auth/users.spec.js b/server/fork/auth/users.spec.js new file mode 100644 index 00000000..b8083b71 --- /dev/null +++ b/server/fork/auth/users.spec.js @@ -0,0 +1,7 @@ +import { createMemoryUsers } from './testUsers.js'; +import { runUserRepositoryContract } from '../../storage/contract/users.contract.js'; + +// Der Contract läuft gegen die Test-Implementierung, damit die Suite selbst geprüft ist. +describe('UserRepository-Contract (In-Memory-Referenz)', ()=>{ + runUserRepositoryContract(async ()=>({ users: createMemoryUsers() })); +});