Merge pull request 'feat(auth): Generischer OIDC-Login (Keycloak + Authentik), Alt-Logins abschaltbar' (#17) from flw-84-oidc-login into main
CI / App (npm ci + Build, ESLint, Stylelint, Jest) (push) Successful in 1m23s
Image / Image bauen und pushen (push) Successful in 4m38s

This commit was merged in pull request #17.
This commit is contained in:
claudia-bot Bot authored and Gitea committed 2026-11-25 09:51:42 +00:00
commit 0bf80006df
32 files changed
+2192 -12

No files matched your search

+26
View File
@@ -21,3 +21,29 @@ AUTHENTIK_PORT=9000
AUTHENTIK_SECRET_KEY=dev-only-insecure-secret-key-change-me
AUTHENTIK_DB_PASSWORD=authentik-dev
AUTHENTIK_BOOTSTRAP_PASSWORD=admin-dev
# --- Auth (ADR 0001, docs/auth/) ---------------------------------------------
# Ohne diese Werte verhält sich die App wie Upstream (nur naturalcrit-Login).
# Aktive Login-Methoden, kommagetrennt: oidc, naturalcrit.
# leer + HB_OIDC_ISSUER gesetzt -> oidc,naturalcrit (Auswahlseite /auth/login)
# leer ohne Issuer -> naturalcrit
# oidc -> nur OIDC (nc_session und /local/login gesperrt)
# naturalcrit -> nur Alt-Login (/auth/oidc/* gesperrt)
HB_AUTH_PROVIDERS=oidc
# Öffentliche URL der App, ohne Schrägstrich am Ende (Redirect-URI: <HB_PUBLIC_URL>/auth/oidc/callback)
HB_PUBLIC_URL=http://localhost:8000
# Mindestens 32 Byte, nur Umgebung. Erzeugen: openssl rand -base64 48
HB_SESSION_SECRET=dev-only-session-secret-change-me-0123456789
HB_SESSION_TTL=7d
# Aus Compose heraus: Keycloak (docker compose --profile keycloak up -d)
HB_OIDC_ISSUER=http://keycloak.localhost:8080/realms/homebrewery
# ... oder authentik (docker compose --profile authentik up -d)
# HB_OIDC_ISSUER=http://authentik.localhost:9000/application/o/homebrewery/
HB_OIDC_CLIENT_ID=homebrewery
HB_OIDC_CLIENT_SECRET=dev-only-client-secret
# Optional
# HB_OIDC_SCOPES=openid profile email
# HB_OIDC_USERNAME_CLAIM=preferred_username
# HB_OIDC_LINK_BY_EMAIL=false
# HB_OIDC_END_SESSION=false
# HB_OIDC_LABEL=Anmelden
+1 -1
View File
@@ -1,5 +1,5 @@
node_modules
storage
/storage
.idea
*.swp
+4
View File
@@ -107,6 +107,10 @@ docker compose up --build # App + MongoDB -> http://localhost:8000
Hinweise: Die IdPs laufen unter `keycloak.localhost:8080` bzw. `authentik.localhost:9000` (Issuer für Browser und App-Container identisch, Bindung nur an 127.0.0.1; `*.localhost` löst moderne Browser/OS automatisch auf, sonst `127.0.0.1 keycloak.localhost authentik.localhost` in `/etc/hosts`). Ports nur ändern, wenn Redirect-/Issuer-Einstellungen mitgezogen werden. Alle Zugangsdaten sind reine Dev-Werte, für den Betrieb in `.env` ersetzen. MongoDB 5+ benötigt eine CPU mit AVX; auf älteren CPUs/VMs `MONGO_TAG=4.4` setzen. Der authentik-Blueprint wird beim Erststart automatisch angewendet (dauert einige Minuten, bis die Discovery-URL 200 liefert).
#### Login über OIDC (Keycloak, authentik, …)
Der Fork bringt einen generischen OIDC-Login (Authorization Code + PKCE) mit. Konfiguration nur über Umgebungsvariablen (`HB_OIDC_ISSUER`, `HB_OIDC_CLIENT_ID`, `HB_OIDC_CLIENT_SECRET`, `HB_PUBLIC_URL`, `HB_SESSION_SECRET`, …, Vorlage in `.env.example`). Die bisherigen Logins (`naturalcrit`: Benutzername/Passwort, Google) bleiben Standard und lassen sich über `HB_AUTH_PROVIDERS` abschalten, abgeschaltete Methoden verschwinden aus der UI und ihre Endpunkte sind gesperrt. Einrichtung, Variablen und Kontozuordnung: [docs/auth/README.md](./docs/auth/README.md), [Keycloak](./docs/auth/keycloak.md), [authentik](./docs/auth/authentik.md). Entscheidung: [ADR 0001](./docs/adr/0001-auth-oidc.md).
### Running the application on FreeBSD or FreeNAS
Please see the docs here: [README.FreeBSD.md](./README.FREEBSD.md)
+33
View File
@@ -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';
+5 -3
View File
@@ -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 <Nav.item color='teal' icon='fas fa-sign-in-alt' onClick={this.localLogin}>
login
</Nav.item>;
@@ -105,8 +107,8 @@ const Account = createReactClass({
// Logged out
// Production site
return <Nav.item href={`https://www.naturalcrit.com/login?redirect=${this.state.url}`} color='teal' icon='fas fa-sign-in-alt'>
login
return <Nav.item href={getLoginUrl(this.state.url)} color='teal' icon='fas fa-sign-in-alt'>
{oidcEnabled() ? getOidcLabel() : 'login'}
</Nav.item>;
}
});
@@ -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`
+13
View File
@@ -17,6 +17,19 @@ services:
condition: service_healthy
environment:
MONGODB_URI: ${MONGODB_URI:-mongodb://mongodb/homebrewery}
# Auth (ADR 0001). Leer lassen = Upstream-Verhalten (nur naturalcrit-Login). Siehe docs/auth/.
HB_AUTH_PROVIDERS: ${HB_AUTH_PROVIDERS:-}
HB_PUBLIC_URL: ${HB_PUBLIC_URL:-}
HB_OIDC_ISSUER: ${HB_OIDC_ISSUER:-}
HB_OIDC_CLIENT_ID: ${HB_OIDC_CLIENT_ID:-}
HB_OIDC_CLIENT_SECRET: ${HB_OIDC_CLIENT_SECRET:-}
HB_OIDC_SCOPES: ${HB_OIDC_SCOPES:-}
HB_OIDC_USERNAME_CLAIM: ${HB_OIDC_USERNAME_CLAIM:-}
HB_OIDC_LINK_BY_EMAIL: ${HB_OIDC_LINK_BY_EMAIL:-}
HB_OIDC_END_SESSION: ${HB_OIDC_END_SESSION:-}
HB_OIDC_LABEL: ${HB_OIDC_LABEL:-}
HB_SESSION_SECRET: ${HB_SESSION_SECRET:-}
HB_SESSION_TTL: ${HB_SESSION_TTL:-}
ports: !override
- "${APP_PORT:-8000}:8000"
+68
View File
@@ -0,0 +1,68 @@
# Login (OIDC) einrichten
Umsetzung von [ADR 0001](../adr/0001-auth-oidc.md). Der Login läuft über einen beliebigen
OpenID-Connect-Provider (getestet mit Keycloak und authentik). Alles wird über
Umgebungsvariablen konfiguriert, siehe `.env.example`.
## Schnellstart mit dem Compose-Setup
```sh
cp .env.example .env # enthält Dev-Werte für Keycloak
docker compose --profile keycloak up -d # Keycloak (Start dauert 1-2 Minuten)
docker compose up --build -d # App mit OIDC-Login -> http://localhost:8000
```
Mit authentik: `HB_OIDC_ISSUER` in `.env` auf die authentik-Zeile umstellen und
`--profile authentik` verwenden. Testbenutzer in beiden: `testuser` / `testuser-dev`.
Details: [keycloak.md](keycloak.md), [authentik.md](authentik.md).
## Variablen
| Variable | Pflicht | Standard | Bedeutung |
| --- | --- | --- | --- |
| `HB_AUTH_PROVIDERS` | nein | s. u. | `oidc`, `naturalcrit` (kommagetrennt) |
| `HB_PUBLIC_URL` | bei `oidc` | – | z. B. `https://brew.example.org`, ohne `/` am Ende |
| `HB_OIDC_ISSUER` | bei `oidc` | – | Issuer-URL (Discovery über `/.well-known/openid-configuration`) |
| `HB_OIDC_CLIENT_ID` | bei `oidc` | – | |
| `HB_OIDC_CLIENT_SECRET` | bei `oidc` | – | vertraulicher Client (`client_secret_basic`) |
| `HB_OIDC_SCOPES` | nein | `openid profile email` | |
| `HB_OIDC_USERNAME_CLAIM` | nein | `preferred_username` | Quelle des Benutzernamens bei Neuanlage |
| `HB_OIDC_LINK_BY_EMAIL` | nein | `false` | verifizierte E-Mail an vorab angelegten Benutzer binden |
| `HB_OIDC_END_SESSION` | nein | `false` | beim Logout auch am IdP abmelden |
| `HB_OIDC_LABEL` | nein | `Anmelden` | Text des Login-Buttons |
| `HB_SESSION_SECRET` | bei `oidc` | – | mindestens 32 Byte |
| `HB_SESSION_TTL` | nein | `7d` | feste Session-Laufzeit (`7d`, `12h`, `3600`) |
Die App startet nicht, wenn `oidc` aktiv ist und Pflichtwerte fehlen.
## Login-Methoden ein-/ausschalten (`HB_AUTH_PROVIDERS`)
Der Redirect-URI beim IdP ist `${HB_PUBLIC_URL}/auth/oidc/callback`, der Post-Logout-URI `${HB_PUBLIC_URL}/`.
| Einstellung | Wirkung |
| --- | --- |
| nicht gesetzt, kein Issuer | Upstream-Verhalten: nur `naturalcrit` |
| nicht gesetzt, `HB_OIDC_ISSUER` gesetzt | `oidc,naturalcrit`: Login-Link führt auf die Auswahlseite `/auth/login`. Außerhalb lokaler Umgebungen bricht der Start ab, solange das Upstream-`secret` (Env `SECRET`) der Standardwert `secret` ist, weil sich sonst `nc_session` fälschen ließe; `SECRET` setzen oder `HB_AUTH_PROVIDERS=oidc` |
| `oidc` | nur OIDC. `nc_session` wird ignoriert, `POST /local/login` liefert 404, Google Drive als Speicherort entfällt |
| `naturalcrit` | nur Alt-Login (Benutzername/Passwort und Google laufen bei Upstream über naturalcrit.com). `/auth/oidc/*` liefern 404, ein vorhandenes `hb_session` wird ignoriert |
Hinweis: Benutzername/Passwort- und Google-Login gehören bei Upstream zu naturalcrit.com und nicht zu dieser App
(ADR 0001, Frage F1). Ein Abschalten bedeutet daher: die `nc_session` wird nicht mehr akzeptiert und
die Login-Links verschwinden aus der Oberfläche.
## Kontozuordnung
- Der Benutzer ist über (`iss`, `sub`) eindeutig. Beim ersten Login wird ein Konto angelegt. Der Benutzername
kommt aus `HB_OIDC_USERNAME_CLAIM` (Fallback: Teil der E-Mail vor dem `@`) und ist danach unveränderlich.
Kollidiert er mit einem Benutzer oder einem Autor in bestehenden Brews, wird `-2`, `-3`, … angehängt.
- Bestehende Namen aus `authors[]` werden nicht automatisch übernommen. Mit `HB_OIDC_LINK_BY_EMAIL=true` bindet der
Login einen **vorab angelegten** Benutzer (ohne OIDC-Bindung) an die verifizierte E-Mail des IdP.
Das Anlegen vorab angelegter Benutzer (`POST /admin/users`) ist nicht Teil von M1.
- `PUT /api/user/rename` ist für OIDC-Sitzungen gesperrt (403, `HBErrorCode: A01`).
## Tests
- Automatisiert: `npx jest server/fork/auth` (Mock-IdP `oidc-provider` im Prozess, kein Container nötig).
- Storage-Contract gegen Mongo: `HB_TEST_MONGODB_URI=mongodb://127.0.0.1:27017 npx jest server/storage`.
- E2E gegen echten IdP und laufende App: `node scripts/oidc-e2e.mjs --idp keycloak|authentik`
(siehe die jeweilige Anleitung).
+32
View File
@@ -0,0 +1,32 @@
# authentik
## Compose-Setup (Dev)
`docker compose --profile authentik up -d` startet authentik 2026.2 (Server, Worker, Postgres). Der Blueprint
`docker/authentik/blueprints/homebrewery.yaml` legt Provider und Anwendung `homebrewery` sowie den Benutzer
`testuser` / `testuser-dev` an (Admin `akadmin` / `admin-dev`). Der erste Start braucht mehrere Minuten
(Migrationen, Blueprints). Bereit, sobald die Discovery-URL antwortet.
```env
HB_AUTH_PROVIDERS=oidc
HB_PUBLIC_URL=http://localhost:8000
HB_OIDC_ISSUER=http://authentik.localhost:9000/application/o/homebrewery/
HB_OIDC_CLIENT_ID=homebrewery
HB_OIDC_CLIENT_SECRET=dev-only-client-secret
HB_SESSION_SECRET=<mindestens 32 Byte>
```
Der Issuer enthält den Schrägstrich am Ende genau so, wie authentik ihn in der Discovery ausgibt.
## Eigener authentik
1. *Applications → Create with Provider*, Typ *OAuth2/OpenID*, Slug z. B. `homebrewery`.
2. *Client type*: Confidential. Client-ID und Secret in die Umgebung übernehmen.
3. *Redirect URIs* (Strict): `${HB_PUBLIC_URL}/auth/oidc/callback`.
4. *Scopes*: `openid`, `profile`, `email`. *Signing Key*: ein Zertifikat auswählen (RS256).
5. Issuer: `https://<host>/application/o/<slug>/`.
## Geprüft
E2E gegen authentik 2026.2 (Compose-Profil) mit laufender App:
`node scripts/oidc-e2e.mjs --idp authentik` (der Skript fährt den Flow-Executor der API durch).
+33
View File
@@ -0,0 +1,33 @@
# Keycloak
## Compose-Setup (Dev)
`docker compose --profile keycloak up -d` startet Keycloak 26 mit importiertem Realm `homebrewery`
(`docker/keycloak/realm-homebrewery.json`): Client `homebrewery` (vertraulich, Secret `dev-only-client-secret`,
PKCE S256), Benutzer `testuser` / `testuser-dev`, Admin `admin` / `admin-dev`.
```env
HB_AUTH_PROVIDERS=oidc
HB_PUBLIC_URL=http://localhost:8000
HB_OIDC_ISSUER=http://keycloak.localhost:8080/realms/homebrewery
HB_OIDC_CLIENT_ID=homebrewery
HB_OIDC_CLIENT_SECRET=dev-only-client-secret
HB_SESSION_SECRET=<mindestens 32 Byte>
```
`keycloak.localhost` löst im Browser auf den Host auf und im Compose-Netz per Alias auf Keycloak,
daher ist der Issuer für Browser und App-Container derselbe.
## Eigener Keycloak
1. Realm wählen, Client anlegen: *Client authentication* an, *Standard flow* an, Direct access grants aus.
2. *Valid redirect URIs*: `${HB_PUBLIC_URL}/auth/oidc/callback`. *Valid post logout redirect URIs*: `${HB_PUBLIC_URL}/`.
3. PKCE: *Advanced → Proof Key for Code Exchange Code Challenge Method* = `S256`.
4. Issuer: `https://<host>/realms/<realm>`. Secret unter *Credentials*.
## Geprüft
E2E gegen Keycloak 26.4 (Compose-Profil) mit laufender App:
`node scripts/oidc-e2e.mjs --idp keycloak` (bei `NODE_ENV=production` hinter http zusätzlich
`--forwarded-proto https`). Geprüft: Weiterleitung mit PKCE/state/nonce, Login, Callback, Session,
Konto `testuser`, Logout (mit `HB_OIDC_END_SESSION=true` über den `end_session_endpoint`), Fehlerfall ohne Transaktion.
+344
View File
@@ -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",
+4 -1
View File
@@ -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",
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env node
// E2E-Smoketest des OIDC-Logins gegen eine laufende App und einen echten IdP (Keycloak oder Authentik
// aus dem Compose-Setup). Fährt den Flow wie ein Browser (Cookie-Jar), ohne Browser-Abhängigkeit.
//
// Aufruf: node scripts/oidc-e2e.mjs --idp keycloak|authentik [--base http://localhost:8000]
// [--user testuser] [--password testuser-dev] [--expect testuser] [--forwarded-proto https]
// Exit-Code 0 = alle Prüfungen bestanden.
const arg = (name, def)=>{
const i = process.argv.indexOf(`--${name}`);
return i > -1 ? process.argv[i + 1] : def;
};
const idpKind = arg('idp');
const base = arg('base', 'http://localhost:8000').replace(/\/$/, '');
const user = arg('user', 'testuser');
const password = arg('password', 'testuser-dev');
const expectName = arg('expect', user);
const forwardedProto = arg('forwarded-proto'); // nur nötig, wenn die App mit NODE_ENV=production hinter http läuft
if(!['keycloak', 'authentik'].includes(idpKind)) {
console.error('--idp keycloak|authentik angeben');
process.exit(2);
}
const jar = new Map();
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).trim();
const value = kv.slice(i + 1);
const key = `${new URL(res.url).hostname}|${name}`;
if(!value || attrs.some((a)=>/expires=Thu, 01 Jan 1970/i.test(a) || /max-age=0/i.test(a))) jar.delete(key); else jar.set(key, { name, value });
}
};
const cookieFor = (url)=>[...jar.entries()].filter(([k])=>k.startsWith(`${new URL(url).hostname}|`)).map(([, c])=>`${c.name}=${c.value}`).join('; ');
const http = async (url, init = {})=>{
const headers = { cookie: cookieFor(url), ...(forwardedProto && url.startsWith(base) ? { 'x-forwarded-proto': forwardedProto } : {}), ...(init.headers || {}) };
const res = await fetch(url, { redirect: 'manual', ...init, headers });
store(res);
return res;
};
const follow = async (url, init)=>{ // folgt Redirects, solange sie beim IdP bleiben; stoppt beim Wechsel zur App
let res = await http(url, init);
for(let i = 0; i < 20; i++) {
const loc = res.headers.get('location');
if(!loc) return { res, url };
const next = new URL(loc, url).href;
if(next.startsWith(base)) return { res, url, callback: next };
url = next;
res = await http(url);
}
throw new Error('Zu viele Redirects');
};
let failed = 0;
const check = (name, ok, detail = '')=>{
console.log(`${ok ? 'OK ' : 'FAIL'} ${name}${detail ? ` (${detail})` : ''}`);
if(!ok) failed++;
};
const hidden = (html, name)=>new RegExp(`name="${name}"[^>]*value="([^"]*)"`).exec(html)?.[1];
const loginKeycloak = async (authUrl)=>{
const { res, url } = await follow(authUrl);
const html = await res.text();
const action = /<form[^>]*id="kc-form-login"[^>]*action="([^"]+)"/.exec(html)?.[1]?.replaceAll('&amp;', '&');
if(!action) throw new Error(`Keycloak-Loginformular nicht gefunden (Status ${res.status})`);
const post = await follow(new URL(action, url).href, {
method : 'POST',
headers : { 'content-type': 'application/x-www-form-urlencoded' },
body : new URLSearchParams({ username: user, password, credentialId: hidden(html, 'credentialId') ?? '' })
});
return post.callback;
};
const loginAuthentik = async (authUrl)=>{
const origin = new URL(authUrl).origin;
const first = await http(authUrl);
const loc = new URL(first.headers.get('location'), origin);
// /if/flow/<slug>/?next=<authorize-url>
const slug = loc.pathname.split('/').filter(Boolean)[2];
let exec = `${origin}/api/v3/flows/executor/${slug}/?query=${encodeURIComponent(loc.search.slice(1))}`;
const jsonHeaders = { 'content-type': 'application/json', accept: 'application/json' };
const send = async (body)=>{
let res = await http(exec, body ? { method: 'POST', headers: jsonHeaders, body: JSON.stringify(body) } : { headers: jsonHeaders });
// authentik normalisiert die Query per Redirect; neue URL merken und erneut senden
for(let i = 0; i < 3 && [301, 302, 303, 307, 308].includes(res.status); i++) {
exec = new URL(res.headers.get('location'), origin).href;
res = await http(exec, body ? { method: 'POST', headers: jsonHeaders, body: JSON.stringify(body) } : { headers: jsonHeaders });
}
const text = await res.text();
try { return JSON.parse(text); } catch { throw new Error(`Authentik-Executor: Status ${res.status}, Antwort kein JSON: ${text.slice(0, 200)}`); }
};
let ch = await send();
for(let i = 0; i < 8; i++) {
if(ch.component === 'ak-stage-identification') ch = await send({ uid_field: user });
else if(ch.component === 'ak-stage-password') ch = await send({ password });
else if(ch.component === 'xak-flow-redirect') break;
else if(ch.component === 'ak-stage-authenticator-validate' && !ch.device_challenges?.length) ch = await send(); // kein MFA-Gerät: Stage neu laden (wird übersprungen)
else if(ch.component === 'ak-stage-consent') ch = await send({});
else throw new Error(`Unerwartete Authentik-Stage: ${ch.component} ${JSON.stringify({ ...ch, flow_info: undefined, pending_user_avatar: undefined }).slice(0, 900)}`);
}
if(ch.component !== 'xak-flow-redirect') throw new Error('Authentik-Flow endete nicht im Redirect');
const { callback } = await follow(new URL(ch.to, origin).href);
return callback;
};
const accountFromPage = async (path)=>{
const html = await (await http(`${base}${path}`)).text();
const m = /window\.__INITIAL_PROPS__ = (\{.*?\})<\/script>/s.exec(html);
return m ? JSON.parse(m[1]) : null;
};
try {
const start = await http(`${base}/auth/oidc/login?redirect=${encodeURIComponent('/account')}`);
const authUrl = start.headers.get('location');
check('Login leitet zum IdP weiter', start.status === 302 && !!authUrl, authUrl?.split('?')[0]);
const q = new URL(authUrl).searchParams;
check('PKCE S256, state und nonce gesetzt', q.get('code_challenge_method') === 'S256' && !!q.get('state') && !!q.get('nonce'));
const callback = await (idpKind === 'keycloak' ? loginKeycloak : loginAuthentik)(authUrl);
check('IdP leitet auf den Callback der App zurück', !!callback, callback?.split('?')[0]);
const cb = await http(callback);
check('Callback stellt Session aus und leitet auf die Zielseite', cb.status === 302 && cb.headers.get('location') === '/account', `${cb.status} ${cb.headers.get('location')}`);
check('Session-Cookie hb_session gesetzt', cb.headers.getSetCookie().some((c)=>c.startsWith('hb_session=') && /httponly/i.test(c)));
const props = await accountFromPage('/account');
check(`Angemeldet als "${expectName}" (provider oidc)`, props?.account?.username === expectName && props.account.provider === 'oidc', JSON.stringify(props?.account));
check('Client-Konfiguration enthält Auth-Provider', props?.config?.auth?.providers?.includes('oidc'), JSON.stringify(props?.config?.auth));
// Zweiter Login desselben Benutzers: gleiches Konto
const out = await http(`${base}/auth/logout`);
check('Logout leitet weiter und löscht die Session', out.status === 302 && !jar.has(`${new URL(base).hostname}|hb_session`), out.headers.get('location')?.split('?')[0]);
const after = await accountFromPage('/account');
check('Nach Logout kein Konto', !after?.account);
// Fehlerfall: Callback ohne Transaktion
const bad = await http(`${base}/auth/oidc/callback?code=x&state=y`);
check('Callback ohne Transaktion → 400', bad.status === 400);
} catch(err) {
console.error('FEHLER:', err.message);
failed++;
}
console.log(failed ? `\n${failed} Prüfung(en) fehlgeschlagen` : '\nAlle Prüfungen bestanden');
process.exit(failed ? 1 : 0);
+2 -2
View File
@@ -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);
});
+13 -1
View File
@@ -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(process.env, { upstreamSecret: config.get('secret'), isLocal: isLocalEnvironment });
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,
+75
View File
@@ -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<boolean>, 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;
}
}
};
+108
View File
@@ -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();
});
});
});
+390
View File
@@ -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
}, { upstreamSecret: 'eigenes-secret' });
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 }, { upstreamSecret: 'eigenes-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 }, { upstreamSecret: 'eigenes-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 }, { upstreamSecret: 'eigenes-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);
});
});
+94
View File
@@ -0,0 +1,94 @@
// 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, { upstreamSecret, isLocal = false } = {})=>{
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');
let issuerUrl;
try { issuerUrl = new URL(config.oidc.issuer); } catch { throw new Error('HB_OIDC_ISSUER ist keine gültige URL'); }
// http://-Issuer nur im Dev-Setup (HB_PUBLIC_URL selbst http://), sonst läuft Discovery/JWKS/Token unverschlüsselt
if(issuerUrl.protocol === 'http:' && config.publicUrl.startsWith('https://')) {
throw new Error('HB_OIDC_ISSUER muss https:// verwenden, wenn HB_PUBLIC_URL https:// ist');
}
// Upstream-nc_session wird mit config "secret" signiert; Standardwert => Sitzung fälschbar
if(providers.includes('naturalcrit') && !isLocal && (!upstreamSecret || upstreamSecret === 'secret')) {
throw new Error('Auth: "naturalcrit" ist neben "oidc" aktiv, aber das Upstream-"secret" ist der Standardwert. Entweder SECRET setzen oder HB_AUTH_PROVIDERS=oidc.');
}
}
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
});
+85
View File
@@ -0,0 +1,85 @@
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)
};
const own = { upstreamSecret: 'eigenes-secret' };
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, own);
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' }, own)).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' }, own).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, own)))).not.toMatch(/secret|"s"/i);
});
describe('Upstream-secret (fälschbare nc_session)', ()=>{
test('Abbruch bei oidc+naturalcrit, Standard-secret, nicht lokal', ()=>{
expect(()=>readAuthConfig(base, { upstreamSecret: 'secret', isLocal: false })).toThrow(/Upstream-"secret".*HB_AUTH_PROVIDERS=oidc/);
expect(()=>readAuthConfig(base, { upstreamSecret: '', isLocal: false })).toThrow(/Upstream-"secret"/);
expect(()=>readAuthConfig(base)).toThrow(/Upstream-"secret"/);
});
test('kein Abbruch: lokal, nur oidc oder eigenes secret', ()=>{
expect(()=>readAuthConfig(base, { upstreamSecret: 'secret', isLocal: true })).not.toThrow();
expect(()=>readAuthConfig({ ...base, HB_AUTH_PROVIDERS: 'oidc' }, { upstreamSecret: 'secret', isLocal: false })).not.toThrow();
expect(()=>readAuthConfig(base, { upstreamSecret: 'eigenes-secret', isLocal: false })).not.toThrow();
});
test('reiner Upstream-Modus bleibt unverändert', ()=>{
expect(()=>readAuthConfig({}, { upstreamSecret: 'secret', isLocal: false })).not.toThrow();
});
});
describe('Issuer-Schema', ()=>{
test('http-Issuer mit https-HB_PUBLIC_URL bricht ab', ()=>{
expect(()=>readAuthConfig({ ...base, HB_OIDC_ISSUER: 'http://idp.example' }, own)).toThrow(/https:\/\//);
});
test('http-Issuer mit http-HB_PUBLIC_URL ist erlaubt (Dev/Compose)', ()=>{
expect(()=>readAuthConfig({ ...base, HB_OIDC_ISSUER: 'http://idp:8080', HB_PUBLIC_URL: 'http://localhost:8000' }, own)).not.toThrow();
});
});
});
+130
View File
@@ -0,0 +1,130 @@
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)=>({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#39;' }[c]));
const page = (title, body)=>`<!DOCTYPE html><html lang="de"><head><meta charset="utf-8"><title>${esc(title)}</title>`
+ `<meta name="viewport" content="width=device-width,initial-scale=1">`
+ `<style>body{font-family:sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem}a.btn{display:block;margin:.75rem 0;padding:.75rem 1rem;background:#0a7f6f;color:#fff;text-decoration:none;border-radius:4px;text-align:center}</style>`
+ `</head><body><h1>${esc(title)}</h1>${body}</body></html>`;
const errorPage = (res, status, message, retryUrl = '/auth/oidc/login')=>{
res.status(status).type('html').send(page('Anmeldung fehlgeschlagen',
`<p>${esc(message)}</p><p><a href="${esc(retryUrl)}">Erneut anmelden</a></p>`));
};
// 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<boolean>, 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',
`<a class="btn" href="/auth/oidc/login?redirect=${encodeURIComponent(redirect)}">${esc(config.oidc.label)}</a>`
+ `<a class="btn" href="${esc(ncUrl)}">NaturalCrit-Konto (Benutzername/Passwort, Google)</a>`));
});
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);
if(err instanceof OidcCallbackError) return errorPage(res, err.status, err.message);
errorPage(res, 500, '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;
};
+102
View File
@@ -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;
}
};
};
+81
View File
@@ -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;
};
+48
View File
@@ -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)
}, { upstreamSecret: 'eigenes-secret' });
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);
});
});
+82
View File
@@ -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 = `<html><body>${form}<script>document.forms[0].submit()</script></body></html>`; } } },
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 = /<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(/<input[^>]*>/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');
};
+39
View File
@@ -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;
}
};
};
+7
View File
@@ -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() }));
});
+58
View File
@@ -0,0 +1,58 @@
// Gemeinsame Contract-Suite für das UserRepository (ADR 0002 §5).
// Aufruf: runUserRepositoryContract(async ()=>({ users, cleanup }))
export const runUserRepositoryContract = (createUsers)=>{
let users;
let cleanup;
beforeAll(async ()=>{ ({ users, cleanup } = await createUsers()); });
afterAll(async ()=>{ await cleanup?.(); });
test('create liefert plain object mit id, E-Mail klein geschrieben', async ()=>{
const u = await users.create({ username: 'alice', oidcIssuer: 'https://idp', oidcSub: 's1', email: 'Alice@Example.TEST', emailVerified: true });
expect(u.id).toEqual(expect.any(String));
expect(u).toMatchObject({ username: 'alice', oidcIssuer: 'https://idp', oidcSub: 's1', email: 'alice@example.test', emailVerified: true });
expect(u.constructor).toBe(Object);
});
test('findByOidc / findById / findByUsername', async ()=>{
const byOidc = await users.findByOidc('https://idp', 's1');
expect(byOidc.username).toBe('alice');
expect((await users.findById(byOidc.id)).username).toBe('alice');
expect((await users.findByUsername('alice')).id).toBe(byOidc.id);
expect(await users.findByOidc('https://idp', 'unbekannt')).toBeNull();
expect(await users.findById('unbekannt')).toBeNull();
expect(await users.usernameExists('alice')).toBe(true);
expect(await users.usernameExists('nobody')).toBe(false);
});
test('Benutzername ist eindeutig', async ()=>{
await expect(users.create({ username: 'alice' })).rejects.toBeDefined();
});
test('(issuer, sub) ist eindeutig, mehrere Benutzer ohne Bindung sind erlaubt', async ()=>{
await expect(users.create({ username: 'alice2', oidcIssuer: 'https://idp', oidcSub: 's1' })).rejects.toBeDefined();
await users.create({ username: 'pre1', email: 'pre@example.test' });
await users.create({ username: 'pre2', email: 'other@example.test' });
});
test('findUnlinkedByEmail findet nur Benutzer ohne OIDC-Bindung', async ()=>{
const found = await users.findUnlinkedByEmail('PRE@example.test');
expect(found.map((u)=>u.username)).toEqual(['pre1']);
expect(await users.findUnlinkedByEmail('alice@example.test')).toEqual([]);
});
test('update ändert Felder, aber nie username', async ()=>{
const u = await users.findByUsername('pre1');
const upd = await users.update(u.id, { username: 'hacked', displayName: 'Pre One', lastLoginAt: new Date() });
expect(upd.username).toBe('pre1');
expect(upd.displayName).toBe('Pre One');
expect(upd.lastLoginAt).toBeInstanceOf(Date);
});
test('delete entfernt den Benutzer', async ()=>{
const u = await users.findByUsername('pre2');
expect(await users.delete(u.id)).toBe(true);
expect(await users.findByUsername('pre2')).toBeNull();
expect(await users.delete(u.id)).toBe(false);
});
};
+23
View File
@@ -0,0 +1,23 @@
import { createMongoStorage } from './mongo/index.js';
let storage;
export const connect = async (config)=>{
storage = createMongoStorage(config);
await storage.connect();
return storage;
};
export const disconnect = async ()=>{
await storage?.disconnect();
storage = undefined;
};
export const getStorage = ()=>{
if(!storage) throw new Error('Storage ist nicht verbunden (storage.connect(config) fehlt)');
return storage;
};
export const isReady = ()=>!!storage && storage.isReady();
export default { connect, disconnect, getStorage, isReady };
+28
View File
@@ -0,0 +1,28 @@
import mongoose from 'mongoose';
import DB from '../../db.js';
import { createUserRepository } from './users.js';
// Mongo-Implementierung der Storage-Schicht (ADR 0002). In M1 nur `users`;
// Brew-Zugriffe laufen bis M2 unverändert über homebrew.model.js.
export const createMongoStorage = (config)=>{
let users;
return {
driver : 'mongo',
async connect() {
await DB.connect(config);
users = createUserRepository();
if(!config.get('local_environments').includes(config.get('node_env'))) {
await users.Model.syncIndexes(); // nur Fork-Modelle, nie Homebrew
}
},
async disconnect() {
await DB.disconnect();
},
isReady() {
return mongoose.connection.readyState === 1;
},
get users() {
return users;
}
};
};
+18
View File
@@ -0,0 +1,18 @@
import mongoose from 'mongoose';
import { randomBytes } from 'crypto';
import { createUserRepository } from './users.js';
import { runUserRepositoryContract } from '../contract/users.contract.js';
const uri = process.env.HB_TEST_MONGODB_URI;
const suite = uri ? describe : describe.skip;
if(!uri) console.warn('HB_TEST_MONGODB_URI fehlt: Mongo-Storage-Contract-Tests werden übersprungen.');
suite('Mongo UserRepository (Contract)', ()=>{
runUserRepositoryContract(async ()=>{
const dbName = `test_${randomBytes(4).toString('hex')}`;
const connection = await mongoose.createConnection(uri, { dbName }).asPromise();
const users = createUserRepository(connection);
await users.Model.init();
return { users, cleanup: async ()=>{ await connection.dropDatabase(); await connection.close(); } };
});
});
+98
View File
@@ -0,0 +1,98 @@
import { randomUUID } from 'crypto';
import mongoose from 'mongoose';
// Fork-Entität "User" (ADR 0001 §4). Collection `users`, eigenes Schema, berührt keine Upstream-Modelle.
const UserSchema = new mongoose.Schema({
id : { type: String, required: true, unique: true },
username : { type: String, required: true, unique: true },
oidcIssuer : { type: String },
oidcSub : { type: String },
email : { type: String, index: true },
emailVerified : { type: Boolean, default: false },
displayName : { type: String },
createdAt : { type: Date, default: Date.now },
lastLoginAt : { type: Date }
}, { collection: 'users', versionKey: false });
// (oidcIssuer, oidcSub) eindeutig, aber nur, wenn gesetzt (vorab angelegte Benutzer haben keine Bindung)
UserSchema.index(
{ oidcIssuer: 1, oidcSub: 1 },
{ unique: true, partialFilterExpression: { oidcSub: { $type: 'string' } } }
);
const toPlain = (doc)=>{
if(!doc) return null;
const o = doc.toObject ? doc.toObject() : doc;
return {
id : o.id,
username : o.username,
oidcIssuer : o.oidcIssuer ?? null,
oidcSub : o.oidcSub ?? null,
email : o.email ?? null,
emailVerified : !!o.emailVerified,
displayName : o.displayName ?? null,
createdAt : o.createdAt,
lastLoginAt : o.lastLoginAt ?? null
};
};
const clean = (obj)=>Object.fromEntries(Object.entries(obj).filter(([, v])=>v !== undefined));
export const createUserRepository = (connection = mongoose.connection)=>{
const User = connection.models.ForkUser ?? connection.model('ForkUser', UserSchema);
return {
Model : User,
async create({ username, oidcIssuer, oidcSub, email, emailVerified, displayName }) {
const doc = await User.create(clean({
id : randomUUID(),
username,
oidcIssuer,
oidcSub,
email : email ? String(email).toLowerCase() : undefined,
emailVerified : !!emailVerified,
displayName
}));
return toPlain(doc);
},
async findById(id) {
return toPlain(await User.findOne({ id }));
},
async findByUsername(username) {
return toPlain(await User.findOne({ username }));
},
async usernameExists(username) {
return !!(await User.exists({ username }));
},
async findByOidc(issuer, sub) {
return toPlain(await User.findOne({ oidcIssuer: issuer, oidcSub: sub }));
},
// Vorab angelegte Benutzer (ohne OIDC-Bindung) mit dieser E-Mail
async findUnlinkedByEmail(email) {
const docs = await User.find({
email : String(email).toLowerCase(),
oidcSub : { $not: { $type: 'string' } }
});
return docs.map(toPlain);
},
async update(id, patch) {
const set = clean({ ...patch });
delete set.id;
delete set.username; // unveränderlich
if(set.email) set.email = String(set.email).toLowerCase();
return toPlain(await User.findOneAndUpdate({ id }, { $set: set }, { returnDocument: 'after' }));
},
async delete(id) {
const res = await User.deleteOne({ id });
return res.deletedCount > 0;
}
};
};