From 6ff41ce8ecbad3ecb09a229dd37c23b0f68431b7 Mon Sep 17 00:00:00 2001 From: "Dev (Paperclip)" Date: Wed, 25 Nov 2026 09:10:29 +0000 Subject: [PATCH] =?UTF-8?q?docs(auth):=20.env.example,=20README,=20IdP-Anl?= =?UTF-8?q?eitungen=20und=20E2E-Skript=20f=C3=BCr=20Keycloak/authentik?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- .env.example | 26 +++ README.md | 336 ++++++++++++++++++------------------ docker-compose.override.yml | 13 ++ docs/auth/README.md | 68 ++++++++ docs/auth/authentik.md | 32 ++++ docs/auth/keycloak.md | 33 ++++ scripts/oidc-e2e.mjs | 145 ++++++++++++++++ 7 files changed, 487 insertions(+), 166 deletions(-) create mode 100644 docs/auth/README.md create mode 100644 docs/auth/authentik.md create mode 100644 docs/auth/keycloak.md create mode 100644 scripts/oidc-e2e.mjs diff --git a/.env.example b/.env.example index c1112dda..6690a842 100644 --- a/.env.example +++ b/.env.example @@ -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: /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 diff --git a/README.md b/README.md index 47362533..b5de6791 100644 --- a/README.md +++ b/README.md @@ -1,166 +1,170 @@ -# The Homebrewery - -[![Homebrewery](https://circleci.com/gh/naturalcrit/homebrewery/tree/master.svg?style=svg)](https://app.circleci.com/pipelines/github/naturalcrit/homebrewery?branch=master) - -The Homebrewery is a tool for making authentic looking [D&D content][dnd-content-url] -using [Markdown][markdown-url]. It is distributed under the terms of the [MIT License](./license). - -[dnd-content-url]: https://dnd.wizards.com/products/tabletop-games/rpg-products/rpg_playershandbook -[markdown-url]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet - -## Quick Start -The easiest way to get started using The Homebrewery is to use it -[on our website][homebrewery-url]. The code is open source, so feel free to -clone it and tinker with it. If you want to make changes to the code, you can run -your own local version for testing by following the installation instructions -below. - -[homebrewery-url]: https://homebrewery.naturalcrit.com - -### Installation -First, install three programs that The Homebrewery requires to run and retrieve -updates: - -1. install [node](https://nodejs.org/en/), version v16 or higher. -1. install [mongodb](https://www.mongodb.com/try/download/community) (Community version) - - For the easiest installation, follow these steps: - 1. In the installer, uncheck the option to run as a service. - 1. You can install MongoDB Compass if you want a GUI to view your database documents. - 1. If you install any version over 6.0, you will have to install [MongoDB Shell](https://www.mongodb.com/try/download/shell). - 1. Go to the C:\ drive and create a folder called "data". - 1. Inside the "data" folder, create a new folder called "db". - 1. Open a command prompt or other terminal and navigate to your MongoDB install folder (C:\Program Files\Mongo\Server\6.0\bin). - 1. In the command prompt, run "mongod", which will start up your local database server. - 1. While MongoD is running, open a second command prompt and navigate to the MongoDB install folder. - 1. Search in Windows for "Advanced system settings" and open it. - 1. Click "Environment variables", find the "path" variable, and double-click to open it. - 1. Click "New" and paste in the path to the MongoDB "bin" folder. - 1. Click "OK" three times to close all the windows. - 1. In the second command prompt, run "mongo", which allows you to edit the database. - 1. Type `use homebrewery` to create The Homebrewery database. You should see `switched to db homebrewery`. - 1. Type `db.brews.insertOne({"title":"test"})` to create a blank document. You should see `{ -acknowledged: true, -insertedId: ObjectId("63c2fce9e5ac5a94fe2410cf") -}` - -1. install [git](https://git-scm.com/downloads) (select the option that allows Git to run from the command prompt). - -Checkout the repo ([documentation][github-clone-repo-docs-url]): -``` -git clone https://github.com/naturalcrit/homebrewery.git -``` - -[github-clone-repo-docs-url]: https://docs.github.com/en/free-pro-team@latest/github/creating-cloning-and-archiving-repositories/cloning-a-repository - -Second, you will need to add the environment variable `NODE_ENV=local` to allow -the project to run locally. - -You can set this **temporarily** (until you close the terminal) in your shell of choice with admin privileges: -* Windows Powershell: `$env:NODE_ENV="local"` -* Windows CMD: `set NODE_ENV=local` -* Linux / macOS: `export NODE_ENV=local` - -If you want to add this variable **permanently** the steps are as follows: - 1. Search in Windows for "Advanced system settings" and open it. - 1. Click "Environment variables". - 1. In System Variables, click "New" - 1. Click "New" and write `NODE_ENV` as a name and `local` as the value. - 1. Click "OK" three times to close all the windows. - This can be undone at any time if needed. - -Third, you will need to install the Node dependencies, compile the app, and run -it using the two commands: - -1. `npm install` -1. `npm start` - -When the Homebrewery server is started for the first time, it will modify the database to create the indexes required for better Homebrewery performance. This may take a few moments to complete for each index, dependent on how much content is in your local database - a brand new, empty database should be done in seconds. - -On completion, you should be able to go to [http://localhost:8000](http://localhost:8000) in your browser and use The Homebrewery offline. - -If you had any issue at all, here are some links that may be useful: -- [Course](https://learn.mongodb.com/courses/m103-basic-cluster-administration) on cluster administration, useful for beginners -- [Mongo community forums](https://www.mongodb.com/community/forums/) -- Useful Stack Overflow links for your most probable errors: [1](https://stackoverflow.com/questions/44962540/mongod-and-mongo-commands-not-working-on-windows-10), [2](https://stackoverflow.com/questions/15053893/mongo-command-not-recognized-when-trying-to-connect-to-a-mongodb-server/41507803#41507803), [3](https://stackoverflow.com/questions/51224959/mongo-is-not-recognized-as-an-internal-or-external-command-operable-program-o) - -If you still have problems, post in [Our Subreddit](https://www.reddit.com/r/homebrewery/) and we will help you. - -### Running the application via Docker - -Please see the docs here: [README.DOCKER.md](./README.DOCKER.md) - -### Lokal starten / Selbst hosten (Fork homebrewery-oidc) - -```bash -cp .env.example .env # optional, alle Werte haben Entwicklungs-Defaults -docker compose up --build # App + MongoDB -> http://localhost:8000 -``` - -`docker-compose.override.yml` (wird automatisch geladen) und `docker/` enthalten die Fork-Erweiterungen; `docker-compose.yml` bleibt Upstream-identisch. - -| Profil | Start | Ergebnis | -|---|---|---| -| `postgres` | `docker compose --profile postgres up -d postgres` | PostgreSQL 18 auf `127.0.0.1:5432` (ab M2) | -| `keycloak` | `docker compose --profile keycloak up -d` | Keycloak :8080, Realm `homebrewery`, Client `homebrewery`/`dev-only-client-secret`, Nutzer `testuser`/`testuser-dev`, Admin `admin`/`admin-dev`. Discovery: `http://keycloak.localhost:8080/realms/homebrewery/.well-known/openid-configuration` (Start dauert 1–2 Min.) | -| `authentik` | `docker compose --profile authentik up -d` | authentik :9000, Provider/App `homebrewery` per Blueprint, gleicher Client und Nutzer, Admin `akadmin`/`admin-dev`. Discovery: `http://authentik.localhost:9000/application/o/homebrewery/.well-known/openid-configuration` | - -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). - -### Running the application on FreeBSD or FreeNAS - -Please see the docs here: [README.FreeBSD.md](./README.FREEBSD.md) - -### Standalone PHB Stylesheet -If you just want the stylesheet that is generated to make pages look like they -are from the Player's Handbook, you will find it in the -[phb.standalone.css](./phb.standalone.css) file. - -If you are developing locally and would like to generate your own, follow the -above steps and then run `npm run phb`. - -## Issues, Suggestions, and Bugs -If you run into any issues using The Homebrewery or have suggestions for -improvement, please submit an issue [on GitHub][repo-issues-url]. -You can also get help for issues on the subreddit [r/homebrewery][subreddit-url] - -[repo-issues-url]: https://github.com/naturalcrit/homebrewery/issues -[subreddit-url]: https://www.reddit.com/r/homebrewery - -## Changelog - -You can check out the [changelog](./changelog.md). - -## License - -This project is licensed under the [MIT license](./license), which means you -are free to use The Homebrewery in any way that you want, except for claiming -that you made it yourself. - -If you wish to sell, or in some way gain profit for, what's created on this site, -it's your responsibility to ensure you have the proper licenses/rights for any -images or resources used. - -## Contributing - -You are welcome to contribute to the development and maintenance of the -project! There are several ways of doing that: -- At the moment, we have a huge backlog of [issues][repo-issues-url] and some - of them are outdated, duplicates, or don't contain any useful info. To help, you can [mark duplicates][github-mark-duplicate-url], try to - reproduce some complex or weird issues, try finding a workaround for a - reported bug, or just mention our issue managers team to let them know about - outdated issues via `@naturalcrit/issue-managers`. -- Our [subreddit][subreddit-url] is constantly growing and there are number of - bug reports. Any help with sorting them out is very welcome. -- And of course you can contribute by fixing a bug or implementing a new - feature by yourself, we are waiting for your - [pull requests][github-pr-docs-url]! - -Anyway, if you would like to get in touch with the team and discuss/coordinate -your contribution to the project, please join our [gitter chat][gitter-url]. - -[github-mark-duplicate-url]: https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/about-duplicate-issues-and-pull-requests -[github-pr-docs-url]: https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request -[gitter-url]: https://gitter.im/naturalcrit/Lobby - - +# The Homebrewery + +[![Homebrewery](https://circleci.com/gh/naturalcrit/homebrewery/tree/master.svg?style=svg)](https://app.circleci.com/pipelines/github/naturalcrit/homebrewery?branch=master) + +The Homebrewery is a tool for making authentic looking [D&D content][dnd-content-url] +using [Markdown][markdown-url]. It is distributed under the terms of the [MIT License](./license). + +[dnd-content-url]: https://dnd.wizards.com/products/tabletop-games/rpg-products/rpg_playershandbook +[markdown-url]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet + +## Quick Start +The easiest way to get started using The Homebrewery is to use it +[on our website][homebrewery-url]. The code is open source, so feel free to +clone it and tinker with it. If you want to make changes to the code, you can run +your own local version for testing by following the installation instructions +below. + +[homebrewery-url]: https://homebrewery.naturalcrit.com + +### Installation +First, install three programs that The Homebrewery requires to run and retrieve +updates: + +1. install [node](https://nodejs.org/en/), version v16 or higher. +1. install [mongodb](https://www.mongodb.com/try/download/community) (Community version) + + For the easiest installation, follow these steps: + 1. In the installer, uncheck the option to run as a service. + 1. You can install MongoDB Compass if you want a GUI to view your database documents. + 1. If you install any version over 6.0, you will have to install [MongoDB Shell](https://www.mongodb.com/try/download/shell). + 1. Go to the C:\ drive and create a folder called "data". + 1. Inside the "data" folder, create a new folder called "db". + 1. Open a command prompt or other terminal and navigate to your MongoDB install folder (C:\Program Files\Mongo\Server\6.0\bin). + 1. In the command prompt, run "mongod", which will start up your local database server. + 1. While MongoD is running, open a second command prompt and navigate to the MongoDB install folder. + 1. Search in Windows for "Advanced system settings" and open it. + 1. Click "Environment variables", find the "path" variable, and double-click to open it. + 1. Click "New" and paste in the path to the MongoDB "bin" folder. + 1. Click "OK" three times to close all the windows. + 1. In the second command prompt, run "mongo", which allows you to edit the database. + 1. Type `use homebrewery` to create The Homebrewery database. You should see `switched to db homebrewery`. + 1. Type `db.brews.insertOne({"title":"test"})` to create a blank document. You should see `{ +acknowledged: true, +insertedId: ObjectId("63c2fce9e5ac5a94fe2410cf") +}` + +1. install [git](https://git-scm.com/downloads) (select the option that allows Git to run from the command prompt). + +Checkout the repo ([documentation][github-clone-repo-docs-url]): +``` +git clone https://github.com/naturalcrit/homebrewery.git +``` + +[github-clone-repo-docs-url]: https://docs.github.com/en/free-pro-team@latest/github/creating-cloning-and-archiving-repositories/cloning-a-repository + +Second, you will need to add the environment variable `NODE_ENV=local` to allow +the project to run locally. + +You can set this **temporarily** (until you close the terminal) in your shell of choice with admin privileges: +* Windows Powershell: `$env:NODE_ENV="local"` +* Windows CMD: `set NODE_ENV=local` +* Linux / macOS: `export NODE_ENV=local` + +If you want to add this variable **permanently** the steps are as follows: + 1. Search in Windows for "Advanced system settings" and open it. + 1. Click "Environment variables". + 1. In System Variables, click "New" + 1. Click "New" and write `NODE_ENV` as a name and `local` as the value. + 1. Click "OK" three times to close all the windows. + This can be undone at any time if needed. + +Third, you will need to install the Node dependencies, compile the app, and run +it using the two commands: + +1. `npm install` +1. `npm start` + +When the Homebrewery server is started for the first time, it will modify the database to create the indexes required for better Homebrewery performance. This may take a few moments to complete for each index, dependent on how much content is in your local database - a brand new, empty database should be done in seconds. + +On completion, you should be able to go to [http://localhost:8000](http://localhost:8000) in your browser and use The Homebrewery offline. + +If you had any issue at all, here are some links that may be useful: +- [Course](https://learn.mongodb.com/courses/m103-basic-cluster-administration) on cluster administration, useful for beginners +- [Mongo community forums](https://www.mongodb.com/community/forums/) +- Useful Stack Overflow links for your most probable errors: [1](https://stackoverflow.com/questions/44962540/mongod-and-mongo-commands-not-working-on-windows-10), [2](https://stackoverflow.com/questions/15053893/mongo-command-not-recognized-when-trying-to-connect-to-a-mongodb-server/41507803#41507803), [3](https://stackoverflow.com/questions/51224959/mongo-is-not-recognized-as-an-internal-or-external-command-operable-program-o) + +If you still have problems, post in [Our Subreddit](https://www.reddit.com/r/homebrewery/) and we will help you. + +### Running the application via Docker + +Please see the docs here: [README.DOCKER.md](./README.DOCKER.md) + +### Lokal starten / Selbst hosten (Fork homebrewery-oidc) + +```bash +cp .env.example .env # optional, alle Werte haben Entwicklungs-Defaults +docker compose up --build # App + MongoDB -> http://localhost:8000 +``` + +`docker-compose.override.yml` (wird automatisch geladen) und `docker/` enthalten die Fork-Erweiterungen; `docker-compose.yml` bleibt Upstream-identisch. + +| Profil | Start | Ergebnis | +|---|---|---| +| `postgres` | `docker compose --profile postgres up -d postgres` | PostgreSQL 18 auf `127.0.0.1:5432` (ab M2) | +| `keycloak` | `docker compose --profile keycloak up -d` | Keycloak :8080, Realm `homebrewery`, Client `homebrewery`/`dev-only-client-secret`, Nutzer `testuser`/`testuser-dev`, Admin `admin`/`admin-dev`. Discovery: `http://keycloak.localhost:8080/realms/homebrewery/.well-known/openid-configuration` (Start dauert 1–2 Min.) | +| `authentik` | `docker compose --profile authentik up -d` | authentik :9000, Provider/App `homebrewery` per Blueprint, gleicher Client und Nutzer, Admin `akadmin`/`admin-dev`. Discovery: `http://authentik.localhost:9000/application/o/homebrewery/.well-known/openid-configuration` | + +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) + +### Standalone PHB Stylesheet +If you just want the stylesheet that is generated to make pages look like they +are from the Player's Handbook, you will find it in the +[phb.standalone.css](./phb.standalone.css) file. + +If you are developing locally and would like to generate your own, follow the +above steps and then run `npm run phb`. + +## Issues, Suggestions, and Bugs +If you run into any issues using The Homebrewery or have suggestions for +improvement, please submit an issue [on GitHub][repo-issues-url]. +You can also get help for issues on the subreddit [r/homebrewery][subreddit-url] + +[repo-issues-url]: https://github.com/naturalcrit/homebrewery/issues +[subreddit-url]: https://www.reddit.com/r/homebrewery + +## Changelog + +You can check out the [changelog](./changelog.md). + +## License + +This project is licensed under the [MIT license](./license), which means you +are free to use The Homebrewery in any way that you want, except for claiming +that you made it yourself. + +If you wish to sell, or in some way gain profit for, what's created on this site, +it's your responsibility to ensure you have the proper licenses/rights for any +images or resources used. + +## Contributing + +You are welcome to contribute to the development and maintenance of the +project! There are several ways of doing that: +- At the moment, we have a huge backlog of [issues][repo-issues-url] and some + of them are outdated, duplicates, or don't contain any useful info. To help, you can [mark duplicates][github-mark-duplicate-url], try to + reproduce some complex or weird issues, try finding a workaround for a + reported bug, or just mention our issue managers team to let them know about + outdated issues via `@naturalcrit/issue-managers`. +- Our [subreddit][subreddit-url] is constantly growing and there are number of + bug reports. Any help with sorting them out is very welcome. +- And of course you can contribute by fixing a bug or implementing a new + feature by yourself, we are waiting for your + [pull requests][github-pr-docs-url]! + +Anyway, if you would like to get in touch with the team and discuss/coordinate +your contribution to the project, please join our [gitter chat][gitter-url]. + +[github-mark-duplicate-url]: https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/about-duplicate-issues-and-pull-requests +[github-pr-docs-url]: https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request +[gitter-url]: https://gitter.im/naturalcrit/Lobby + + diff --git a/docker-compose.override.yml b/docker-compose.override.yml index 809b574b..25a3cabd 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -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" diff --git a/docs/auth/README.md b/docs/auth/README.md new file mode 100644 index 00000000..0848bfab --- /dev/null +++ b/docs/auth/README.md @@ -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` | +| `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). diff --git a/docs/auth/authentik.md b/docs/auth/authentik.md new file mode 100644 index 00000000..c8a80949 --- /dev/null +++ b/docs/auth/authentik.md @@ -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= +``` + +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:///application/o//`. + +## 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). diff --git a/docs/auth/keycloak.md b/docs/auth/keycloak.md new file mode 100644 index 00000000..889a9cd1 --- /dev/null +++ b/docs/auth/keycloak.md @@ -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= +``` + +`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:///realms/`. 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. diff --git a/scripts/oidc-e2e.mjs b/scripts/oidc-e2e.mjs new file mode 100644 index 00000000..41040573 --- /dev/null +++ b/scripts/oidc-e2e.mjs @@ -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 = /]*id="kc-form-login"[^>]*action="([^"]+)"/.exec(html)?.[1]?.replaceAll('&', '&'); + 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//?next= + 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);