Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0926dea8b0
|
||
|
|
a1d7e1b51b
|
||
|
|
18f26b7fd6
|
||
|
|
75548d39f3
|
||
|
|
1fe99698fb
|
||
|
|
162db8ca63
|
||
|
|
cafa5cddcd
|
||
|
|
f96dec267b
|
||
|
|
3b83125771
|
||
|
|
5e07ef6e8d
|
||
|
|
aeca3926a3
|
||
|
|
03455c5bf5 | ||
|
|
bbf838c5d6
|
||
|
|
3a77763641
|
||
|
|
adaa10a4dc
|
||
|
|
9183363ea1
|
||
|
|
448c67912f
|
||
|
|
06b7ad2c77
|
||
|
|
400411d736
|
||
|
|
84dd8e6bf4
|
||
|
|
bbfebc0095
|
||
|
|
23d9b83567
|
||
|
|
a55c403527
|
||
|
|
0bf80006df
|
||
|
|
66bb91cb3e
|
||
|
|
fb9f4b0345
|
||
|
|
6ff41ce8ec
|
||
|
|
fe278d465f
|
||
|
|
727a090bb7
|
||
|
|
d4724ac6de
|
||
|
|
7edca3fa8f
|
||
|
|
6473d7108b
|
||
|
|
0880870a9f
|
||
|
|
7b159a0355
|
||
|
|
1703b3806a
|
||
|
|
8f06133181
|
||
|
|
efac56ba76
|
||
|
|
022ae1daef
|
||
|
|
8c112f50e6
|
||
|
|
a181ed3ebd | ||
|
|
30a4bf4be0
|
||
|
|
86f9e963d2 | ||
|
|
23c94e01f6 |
No files matched your search
@@ -0,0 +1,81 @@
|
||||
# Kopieren nach .env. Nur Entwicklungswerte – keine echten Secrets einchecken.
|
||||
APP_PORT=8000
|
||||
MONGODB_URI=mongodb://mongodb/homebrewery
|
||||
MONGO_TAG=8
|
||||
|
||||
# Storage-Backend (ADR 0002, docs/storage/): mongo (Standard) oder postgres.
|
||||
# Postgres: docker compose --profile postgres up --build homebrewery-pg
|
||||
HB_DB_DRIVER=mongo
|
||||
# HB_POSTGRES_URL=postgres://homebrewery:homebrewery-dev@postgres:5432/homebrewery
|
||||
# HB_POSTGRES_POOL_MAX=10
|
||||
|
||||
# Profil postgres
|
||||
POSTGRES_DB=homebrewery
|
||||
POSTGRES_USER=homebrewery
|
||||
POSTGRES_PASSWORD=homebrewery-dev
|
||||
POSTGRES_PORT=5432
|
||||
|
||||
# Profil keycloak (Discovery: http://keycloak.localhost:8080/realms/homebrewery/.well-known/openid-configuration)
|
||||
KEYCLOAK_TAG=26.4
|
||||
KEYCLOAK_PORT=8080
|
||||
KEYCLOAK_ADMIN=admin
|
||||
KEYCLOAK_ADMIN_PASSWORD=admin-dev
|
||||
|
||||
# Profil authentik (Discovery: http://authentik.localhost:9000/application/o/homebrewery/.well-known/openid-configuration)
|
||||
AUTHENTIK_TAG=2026.2
|
||||
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
|
||||
# PUT /api/user/rename für naturalcrit-Sitzungen: off (Standard, gesperrt) oder signed (Nachweis oldSession, docs/auth/)
|
||||
# HB_NATURALCRIT_RENAME=off
|
||||
|
||||
# --- Git-Backend (ADR 0003, docs/git/) -----------------------------------------
|
||||
# Brews in beliebigen Git-Repos speichern (HTTPS + Personal Access Token). Nur für OIDC-Konten.
|
||||
# Ohne Schlüssel ist das Feature aus. Erzeugen: openssl rand -base64 32 (Schlüssel nie einchecken, nicht verlieren:
|
||||
# ohne ihn sind gespeicherte Tokens unbrauchbar)
|
||||
# HB_GIT_TOKEN_KEY=
|
||||
# Alte Schlüssel (kommagetrennt) nur zum Entschlüsseln bei Rotation
|
||||
# HB_GIT_TOKEN_KEYS_OLD=
|
||||
# Empfohlen im Betrieb: nur diese Hosts (Wildcards wie *.example.org erlaubt)
|
||||
# HB_GIT_ALLOWED_HOSTS=git.example.org,github.com
|
||||
# Nur für Entwicklung: private Ziele (z. B. Gitea im Compose-Netz) und http:// erlauben
|
||||
# HB_GIT_ALLOW_PRIVATE=false
|
||||
# HB_GIT_ALLOW_HTTP=false
|
||||
# HB_GIT_TIMEOUT_MS=20000
|
||||
# HB_GIT_OPEN_TIMEOUT_MS=4000
|
||||
# HB_GIT_MAX_FILE_BYTES=5242880
|
||||
# HB_GIT_MAX_CONCURRENCY=2
|
||||
# HB_GIT_COMMITTER_NAME=Homebrewery
|
||||
# HB_GIT_COMMITTER_EMAIL=
|
||||
# Bild-Upload (ADR 0004): nur mit aktivem Git-Backend, Standard an
|
||||
# HB_ASSETS_ENABLED=true
|
||||
# HB_ASSET_MAX_BYTES=5242880
|
||||
# HB_ASSET_MAX_BYTES_PER_BREW=52428800
|
||||
# HB_ASSET_TYPES=png,jpeg,gif,webp
|
||||
@@ -0,0 +1,100 @@
|
||||
# Fork-CI für Pull Requests und main (Gitea #4, FLW-82).
|
||||
# Nutzt ausschließlich die Upstream-npm-Skripte; die Upstream-CI unter .github/ und
|
||||
# .circleci/ bleibt unverändert (Merges aus naturalcrit/homebrewery konfliktfrei).
|
||||
# Läuft auf jedem Gitea act_runner mit dem Label ubuntu-latest.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
# package.json verlangt Node >=26.4.0 und npm >=10.8 <12; das Lockfile zieht das
|
||||
# npm-Paket "node" ^26.13.0. Lokal verifiziert mit Node 26.13.1 / npm 11.20.0.
|
||||
NODE_VERSION: 26.13.1
|
||||
|
||||
jobs:
|
||||
app:
|
||||
name: App (npm ci + Build, ESLint, Stylelint, Jest)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
# npm-Cache nur mit Repo-Variable CI_CACHE=true: Ist der Cache-Server des
|
||||
# act_runner aus dem Job-Container nicht erreichbar, kostet jeder
|
||||
# Cache-Schritt mehrere Minuten Timeout.
|
||||
- uses: actions/cache@v6
|
||||
if: vars.CI_CACHE == 'true'
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
|
||||
restore-keys: npm-${{ runner.os }}-
|
||||
|
||||
# postinstall führt "npm run build" (vite build) aus, prüft also auch den Build.
|
||||
- name: Abhängigkeiten und Build (npm ci)
|
||||
run: npm ci --no-audit --no-fund
|
||||
|
||||
# Upstream hat derzeit nur Warnungen (keine Fehler); Warnungen brechen nicht ab.
|
||||
- name: ESLint (npm run lint:dry)
|
||||
run: npm run lint:dry
|
||||
|
||||
- name: Stylelint (npm run stylelint:dry)
|
||||
run: npm run stylelint:dry
|
||||
|
||||
# Kommt ohne MongoDB aus (Mongoose wird in den Specs gemockt).
|
||||
- name: Jest (npm test)
|
||||
run: npm test
|
||||
|
||||
# Storage-Contract-Suite und API-Smoke gegen beide Backends (ADR 0002 §5, Gitea #7).
|
||||
# Service-Container: act_runner startet sie im selben Docker-Netz, Hostname = Service-Name.
|
||||
storage:
|
||||
name: Storage (${{ matrix.backend }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
backend: [mongo, postgres]
|
||||
services:
|
||||
mongo:
|
||||
image: mongo:8
|
||||
postgres:
|
||||
image: postgres:18
|
||||
env:
|
||||
POSTGRES_PASSWORD: hb-ci-only
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U postgres"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 10
|
||||
env:
|
||||
HB_TEST_MONGODB_URI: ${{ matrix.backend == 'mongo' && 'mongodb://mongo:27017' || '' }}
|
||||
HB_TEST_POSTGRES_URL: ${{ matrix.backend == 'postgres' && 'postgres://postgres:hb-ci-only@postgres:5432/postgres' || '' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Abhängigkeiten und Build (npm ci)
|
||||
run: npm ci --no-audit --no-fund
|
||||
|
||||
- name: Contract-Suite und API-Smoke (${{ matrix.backend }})
|
||||
run: npx jest server/storage tests/fork --runInBand
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# Docker Hub: Repo-Beschreibung (Overview + Short description) aus docs/dockerhub/README.md setzen (FLW-263).
|
||||
# Auslöser: Release-Tag vX.Y.Z (wie der Docker-Hub-Pfad in image.yml), Änderungen an der Datei auf main, manuell.
|
||||
# Secrets: DOCKER_HUB_USER, DOCKER_HUB_TOKEN (Access Token mit Read, Write, Delete).
|
||||
# Fehlen sie, wird mit Warnung übersprungen. Das Token wird nie ausgegeben.
|
||||
name: Docker Hub Description
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- docs/dockerhub/README.md
|
||||
- .gitea/workflows/dockerhub-description.yml
|
||||
tags: ["v*"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: dockerhub-description
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
description:
|
||||
name: Beschreibung nach Docker Hub schreiben
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Prüfen
|
||||
id: check
|
||||
env:
|
||||
REF: ${{ github.ref }}
|
||||
REF_NAME: ${{ github.ref_name }}
|
||||
HUB_USER: ${{ secrets.DOCKER_HUB_USER }}
|
||||
HUB_TOKEN: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
run: |
|
||||
run=true
|
||||
if [[ "$REF" == refs/tags/* ]] && ! [[ "$REF_NAME" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "Kein Release-Tag (${REF_NAME}), übersprungen."; run=false
|
||||
elif [ -z "$HUB_USER" ] || [ -z "$HUB_TOKEN" ]; then
|
||||
echo "::warning::DOCKER_HUB_USER/DOCKER_HUB_TOKEN fehlen, Docker-Hub-Beschreibung wird übersprungen."; run=false
|
||||
fi
|
||||
echo "run=${run}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/checkout@v7
|
||||
if: steps.check.outputs.run == 'true'
|
||||
|
||||
- name: Platzhalter ersetzen (nur in der ausgecheckten Kopie)
|
||||
if: steps.check.outputs.run == 'true'
|
||||
env:
|
||||
HUB_USER: ${{ secrets.DOCKER_HUB_USER }}
|
||||
run: sed -i "s#<DOCKER_HUB_USER>#${HUB_USER}#g" docs/dockerhub/README.md
|
||||
|
||||
- name: Größe prüfen (Docker-Hub-Limit 25.000 Bytes)
|
||||
if: steps.check.outputs.run == 'true'
|
||||
run: |
|
||||
size=$(wc -c < docs/dockerhub/README.md)
|
||||
echo "README: ${size} Bytes"
|
||||
[ "$size" -lt 25000 ] || { echo "::error::docs/dockerhub/README.md ist zu groß für Docker Hub."; exit 1; }
|
||||
|
||||
- uses: peter-evans/dockerhub-description@v5
|
||||
if: steps.check.outputs.run == 'true'
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
repository: ${{ secrets.DOCKER_HUB_USER }}/homebrewery-oidc
|
||||
readme-filepath: docs/dockerhub/README.md
|
||||
short-description: "Homebrewery fork: OIDC login, PostgreSQL 18, Git backend, image upload."
|
||||
@@ -0,0 +1,94 @@
|
||||
# Bereits in Gitea gebautes Release-Image nach Docker Hub übertragen, OHNE neu zu bauen (FLW-230).
|
||||
# Manuell starten mit Input "version" (Format vX.Y.Z, keine Vorabversionen).
|
||||
# Kopiert git.morlana.online/f.weber/homebrewery-oidc:<version> per `crane copy`
|
||||
# (gleicher Digest) nach <DOCKER_HUB_USER>/homebrewery-oidc:<version>. :latest wird nur gesetzt,
|
||||
# wenn <version> die höchste Release-Version mit Gitea-Image ist; ältere Versionen setzen latest nie zurück.
|
||||
# Secrets: DOCKER_HUB_USER, DOCKER_HUB_TOKEN, REGISTRY_TOKEN (wie image.yml, nur Lesen nötig).
|
||||
name: Docker Hub Sync
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Release-Version, z. B. v1.0.0"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
|
||||
env:
|
||||
REGISTRY: git.morlana.online
|
||||
IMAGE: git.morlana.online/f.weber/homebrewery-oidc
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
name: Nach Docker Hub kopieren
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Version prüfen
|
||||
env:
|
||||
VERSION: ${{ inputs.version }}
|
||||
HUB_USER: ${{ secrets.DOCKER_HUB_USER }}
|
||||
HUB_TOKEN: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
run: |
|
||||
if ! [[ "$VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::error::Version muss dem Format vX.Y.Z entsprechen."; exit 1
|
||||
fi
|
||||
if [ -z "$HUB_USER" ] || [ -z "$HUB_TOKEN" ]; then
|
||||
echo "::error::Secrets DOCKER_HUB_USER/DOCKER_HUB_TOKEN fehlen."; exit 1
|
||||
fi
|
||||
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
|
||||
- uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.REGISTRY_TOKEN != '' && (vars.REGISTRY_USER || github.repository_owner) || github.actor }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN || secrets.GITEA_TOKEN }}
|
||||
|
||||
- uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
|
||||
- name: latest bestimmen
|
||||
id: v
|
||||
env:
|
||||
VERSION: ${{ inputs.version }}
|
||||
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
|
||||
run: |
|
||||
# Höchste Release-Version, für die in Gitea ein Image existiert (Upstream-Tags ohne Image zählen nicht).
|
||||
highest=""
|
||||
for t in $(git ls-remote --tags --refs "$REPO_URL" 'v*' | sed 's#.*refs/tags/##' \
|
||||
| grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -Vr); do
|
||||
if docker buildx imagetools inspect "${IMAGE}:${t}" >/dev/null 2>&1; then highest="$t"; break; fi
|
||||
done
|
||||
highest="${highest:-$VERSION}"
|
||||
latest=false
|
||||
if [ "$(printf '%s\n%s\n' "$VERSION" "$highest" | sort -V | tail -n1)" = "$VERSION" ]; then
|
||||
latest=true
|
||||
fi
|
||||
echo "latest=${latest}" >> "$GITHUB_OUTPUT"
|
||||
echo "Version ${VERSION}, höchste Release-Version mit Image ${highest}, latest setzen: ${latest}"
|
||||
|
||||
- name: crane installieren
|
||||
run: |
|
||||
curl -fsSL https://github.com/google/go-containerregistry/releases/download/v0.20.3/go-containerregistry_Linux_x86_64.tar.gz \
|
||||
| tar -xz -C /usr/local/bin crane 2>/dev/null || { mkdir -p "$HOME/bin" && curl -fsSL https://github.com/google/go-containerregistry/releases/download/v0.20.3/go-containerregistry_Linux_x86_64.tar.gz | tar -xz -C "$HOME/bin" crane && echo "$HOME/bin" >> "$GITHUB_PATH"; }
|
||||
|
||||
- name: Kopieren
|
||||
env:
|
||||
VERSION: ${{ inputs.version }}
|
||||
LATEST: ${{ steps.v.outputs.latest }}
|
||||
HUB_USER: ${{ secrets.DOCKER_HUB_USER }}
|
||||
run: |
|
||||
dest="${HUB_USER}/homebrewery-oidc"
|
||||
# crane copy überträgt Manifest unverändert -> identischer Digest.
|
||||
crane copy "${IMAGE}:${VERSION}" "${dest}:${VERSION}"
|
||||
if [ "$LATEST" = "true" ]; then crane copy "${IMAGE}:${VERSION}" "${dest}:latest"; fi
|
||||
echo "Quelle:"; docker buildx imagetools inspect "${IMAGE}:${VERSION}" | grep -E '^(Name|Digest):'
|
||||
echo "Ziel:"; docker buildx imagetools inspect "${dest}:${VERSION}" | grep -E '^(Name|Digest):'
|
||||
if [ "$LATEST" = "true" ]; then docker buildx imagetools inspect "${dest}:latest" | grep -E '^(Name|Digest):'; fi
|
||||
@@ -0,0 +1,120 @@
|
||||
# Container-Image bauen und in die Gitea-Container-Registry pushen (Gitea #4, FLW-82).
|
||||
# Baut docker/Dockerfile (wie Compose, mit docker/Dockerfile.dockerignore) nach
|
||||
# git.morlana.online/f.weber/homebrewery-oidc
|
||||
# Tags:
|
||||
# push auf main -> :main, :sha-<7 Zeichen>
|
||||
# Tag vX.Y.Z -> :vX.Y.Z, :latest, :sha-<7 Zeichen> (Vorabversionen wie v1.0.0-rc.1 ohne :latest)
|
||||
# Zusätzlich Docker Hub (FLW-230): NUR bei Release-Tags ^vX.Y.Z$ (keine Vorabversionen, nicht main/sha-*)
|
||||
# -> <DOCKER_HUB_USER>/homebrewery-oidc:vX.Y.Z und :latest, im selben Build (gleicher Digest wie Gitea).
|
||||
# Fehlen die Repo-Secrets DOCKER_HUB_USER/DOCKER_HUB_TOKEN, wird Docker Hub übersprungen.
|
||||
# Nachholen bereits gebauter Versionen: dockerhub-sync.yml.
|
||||
# Login: Repo-Secret REGISTRY_TOKEN (PAT mit write:package). Fehlt es, wird der
|
||||
# automatische GITEA_TOKEN versucht. Details in FORK.md, Abschnitt "CI and container image".
|
||||
name: Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
concurrency:
|
||||
group: image-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
REGISTRY: git.morlana.online
|
||||
IMAGE: git.morlana.online/f.weber/homebrewery-oidc
|
||||
|
||||
jobs:
|
||||
image:
|
||||
name: Image bauen und pushen
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Tags und Labels bestimmen
|
||||
id: meta
|
||||
env:
|
||||
REF: ${{ github.ref }}
|
||||
REF_NAME: ${{ github.ref_name }}
|
||||
SHA: ${{ github.sha }}
|
||||
SOURCE: ${{ github.server_url }}/${{ github.repository }}
|
||||
HUB_USER: ${{ secrets.DOCKER_HUB_USER }}
|
||||
HUB_TOKEN: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
run: |
|
||||
hub=false
|
||||
hub_names=""
|
||||
names="sha-${SHA:0:7}"
|
||||
version="sha-${SHA:0:7}"
|
||||
case "$REF" in
|
||||
refs/heads/main)
|
||||
names="${names} main"
|
||||
version="main"
|
||||
;;
|
||||
refs/tags/v*)
|
||||
names="${names} ${REF_NAME}"
|
||||
version="${REF_NAME}"
|
||||
if [[ "$REF_NAME" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
names="${names} latest"
|
||||
hub_names="${REF_NAME} latest"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
tags=""
|
||||
for n in $names; do tags="${tags:+${tags},}${IMAGE}:${n}"; done
|
||||
if [ -n "$hub_names" ]; then
|
||||
if [ -n "$HUB_USER" ] && [ -n "$HUB_TOKEN" ]; then
|
||||
hub=true
|
||||
for n in $hub_names; do tags="${tags},${HUB_USER}/homebrewery-oidc:${n}"; done
|
||||
else
|
||||
echo "::warning::DOCKER_HUB_USER/DOCKER_HUB_TOKEN fehlen, Docker Hub wird übersprungen."
|
||||
fi
|
||||
fi
|
||||
{
|
||||
echo "tags=${tags}"
|
||||
echo "hub=${hub}"
|
||||
echo "labels<<EOF"
|
||||
echo "org.opencontainers.image.title=homebrewery-oidc"
|
||||
echo "org.opencontainers.image.description=Homebrewery-Fork mit OIDC-Login"
|
||||
echo "org.opencontainers.image.source=${SOURCE}"
|
||||
echo "org.opencontainers.image.revision=${SHA}"
|
||||
echo "org.opencontainers.image.version=${version}"
|
||||
echo "org.opencontainers.image.licenses=MIT"
|
||||
echo "EOF"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
echo "Tags: ${names} (Docker Hub: ${hub})"
|
||||
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
|
||||
- uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.REGISTRY_TOKEN != '' && (vars.REGISTRY_USER || github.repository_owner) || github.actor }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN || secrets.GITEA_TOKEN }}
|
||||
|
||||
- name: Docker Hub Login (nur Release-Tags)
|
||||
if: steps.meta.outputs.hub == 'true'
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
|
||||
- name: Image bauen und pushen
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/Dockerfile
|
||||
# Repo-Variable IMAGE_PLATFORMS; Ziel ist linux/amd64.
|
||||
platforms: ${{ vars.IMAGE_PLATFORMS || 'linux/amd64' }}
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
provenance: false
|
||||
cache-from: type=registry,ref=${{ env.IMAGE }}:buildcache
|
||||
cache-to: type=registry,ref=${{ env.IMAGE }}:buildcache,mode=max,image-manifest=true,oci-mediatypes=true,ignore-error=true
|
||||
+2
-1
@@ -1,5 +1,5 @@
|
||||
node_modules
|
||||
storage
|
||||
/storage
|
||||
.idea
|
||||
*.swp
|
||||
|
||||
@@ -15,3 +15,4 @@ startMViewer.bat
|
||||
.vscode
|
||||
|
||||
coverage
|
||||
.env
|
||||
@@ -0,0 +1,171 @@
|
||||
# Homebrewery OIDC fork
|
||||
|
||||
This fork extends [naturalcrit/homebrewery](https://github.com/naturalcrit/homebrewery)
|
||||
for self-hosting while preserving its complete upstream history and MIT license.
|
||||
Keep fork changes small and isolated in modules or configuration so upstream
|
||||
updates remain practical to merge.
|
||||
|
||||
## Remotes and branches
|
||||
|
||||
- `origin`: `https://git.morlana.online/f.weber/homebrewery-oidc.git`
|
||||
- `upstream`: `https://github.com/naturalcrit/homebrewery.git`
|
||||
- `main`: reviewed integration branch for this fork.
|
||||
- `upstream`: pristine upstream `master`; never add fork commits here.
|
||||
|
||||
The initial import (2026-11-24) is upstream commit
|
||||
`6d219487de77f42868e38beeee0e4e7e9fb38679` (10,360 reachable commits, after tag `v3.21.0`).
|
||||
Both `main` and `upstream` initially point to that exact commit. The one-time
|
||||
import into the empty repository is the only direct-to-`main` exception.
|
||||
|
||||
## Reproducible upstream sync
|
||||
|
||||
Start from a clean working tree. Configure the upstream remote once after cloning:
|
||||
|
||||
```sh
|
||||
git clone https://git.morlana.online/f.weber/homebrewery-oidc.git
|
||||
cd homebrewery-oidc
|
||||
git remote add upstream https://github.com/naturalcrit/homebrewery.git
|
||||
```
|
||||
|
||||
For each update (choose a unique branch name):
|
||||
|
||||
```sh
|
||||
git fetch origin
|
||||
git switch main
|
||||
git merge --ff-only origin/main
|
||||
git switch -c sync/upstream-YYYY-MM-DD
|
||||
git fetch upstream
|
||||
UPSTREAM_SHA=$(git rev-parse upstream/master)
|
||||
git merge "$UPSTREAM_SHA"
|
||||
# Resolve conflicts, preserving the fork's isolated features; commit if needed.
|
||||
npm ci # lockfile-exact; needs Node 26 (on the VM use the container below)
|
||||
npm run build
|
||||
npm test
|
||||
npm run lint:dry
|
||||
git push -u origin sync/upstream-YYYY-MM-DD
|
||||
```
|
||||
|
||||
Open a PR against `main`, name the merged upstream commit (`$UPSTREAM_SHA`) and
|
||||
the imported range `origin/upstream..$UPSTREAM_SHA`, include validation results, and request Archimedes' review (Claudia reviews Archimedes' own PRs).
|
||||
Do not merge your own PR. Do not rebase or squash imported upstream history.
|
||||
After the reviewed sync merges, advance the pristine tracking branch to exactly
|
||||
the upstream commit that was merged into `main` (never to a newer, unreviewed
|
||||
`upstream/master`):
|
||||
|
||||
```sh
|
||||
git fetch origin
|
||||
UPSTREAM_SHA=<upstream commit named in the sync PR>
|
||||
git merge-base --is-ancestor "$UPSTREAM_SHA" origin/main &&
|
||||
git merge-base --is-ancestor origin/upstream "$UPSTREAM_SHA" &&
|
||||
git push origin "$UPSTREAM_SHA:refs/heads/upstream"
|
||||
```
|
||||
|
||||
The first check ensures the commit really is merged into `main`; the second
|
||||
prevents `upstream` from moving backwards or onto rewritten history. The push is
|
||||
not a force push. Afterwards `git log origin/upstream..origin/main` shows exactly
|
||||
the fork delta. If upstream rewrites history,
|
||||
stop for review instead of force-pushing. Never merge `main` into `upstream`.
|
||||
Use a feature branch from current `main` and a reviewed PR for fork changes.
|
||||
Keep credentials in the environment; never put tokens in remote URLs or files.
|
||||
|
||||
## CI and container image
|
||||
|
||||
Fork-owned Gitea Actions workflows live in `.gitea/workflows/`. The upstream CI in
|
||||
`.github/` and `.circleci/` stays untouched (it does not run on Gitea) so upstream
|
||||
merges remain conflict-free.
|
||||
|
||||
| Workflow | Trigger | What it does |
|
||||
| --- | --- | --- |
|
||||
| `ci.yml` | pull requests, push to `main` | `npm ci` (includes the Vite build via `postinstall`), `npm run lint:dry`, `npm run stylelint:dry`, `npm test`. Upstream currently has ESLint warnings but no errors; warnings do not fail the job. The tests need no MongoDB. |
|
||||
| `image.yml` | push to `main`, tags `v*`, manual | builds `docker/Dockerfile` (same as Compose) and pushes `git.morlana.online/f.weber/homebrewery-oidc`; release tags `vX.Y.Z` additionally go to Docker Hub (`<DOCKER_HUB_USER>/homebrewery-oidc`) |
|
||||
| `dockerhub-sync.yml` | manual (input `version`) | copies an already built `vX.Y.Z` image from Gitea to Docker Hub without rebuilding (same digest); sets `latest` only if the version is the highest release |
|
||||
| `dockerhub-description.yml` | release tag `vX.Y.Z`, push to `main` touching `docs/dockerhub/README.md`, manual | sets the Docker Hub overview from `docs/dockerhub/README.md` (English, < 25,000 bytes, absolute links only) plus a short description (≤ 100 characters), using `peter-evans/dockerhub-description`; skipped with a warning if `DOCKER_HUB_USER`/`DOCKER_HUB_TOKEN` are missing (the token needs Read, Write and Delete); `<DOCKER_HUB_USER>` in the file is replaced by the secret at publish time. A maintenance tag on an older commit overwrites the description with that older text; the first run needs the Hub repository to exist (created by `image.yml`) |
|
||||
|
||||
The authoritative image definition is `docker/Dockerfile` with
|
||||
`docker/Dockerfile.dockerignore` (BuildKit picks it up automatically for `context: .`).
|
||||
Compose (`docker-compose.override.yml`) builds the same file, so the published registry
|
||||
image matches the one built locally. The upstream `Dockerfile` stays unchanged and is not
|
||||
used by the fork. No configuration or secret is baked into the image: configure the
|
||||
container at runtime through environment variables (for example `MONGODB_URI`;
|
||||
`NODE_ENV=docker` is preset) or by mounting `config/docker.json`; `server/config.js`
|
||||
reads argv, then env, then that file, then `config/default.json`. The container exits if
|
||||
MongoDB is unreachable.
|
||||
|
||||
Image tags:
|
||||
|
||||
| Event | Tags |
|
||||
| --- | --- |
|
||||
| push to `main` | `main`, `sha-<7 chars>` |
|
||||
| tag `vX.Y.Z` | `vX.Y.Z`, `latest`, `sha-<7 chars>` (pre-release tags such as `v1.0.0-rc.1` get no `latest`) |
|
||||
|
||||
Docker Hub receives only release tags `vX.Y.Z` (as `vX.Y.Z` and `latest`, same build and
|
||||
digest as in Gitea). `main`, `sha-*` and pre-releases are never pushed there. If the secrets
|
||||
`DOCKER_HUB_USER` and `DOCKER_HUB_TOKEN` (access token with Read & Write) are missing, the
|
||||
Docker Hub part is skipped with a warning and the Gitea push is unaffected. To backfill a
|
||||
version, run `dockerhub-sync.yml` with e.g. `v1.0.0`.
|
||||
|
||||
`buildcache` is the BuildKit layer cache, not a runnable image.
|
||||
|
||||
Running the published image (Compose template with PostgreSQL 18, OIDC, Git backend and image upload, German): [docs/deploy/README.md](docs/deploy/README.md).
|
||||
|
||||
Runner and repository settings (repository → Settings → Actions):
|
||||
|
||||
- **Runner:** jobs use `runs-on: ubuntu-latest` (public runner, as in the DnD Character Manager).
|
||||
- **Secret `REGISTRY_TOKEN`:** access token of an account with write access to the
|
||||
`f.weber` packages, scope `write:package`. Without it the workflow falls back to the
|
||||
automatic `GITEA_TOKEN`, which may not be allowed to push packages.
|
||||
- **Variable `REGISTRY_USER`** (optional): owner of `REGISTRY_TOKEN`; defaults to the repository owner.
|
||||
- **Variable `CI_CACHE`** (optional): `true` enables the npm cache. Leave it unset until the
|
||||
act_runner cache server is reachable from job containers; otherwise every cache step
|
||||
waits for a connection timeout.
|
||||
- **Variable `IMAGE_PLATFORMS`** (optional): defaults to `linux/amd64`.
|
||||
|
||||
## Fork roadmap
|
||||
|
||||
These are planned features, not functionality delivered by the initial import:
|
||||
|
||||
| Milestone | Scope |
|
||||
| --- | --- |
|
||||
| [M0](https://git.morlana.online/f.weber/homebrewery-oidc/milestone/4) | Upstream import, CI, development setup |
|
||||
| [M1](https://git.morlana.online/f.weber/homebrewery-oidc/milestone/5) | OIDC login |
|
||||
| [M2](https://git.morlana.online/f.weber/homebrewery-oidc/milestone/6) | PostgreSQL backend (PostgreSQL 18+) |
|
||||
| [M3](https://git.morlana.online/f.weber/homebrewery-oidc/milestone/7) | Git backend including sharing |
|
||||
| [M4](https://git.morlana.online/f.weber/homebrewery-oidc/milestone/8) | Image uploads to the Git repository |
|
||||
|
||||
Track implementation and review status on the
|
||||
[roadmap board](https://git.morlana.online/f.weber/homebrewery-oidc/projects/2).
|
||||
|
||||
## Local startup
|
||||
|
||||
Consult `package.json` for the actual engine requirements: this imported revision
|
||||
requires Node >=26.4.0 and npm >=10.8 <12. The older Node guidance in the upstream
|
||||
README (v16+) does not match this revision. MongoDB must be >= 4.4, the minimum
|
||||
supported by the bundled MongoDB driver (7.7).
|
||||
|
||||
```sh
|
||||
export NODE_ENV=local
|
||||
export MONGODB_URI=mongodb://127.0.0.1:27017/homebrewery
|
||||
npm install # also runs the production asset build via postinstall
|
||||
npm start # http://localhost:8000
|
||||
```
|
||||
|
||||
### Development VM
|
||||
|
||||
The VM runs Node 24, and its CPU lacks AVX, so MongoDB >= 5.0 exits immediately
|
||||
(code 132). Do not install Node system-wide; use disposable containers instead:
|
||||
|
||||
```sh
|
||||
docker network create hb-dev
|
||||
docker run -d --name hb-mongo --network hb-dev --memory 400m \
|
||||
mongo:4.4 --wiredTigerCacheSizeGB 0.25
|
||||
docker run --rm --name hb-app --network hb-dev --memory 1200m \
|
||||
--user "$(id -u):$(id -g)" -e HOME=/tmp -e NODE_ENV=local \
|
||||
-e MONGODB_URI=mongodb://hb-mongo:27017/homebrewery \
|
||||
-p 127.0.0.1:8000:8000 -v "$PWD":/app -w /app \
|
||||
node:26 sh -c 'npm install && npm start'
|
||||
# when finished
|
||||
docker rm -f hb-app hb-mongo && docker network rm hb-dev
|
||||
```
|
||||
|
||||
MongoDB 4.4 is end-of-life: use it only with disposable test data. Verified on
|
||||
2026-11-24 with `node:26` (Node 26.13.1, npm 11.20.0) and `mongo:4.4`.
|
||||
@@ -90,6 +90,35 @@ If you still have problems, post in [Our Subreddit](https://www.reddit.com/r/hom
|
||||
|
||||
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).
|
||||
|
||||
#### Brews in Git speichern
|
||||
|
||||
Angemeldete OIDC-Nutzer können Brews in einem beliebigen Git-Repository speichern (HTTPS + Personal Access Token, providerneutral: Gitea, Forgejo, GitHub, GitLab, …). Speichern erzeugt einen Commit, beim Öffnen wird der Remote-Stand übernommen, Konflikte werden erkannt und angezeigt. Das Feature ist aus, solange `HB_GIT_TOKEN_KEY` fehlt. Einrichtung, Variablen, Sicherheit und Anbieter-Hinweise: [docs/git/README.md](./docs/git/README.md). Entscheidung: [ADR 0003](./docs/adr/0003-git-backend-und-teilen.md). Fehlersuche und nachträgliches Aktivieren: [docs/git/README.md](./docs/git/README.md#fehlersuche--nachträglich-aktivieren).
|
||||
|
||||
#### Betrieb mit dem veröffentlichten Image
|
||||
|
||||
Compose-Vorlage (App + PostgreSQL 18, OIDC, Git, Bild-Upload) ohne Repo-Checkout: [docs/deploy/README.md](./docs/deploy/README.md). Wichtig: Jede `HB_*`-Variable muss im Container ankommen (`environment:`/`env_file:`), und nach Änderungen gilt `docker compose up -d`, nicht `restart`.
|
||||
|
||||
### Running the application on FreeBSD or FreeNAS
|
||||
|
||||
Please see the docs here: [README.FreeBSD.md](./README.FREEBSD.md)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import './assets.less';
|
||||
import React, { useRef } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { imageFiles, formatBytes } from './assetClient.js';
|
||||
|
||||
// Button in der Snippet-Bar (ADR 0004 §5): Dateiauswahl, Fortschritt und Fehlertexte direkt am Button.
|
||||
// Sichtbar nur bei Git-verknüpften Brews (assetUpload.available).
|
||||
const AssetUploadButton = ({ assetUpload })=>{
|
||||
const input = useRef(null);
|
||||
if(!assetUpload?.available) return null;
|
||||
const { cfg, busy, percent, name, errors, done, upload, dismiss } = assetUpload;
|
||||
const accept = cfg.types.map((t)=>`image/${t}`).join(',');
|
||||
|
||||
return (
|
||||
<div className='assetUpload'>
|
||||
<button className={cx('editorTool', 'assetUploadButton', { active: !busy })}
|
||||
disabled={busy}
|
||||
title={`Bild ins Git-Repository hochladen (${cfg.types.join(', ').toUpperCase()}, max. ${formatBytes(cfg.maxBytes)}). Auch per Drag-and-drop oder Einfügen. Hinweis: Metadaten (z. B. GPS) bleiben erhalten, Bilder sind über den Teilen-Link öffentlich.`}
|
||||
onClick={()=>input.current?.click()}>
|
||||
<i className={busy ? 'fas fa-spinner fa-spin' : 'fas fa-image'} />
|
||||
</button>
|
||||
<input ref={input} type='file' hidden multiple accept={accept}
|
||||
onChange={(e)=>{ const files = imageFiles(e.target.files); e.target.value = ''; upload(files); }} />
|
||||
{(busy || errors.length > 0 || done > 0) && (
|
||||
<div className={cx('assetUploadStatus', { error: errors.length > 0 })} role='status'>
|
||||
{busy && <span>„{name}“ wird hochgeladen{percent != null ? ` (${percent} %)` : ''} …</span>}
|
||||
{!busy && done > 0 && errors.length === 0 && <span>{done === 1 ? 'Bild eingefügt.' : `${done} Bilder eingefügt.`} Hinweis: Fotos können Metadaten (z. B. GPS) enthalten und sind über den Teilen-Link öffentlich.</span>}
|
||||
{!busy && errors.map((msg, i)=><span key={i}>{msg}</span>)}
|
||||
{!busy && <button className='dismiss' onClick={dismiss} title='Schließen'><i className='fas fa-times' /></button>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AssetUploadButton;
|
||||
@@ -0,0 +1,76 @@
|
||||
import request from '../../homebrew/utils/request-middleware.js';
|
||||
|
||||
// Client-Seite des Bild-Uploads (ADR 0004 §5). Reine Funktionen und dünne API-Hülle, ohne React.
|
||||
|
||||
export const MIME_TYPE = { 'image/png': 'png', 'image/jpeg': 'jpeg', 'image/gif': 'gif', 'image/webp': 'webp' };
|
||||
|
||||
const MIB = 1024 * 1024;
|
||||
export const formatBytes = (n)=>{
|
||||
if(n >= MIB) return `${+(n / MIB).toFixed(1)} MiB`;
|
||||
if(n >= 1024) return `${Math.round(n / 1024)} KiB`;
|
||||
return `${n} Byte`;
|
||||
};
|
||||
|
||||
// Vorabprüfung mit den Limits des Servers, spart den Upload. Der Server prüft ohnehin erneut.
|
||||
export const validateFile = (file, cfg)=>{
|
||||
const type = MIME_TYPE[file.type];
|
||||
if(!type || !cfg.types.includes(type))
|
||||
return `„${file.name}“: Dieser Dateityp ist nicht erlaubt. Erlaubt sind: ${cfg.types.join(', ').toUpperCase()}.`;
|
||||
if(file.size > cfg.maxBytes)
|
||||
return `„${file.name}“ ist zu groß (${formatBytes(file.size)}). Erlaubt sind höchstens ${formatBytes(cfg.maxBytes)}.`;
|
||||
if(file.size === 0) return `„${file.name}“ ist leer.`;
|
||||
return null;
|
||||
};
|
||||
|
||||
export const imageFiles = (fileList)=>Array.from(fileList ?? []).filter((f)=>f.type?.startsWith('image/'));
|
||||
|
||||
// Verständliche Meldung zu einem Fehler der API (A01–A07, G02–G05, G08, 412, 401)
|
||||
export const describeError = (err)=>{
|
||||
const code = err?.HBErrorCode;
|
||||
const msg = err?.message;
|
||||
if(err?.status === 412) return msg || 'Die Seite ist veraltet. Bitte neu laden.';
|
||||
if(err?.status === 401) return 'Bitte melde dich an und prüfe, ob du Autor dieses Brews bist.';
|
||||
if(code === 'G02') return 'Anmeldung am Git-Server fehlgeschlagen. Prüfe den Token der Verbindung (Schreibrecht nötig).';
|
||||
if(code === 'G03') return 'Repository oder Branch nicht gefunden.';
|
||||
if(code === 'G04') return 'Der Git-Server ist nicht erreichbar. Bitte später erneut versuchen.';
|
||||
if(code === 'G05') return 'Speichern im Repository gerade nicht möglich. Bitte erneut versuchen.';
|
||||
return msg || 'Das Bild konnte nicht hochgeladen werden.';
|
||||
};
|
||||
|
||||
const unwrap = (promise)=>promise.then((res)=>res.body).catch((err)=>{
|
||||
const body = err.response?.body ?? {};
|
||||
const e = new Error(body.message || err.message);
|
||||
e.status = err.response?.status;
|
||||
e.HBErrorCode = body.HBErrorCode;
|
||||
e.body = body;
|
||||
throw e;
|
||||
});
|
||||
|
||||
export const assetApi = {
|
||||
config : ()=>unwrap(request.get('/api/git/assets/config')),
|
||||
upload : (editId, file, { onProgress } = {})=>{
|
||||
const req = request.post(`/api/git/brews/${editId}/assets`)
|
||||
.set('Content-Type', file.type)
|
||||
.set('X-HB-Filename', encodeURIComponent(file.name || 'image'))
|
||||
.send(file);
|
||||
if(onProgress) req.on('progress', (e)=>{ if(e.direction === 'upload' && e.percent != null) onProgress(Math.round(e.percent)); });
|
||||
return unwrap(req);
|
||||
}
|
||||
};
|
||||
|
||||
// Dateien nacheinander hochladen. Liefert Markdown für alle erfolgreichen und die Fehlermeldungen.
|
||||
export const uploadFiles = async (editId, files, cfg, { api = assetApi, onProgress } = {})=>{
|
||||
const markdown = [];
|
||||
const errors = [];
|
||||
for (const [i, file] of files.entries()) {
|
||||
const invalid = validateFile(file, cfg);
|
||||
if(invalid) { errors.push(invalid); continue; }
|
||||
try {
|
||||
const res = await api.upload(editId, file, { onProgress: (p)=>onProgress?.({ index: i, total: files.length, percent: p, name: file.name }) });
|
||||
markdown.push(res.markdown ?? `![${file.name.replace(/\.[^.]+$/, '')}](${res.url})`);
|
||||
} catch (err) {
|
||||
errors.push(`„${file.name}“: ${describeError(err)}`);
|
||||
}
|
||||
}
|
||||
return { markdown, errors };
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
@import '@sharedStyles/core.less';
|
||||
|
||||
.assetUpload {
|
||||
position : relative;
|
||||
display : inline-block;
|
||||
.assetUploadStatus {
|
||||
position : absolute;
|
||||
z-index : 20;
|
||||
top : 100%;
|
||||
right : 0;
|
||||
display : grid;
|
||||
gap : 4px;
|
||||
width : 280px;
|
||||
padding : 8px 24px 8px 8px;
|
||||
font-size : 12px;
|
||||
color : white;
|
||||
background-color : #333333;
|
||||
&.error span { color : #ff9a9a; font-weight : 800; }
|
||||
.dismiss {
|
||||
position : absolute;
|
||||
top : 4px;
|
||||
right : 4px;
|
||||
color : white;
|
||||
cursor : pointer;
|
||||
background : none;
|
||||
border : none;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { gitApi } from '../git/gitApi.js';
|
||||
import { assetApi, imageFiles, uploadFiles } from './assetClient.js';
|
||||
|
||||
export const LINK_EVENT = 'hb:git-link-changed';
|
||||
|
||||
// Bild-Upload im Editor (ADR 0004 §5): Zustand für Button, Drag-and-drop und Einfügen aus der Zwischenablage.
|
||||
// `containerRef`: Wurzelelement des Editors, `inject(text)`: Text an der Cursorposition einfügen.
|
||||
export const useAssetUpload = ({ editId, containerRef, inject, active = true })=>{
|
||||
const [cfg, setCfg] = useState(null); // null: unbekannt/aus
|
||||
const [linked, setLinked] = useState(false);
|
||||
const [state, setState] = useState({ busy: false, percent: null, name: '', errors: [], done: 0 });
|
||||
const busyRef = useRef(false);
|
||||
const injectRef = useRef(inject);
|
||||
injectRef.current = inject;
|
||||
|
||||
useEffect(()=>{
|
||||
let live = true;
|
||||
assetApi.config().then((c)=>live && setCfg(c.enabled ? c : null)).catch(()=>live && setCfg(null));
|
||||
return ()=>{ live = false; };
|
||||
}, []);
|
||||
|
||||
useEffect(()=>{
|
||||
if(!editId || !cfg) { setLinked(false); return; }
|
||||
let live = true;
|
||||
const refresh = ()=>gitApi.status(editId).then((s)=>live && setLinked(!!s.linked)).catch(()=>live && setLinked(false));
|
||||
refresh();
|
||||
window.addEventListener(LINK_EVENT, refresh);
|
||||
return ()=>{ live = false; window.removeEventListener(LINK_EVENT, refresh); };
|
||||
}, [editId, cfg]);
|
||||
|
||||
const available = !!(cfg && linked && editId);
|
||||
|
||||
const upload = useCallback(async (files)=>{
|
||||
if(!available || busyRef.current || !files.length) return;
|
||||
busyRef.current = true;
|
||||
setState({ busy: true, percent: 0, name: files[0].name, errors: [], done: 0 });
|
||||
const { markdown, errors } = await uploadFiles(editId, files, cfg, {
|
||||
onProgress : ({ percent, name })=>setState((s)=>({ ...s, percent, name }))
|
||||
});
|
||||
if(markdown.length) injectRef.current(`${markdown.join('\n')}\n`);
|
||||
busyRef.current = false;
|
||||
setState({ busy: false, percent: null, name: '', errors, done: markdown.length });
|
||||
}, [available, editId, cfg]);
|
||||
|
||||
// Drag-and-drop und Einfügen im Text-Editor (Capture-Phase, vor CodeMirror). Nur Bilddateien, Text bleibt unberührt.
|
||||
useEffect(()=>{
|
||||
const root = containerRef?.current;
|
||||
if(!root || !available || !active) return;
|
||||
const inText = (e)=>!!e.target.closest?.('.codeEditor.brewText');
|
||||
const hasFiles = (dt)=>!!dt && (Array.from(dt.types ?? []).includes('Files') || dt.files?.length > 0);
|
||||
const onDragOver = (e)=>{
|
||||
if(inText(e) && hasFiles(e.dataTransfer)) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }
|
||||
};
|
||||
const onDrop = (e)=>{
|
||||
if(!inText(e)) return;
|
||||
const files = imageFiles(e.dataTransfer?.files);
|
||||
if(!files.length) return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
upload(files);
|
||||
};
|
||||
const onPaste = (e)=>{
|
||||
if(!inText(e)) return;
|
||||
const files = imageFiles(e.clipboardData?.files);
|
||||
if(!files.length) return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
upload(files);
|
||||
};
|
||||
root.addEventListener('dragover', onDragOver, true);
|
||||
root.addEventListener('drop', onDrop, true);
|
||||
root.addEventListener('paste', onPaste, true);
|
||||
return ()=>{
|
||||
root.removeEventListener('dragover', onDragOver, true);
|
||||
root.removeEventListener('drop', onDrop, true);
|
||||
root.removeEventListener('paste', onPaste, true);
|
||||
};
|
||||
}, [containerRef, available, active, upload]);
|
||||
|
||||
const dismiss = useCallback(()=>setState((s)=>({ ...s, errors: [], done: 0 })), []);
|
||||
|
||||
return { available, cfg, upload, dismiss, ...state };
|
||||
};
|
||||
@@ -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';
|
||||
@@ -0,0 +1,102 @@
|
||||
import './git.less';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { gitApi } from './gitApi.js';
|
||||
import { classifyListError } from './panelState.js';
|
||||
|
||||
// Verbindungen verwalten (ADR 0003 §7): anlegen, testen, löschen, Brews aus dem Repo importieren.
|
||||
// Das Token-Feld ist reines Eingabefeld und wird nie vorbefüllt; der Server gibt den Token nie zurück.
|
||||
const EMPTY = { label: '', repoUrl: '', authUsername: 'git', token: '' };
|
||||
|
||||
const GitConnectionsPanel = ()=>{
|
||||
const [state, setState] = useState('loading'); // loading | hidden | notice | ready
|
||||
const [notice, setNotice] = useState('');
|
||||
const [conns, setConns] = useState([]);
|
||||
const [form, setForm] = useState(EMPTY);
|
||||
const [msg, setMsg] = useState({}); // pro Verbindung: { ok, text }
|
||||
const [formError, setFormError] = useState('');
|
||||
const [files, setFiles] = useState({}); // pro Verbindung: { branch, files }
|
||||
|
||||
const reload = ()=>gitApi.listConnections().then((list)=>{ setConns(list); setState('ready'); })
|
||||
.catch((err)=>{
|
||||
const { state: next, notice: text } = classifyListError(err);
|
||||
if(next === 'error') { setFormError(err.message); setState('ready'); } else { setNotice(text ?? ''); setState(next); }
|
||||
});
|
||||
useEffect(()=>{ reload(); }, []);
|
||||
|
||||
if(state === 'notice') return (
|
||||
<div className='dataGroup gitConnections'>
|
||||
<h3>Git-Verbindungen <i className='fab fa-git-alt'></i></h3>
|
||||
<p className='notice'>{notice}</p>
|
||||
</div>
|
||||
);
|
||||
if(state !== 'ready') return null; // lädt oder nicht angemeldet
|
||||
|
||||
const set = (id, ok, text)=>setMsg((m)=>({ ...m, [id]: { ok, text } }));
|
||||
|
||||
const create = async (e)=>{
|
||||
e.preventDefault();
|
||||
setFormError('');
|
||||
try {
|
||||
await gitApi.createConnection(form);
|
||||
setForm(EMPTY);
|
||||
await reload();
|
||||
} catch (err) { setFormError(err.message); }
|
||||
};
|
||||
|
||||
const test = (c)=>gitApi.testConnection(c.id)
|
||||
.then((r)=>{ set(c.id, true, `Verbindung ok (Standard-Branch ${r.defaultBranch ?? '?'}, ${r.branchCount} Branches)`); reload(); })
|
||||
.catch((err)=>set(c.id, false, `${err.HBErrorCode ?? ''} ${err.message}`));
|
||||
|
||||
const remove = async (c)=>{
|
||||
if(!window.confirm(`Verbindung „${c.label}“ löschen? Verknüpfte Brews bleiben als normale Brews erhalten.`)) return;
|
||||
await gitApi.deleteConnection(c.id).catch((err)=>set(c.id, false, err.message));
|
||||
reload();
|
||||
};
|
||||
|
||||
const showFiles = (c)=>gitApi.listFiles(c.id, c.defaultBranch, c.brewDir)
|
||||
.then((r)=>setFiles((f)=>({ ...f, [c.id]: { branch: r.branch, files: r.files } })))
|
||||
.catch((err)=>set(c.id, false, `${err.HBErrorCode ?? ''} ${err.message}`));
|
||||
|
||||
const importFile = (c, branch, path)=>gitApi.importBrew({ connectionId: c.id, branch, path })
|
||||
.then((brew)=>{ window.location.href = `/edit/${brew.editId}`; })
|
||||
.catch((err)=>set(c.id, false, `${err.HBErrorCode ?? ''} ${err.message}`));
|
||||
|
||||
return (
|
||||
<div className='dataGroup gitConnections'>
|
||||
<h3>Git-Verbindungen <i className='fab fa-git-alt'></i></h3>
|
||||
<p>Brews in einem beliebigen Git-Repository speichern (HTTPS + Personal Access Token). Der Token wird verschlüsselt gespeichert und nie angezeigt.</p>
|
||||
{conns.map((c)=>(
|
||||
<div className='gitConn' key={c.id}>
|
||||
<div className='label'>{c.label}</div>
|
||||
<div className='url'>{c.repoUrl}</div>
|
||||
<div className='meta'>Standard-Branch {c.defaultBranch}, Ordner {c.brewDir || '/'}{c.lastVerifiedAt ? '' : ' · noch nicht getestet'}</div>
|
||||
<div className='actions'>
|
||||
<button onClick={()=>test(c)}>Testen</button>
|
||||
<button onClick={()=>showFiles(c)}>Brews aus Repo importieren</button>
|
||||
<button onClick={()=>remove(c)}>Löschen</button>
|
||||
</div>
|
||||
{msg[c.id] && <div className={msg[c.id].ok ? 'ok' : 'error'}>{msg[c.id].text}</div>}
|
||||
{files[c.id] && (
|
||||
<ul className='files'>
|
||||
{files[c.id].files.length === 0 && <li>Keine .md-Dateien in {c.brewDir || '/'} auf {files[c.id].branch}.</li>}
|
||||
{files[c.id].files.map((f)=>(
|
||||
<li key={f}>{f} <button onClick={()=>importFile(c, files[c.id].branch, f)}>Importieren</button></li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<form onSubmit={create}>
|
||||
<strong>Neue Verbindung</strong>
|
||||
<input placeholder='Bezeichnung' value={form.label} required maxLength={80} onChange={(e)=>setForm({ ...form, label: e.target.value })} />
|
||||
<input placeholder='https://git.example.org/nutzer/repo.git' value={form.repoUrl} required onChange={(e)=>setForm({ ...form, repoUrl: e.target.value })} />
|
||||
<input placeholder='Benutzername (Standard: git)' value={form.authUsername} onChange={(e)=>setForm({ ...form, authUsername: e.target.value })} />
|
||||
<input type='password' autoComplete='off' placeholder='Personal Access Token' value={form.token} required onChange={(e)=>setForm({ ...form, token: e.target.value })} />
|
||||
<button type='submit'>Verbindung anlegen</button>
|
||||
{formError && <div className='error'>{formError}</div>}
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default GitConnectionsPanel;
|
||||
@@ -0,0 +1,81 @@
|
||||
import React, { useState } from 'react';
|
||||
import Nav from '@navbar/nav.jsx';
|
||||
import { gitApi, setGitOverwrite, SAVE_EVENT } from './gitApi.js';
|
||||
|
||||
// Fehlertexte und Konfliktdialog für G01–G10 (ADR 0003 §5, §7).
|
||||
const TEXTS = {
|
||||
G02 : 'Anmeldung am Git-Server fehlgeschlagen. Prüfe den Token der Verbindung (Account-Seite).',
|
||||
G03 : 'Repository, Branch oder Datei wurden nicht gefunden.',
|
||||
G04 : 'Der Git-Server ist nicht erreichbar oder zu langsam. Deine Änderungen sind noch nicht gespeichert, bitte später erneut speichern.',
|
||||
G05 : 'Speichern im Repository ist gerade nicht möglich (viele gleichzeitige Änderungen). Bitte gleich erneut speichern.',
|
||||
G06 : 'Die Datei existiert im Repository bereits.',
|
||||
G07 : 'Das Git-Backend steht nur Konten mit OIDC-Anmeldung zur Verfügung.',
|
||||
G08 : 'Ungültige Eingabe für Git.',
|
||||
G09 : 'Die Datei ist für das Git-Backend zu groß.',
|
||||
G10 : 'Das Git-Backend ist auf diesem Server nicht aktiviert.'
|
||||
};
|
||||
|
||||
const downloadOwnVersion = (brew)=>{
|
||||
const blob = new Blob([brew?.text ?? ''], { type: 'text/markdown' });
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = `${(brew?.title || 'brew').replace(/[^\w-]+/g, '_')}-meine-version.md`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
};
|
||||
|
||||
const GitErrorNavItem = ({ error, clearError, brew })=>{
|
||||
const body = error.response?.body ?? {};
|
||||
const code = body.HBErrorCode;
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
if(code === 'G01' && body.operation === 'delete') {
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Konflikt
|
||||
<div className='errorContainer' onClick={clearError}>
|
||||
Die Datei wurde im Git-Repository geändert. Der Brew wurde nicht gelöscht. Prüfe die Änderung im Repository und lösche erneut.
|
||||
</div>
|
||||
</Nav.item>;
|
||||
}
|
||||
|
||||
if(code === 'G01') {
|
||||
const keepMine = ()=>{
|
||||
setGitOverwrite(body.remoteBlobSha ?? 'none');
|
||||
clearError();
|
||||
document.dispatchEvent(new CustomEvent(SAVE_EVENT));
|
||||
};
|
||||
const loadRemote = async ()=>{
|
||||
setBusy(true);
|
||||
try { await gitApi.pull(brew.editId); window.location.reload(); } catch { setBusy(false); }
|
||||
};
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Konflikt
|
||||
<div className='errorContainer'>
|
||||
Die Datei wurde im Git-Repository geändert{body.remoteCommitSha ? ` (${body.remoteCommitSha.slice(0, 7)})` : ''}.<br />
|
||||
<div className='confirm' onClick={busy ? undefined : keepMine}>Meine Version behalten</div>
|
||||
<div className='deny' onClick={busy ? undefined : ()=>downloadOwnVersion(brew)}>Meine Version sichern</div>
|
||||
<div className='deny' onClick={busy ? undefined : loadRemote}>Remote-Version laden</div>
|
||||
<div className='deny' onClick={clearError}>Abbrechen</div>
|
||||
</div>
|
||||
</Nav.item>;
|
||||
}
|
||||
|
||||
if(body.operation === 'delete') {
|
||||
const text = (code === 'G04' || code === 'G05')
|
||||
? 'Löschen im Repository ist gerade nicht möglich. Es wurde nichts gelöscht, bitte später erneut versuchen.'
|
||||
: `Löschen fehlgeschlagen, es wurde nichts gelöscht. ${TEXTS[code] ?? body.message ?? ''}`.trim();
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Oops!
|
||||
<div className='errorContainer' onClick={clearError}>{text}</div>
|
||||
</Nav.item>;
|
||||
}
|
||||
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Oops!
|
||||
<div className='errorContainer' onClick={clearError}>
|
||||
{TEXTS[code] ?? body.message ?? 'Git-Fehler.'}
|
||||
</div>
|
||||
</Nav.item>;
|
||||
};
|
||||
|
||||
export default GitErrorNavItem;
|
||||
@@ -0,0 +1,84 @@
|
||||
import './git.less';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import Moment from 'moment';
|
||||
import Nav from '@navbar/nav.jsx';
|
||||
import { gitApi } from './gitApi.js';
|
||||
|
||||
// Git-Status im Editor-Navbar (ADR 0003 §7): Branch, Pfad, kurzer SHA, Fehler; Pull; Verknüpfen/Lösen.
|
||||
const short = (sha)=>sha ? sha.slice(0, 7) : '';
|
||||
|
||||
const GitNavItem = ({ brew, lastSavedTime, onLinkedChange })=>{
|
||||
const editId = brew?.editId;
|
||||
const [status, setStatus] = useState(null); // null: unbekannt/aus
|
||||
const [conns, setConns] = useState(null);
|
||||
const [form, setForm] = useState({ connectionId: '', branch: '', path: '' });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const refresh = ()=>gitApi.status(editId).then(setStatus).catch(()=>setStatus(null));
|
||||
useEffect(()=>{ if(editId) refresh(); }, [editId, lastSavedTime]);
|
||||
|
||||
// Verbindungen nur laden, wenn verknüpft werden soll (403/503: Git nicht verfügbar → Item bleibt unsichtbar)
|
||||
useEffect(()=>{
|
||||
if(status && !status.linked && conns === null) {
|
||||
gitApi.listConnections().then((list)=>{ setConns(list); setForm((f)=>({ ...f, connectionId: list[0]?.id ?? '' })); }).catch(()=>setConns(false));
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
useEffect(()=>{ onLinkedChange?.(!!status?.linked); window.dispatchEvent(new Event('hb:git-link-changed')); }, [status?.linked]); // zweiter Teil: ADR 0004 (Upload-Button)
|
||||
|
||||
if(!editId || !status) return null;
|
||||
|
||||
const run = async (fn)=>{
|
||||
setBusy(true); setError('');
|
||||
try { await fn(); await refresh(); } catch (err) { setError(`${err.HBErrorCode ?? ''} ${err.message}`.trim()); }
|
||||
setBusy(false);
|
||||
};
|
||||
|
||||
if(status.linked) {
|
||||
return (
|
||||
<Nav.dropdown className='gitNav'>
|
||||
<Nav.item icon={status.lastError ? 'fas fa-exclamation-triangle' : 'fab fa-git-alt'} className={status.lastError ? 'error' : ''}>
|
||||
{status.branch}
|
||||
</Nav.item>
|
||||
<div className='gitDropdown'>
|
||||
<div className='meta'>{status.connectionLabel}: {status.repoUrl}</div>
|
||||
<div className='meta'>{status.branch} · {status.path}{status.lastCommitSha ? ` · ${short(status.lastCommitSha)}` : ''}</div>
|
||||
{status.snapshotAt && <div className='meta' title='Stand, den Teilen-Links ausliefern'>Teilen-Stand: {Moment(status.snapshotAt).format('LLL')}</div>}
|
||||
{status.lastError === 'G04' && <div className='error'>Git nicht erreichbar, angezeigt wird der zuletzt gespeicherte Stand.</div>}
|
||||
{status.lastError && status.lastError !== 'G04' && <div className='error'>Letzter Fehler: {status.lastError}</div>}
|
||||
{error && <div className='error'>{error}</div>}
|
||||
<button disabled={busy} onClick={()=>run(async ()=>{
|
||||
if(!window.confirm('Remote-Stand laden? Ungespeicherte Änderungen im Editor gehen verloren.')) return;
|
||||
await gitApi.pull(editId);
|
||||
window.location.reload();
|
||||
})}>Pull</button>
|
||||
{status.isConnectionOwner && <button disabled={busy} onClick={()=>run(async ()=>{
|
||||
if(window.confirm('Verknüpfung lösen? Der Brew bleibt erhalten, die Datei im Repository auch.')) await gitApi.unlinkBrew(editId);
|
||||
})}>Verknüpfung lösen</button>}
|
||||
</div>
|
||||
</Nav.dropdown>
|
||||
);
|
||||
}
|
||||
|
||||
if(!conns || conns.length === 0) return null; // nichts zu verknüpfen (kein OIDC-Konto oder keine Verbindung)
|
||||
|
||||
return (
|
||||
<Nav.dropdown className='gitNav'>
|
||||
<Nav.item icon='fab fa-git-alt'>Git</Nav.item>
|
||||
<div className='gitDropdown'>
|
||||
<select value={form.connectionId} onChange={(e)=>setForm({ ...form, connectionId: e.target.value })}>
|
||||
{conns.map((c)=><option key={c.id} value={c.id}>{c.label}</option>)}
|
||||
</select>
|
||||
<input placeholder='Branch (Standard der Verbindung)' value={form.branch} onChange={(e)=>setForm({ ...form, branch: e.target.value })} />
|
||||
<input placeholder='Pfad, z. B. brews/mein-brew.md' value={form.path} onChange={(e)=>setForm({ ...form, path: e.target.value })} />
|
||||
{error && <div className='error'>{error}</div>}
|
||||
<button disabled={busy || !form.connectionId} onClick={()=>run(()=>gitApi.linkBrew(editId, { connectionId: form.connectionId, branch: form.branch || undefined, path: form.path || undefined }))}>
|
||||
In Git speichern
|
||||
</button>
|
||||
</div>
|
||||
</Nav.dropdown>
|
||||
);
|
||||
};
|
||||
|
||||
export default GitNavItem;
|
||||
@@ -0,0 +1,36 @@
|
||||
@import '@sharedStyles/core.less';
|
||||
|
||||
.gitConnections {
|
||||
.gitConn {
|
||||
padding : 8px 0;
|
||||
border-bottom : 1px solid #cccccc;
|
||||
.label { font-weight : 800; }
|
||||
.url, .meta { font-size : 0.9em; color : #555555; word-break : break-all; }
|
||||
.actions button { margin : 4px 6px 0 0; }
|
||||
}
|
||||
form {
|
||||
display : grid;
|
||||
gap : 6px;
|
||||
margin-top : 10px;
|
||||
input { padding : 4px; }
|
||||
}
|
||||
.error { color : @red; font-weight : 800; }
|
||||
.ok { color : @teal; font-weight : 800; }
|
||||
.notice { color : #555555; font-style : italic; }
|
||||
ul.files { list-style : none; padding : 0; li { margin : 2px 0; } }
|
||||
}
|
||||
|
||||
.gitNav {
|
||||
.gitDropdown {
|
||||
display : grid;
|
||||
gap : 6px;
|
||||
min-width : 260px;
|
||||
padding : 8px;
|
||||
font-size : 12px;
|
||||
color : white;
|
||||
background-color : #333333;
|
||||
input, select { padding : 3px; }
|
||||
.error { color : #ff9a9a; font-weight : 800; }
|
||||
.meta { opacity : 0.8; word-break : break-all; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import superagent from 'superagent';
|
||||
import request from '../../homebrew/utils/request-middleware.js';
|
||||
|
||||
const patch = (path)=>superagent.patch(path).set('Homebrewery-Version', global.version);
|
||||
|
||||
// Dünne Hülle um /api/git/* (ADR 0003 §7). Fehler tragen `HBErrorCode` und `message` des Servers.
|
||||
const unwrap = (promise)=>promise.then((res)=>res.body).catch((err)=>{
|
||||
const body = err.response?.body ?? {};
|
||||
const e = new Error(body.message || err.message);
|
||||
e.status = err.response?.status;
|
||||
e.HBErrorCode = body.HBErrorCode;
|
||||
e.body = body;
|
||||
throw e;
|
||||
});
|
||||
|
||||
export const gitApi = {
|
||||
listConnections : ()=>unwrap(request.get('/api/git/connections')),
|
||||
createConnection : (data)=>unwrap(request.post('/api/git/connections').send(data)),
|
||||
updateConnection : (id, data)=>unwrap(patch(`/api/git/connections/${id}`).send(data)),
|
||||
deleteConnection : (id)=>unwrap(request.delete(`/api/git/connections/${id}`)),
|
||||
testConnection : (id)=>unwrap(request.post(`/api/git/connections/${id}/test`)),
|
||||
listBranches : (id)=>unwrap(request.get(`/api/git/connections/${id}/branches`)),
|
||||
listFiles : (id, branch, dir)=>unwrap(request.get(`/api/git/connections/${id}/files`).query({ branch, dir })),
|
||||
importBrew : (data)=>unwrap(request.post('/api/git/brews/import').send(data)),
|
||||
linkBrew : (editId, data)=>unwrap(request.post(`/api/git/brews/${editId}/link`).send(data)),
|
||||
unlinkBrew : (editId)=>unwrap(request.delete(`/api/git/brews/${editId}/link`)),
|
||||
status : (editId)=>unwrap(request.get(`/api/git/brews/${editId}`)),
|
||||
pull : (editId)=>unwrap(request.post(`/api/git/brews/${editId}/pull`))
|
||||
};
|
||||
|
||||
// "Meine Version behalten" (Konfliktdialog G01): der nächste Save hängt ?gitOverwrite=<blob> an.
|
||||
let overwriteBlob = null;
|
||||
export const setGitOverwrite = (blob)=>{ overwriteBlob = blob; };
|
||||
export const consumeGitOverwrite = ()=>{ const b = overwriteBlob; overwriteBlob = null; return b; };
|
||||
export const SAVE_EVENT = 'hb:git-save';
|
||||
@@ -0,0 +1,18 @@
|
||||
// Zustand des Git-Panels auf der Account-Seite (FLW-258): aus dem Fehler von GET /api/git/connections
|
||||
// wird entschieden, ob das Panel einen Hinweis zeigt, normal arbeitet oder unsichtbar bleibt.
|
||||
export const NOTICES = {
|
||||
disabled : 'Git-Backend auf diesem Server nicht aktiviert – siehe docs/git (Abschnitt „Fehlersuche / nachträglich aktivieren“).',
|
||||
noOidc : 'Nur mit OIDC-Anmeldung verfügbar.'
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {{ status?: number, HBErrorCode?: string }} err Fehler aus gitApi.listConnections()
|
||||
* @returns {{ state: 'notice'|'hidden'|'error', notice?: string }}
|
||||
* notice = Hinweis anzeigen, hidden = nichts anzeigen (nicht angemeldet), error = Panel mit Fehlermeldung
|
||||
*/
|
||||
export const classifyListError = (err)=>{
|
||||
if(err?.status === 503 && (!err.HBErrorCode || err.HBErrorCode === 'G10')) return { state: 'notice', notice: NOTICES.disabled };
|
||||
if(err?.status === 403 && (!err.HBErrorCode || err.HBErrorCode === 'G07')) return { state: 'notice', notice: NOTICES.noOidc };
|
||||
if(err?.status === 401) return { state: 'hidden' };
|
||||
return { state: 'error' };
|
||||
};
|
||||
@@ -8,6 +8,7 @@ import CodeEditor from '@components/codeEditor/codeEditor.jsx';
|
||||
import SnippetBar from './snippetbar/snippetbar.jsx';
|
||||
import MetadataEditor from './metadataEditor/metadataEditor.jsx';
|
||||
import SettingsEditor from './settingsEditor/settingsEditor.jsx';
|
||||
import { useAssetUpload } from '../../fork/assets/useAssetUpload.js'; // [fork] ADR-0004
|
||||
|
||||
const EDITOR_THEME_KEY = 'HB_editor_theme';
|
||||
const EDITOR_SETTINGS_KEY = 'HB_edit_settings';
|
||||
@@ -167,6 +168,7 @@ const Editor = forwardRef(
|
||||
const handleInject = (injectText)=>{
|
||||
codeEditor.current?.injectText(injectText);
|
||||
};
|
||||
const assetUpload = useAssetUpload({ editId: brew.editId, containerRef: editor, inject: handleInject, active: view === 'text' }); // [fork] ADR-0004
|
||||
|
||||
const handleViewChange = (newView)=>{
|
||||
setMoveArrows(newView === 'text');
|
||||
@@ -389,6 +391,7 @@ const Editor = forwardRef(
|
||||
themeBundle={themeBundle}
|
||||
cursorPos={codeEditor.current?.getCursorPosition() || {}}
|
||||
updateBrew={updateBrew}
|
||||
assetUpload={assetUpload}
|
||||
/>
|
||||
|
||||
{renderEditor()}
|
||||
|
||||
@@ -8,6 +8,7 @@ import cx from 'classnames';
|
||||
|
||||
import { loadHistory } from '../../utils/versionHistory.js';
|
||||
import { brewSnippetsToJSON } from '@shared/helpers.js';
|
||||
import AssetUploadButton from '../../../fork/assets/AssetUploadButton.jsx'; // [fork] ADR-0004
|
||||
|
||||
/*eslint-disable camelcase*/
|
||||
import Legacy5ePHB from '@themes/Legacy/5ePHB/snippets.js';
|
||||
@@ -46,7 +47,8 @@ const SnippetBar = ({
|
||||
formatCode = ()=>{},
|
||||
cursorPos = {},
|
||||
themeBundle = [],
|
||||
updateBrew = ()=>{}
|
||||
updateBrew = ()=>{},
|
||||
assetUpload = null // [fork] ADR-0004
|
||||
})=>{
|
||||
const [snippets, setSnippets] = useState([]);
|
||||
const [historyExists, setHistoryExists] = useState(false);
|
||||
@@ -216,6 +218,7 @@ const SnippetBar = ({
|
||||
onClick={formatCode} >
|
||||
<i className='fas fa-wand-magic-sparkles' />
|
||||
</button>
|
||||
{view === 'text' && <AssetUploadButton assetUpload={assetUpload} />}
|
||||
</div></>}
|
||||
|
||||
<div className='tabs'>
|
||||
|
||||
@@ -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,8 +1,9 @@
|
||||
import './error-navitem.less';
|
||||
import React from 'react';
|
||||
import Nav from './nav.jsx';
|
||||
import GitErrorNavItem from '../../fork/git/GitErrorNavItem.jsx'; // [fork] ADR-0003
|
||||
|
||||
const ErrorNavItem = ({ error = '', clearError })=>{
|
||||
const ErrorNavItem = ({ error = '', clearError, brew })=>{
|
||||
const response = error.response;
|
||||
const errorCode = error.code;
|
||||
const status = response?.status;
|
||||
@@ -17,6 +18,8 @@ const ErrorNavItem = ({ error = '', clearError })=>{
|
||||
console.log(errMsg);
|
||||
} catch {}
|
||||
|
||||
if(typeof HBErrorCode === 'string' && /^G\d\d$/.test(HBErrorCode)) return <GitErrorNavItem error={error} clearError={clearError} brew={brew} />; // [fork] ADR-0003, vor der 409-Behandlung
|
||||
|
||||
if(status === 409) {
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Oops!
|
||||
|
||||
@@ -2,6 +2,7 @@ import React from 'react';
|
||||
import moment from 'moment';
|
||||
import UIPage from '../basePages/uiPage/uiPage.jsx';
|
||||
import NaturalCritIcon from '@components/svg/naturalcrit-d20.svg.jsx';
|
||||
import GitConnectionsPanel from '../../../fork/git/GitConnectionsPanel.jsx'; // [fork] ADR-0003
|
||||
|
||||
let SAVEKEY = '';
|
||||
|
||||
@@ -68,6 +69,7 @@ const AccountPage = (props)=>{
|
||||
{renderSaveLocationButton('Homebrewery', 'HOMEBREWERY')}
|
||||
{renderSaveLocationButton('Google Drive', 'GOOGLE-DRIVE', accountDetails.googleId)}
|
||||
</div>
|
||||
{accountDetails.username && <GitConnectionsPanel />}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -23,6 +23,8 @@ import VaultNavItem from '@navbar/vault.navitem.jsx';
|
||||
import PrintNavItem from '@navbar/print.navitem.jsx';
|
||||
import ShareNavItem from '@navbar/share.navitem.jsx';
|
||||
import RecentNavItems from '@navbar/recent.navitem.jsx';
|
||||
import GitNavItem from '../../../../fork/git/GitNavItem.jsx'; // [fork] ADR-0003
|
||||
import { SAVE_EVENT as GIT_SAVE_EVENT } from '../../../../fork/git/gitApi.js';
|
||||
const { both: RecentNavItem } = RecentNavItems;
|
||||
import googleDriveIcon from '../../../googleDrive.svg';
|
||||
|
||||
@@ -34,6 +36,7 @@ const METAKEY = 'HB_newPage_meta';
|
||||
const SAVEKEY_PREFIX = 'HB_editor_defaultSave_';
|
||||
|
||||
const SAVE_TIMEOUT = 10000; //Autosave 10 seconds after last change
|
||||
const GIT_SAVE_TIMEOUT = 60000; // [fork] ADR-0003 F6: Autosave für Git-verknüpfte Brews 60 s (ein Commit pro Save)
|
||||
const UNSAVED_WARNING_TIMEOUT = 900000; //Warn user afer 15 minutes of unsaved changes
|
||||
const UNSAVED_WARNING_POPUP_TIMEOUT = 4000; //Show the warning for 4 seconds
|
||||
|
||||
@@ -53,6 +56,7 @@ const EditorPage = (props)=>{
|
||||
const [currentBrew, setCurrentBrew] = useState(brew);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [lastSavedTime, setLastSavedTime] = useState(new Date());
|
||||
const [gitLinked, setGitLinked] = useState(false); // [fork]
|
||||
const [autoSaveEnabled, setAutoSaveEnabled] = useState(!sandbox);
|
||||
const [warnUnsavedChanges, setWarnUnsavedChanges] = useState(true);
|
||||
const [unsavedChanges, setUnsavedChanges] = useState(false);
|
||||
@@ -94,12 +98,15 @@ const EditorPage = (props)=>{
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handleControlKeys);
|
||||
const handleGitSave = ()=>trySave(true, true, saveGoogle); // [fork] ADR-0003: "Meine Version behalten"
|
||||
document.addEventListener(GIT_SAVE_EVENT, handleGitSave);
|
||||
window.onbeforeunload = ()=>{
|
||||
if(unsavedChangesRef.current)
|
||||
return 'You have unsaved changes!';
|
||||
};
|
||||
return ()=>{
|
||||
document.removeEventListener('keydown', handleControlKeys);
|
||||
document.removeEventListener(GIT_SAVE_EVENT, handleGitSave);
|
||||
window.onbeforeunload = null;
|
||||
};
|
||||
}, []);
|
||||
@@ -207,7 +214,8 @@ const EditorPage = (props)=>{
|
||||
clearTimeout(saveTimeout.current);
|
||||
if(isSaving) return;
|
||||
if(!forceSave && !hasChanges) return;
|
||||
const newTimeout = forceSave ? 0 : SAVE_TIMEOUT;
|
||||
const autoSaveTimeout = gitLinked ? GIT_SAVE_TIMEOUT : SAVE_TIMEOUT; // [fork] ADR-0003 F6
|
||||
const newTimeout = forceSave ? 0 : autoSaveTimeout;
|
||||
|
||||
saveTimeout.current = setTimeout(async ()=>{
|
||||
setIsSaving(true);
|
||||
@@ -372,11 +380,12 @@ const EditorPage = (props)=>{
|
||||
<Nav.section>
|
||||
{(pageName == 'editPage') && renderGoogleDriveIcon()}
|
||||
{error
|
||||
? <ErrorNavItem error={error} clearError={clearError} />
|
||||
? <ErrorNavItem error={error} clearError={clearError} brew={currentBrew} />
|
||||
: <Nav.dropdown className='save-menu'>
|
||||
{renderSaveButton()}
|
||||
{(pageName == 'editPage') && renderAutoSaveButton()}
|
||||
</Nav.dropdown>}
|
||||
{(pageName == 'editPage') && <GitNavItem brew={currentBrew} lastSavedTime={lastSavedTime} onLinkedChange={setGitLinked} />}
|
||||
<NewBrewItem />
|
||||
<PrintNavItem />
|
||||
<HelpNavItem />
|
||||
|
||||
@@ -8,6 +8,7 @@ import { DEFAULT_BREW_LOAD } from '../../../../server/brewDefaults.js';
|
||||
|
||||
// Page specific imports
|
||||
import { gzipSync, strToU8 } from 'fflate';
|
||||
import { consumeGitOverwrite } from '../../../fork/git/gitApi.js'; // [fork] ADR-0003
|
||||
import { updateHistory, versionHistoryGarbageCollection } from '../../utils/versionHistory.js';
|
||||
|
||||
const EditPage = (props)=>{
|
||||
@@ -22,10 +23,11 @@ const EditPage = (props)=>{
|
||||
|
||||
const compressedBrew = gzipSync(strToU8(JSON.stringify(brew)));
|
||||
const transfer = saveToGoogle === _.isNil(brew.googleId);
|
||||
const params = transfer ? `?${saveToGoogle ? 'saveToGoogle' : 'removeFromGoogle'}=true` : '';
|
||||
const gitOverwrite = consumeGitOverwrite(); // [fork] ADR-0003: nur nach "Meine Version behalten"
|
||||
const params = [transfer && `${saveToGoogle ? 'saveToGoogle' : 'removeFromGoogle'}=true`, gitOverwrite && `gitOverwrite=${encodeURIComponent(gitOverwrite)}`].filter(Boolean).join('&');
|
||||
|
||||
const res = await request
|
||||
.put(`/api/update/${brew.editId}${params}`)
|
||||
.put(`/api/update/${brew.editId}${params ? `?${params}` : ''}`)
|
||||
.set('Content-Encoding', 'gzip')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(compressedBrew);
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
# Wird von `docker compose` automatisch zusätzlich zu docker-compose.yml (Upstream) geladen.
|
||||
# Enthält alle Fork-Erweiterungen, damit docker-compose.yml unverändert bleibt.
|
||||
services:
|
||||
mongodb:
|
||||
image: mongo:${MONGO_TAG:-8}
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "mongosh --quiet --eval \"db.adminCommand('ping')\" || mongo --quiet --eval \"db.adminCommand('ping')\""]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
homebrewery:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/Dockerfile
|
||||
depends_on:
|
||||
mongodb:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
# Storage-Backend (ADR 0002): mongo (Standard) oder postgres. Postgres: Compose-Profil `postgres`, Service `homebrewery-pg`.
|
||||
HB_DB_DRIVER: ${HB_DB_DRIVER:-mongo}
|
||||
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:-}
|
||||
HB_NATURALCRIT_RENAME: ${HB_NATURALCRIT_RENAME:-}
|
||||
# Git-Backend (ADR 0003, docs/git/). Ohne HB_GIT_TOKEN_KEY ist es deaktiviert.
|
||||
HB_GIT_TOKEN_KEY: ${HB_GIT_TOKEN_KEY:-}
|
||||
HB_GIT_TOKEN_KEYS_OLD: ${HB_GIT_TOKEN_KEYS_OLD:-}
|
||||
HB_GIT_ALLOWED_HOSTS: ${HB_GIT_ALLOWED_HOSTS:-}
|
||||
HB_GIT_ALLOW_PRIVATE: ${HB_GIT_ALLOW_PRIVATE:-}
|
||||
HB_GIT_ALLOW_HTTP: ${HB_GIT_ALLOW_HTTP:-}
|
||||
HB_GIT_TIMEOUT_MS: ${HB_GIT_TIMEOUT_MS:-}
|
||||
HB_GIT_OPEN_TIMEOUT_MS: ${HB_GIT_OPEN_TIMEOUT_MS:-}
|
||||
HB_GIT_MAX_FILE_BYTES: ${HB_GIT_MAX_FILE_BYTES:-}
|
||||
HB_GIT_MAX_CONCURRENCY: ${HB_GIT_MAX_CONCURRENCY:-}
|
||||
HB_GIT_COMMITTER_NAME: ${HB_GIT_COMMITTER_NAME:-}
|
||||
HB_GIT_COMMITTER_EMAIL: ${HB_GIT_COMMITTER_EMAIL:-}
|
||||
# Bild-Upload (ADR 0004, nur mit aktivem Git-Backend)
|
||||
HB_ASSETS_ENABLED: ${HB_ASSETS_ENABLED:-}
|
||||
HB_ASSET_MAX_BYTES: ${HB_ASSET_MAX_BYTES:-}
|
||||
HB_ASSET_MAX_BYTES_PER_BREW: ${HB_ASSET_MAX_BYTES_PER_BREW:-}
|
||||
HB_ASSET_TYPES: ${HB_ASSET_TYPES:-}
|
||||
ports: !override
|
||||
- "${APP_PORT:-8000}:8000"
|
||||
|
||||
# --- Profil: postgres (ADR 0002) ---
|
||||
# Startet die App mit PostgreSQL 18 ohne Mongo:
|
||||
# docker compose --profile postgres up --build homebrewery-pg
|
||||
# (Die Service-Namen müssen angegeben werden, sonst startet Compose zusätzlich `homebrewery` und `mongodb`.)
|
||||
homebrewery-pg:
|
||||
profiles: ["postgres"]
|
||||
extends:
|
||||
service: homebrewery
|
||||
image: homebrewery
|
||||
depends_on: !override
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
HB_DB_DRIVER: postgres
|
||||
HB_POSTGRES_URL: ${HB_POSTGRES_URL:-postgres://${POSTGRES_USER:-homebrewery}:${POSTGRES_PASSWORD:-homebrewery-dev}@postgres:5432/${POSTGRES_DB:-homebrewery}}
|
||||
HB_POSTGRES_POOL_MAX: ${HB_POSTGRES_POOL_MAX:-10}
|
||||
postgres:
|
||||
profiles: ["postgres"]
|
||||
image: postgres:18
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-homebrewery}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-homebrewery}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-homebrewery-dev}
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql
|
||||
ports:
|
||||
- "127.0.0.1:${POSTGRES_PORT:-5432}:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
# --- Profil: keycloak (Test-IdP, Realm "homebrewery") ---
|
||||
keycloak:
|
||||
profiles: ["keycloak"]
|
||||
image: quay.io/keycloak/keycloak:${KEYCLOAK_TAG:-26.4}
|
||||
command: ["start-dev", "--import-realm"]
|
||||
environment:
|
||||
KC_BOOTSTRAP_ADMIN_USERNAME: ${KEYCLOAK_ADMIN:-admin}
|
||||
KC_BOOTSTRAP_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD:-admin-dev}
|
||||
KC_HTTP_PORT: ${KEYCLOAK_PORT:-8080}
|
||||
# Einheitlicher Issuer für Browser (Host) und App-Container: http://keycloak.localhost:<KEYCLOAK_PORT>
|
||||
KC_HOSTNAME: http://keycloak.localhost:${KEYCLOAK_PORT:-8080}
|
||||
volumes:
|
||||
- ./docker/keycloak/realm-homebrewery.json:/opt/keycloak/data/import/realm-homebrewery.json:ro
|
||||
ports:
|
||||
- "127.0.0.1:${KEYCLOAK_PORT:-8080}:${KEYCLOAK_PORT:-8080}"
|
||||
networks:
|
||||
default:
|
||||
aliases: [keycloak.localhost]
|
||||
|
||||
# --- Profil: authentik (Test-IdP, per Blueprint vorkonfiguriert) ---
|
||||
authentik-db:
|
||||
profiles: ["authentik"]
|
||||
image: postgres:18
|
||||
environment:
|
||||
POSTGRES_DB: authentik
|
||||
POSTGRES_USER: authentik
|
||||
POSTGRES_PASSWORD: ${AUTHENTIK_DB_PASSWORD:-authentik-dev}
|
||||
volumes:
|
||||
- authentikdb:/var/lib/postgresql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U authentik -d authentik"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
authentik:
|
||||
profiles: ["authentik"]
|
||||
image: ghcr.io/goauthentik/server:${AUTHENTIK_TAG:-2026.2}
|
||||
command: server
|
||||
environment: &authentik-env
|
||||
AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY:-dev-only-insecure-secret-key-change-me}
|
||||
AUTHENTIK_POSTGRESQL__HOST: authentik-db
|
||||
AUTHENTIK_POSTGRESQL__USER: authentik
|
||||
AUTHENTIK_POSTGRESQL__NAME: authentik
|
||||
AUTHENTIK_POSTGRESQL__PASSWORD: ${AUTHENTIK_DB_PASSWORD:-authentik-dev}
|
||||
AUTHENTIK_BOOTSTRAP_PASSWORD: ${AUTHENTIK_BOOTSTRAP_PASSWORD:-admin-dev}
|
||||
AUTHENTIK_BOOTSTRAP_EMAIL: admin@example.test
|
||||
AUTHENTIK_ERROR_REPORTING__ENABLED: "false"
|
||||
AUTHENTIK_LISTEN__HTTP: 0.0.0.0:${AUTHENTIK_PORT:-9000}
|
||||
volumes:
|
||||
- ./docker/authentik/blueprints:/blueprints/custom:ro
|
||||
ports:
|
||||
- "127.0.0.1:${AUTHENTIK_PORT:-9000}:${AUTHENTIK_PORT:-9000}"
|
||||
# Einheitlicher Issuer: http://authentik.localhost:9000 (Browser und App-Container)
|
||||
networks:
|
||||
default:
|
||||
aliases: [authentik.localhost]
|
||||
depends_on:
|
||||
authentik-db:
|
||||
condition: service_healthy
|
||||
authentik-worker:
|
||||
profiles: ["authentik"]
|
||||
image: ghcr.io/goauthentik/server:${AUTHENTIK_TAG:-2026.2}
|
||||
command: worker
|
||||
environment: *authentik-env
|
||||
volumes:
|
||||
- ./docker/authentik/blueprints:/blueprints/custom:ro
|
||||
depends_on:
|
||||
authentik-db:
|
||||
condition: service_healthy
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
authentikdb:
|
||||
@@ -0,0 +1,11 @@
|
||||
# Eigenes Dockerfile für den Fork (Upstream-Dockerfile erwartet eine nicht eingecheckte config/docker.json).
|
||||
FROM node:26.4.0-alpine
|
||||
RUN apk --no-cache add git
|
||||
ENV NODE_ENV=docker
|
||||
WORKDIR /usr/src/app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --ignore-scripts
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
EXPOSE 8000
|
||||
CMD [ "npm", "start" ]
|
||||
@@ -0,0 +1,10 @@
|
||||
node_modules
|
||||
npm-debug.log
|
||||
.git
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.npm-cache
|
||||
.runtime-tmp
|
||||
tests
|
||||
docker-compose*.yml
|
||||
@@ -0,0 +1,53 @@
|
||||
version: 1
|
||||
metadata:
|
||||
name: Homebrewery Dev
|
||||
entries:
|
||||
- model: authentik_blueprints.metaapplyblueprint
|
||||
attrs:
|
||||
identifiers:
|
||||
name: Default - Provider authorization flow (implicit consent)
|
||||
required: true
|
||||
- model: authentik_blueprints.metaapplyblueprint
|
||||
attrs:
|
||||
identifiers:
|
||||
name: Default - Provider invalidation flow
|
||||
required: true
|
||||
- model: authentik_blueprints.metaapplyblueprint
|
||||
attrs:
|
||||
identifiers:
|
||||
name: System - OAuth2 Provider - Scopes
|
||||
required: true
|
||||
- model: authentik_core.user
|
||||
identifiers:
|
||||
username: testuser
|
||||
attrs:
|
||||
name: Test User
|
||||
email: testuser@example.test
|
||||
password: testuser-dev
|
||||
is_active: true
|
||||
- model: authentik_providers_oauth2.oauth2provider
|
||||
id: provider
|
||||
identifiers:
|
||||
name: homebrewery
|
||||
attrs:
|
||||
authorization_flow: !Find [authentik_flows.flow, [slug, default-provider-authorization-implicit-consent]]
|
||||
invalidation_flow: !Find [authentik_flows.flow, [slug, default-provider-invalidation-flow]]
|
||||
client_type: confidential
|
||||
client_id: homebrewery
|
||||
client_secret: dev-only-client-secret
|
||||
redirect_uris:
|
||||
- matching_mode: regex
|
||||
url: http://localhost:8000/.*
|
||||
- matching_mode: regex
|
||||
url: http://homebrewery.local.naturalcrit.com:8000/.*
|
||||
signing_key: !Find [authentik_crypto.certificatekeypair, [name, authentik Self-signed Certificate]]
|
||||
property_mappings:
|
||||
- !Find [authentik_providers_oauth2.scopemapping, [scope_name, openid]]
|
||||
- !Find [authentik_providers_oauth2.scopemapping, [scope_name, profile]]
|
||||
- !Find [authentik_providers_oauth2.scopemapping, [scope_name, email]]
|
||||
- model: authentik_core.application
|
||||
identifiers:
|
||||
slug: homebrewery
|
||||
attrs:
|
||||
name: Homebrewery
|
||||
provider: !KeyOf provider
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"realm": "homebrewery",
|
||||
"enabled": true,
|
||||
"registrationAllowed": false,
|
||||
"loginWithEmailAllowed": true,
|
||||
"sslRequired": "none",
|
||||
"clients": [
|
||||
{
|
||||
"clientId": "homebrewery",
|
||||
"name": "Homebrewery (Dev)",
|
||||
"enabled": true,
|
||||
"protocol": "openid-connect",
|
||||
"publicClient": false,
|
||||
"secret": "dev-only-client-secret",
|
||||
"standardFlowEnabled": true,
|
||||
"directAccessGrantsEnabled": false,
|
||||
"redirectUris": ["http://localhost:8000/*", "http://homebrewery.local.naturalcrit.com:8000/*"],
|
||||
"webOrigins": ["+"],
|
||||
"attributes": { "pkce.code.challenge.method": "S256", "post.logout.redirect.uris": "+" }
|
||||
}
|
||||
],
|
||||
"users": [
|
||||
{
|
||||
"username": "testuser",
|
||||
"email": "testuser@example.test",
|
||||
"emailVerified": true,
|
||||
"firstName": "Test",
|
||||
"lastName": "User",
|
||||
"enabled": true,
|
||||
"credentials": [{ "type": "password", "value": "testuser-dev", "temporary": false }]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
# ADR 0001: Authentifizierung über generisches OIDC
|
||||
|
||||
- Status: Angenommen (Entscheidungen Florian 2026-11-25, siehe Ende)
|
||||
- Datum: 2026-11-23, überarbeitet 2026-11-25 (Review PR #12)
|
||||
- Umsetzung: M1, Issue #6; Abschnitt 7 (Rename-Sperre für naturalcrit): #21
|
||||
- Basis: Analyse auf Upstream `73df298c`, gegen `6d219487` geprüft (seitdem nur `splitPane.jsx` und `listPage.jsx` geändert, beide hier nicht betroffen)
|
||||
|
||||
## Kontext
|
||||
|
||||
### So funktioniert Login im Upstream-Code
|
||||
|
||||
Homebrewery hat **keinen eigenen Login und keine Benutzertabelle**. Konten
|
||||
liegen in der separaten Anwendung naturalcrit.com (eigenes Repo). Dort finden
|
||||
Benutzername/Passwort- und Google-Login statt. Homebrewery sieht davon nur das
|
||||
Ergebnis:
|
||||
|
||||
- naturalcrit.com setzt das Cookie `nc_session` für die Domain `.naturalcrit.com`.
|
||||
Es enthält ein mit `jwt-simple` (HS256) und dem gemeinsamen Schlüssel `secret`
|
||||
signiertes JWT mit `{ username, googleId?, googleAccessToken?, googleRefreshToken?, issued }`.
|
||||
- `server/app.js` („Account Middleware“) dekodiert das Cookie bei jedem Request
|
||||
nach `req.account`. `jwt-simple.decode` prüft **kein** `exp`, und eine
|
||||
Sitzung läuft serverseitig nie ab.
|
||||
- Alle Rechte hängen am String `req.account.username`. Brews speichern in
|
||||
`authors[]` und `invitedAuthors[]` reine Benutzernamen (`server/homebrew.api.js`
|
||||
`getBrew`, `deleteBrew`, `server/page-routes.js` `/user/:username`, `/account`,
|
||||
`/share/:id`, `server/app.js` `/api/user/rename`).
|
||||
- Lokale Umgebungen (`NODE_ENV` in `local_environments`) bieten
|
||||
`POST /local/login`. Damit kann sich jeder **ohne Passwort** als beliebiger
|
||||
Benutzer anmelden. Der Client setzt das Cookie dann selbst per `document.cookie`
|
||||
(`client/homebrew/navbar/account.navitem.jsx`).
|
||||
- Logout löscht das Cookie clientseitig per `document.cookie`, es kann also nicht
|
||||
`httpOnly` sein.
|
||||
- Login-Links zeigen fest auf `https://www.naturalcrit.com/login`
|
||||
(`account.navitem.jsx`, `client/homebrew/pages/errorPage/errors/errorIndex.js`).
|
||||
- Google Drive als Speicherort braucht die Google-Tokens aus `nc_session`
|
||||
(`server/googleActions.js` `authCheck`).
|
||||
|
||||
### Vorgaben (Florian, #1)
|
||||
|
||||
OIDC generisch, getestet mit Authentik und Keycloak. Die bisherigen Logins
|
||||
bleiben, sind aber per Konfiguration abschaltbar. Änderungen gekapselt, Fork
|
||||
bleibt upstream-synchron.
|
||||
|
||||
## Entscheidung
|
||||
|
||||
### 1. Modul und Bibliothek
|
||||
|
||||
Neues Modul `server/fork/auth/` mit der Bibliothek **`openid-client` v6**
|
||||
(panva, OpenID-zertifiziert, kann Discovery, PKCE, `state`, `nonce` und
|
||||
Token-Validierung). Das Modul exportiert `createAuthRouter(config)` und
|
||||
`accountMiddleware(config)`.
|
||||
|
||||
Dateien:
|
||||
|
||||
| Datei | Inhalt |
|
||||
| --- | --- |
|
||||
| `server/fork/auth/index.js` | Router + Middleware zusammenstecken, Konfiguration validieren |
|
||||
| `server/fork/auth/config.js` | Konfiguration lesen/prüfen (siehe Tabelle unten) |
|
||||
| `server/fork/auth/oidc.js` | Discovery (gecacht), Login-URL, Callback-Verarbeitung |
|
||||
| `server/fork/auth/session.js` | Session-Cookie ausstellen, prüfen, löschen |
|
||||
| `server/fork/auth/accountMapping.js` | (iss, sub) auf Benutzer abbilden, siehe Abschnitt 4 |
|
||||
| `server/fork/auth/*.spec.js` | Unit-Tests mit gemocktem IdP |
|
||||
| `client/fork/auth/loginUrl.js` | `getLoginUrl(redirect)`, `logout()` für den Client |
|
||||
|
||||
### 2. OIDC-Flow (Authorization Code + PKCE)
|
||||
|
||||
- **Discovery:** `HB_OIDC_ISSUER` ist die Issuer-URL. Die Metadaten werden
|
||||
beim ersten Login über `/.well-known/openid-configuration` geladen und im
|
||||
Prozess gecacht (Neuversuch bei Fehler, kein Start-Abbruch, wenn der IdP
|
||||
beim Booten nicht erreichbar ist).
|
||||
- **Client:** vertraulicher Client (`client_secret_basic`) mit
|
||||
`HB_OIDC_CLIENT_ID` / `HB_OIDC_CLIENT_SECRET`. Redirect-URI:
|
||||
`${HB_PUBLIC_URL}/auth/oidc/callback`.
|
||||
- **`GET /auth/oidc/login?redirect=<pfad>`**
|
||||
1. `code_verifier`, `state` und `nonce` erzeugen (je 32 Byte Zufall,
|
||||
base64url), PKCE-Methode `S256`.
|
||||
2. Transaktion `{ codeVerifier, state, nonce, redirect, createdAt }` in das
|
||||
Cookie `hb_oidc_tx` schreiben: signiert und verschlüsselt (AES-256-GCM
|
||||
mit Schlüssel aus `HB_SESSION_SECRET`, HKDF-Kontext `oidc-tx`),
|
||||
`httpOnly`, `Secure` (außer lokal), `SameSite=Lax`, `Path=/auth/oidc`,
|
||||
`Max-Age=600`.
|
||||
3. Redirect zum `authorization_endpoint` mit
|
||||
`scope=${HB_OIDC_SCOPES}` (Standard `openid profile email`).
|
||||
- **`GET /auth/oidc/callback`**
|
||||
1. `hb_oidc_tx` lesen und sofort löschen. Fehlt die Transaktion, ist sie
|
||||
abgelaufen oder passt `state` nicht, folgt 400 mit Fehlerseite (Link
|
||||
„Erneut anmelden“).
|
||||
2. Code tauschen (`authorizationCodeGrant` mit `pkceCodeVerifier`,
|
||||
`expectedState`, `expectedNonce`). `openid-client` prüft `iss`, `aud`,
|
||||
`exp`, `iat`, `nonce` und die Signatur über die JWKS.
|
||||
3. Claims aus dem ID-Token, bei fehlender `email` zusätzlich vom
|
||||
`userinfo_endpoint`.
|
||||
4. Konto zuordnen (Abschnitt 4), Session ausstellen (Abschnitt 3).
|
||||
5. Redirect auf `redirect`, aber **nur**, wenn er ein relativer Pfad ist
|
||||
(`/` am Anfang, kein `//`, kein `\`). Sonst Redirect auf `/`.
|
||||
- **`GET /auth/logout`** löscht das Session-Cookie. Ist
|
||||
`HB_OIDC_END_SESSION=true` gesetzt und hat der IdP einen
|
||||
`end_session_endpoint`, folgt ein Redirect dorthin mit `client_id` und
|
||||
`post_logout_redirect_uri=${HB_PUBLIC_URL}/`. Keycloak ab 18 und Authentik
|
||||
akzeptieren das ohne `id_token_hint`, deshalb speichern wir kein ID-Token.
|
||||
- IdP-Access- und Refresh-Tokens werden **nicht** gespeichert. Die App braucht
|
||||
sie nach dem Login nicht.
|
||||
|
||||
### 3. Session-Handling
|
||||
|
||||
- Eigenes Cookie **`hb_session`**: JWT HS256, signiert mit `HB_SESSION_SECRET`
|
||||
(mindestens 32 Byte, getrennt vom Upstream-`secret`). Inhalt:
|
||||
`{ v: 1, uid, username, iss, sub, iat, exp }`.
|
||||
Flags: `httpOnly`, `Secure` (außer lokal), `SameSite=Lax`, `Path=/`,
|
||||
`Max-Age = HB_SESSION_TTL` (Standard 7 Tage).
|
||||
- **Feste Laufzeit, keine gleitende Verlängerung.** Nach Ablauf meldet sich
|
||||
der Nutzer erneut an. Läuft die IdP-Sitzung noch, geht das ohne Eingabe.
|
||||
So greift eine Sperre am IdP spätestens nach `HB_SESSION_TTL`.
|
||||
- Für `hb_session` verwenden wir `jsonwebtoken` statt `jwt-simple`, weil es
|
||||
`exp` prüft und den Algorithmus fest auf `HS256` setzen kann
|
||||
(`algorithms: ['HS256']`).
|
||||
- **Einhängen ohne Upstream-Umbau:** `accountMiddleware` läuft direkt **nach**
|
||||
der Upstream-Account-Middleware in `server/app.js` und setzt `req.account`
|
||||
neu:
|
||||
1. Gültiges `hb_session` vorhanden: `req.account = { username, uid, provider: 'oidc' }`.
|
||||
2. Sonst, wenn der Provider `naturalcrit` aktiviert ist: Wert der
|
||||
Upstream-Middleware (aus `nc_session`) behalten und `provider: 'naturalcrit'` ergänzen.
|
||||
3. Sonst: `req.account = undefined`.
|
||||
|
||||
Damit bleibt der Vertrag `req.account.username` für den gesamten
|
||||
Upstream-Code unverändert.
|
||||
- CSRF: Schreibende `/api`-Routen verlangen schon im Upstream den Header
|
||||
`Homebrewery-Version` (`server/middleware/check-client-version.js`). Ohne
|
||||
CORS-Freigabe kann ihn keine fremde Seite setzen. Mit `SameSite=Lax` reicht
|
||||
das. Die Fork-Routen unter `/api/git/*` (ADR 0003/0004) nutzen dieselbe
|
||||
Middleware.
|
||||
|
||||
### 4. Konto-Zuordnung (`sub` / E-Mail)
|
||||
|
||||
Neue Entität **User** (Repository aus ADR 0002, Tabelle bzw. Collection `users`):
|
||||
|
||||
| Feld | Typ | Regel |
|
||||
| --- | --- | --- |
|
||||
| `id` | UUID | intern |
|
||||
| `username` | string | eindeutig, unveränderlich nach Anlage, `^[A-Za-z0-9._-]{2,40}$` |
|
||||
| `oidcIssuer` | string? | zusammen mit `oidcSub` eindeutig |
|
||||
| `oidcSub` | string? | |
|
||||
| `email` | string? | klein geschrieben gespeichert, nicht eindeutig |
|
||||
| `emailVerified` | bool | |
|
||||
| `displayName` | string? | für Commit-Autor (ADR 0003) |
|
||||
| `createdAt`, `lastLoginAt` | Datum | |
|
||||
|
||||
Ablauf im Callback:
|
||||
|
||||
1. **Primärschlüssel ist (`iss`, `sub`).** Gibt es den Benutzer, wird er
|
||||
angemeldet. `email`, `emailVerified`, `displayName` und `lastLoginAt` werden
|
||||
aktualisiert, `username` **nie**.
|
||||
2. **Verknüpfung per E-Mail** nur bei `HB_OIDC_LINK_BY_EMAIL=true` (Standard
|
||||
`false`), **nur** bei `email_verified === true` und **nur** mit einem
|
||||
vorab angelegten Benutzer, der noch keine OIDC-Bindung hat. Solche
|
||||
Datensätze legt der Admin über `POST /admin/users` an
|
||||
(`{ username, email }`, Basic Auth wie die übrigen Admin-Routen), um
|
||||
bestehende Benutzernamen aus `authors[]` an eine Person zu binden. Gibt es
|
||||
mehrere Treffer, wird nicht verknüpft und ein Fehler geloggt.
|
||||
(`POST /admin/users` ist noch nicht umgesetzt, siehe F3.)
|
||||
3. **Neuanlage:** Der Benutzername kommt aus dem Claim `HB_OIDC_USERNAME_CLAIM`
|
||||
(Standard `preferred_username`, Fallback der Teil der E-Mail vor dem `@`,
|
||||
dann `user`). Er wird auf das Muster oben gekürzt bzw. bereinigt. Ist er
|
||||
schon vergeben, **als Benutzer oder als Autor in irgendeinem Brew**
|
||||
(`brews.existsAuthor(name)`), wird `-2`, `-3`, … angehängt. Ohne die
|
||||
Autoren-Prüfung könnte ein neues Konto fremde Brews übernehmen, die unter
|
||||
einem naturalcrit-Benutzernamen gespeichert sind.
|
||||
4. Benutzernamen dürfen keine E-Mail-Adresse sein. Der Vault blendet
|
||||
E-Mail-artige Autoren aus (`server/vault.api.js`).
|
||||
5. **`PUT /api/user/rename` ist für OIDC-Sessions gesperrt.** Die
|
||||
Upstream-Route prüft nur `req.account.username === newUsername`, aber
|
||||
nicht, ob der Aufrufer den alten Namen `username` besitzt. Sie ist für
|
||||
naturalcrit gedacht: Dort ändert naturalcrit.com den Namen im JWT, und
|
||||
der Client zieht danach `authors[]` nach. Ein OIDC-Benutzername ist
|
||||
unveränderlich (Punkt 1), ein Aufruf aus einer OIDC-Session könnte also
|
||||
nur fremde Brews auf das eigene Konto ziehen. Der Fork-Router registriert
|
||||
deshalb vor der Upstream-Route `PUT /api/user/rename` und antwortet bei
|
||||
`req.account.provider === 'oidc'` mit `403` (`HBErrorCode: 'A01'`). Bei
|
||||
naturalcrit-Sessions ruft er `next()` auf, die Upstream-Route bleibt
|
||||
unverändert. Fork-Daten, die einem Konto gehören (Git-Verbindungen,
|
||||
ADR 0003), hängen an `users.id`, nicht am Namen, und sind von einem
|
||||
Rename nie betroffen.
|
||||
|
||||
### 5. Alt-Logins abschalten
|
||||
|
||||
`HB_AUTH_PROVIDERS`, kommagetrennt, mögliche Werte `oidc`, `naturalcrit`.
|
||||
|
||||
| Wert | Wirkung |
|
||||
| --- | --- |
|
||||
| `oidc` | Routen `/auth/oidc/*` aktiv, Login-Link zeigt auf `/auth/oidc/login` |
|
||||
| `naturalcrit` | `nc_session` wird akzeptiert (Upstream-Verhalten: naturalcrit-SSO mit Benutzername/Passwort und Google, lokal `POST /local/login`) |
|
||||
|
||||
- **Standard ohne Angabe:** `naturalcrit`, also exakt Upstream-Verhalten.
|
||||
Ist `HB_OIDC_ISSUER` gesetzt und `HB_AUTH_PROVIDERS` leer, gilt
|
||||
`oidc,naturalcrit`.
|
||||
- Ohne `naturalcrit` ignoriert `accountMiddleware` `nc_session`, und der
|
||||
Fork-Router beantwortet `POST /local/login` vor der Upstream-Route mit 404.
|
||||
Google Drive als Speicherort ist dann nicht verfügbar. Die Upstream-UI
|
||||
zeigt dafür schon heute den Hinweis „You must be signed in to a Google
|
||||
account“.
|
||||
- Mit beiden Providern zeigt der Login-Link eine kleine Auswahlseite
|
||||
`GET /auth/login` (Fork-Seite mit zwei Buttons).
|
||||
- Die Startprüfung bricht ab, wenn `oidc` aktiv ist, aber `HB_OIDC_ISSUER`,
|
||||
`HB_OIDC_CLIENT_ID`, `HB_OIDC_CLIENT_SECRET`, `HB_PUBLIC_URL` oder
|
||||
`HB_SESSION_SECRET` fehlen.
|
||||
|
||||
### 6. Client
|
||||
|
||||
- `server/app.js` `renderPage` gibt zusätzlich `configuration.auth = { providers, loginUrl, logoutUrl, oidcLabel }`
|
||||
mit. `oidcLabel` kommt aus `HB_OIDC_LABEL`, Standard „Anmelden“.
|
||||
- `client/fork/auth/loginUrl.js`:
|
||||
`getLoginUrl(redirect)` liefert `/auth/oidc/login?redirect=…`, `/auth/login?…`
|
||||
oder den Upstream-Link zu naturalcrit. `logout()` navigiert bei
|
||||
`provider === 'oidc'` zu `/auth/logout`, sonst greift die bisherige
|
||||
Cookie-Löschung.
|
||||
- `account.navitem.jsx` und `errorIndex.js` nutzen diese Helfer statt der
|
||||
festen URL.
|
||||
|
||||
### 7. Umbenennen (`PUT /api/user/rename`)
|
||||
|
||||
Ergänzt mit #21 (Entscheidung F14). Die Upstream-Route schreibt
|
||||
`authors[]` von `username` auf `newUsername` um und prüft dabei nur, ob
|
||||
`newUsername` der eigenen Sitzung gehört. Ob der Aufrufer den **alten** Namen
|
||||
besitzt, prüft sie nicht. Mit einer naturalcrit-Sitzung konnte so jeder
|
||||
angemeldete Benutzer die Brews eines fremden Namens auf sich umschreiben.
|
||||
|
||||
Das `nc_session`-JWT enthält nur `{ username, googleId?, …, issued }`, also
|
||||
keine stabile Konto-ID, und naturalcrit bietet keine Schnittstelle, die eine
|
||||
Umbenennung bestätigt. Einen Nachweis aus der laufenden Sitzung gibt es
|
||||
deshalb nicht. Der Fork sperrt den Endpunkt für naturalcrit standardmäßig und
|
||||
lässt ihn nur mit einem kryptografischen Nachweis für den alten Namen zu.
|
||||
|
||||
Der Fork-Router beantwortet `PUT /api/user/rename` vor der Upstream-Route
|
||||
(`server/fork/auth/rename.js`, `renameGuard`). `server/app.js` ändert sich
|
||||
dafür nicht, der Router ist schon eingehängt (Abschnitt „Betroffene
|
||||
Upstream-Dateien“). Prüfreihenfolge:
|
||||
|
||||
| Fall | Antwort |
|
||||
| --- | --- |
|
||||
| OIDC-Sitzung | 403, `HBErrorCode: A01` (unverändert, unabhängig von `HB_NATURALCRIT_RENAME`) |
|
||||
| ohne Anmeldung (auch `nc_session`, wenn `naturalcrit` abgeschaltet ist) | 403 ohne Code, die Upstream-Route wird nicht erreicht |
|
||||
| naturalcrit, `HB_NATURALCRIT_RENAME=off` (Standard) | 403, `HBErrorCode: A02` |
|
||||
| naturalcrit, `signed`, `username`/`newUsername` fehlen | 400 wie Upstream |
|
||||
| naturalcrit, `signed`, `newUsername` ≠ Sitzungsname oder Nachweis fehlt/ungültig | 403, `HBErrorCode: A03` |
|
||||
| naturalcrit, `signed`, Nachweis gültig | weiter zur Upstream-Route (200) |
|
||||
|
||||
**Nachweis (`signed`):** Der Request-Body enthält zusätzlich `oldSession`,
|
||||
ein `nc_session`-Token des alten Namens. Gültig ist es, wenn es mit dem
|
||||
Upstream-`secret` (Env `SECRET`) per HS256 signiert ist (andere Algorithmen
|
||||
und `none` werden abgelehnt), ein vorhandenes `exp` nicht abgelaufen ist und
|
||||
`username` im Token exakt dem Feld `username` im Body entspricht. Wer ein
|
||||
solches Token vorlegt, hatte eine Sitzung unter dem alten Namen und konnte
|
||||
dessen Brews ohnehin bearbeiten. Die Umbenennung gibt ihm also keine
|
||||
zusätzlichen Rechte. Der Wächter entfernt `oldSession` aus dem Body, bevor
|
||||
die Upstream-Route ihn sieht. Außerhalb lokaler Umgebungen startet die App
|
||||
mit `signed` nicht, solange `SECRET` der Standardwert `secret` ist, weil der
|
||||
Nachweis sonst fälschbar wäre.
|
||||
|
||||
**Einschränkung:** Der Account-Server muss `oldSession` mitschicken. Die
|
||||
Umbenennung auf naturalcrit.com tut das nicht. Wer dort seinen Namen ändert,
|
||||
kann die Brews auf einer Fork-Instanz deshalb nicht selbst umschreiben, auch
|
||||
nicht mit `signed`. Dann bleibt nur ein Eingriff durch den Betreiber in der
|
||||
Datenbank, oder ein naturalcrit-kompatibler Account-Server sendet das alte
|
||||
Token vor dem Austausch des Cookies mit. Bei selbst gehosteten Instanzen erreicht die
|
||||
`nc_session` von naturalcrit.com die App ohnehin nicht (Cookie-Domain
|
||||
`.naturalcrit.com`, siehe „Folgen“).
|
||||
|
||||
### Konfiguration (vollständig)
|
||||
|
||||
| Variable | Pflicht | Standard | Bedeutung |
|
||||
| --- | --- | --- | --- |
|
||||
| `HB_AUTH_PROVIDERS` | nein | siehe oben | `oidc`, `naturalcrit` |
|
||||
| `HB_PUBLIC_URL` | bei `oidc` | – | z. B. `https://brew.example.org`, ohne `/` am Ende |
|
||||
| `HB_OIDC_ISSUER` | bei `oidc` | – | Issuer-URL (Keycloak: `…/realms/<realm>`, Authentik: `…/application/o/<slug>/`) |
|
||||
| `HB_OIDC_CLIENT_ID` | bei `oidc` | – | |
|
||||
| `HB_OIDC_CLIENT_SECRET` | bei `oidc` | – | nur über Umgebung |
|
||||
| `HB_OIDC_SCOPES` | nein | `openid profile email` | |
|
||||
| `HB_OIDC_USERNAME_CLAIM` | nein | `preferred_username` | |
|
||||
| `HB_OIDC_LINK_BY_EMAIL` | nein | `false` | |
|
||||
| `HB_OIDC_END_SESSION` | nein | `false` | RP-initiierter Logout |
|
||||
| `HB_OIDC_LABEL` | nein | `Anmelden` | Button-Text |
|
||||
| `HB_SESSION_SECRET` | bei `oidc` | – | ≥ 32 Byte, nur Umgebung |
|
||||
| `HB_SESSION_TTL` | nein | `7d` | Format wie `jsonwebtoken` `expiresIn` |
|
||||
| `HB_NATURALCRIT_RENAME` | nein | `off` | `off`: `PUT /api/user/rename` für naturalcrit gesperrt; `signed`: nur mit Nachweis `oldSession` (Abschnitt 7) |
|
||||
|
||||
### Tests
|
||||
|
||||
- Unit: `oidc.js` gegen einen In-Process-Mock-IdP (`oidc-provider` von panva
|
||||
als devDependency, startet ohne Container). Fälle: Erfolg, falscher `state`,
|
||||
abgelaufene Transaktion, falscher `nonce`, offener Redirect, unbekannter
|
||||
Benutzer, E-Mail-Verknüpfung an/aus, Namenskollision mit Brew-Autor.
|
||||
- API (supertest): `PUT /api/user/rename` mit OIDC-Session → 403 `A01`
|
||||
(auch mit `signed` und gültigem Nachweis); ohne Anmeldung → 403;
|
||||
naturalcrit mit `off` → 403 `A02` (fremder und eigener alter Name);
|
||||
naturalcrit mit `signed`: eigener Rename mit Nachweis → 200, fremder alter
|
||||
Name ohne bzw. mit falschem Nachweis (eigenes Token, fremder Schlüssel,
|
||||
HS512, `none`, abgelaufen) → 403 `A03`. In allen 403-Fällen wird die
|
||||
Upstream-Route nicht erreicht.
|
||||
- Integration (manuell bzw. CI-Job aus #4): Login gegen Keycloak und
|
||||
Authentik aus dem Compose-Setup (#3) mit je einem dokumentierten
|
||||
Client-Setup in `docs/auth/keycloak.md` und `docs/auth/authentik.md`.
|
||||
|
||||
## Betroffene Upstream-Dateien
|
||||
|
||||
| Datei | Änderung |
|
||||
| --- | --- |
|
||||
| `server/app.js` | Import; `app.use(forkAuth.accountMiddleware(config))` und `app.use(forkAuth.createAuthRouter(config))` direkt nach der Account-Middleware; `configuration.auth` in `renderPage` |
|
||||
| `client/homebrew/navbar/account.navitem.jsx` | Login-Link und Logout über `client/fork/auth/loginUrl.js` |
|
||||
| `client/homebrew/pages/errorPage/errors/errorIndex.js` | `loginUrl` über Helfer statt Konstante |
|
||||
| `package.json` | Abhängigkeiten `openid-client`, `jsonwebtoken`; devDependency `oidc-provider` |
|
||||
|
||||
`server/token.js`, `server/googleActions.js` und das Upstream-JWT-Format
|
||||
bleiben unverändert. Die Rename-Sperre (Abschnitt 7) braucht keinen weiteren
|
||||
Eingriff, sie hängt im schon eingehängten Fork-Router.
|
||||
|
||||
## Alternativen
|
||||
|
||||
| Alternative | Warum verworfen |
|
||||
| --- | --- |
|
||||
| `passport` + `passport-openidconnect` | Weitere Abstraktionsschicht und eigene Session-Middleware (`express-session`), PKCE nur teilweise; bringt nichts, was `openid-client` nicht direkt kann |
|
||||
| OIDC-Session in `nc_session` mit Upstream-`secret` | Wäre von naturalcrit-Tokens nicht unterscheidbar; das Abschalten von `naturalcrit` ginge nicht sauber; Cookie kann wegen der Client-Logout-Logik nicht `httpOnly` sein |
|
||||
| Serverseitige Sessions (`express-session` + Store in Mongo/PG) | Sofortiger Widerruf möglich, aber zusätzlicher Store pro DB-Backend (ADR 0002) und mehr Code. Feste kurze JWT-Laufzeit reicht für den Anwendungsfall |
|
||||
| Vorgeschalteter Auth-Proxy (oauth2-proxy, Authentik-Outpost) mit Header-Vertrauen | Nicht generisch im App-Sinn, die Share-Links müssen ohne Login erreichbar bleiben, und Header-Spoofing-Risiko bei Fehlkonfiguration |
|
||||
| Konten automatisch über `preferred_username` an bestehende Autoren binden | Übernahme fremder Brews möglich, wenn der IdP freie Benutzernamen zulässt |
|
||||
| Eigener Benutzername/Passwort-Login im Fork | Nicht gefordert; IdP übernimmt Passwort-Verwaltung, MFA und Sperren |
|
||||
|
||||
## Folgen
|
||||
|
||||
- Positiv: Der Upstream-Code bleibt beim Vertrag `req.account.username`.
|
||||
Der Fork-Diff in Upstream-Dateien beträgt etwa 15 Zeilen.
|
||||
- Positiv: Das OIDC-Session-Cookie ist `httpOnly`, läuft ab und hat einen
|
||||
eigenen Schlüssel.
|
||||
- Negativ: Eine Sperre am IdP wirkt erst nach Ablauf von `HB_SESSION_TTL`.
|
||||
- Negativ: Ist nur `oidc` aktiv, gibt es kein Google Drive als Speicherort.
|
||||
- Negativ: Die erste Fork-Benutzertabelle entsteht. Sie hängt an der
|
||||
Storage-Schicht aus ADR 0002, deshalb muss M1 das `UserRepository` für Mongo
|
||||
schon mitbringen (Postgres folgt in M2). Konkret gehören zu M1 (#6): das
|
||||
Gerüst `server/storage/` (`index.js` mit `getStorage()`/`connect()`,
|
||||
`mongo/index.js`, `mongo/users.js`, `contract/users.contract.js`) und die
|
||||
Umstellung von `server.js` auf `storage.connect(config)`. Die Umstellung der
|
||||
Brew-Zugriffe und Postgres bleiben in M2 (#7).
|
||||
- Positiv: `PUT /api/user/rename` kann keine Brews eines fremden Namens mehr
|
||||
umschreiben, weder mit OIDC- noch mit naturalcrit-Sitzung (Abschnitt 7, #21).
|
||||
Im Upstream besteht die Lücke mit naturalcrit-Sitzungen weiter. Florian
|
||||
meldet sie selbst an naturalcrit (F14), der Fork veröffentlicht dazu nichts.
|
||||
- Negativ: Mit dem Standard `HB_NATURALCRIT_RENAME=off` können naturalcrit-
|
||||
Benutzer ihre Brews nach einer Namensänderung nicht mehr selbst umschreiben.
|
||||
`signed` hilft nur, wenn der Account-Server den Nachweis `oldSession`
|
||||
mitschickt, naturalcrit.com tut das nicht.
|
||||
- Hinweis: In einer selbst gehosteten Instanz gibt es Benutzername/Passwort-
|
||||
und Google-Login nur, wenn zusätzlich ein naturalcrit-kompatibler
|
||||
Account-Server mit demselben `secret` und derselben Cookie-Domain läuft.
|
||||
Siehe Entscheidung F1.
|
||||
|
||||
## Entscheidungen (Florian, 2026-11-25)
|
||||
|
||||
- **F1 – Bisherige Logins:** Wie in #1 entschieden: Die bisherigen Logins
|
||||
bleiben, sind aber abschaltbar. Der Codepfad `naturalcrit` bleibt erhalten
|
||||
und wird über `HB_AUTH_PROVIDERS` einzeln abgeschaltet. Einen eigenen
|
||||
Passwort-Login bekommt der Fork nicht.
|
||||
- **F2 – Session-Laufzeit:** 7 Tage fest, ohne gleitende Verlängerung. Danach
|
||||
meldet sich der Nutzer still über den IdP neu an (wie in Abschnitt 3).
|
||||
- **F3 – Bestehende Benutzernamen:** Es gibt keine Bestandsdatenbank mit
|
||||
naturalcrit-Namen. Stand M1: `HB_OIDC_LINK_BY_EMAIL` ist umgesetzt
|
||||
(Standard `false`) und bleibt. `POST /admin/users` ist nicht umgesetzt und
|
||||
wird auf später verschoben. Ohne die Route gibt es keine vorab angelegten
|
||||
Benutzer, das Flag bewirkt deshalb derzeit nichts.
|
||||
- **F14 – Rename-Lücke für naturalcrit-Sitzungen:** Florian meldet die Lücke
|
||||
selbst an naturalcrit. Der Fork schließt sie unabhängig davon auch für den
|
||||
Provider `naturalcrit` (#21, Abschnitt 7): standardmäßig gesperrt, optional
|
||||
mit signiertem Nachweis für den alten Namen.
|
||||
@@ -0,0 +1,304 @@
|
||||
# ADR 0002: Repository-Schicht, MongoDB **oder** PostgreSQL pro Instanz
|
||||
|
||||
- Status: Angenommen (Entscheidungen Florian 2026-11-25, siehe Ende)
|
||||
- Datum: 2026-11-23, überarbeitet 2026-11-25 (Review PR #12)
|
||||
- Umsetzung: M2, Issue #7 (das `UserRepository` für Mongo schon in M1, siehe ADR 0001)
|
||||
- Basis: Analyse auf Upstream `73df298c`, gegen `6d219487` geprüft (seitdem nur `splitPane.jsx` und `listPage.jsx` geändert, beide hier nicht betroffen)
|
||||
|
||||
## Kontext
|
||||
|
||||
### Datenzugriff im Upstream-Code
|
||||
|
||||
- Mongoose-Modelle: `server/homebrew.model.js` (`Homebrew`, Text als
|
||||
`textBin` per zlib komprimiert, Statics `get`, `getByUser`, `increaseView`)
|
||||
und `server/notifications.model.js` (`Notification`).
|
||||
- Verbindungsaufbau: `server/db.js` (`connect`, `disconnect`), aufgerufen aus
|
||||
`server.js`. `server/middleware/dbCheck.js` prüft
|
||||
`mongoose.connection.readyState`.
|
||||
- Direkte Modellzugriffe mit Mongo-Abfragesyntax gibt es in:
|
||||
- `server/homebrew.api.js`: `getBrew` (`HomebrewModel.get` mit
|
||||
`{ editId }`, `{ shareId }`, `{ $or: […] }`), `getUsersBrewThemes`
|
||||
(`getByUser` mit `{ tags: { $in } }`), `newBrew` (`new HomebrewModel`,
|
||||
`.save()`), `updateBrew` (`findOne({ _id })`, `.save()`), `deleteBrew`
|
||||
(`deleteOne`, `markModified`, `.save()`).
|
||||
- `server/page-routes.js`: `/user/:username` (`getByUser`), `/account`
|
||||
(`countDocuments`), `/share/:id` (`increaseView`).
|
||||
- `server/app.js`: `/api/user/rename` (`getByUser`, `updateOne`).
|
||||
- `server/vault.api.js`: Volltextsuche `$text` auf `title`, Sortierung,
|
||||
Paging, `countDocuments`.
|
||||
- `server/admin.api.js`: Suche, Statistiken, Sperren (`lock`),
|
||||
Aggregationen für Aufräum-Jobs (`cleanupJunk`, `cleanupLost`,
|
||||
`finduncompressed`, `compress`), Notifications.
|
||||
- Die Upstream-Tests (`server/homebrew.api.spec.js`, `server/admin.api.spec.js`)
|
||||
ersetzen das Modell per `jest.mock('./homebrew.model.js')` und mocken
|
||||
einzelne Statics wie `model.get`.
|
||||
|
||||
### Vorgaben (Florian, #1)
|
||||
|
||||
Pro Instanz **entweder** Mongo **oder** PostgreSQL 18+, kein Migrationsskript
|
||||
zwischen beiden. Der Fork bleibt upstream-synchron.
|
||||
|
||||
Dazu kommen die neuen Fork-Entitäten `users` (ADR 0001), `git_connections`,
|
||||
`brew_git_links` (ADR 0003) und `brew_assets` (ADR 0004). Sie brauchen
|
||||
ebenfalls beide Backends.
|
||||
|
||||
## Entscheidung
|
||||
|
||||
### 1. Repository-Schicht `server/storage/`
|
||||
|
||||
```
|
||||
server/storage/
|
||||
index.js // getStorage(), connect(config), disconnect(), isReady()
|
||||
contract/ // gemeinsame Tests (siehe Abschnitt 5)
|
||||
mongo/
|
||||
index.js // createMongoStorage(config)
|
||||
brews.js // nutzt ../../homebrew.model.js unverändert
|
||||
notifications.js // nutzt ../../notifications.model.js unverändert
|
||||
users.js gitConnections.js brewGitLinks.js brewAssets.js // neue Mongoose-Modelle
|
||||
postgres/
|
||||
index.js // createPostgresStorage(config), Pool, Migrator
|
||||
db.js // Kysely-Instanz
|
||||
brews.js notifications.js users.js gitConnections.js brewGitLinks.js brewAssets.js
|
||||
migrations/0001_initial.js …
|
||||
```
|
||||
|
||||
`getStorage()` gibt ein Objekt `{ brews, notifications, users, gitConnections, brewGitLinks, brewAssets }`
|
||||
zurück. Alle Methoden sind `async` und geben **plain objects** zurück, keine
|
||||
Mongoose-Dokumente. Der Brew-Text kommt immer als entpacktes `text`, `textBin`
|
||||
taucht außerhalb der Mongo-Implementierung nicht auf.
|
||||
|
||||
**BrewRepository** (fester Methodensatz, mehr nicht):
|
||||
|
||||
| Methode | ersetzt |
|
||||
| --- | --- |
|
||||
| `findByEditId(id, { fields? })` | `HomebrewModel.get({ editId })` |
|
||||
| `findByShareId(id, { fields? })` | `HomebrewModel.get({ shareId })` |
|
||||
| `findByEditOrShareId(id)` | `HomebrewModel.get({ $or })` (Admin) |
|
||||
| `listByAuthor(username, { includeUnpublished, fields, tagsAny? })` | `getByUser(…)` |
|
||||
| `countByAuthor(username, { storage: 'homebrewery' })` | `countDocuments` in `/account` |
|
||||
| `existsAuthor(username)` | neu, ADR 0001 |
|
||||
| `create(brew)` → brew mit `id`, `editId`, `shareId` | `new HomebrewModel(brew).save()` |
|
||||
| `update(brew)` (per `id`, ganzes Dokument) → brew | `findOne({ _id })` + `_.assign` + `.save()` |
|
||||
| `deleteById(id)`, `deleteByEditId(editId)` | `deleteOne` |
|
||||
| `incrementViews(shareId)` → brew | `increaseView` |
|
||||
| `renameAuthor(oldName, newName)` | Schleife mit `updateOne` in `/api/user/rename` |
|
||||
| `searchPublished({ title, author, renderer, sort, dir, skip, limit, withTotal })` → `{ brews, total }` (`total` nur mit `withTotal: true`; `limit: 0` liefert keine Brews, für `/api/vault/total`) | `vault.api.js` |
|
||||
| Admin: `countAll()`, `countPublished()`, `listLocked(…)`, `countLocked()`, `setLock(shareId, lock, { overwrite })`, `removeLock(shareId)`, `requestReview(shareId)`, `listReviewRequests()`, `removeReviewRequest(shareId)` (Lock-/Review-Methoden liefern `{ result, brew }`, PG atomar per Transaktion mit `FOR UPDATE`) | `admin.api.js` |
|
||||
|
||||
**Fork-Repositories** (`users`, `gitConnections`, `brewGitLinks`,
|
||||
`brewAssets`): Die Felder legen ADR 0001, 0003 und 0004 fest. Für den Besitz
|
||||
gilt: `gitConnections` wird nur über `ownerUserId` (= `users.id`) gefunden
|
||||
(`listByOwner(userId)`, `findByIdForOwner(id, userId)`), nie über einen
|
||||
Benutzernamen. `brews.renameAuthor` ändert ausschließlich `authors[]` und
|
||||
berührt keine Fork-Collection bzw. -Tabelle. Damit bleiben Verbindungen und
|
||||
Links bei einem Rename unverändert (ADR 0001, Abschnitt 4, Punkt 5).
|
||||
|
||||
Das Feld `id` ist das neutrale Gegenstück zu Mongos `_id` (Mongo: String
|
||||
der ObjectId; PG: UUID). Upstream-Code, der `brew._id` prüft (z. B. „hat der
|
||||
Brew schon einen Stub?“ in `updateBrew`), prüft dann `brew.id`.
|
||||
|
||||
**Mongo-Implementierung:** ruft exakt die Statics und Methoden auf, die der
|
||||
Upstream-Code heute aufruft (`HomebrewModel.get`, `getByUser`,
|
||||
`increaseView` …). So bleiben die bestehenden Upstream-Specs mit
|
||||
`jest.mock('./homebrew.model.js')` gültig, weil Jest das Modul überall im
|
||||
Registry ersetzt. Die Upstream-Modelldateien bleiben **unverändert**.
|
||||
|
||||
**Admin-Wartungsjobs** (`cleanupJunk`, `cleanupLost`, `finduncompressed`,
|
||||
`compress`) sind reine Mongo-Wartung und bleiben direkt auf dem Modell. Unter
|
||||
Postgres antworten sie mit `501 Not Implemented` (kleiner Guard
|
||||
`if(storage.driver !== 'mongo')`), weil es dort kein `textBin`-Altformat gibt.
|
||||
`/admin/clean/script/:id` läuft dagegen über `getBrew` und `updateBrew` (damit über das Repository)
|
||||
und funktioniert auf beiden Backends. Notifications nutzen `id`
|
||||
statt `_id`.
|
||||
|
||||
### 2. Auswahl des Backends
|
||||
|
||||
| Variable | Bedeutung |
|
||||
| --- | --- |
|
||||
| `HB_DB_DRIVER` | `mongo` (Standard) oder `postgres` |
|
||||
| `MONGODB_URI` | wie Upstream (`server/db.js` `getMongoDBURL`) |
|
||||
| `HB_POSTGRES_URL` | z. B. `postgres://hb:…@postgres:5432/homebrewery` |
|
||||
| `HB_POSTGRES_POOL_MAX` | Standard `10` |
|
||||
|
||||
- Beim Start wird genau ein Backend verbunden. Mit `postgres` ohne
|
||||
`HB_POSTGRES_URL` bricht der Start mit klarer Meldung ab. Bei `postgres`
|
||||
wird Mongoose gar nicht verbunden.
|
||||
- Beim Start mit Postgres prüft die App `SHOW server_version_num` ≥ `180000`
|
||||
und bricht sonst ab.
|
||||
- Es gibt **keinen** Datenumzug zwischen den Backends. Wer wechselt, startet
|
||||
eine leere Instanz. Einzelne Brews lassen sich über die vorhandene
|
||||
Upstream-Funktion „Download“ bzw. „Import“ mitnehmen.
|
||||
- `dbCheck` fragt `getStorage().isReady()` statt `mongoose.connection.readyState`.
|
||||
|
||||
### 3. PostgreSQL-Schema
|
||||
|
||||
Werkzeug: **Kysely** (Query-Builder, keine Codegenerierung, kein natives
|
||||
Binary) mit dem eingebauten `Migrator` und dem Treiber **`pg`**. Migrationen
|
||||
sind JS-Dateien in `server/storage/postgres/migrations/`, benannt
|
||||
`NNNN_beschreibung.js` mit `up(db)` und `down(db)`. Sie laufen **beim Start
|
||||
automatisch** (`migrateToLatest`). Kysely sperrt dabei über die eigene
|
||||
Lock-Tabelle, damit zwei Starts nicht gleichzeitig migrieren. Bei einem
|
||||
Fehler bricht der Start ab.
|
||||
|
||||
Erste Migration `0001_initial.js` (PG 18: `uuidv7()` ist eingebaut):
|
||||
|
||||
```sql
|
||||
CREATE TABLE brews (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
share_id text NOT NULL UNIQUE,
|
||||
edit_id text NOT NULL UNIQUE,
|
||||
google_id text,
|
||||
title text NOT NULL DEFAULT '',
|
||||
text text NOT NULL DEFAULT '', -- PG komprimiert per TOAST, kein textBin
|
||||
page_count integer NOT NULL DEFAULT 1,
|
||||
description text NOT NULL DEFAULT '',
|
||||
tags text[] NOT NULL DEFAULT '{}',
|
||||
systems text[],
|
||||
lang text NOT NULL DEFAULT 'en',
|
||||
renderer text NOT NULL DEFAULT '',
|
||||
authors text[] NOT NULL DEFAULT '{}',
|
||||
invited_authors text[] NOT NULL DEFAULT '{}',
|
||||
published boolean NOT NULL DEFAULT false,
|
||||
thumbnail text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_viewed timestamptz NOT NULL DEFAULT now(),
|
||||
views integer NOT NULL DEFAULT 0,
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
lock jsonb,
|
||||
title_tsv tsvector GENERATED ALWAYS AS (to_tsvector('simple', title)) STORED
|
||||
);
|
||||
CREATE INDEX brews_authors_gin ON brews USING gin (authors);
|
||||
CREATE INDEX brews_tags_gin ON brews USING gin (tags);
|
||||
CREATE INDEX brews_title_tsv_gin ON brews USING gin (title_tsv);
|
||||
CREATE INDEX brews_published_updated ON brews (published, updated_at DESC);
|
||||
CREATE INDEX brews_google_id ON brews (google_id) WHERE google_id IS NOT NULL;
|
||||
CREATE INDEX brews_lock ON brews ((lock IS NOT NULL)) WHERE lock IS NOT NULL;
|
||||
|
||||
CREATE TABLE notifications (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
dismiss_key text NOT NULL UNIQUE,
|
||||
title text NOT NULL DEFAULT '',
|
||||
text text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
start_at timestamptz NOT NULL DEFAULT now(),
|
||||
stop_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
username text NOT NULL UNIQUE,
|
||||
oidc_issuer text,
|
||||
oidc_sub text,
|
||||
email text,
|
||||
email_verified boolean NOT NULL DEFAULT false,
|
||||
display_name text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_login_at timestamptz,
|
||||
UNIQUE (oidc_issuer, oidc_sub)
|
||||
);
|
||||
CREATE INDEX users_email ON users (email);
|
||||
```
|
||||
|
||||
Die Tabellen `git_connections`, `brew_git_links` (ADR 0003) und `brew_assets`
|
||||
(ADR 0004) kommen als eigene Migrationen in M3/M4. Ihre Spalten sind in den
|
||||
jeweiligen ADRs festgelegt.
|
||||
|
||||
Abbildung der Felder: snake_case in PG, camelCase im Repository-Ergebnis.
|
||||
Die Umrechnung erledigt **eine** Funktion `rowToBrew` / `brewToRow` je
|
||||
Tabelle, kein Kysely-Plugin. `vault`-Suche: `title_tsv @@ websearch_to_tsquery('simple', $1)`.
|
||||
Die Treffer weichen leicht von Mongos `$text` ab (kein englisches Stemming),
|
||||
das ist akzeptiert.
|
||||
|
||||
**Mongo:** keine Migrationen. Für die neuen Fork-Collections legen die
|
||||
Modelle ihre Indizes über Mongoose an. `autoIndex` bleibt wie im Upstream nur
|
||||
lokal an. In Produktion ruft `createMongoStorage` beim Start einmal
|
||||
`Model.syncIndexes()` für die **Fork**-Modelle auf (nicht für `Homebrew`).
|
||||
|
||||
### 4. Umstellung der Aufrufstellen
|
||||
|
||||
Die Upstream-Aufrufstellen (Liste oben) werden **einmalig und mechanisch**
|
||||
auf `getStorage().brews.*` umgestellt. Regeln für die Umsetzung:
|
||||
|
||||
1. Keine Logikänderung in derselben Änderung, nur Ersatz der Datenzugriffe.
|
||||
2. Nicht jede Zeile kommentieren: Pro Funktion steht ein
|
||||
`// [fork] ADR-0002`-Kommentar über dem ersten Zugriff.
|
||||
3. Mongoose-spezifische Aufrufe (`markModified`, `toObject`, `.save()`)
|
||||
verschwinden aus `homebrew.api.js`. Das erledigt das Repository.
|
||||
4. Die Upstream-Specs müssen ohne Anpassung grün bleiben. Ist das an einer
|
||||
Stelle nicht möglich, wird die Spec minimal angepasst und die Abweichung
|
||||
im PR begründet.
|
||||
|
||||
### 5. Testansatz gegen beide Datenbanken
|
||||
|
||||
- **Contract-Suite** `server/storage/contract/*.contract.js`: eine Funktion
|
||||
`runBrewRepositoryContract(createStorage)` usw. pro Repository, mit allen
|
||||
Methoden aus der Tabelle oben inklusive Randfällen (unbekannte ID,
|
||||
Eindeutigkeitsverletzung, Sortierung, Paging, Volltext, Umbenennen von
|
||||
Autoren). Pflichtfälle zu Besitz und Rename (ab M3, sobald es
|
||||
`gitConnections` gibt): Nach `brews.renameAuthor('a', 'b')` liefert
|
||||
`gitConnections.listByOwner(userId)` dieselben Verbindungen, und
|
||||
`brewGitLinks` ist unverändert. `findByIdForOwner` mit fremder `userId`
|
||||
liefert `null`. Das Löschen eines Benutzers entfernt seine Verbindungen und
|
||||
deren Links, die Brews bleiben.
|
||||
- Zwei Spec-Dateien rufen sie auf: `server/storage/mongo/storage.spec.js`
|
||||
und `server/storage/postgres/storage.spec.js`. Sie lesen
|
||||
`HB_TEST_MONGODB_URI` bzw. `HB_TEST_POSTGRES_URL` und überspringen sich mit
|
||||
`describe.skip` und Warnung, wenn die Variable fehlt. Jede Suite nutzt eine
|
||||
frische Datenbank bzw. ein frisches Schema (`test_<random>`) und räumt
|
||||
danach auf.
|
||||
- CI (#4): Ein Job mit Service-Containern `mongo:8` und `postgres:18` setzt
|
||||
beide Variablen. Lokal laufen die Suites gegen das Compose-Setup (#3).
|
||||
- Keine In-Memory-Ersatzdatenbanken (`mongodb-memory-server`, `pg-mem`):
|
||||
Der Download ist groß bzw. das SQL-Verhalten ungenau, und auf der VM ist
|
||||
wenig Speicher frei.
|
||||
- Die API-Specs (`homebrew.api.spec.js` usw.) bleiben Unit-Tests mit Mock.
|
||||
Zusätzlich gibt es einen schmalen API-Smoke-Test
|
||||
(`tests/fork/api-smoke.test.js`, supertest), der Neuanlage, Laden, Update,
|
||||
Teilen und Löschen gegen das jeweils konfigurierte echte Backend ausführt.
|
||||
|
||||
## Betroffene Upstream-Dateien
|
||||
|
||||
| Datei | Änderung |
|
||||
| --- | --- |
|
||||
| `server.js` | `DB.connect` durch `storage.connect(config)` ersetzen |
|
||||
| `server/middleware/dbCheck.js` | `getStorage().isReady()` statt `mongoose.connection.readyState` |
|
||||
| `server/homebrew.api.js` | Datenzugriffe in `getBrew`, `getUsersBrewThemes`, `newBrew`, `updateBrew`, `deleteBrew` |
|
||||
| `server/page-routes.js` | `/user/:username`, `/account`, `/share/:id` |
|
||||
| `server/app.js` | `/api/user/rename` |
|
||||
| `server/vault.api.js` | `findBrews` über `searchPublished` |
|
||||
| `server/admin.api.js` | Statistiken, Sperren, Notifications über Repository; Wartungsjobs mit PG-Guard |
|
||||
| `package.json` | `kysely`, `pg` |
|
||||
|
||||
Unverändert: `server/homebrew.model.js`, `server/notifications.model.js`,
|
||||
`server/db.js` (wird von `server/storage/mongo/index.js` benutzt).
|
||||
|
||||
## Alternativen
|
||||
|
||||
| Alternative | Warum verworfen |
|
||||
| --- | --- |
|
||||
| Prisma | Generierter Client und Query-Engine, großer Speicher- und Build-Aufwand. Das Mongo-Schema müsste parallel als Prisma-Schema gepflegt werden |
|
||||
| Knex | Ähnlich wie Kysely, aber schwächer gepflegt. Kysely-Migrator und Query-Builder sind schlanker |
|
||||
| `node-pg-migrate` + rohes SQL | Gute Alternative. Kysely gewinnt, weil die dynamischen Vault- und Admin-Filter mit einem Query-Builder sicherer und lesbarer sind |
|
||||
| Mongo-kompatible Fassade über PG (FerretDB) | Weitere Laufzeitkomponente. `$text`, Aggregationen und Indexverhalten nur teilweise kompatibel. Am Ende wäre es kein echtes PG-Backend |
|
||||
| PG mit einer `jsonb`-Spalte pro Brew | Weniger Code, aber keine sinnvollen Indizes und Constraints. Widerspricht dem Ziel eines echten PG-Backends |
|
||||
| Eigene Fork-Routen statt Umstellung der Upstream-Aufrufstellen | Dupliziert die Brew-Logik (Patches, Versionsprüfung, Google Drive) und driftet bei jedem Upstream-Update weg. Ein einmaliger mechanischer Diff ist leichter zu mergen |
|
||||
|
||||
## Folgen
|
||||
|
||||
- Positiv: Ein klarer, getesteter Vertrag. Weitere Fork-Entitäten kommen ohne
|
||||
Mongo-Wissen in der Fachlogik aus.
|
||||
- Negativ: Die Umstellung der Aufrufstellen ist der größte Upstream-Diff des
|
||||
Forks. Ändert Upstream dort etwas, gibt es Merge-Konflikte. Abhilfe:
|
||||
mechanische, kommentierte Änderungen (Abschnitt 4) und die Contract-Suite
|
||||
als Sicherheitsnetz.
|
||||
- Negativ: Die Mongo-Wartungsjobs im Admin-Bereich gibt es unter PG nicht.
|
||||
- Negativ: Die Vault-Suche verhält sich unter PG leicht anders (kein Stemming).
|
||||
|
||||
## Entscheidungen (Florian, 2026-11-25)
|
||||
|
||||
- **F4 – Standard-Backend im Compose-Setup:** `postgres` (PostgreSQL 18).
|
||||
Mongo bleibt Option für Upstream-nahe Instanzen.
|
||||
- **F5 – Admin-Wartungsjobs unter PG:** Unter PostgreSQL nicht nötig.
|
||||
`cleanupJunk`, `cleanupLost` und `compress` antworten mit
|
||||
`501 Not Implemented`.
|
||||
@@ -0,0 +1,472 @@
|
||||
# ADR 0003: Git-Backend über HTTPS + PAT, Teilen per Server-Snapshot
|
||||
|
||||
- Status: Angenommen (Entscheidungen Florian 2026-11-25, siehe Ende)
|
||||
- Datum: 2026-11-23, überarbeitet 2026-11-25 (Review PR #12)
|
||||
- Umsetzung: M3, Issues #8 (Git-Backend) und #9 (Teilen)
|
||||
- Abhängig von: ADR 0001 (Benutzer), ADR 0002 (Repositories)
|
||||
- Basis: Analyse auf Upstream `73df298c`, gegen `6d219487` geprüft (seitdem nur `splitPane.jsx` und `listPage.jsx` geändert, beide hier nicht betroffen)
|
||||
|
||||
## Kontext
|
||||
|
||||
- Upstream hat mit Google Drive schon einen externen Speicherort. Die DB hält
|
||||
einen **Stub** (Metadaten, `authors`, `shareId`/`editId`), der Inhalt liegt
|
||||
in Drive (`server/googleActions.js`, `server/homebrew.api.js`
|
||||
`getBrew`/`updateBrew`/`excludeGoogleProps`/`excludeStubProps`). Leser
|
||||
eines geteilten Drive-Brews brauchen keinen Drive-Zugang, weil der Server
|
||||
mit dem Service-Account liest.
|
||||
- Speichern läuft immer über `PUT /api/update/:id`: Versionsprüfung
|
||||
(`version`), Hash-Prüfung, Patches anwenden, dann
|
||||
`brew.text = api.mergeBrewText(brew)` und speichern. `mergeBrewText` erzeugt
|
||||
**ein** Markdown-Dokument mit ```` ```metadata ```` (YAML), ```` ```css ````
|
||||
und dem Text. Genau das liefert auch `/source/:id` bzw. `/download/:id`, und
|
||||
der Import (`splitTextStyleAndMetadata` in `shared/helpers.js`) liest es
|
||||
wieder ein.
|
||||
- Der Editor speichert automatisch **10 s nach der letzten Änderung**
|
||||
(`SAVE_TIMEOUT` in `client/homebrew/pages/basePages/editPage/editorPage.jsx`).
|
||||
- Das Docker-Image enthält schon `git` (`Dockerfile`: `apk add git`).
|
||||
- Vorgaben (Florian, #1): providerneutral über **HTTPS + Personal Access
|
||||
Token**, kein SSH, kein OAuth-Connect. Teilen per Server-Snapshot: Leser
|
||||
brauchen keinen Repo-Zugriff, ausgeliefert wird der zuletzt gespeicherte
|
||||
Stand.
|
||||
|
||||
## Entscheidung
|
||||
|
||||
### 1. Grundprinzip: DB-Brew als Snapshot + Git-Verknüpfung
|
||||
|
||||
Ein Git-Brew ist ein **normaler, vollständiger DB-Brew** (Text inklusive)
|
||||
plus ein Eintrag in `brew_git_links`. Anders als bei Google Drive ist der
|
||||
DB-Text kein Stub, sondern der **Snapshot des zuletzt gespeicherten Stands**.
|
||||
Daraus folgt:
|
||||
|
||||
- `/share/:id`, `/api/fetch/:id`, `/css/:id`, `/metadata/:id`, `/source/:id`,
|
||||
`/download/:id`, Theme-Bundles und der Vault funktionieren für Git-Brews
|
||||
**ohne jede Änderung** und ohne Git-Zugriff. Damit ist Teilen (#9) im
|
||||
Kern erledigt.
|
||||
- Git ist beim Speichern das führende Ziel (Commit zuerst, Abschnitt 5). Die DB
|
||||
folgt dem erfolgreichen Push.
|
||||
|
||||
Dateiformat im Repo: exakt die Ausgabe von `api.mergeBrewText(brew)`, also
|
||||
dieselbe Datei wie beim Upstream-Download. DB-only bleiben (nicht in der
|
||||
Datei): `authors`, `invitedAuthors`, `published`, `views`, `lastViewed`,
|
||||
`thumbnail`, `lang`, `lock`, `shareId`, `editId`, `version`.
|
||||
|
||||
### 2. Datenmodell
|
||||
|
||||
**`git_connections`** (pro Benutzer, beliebig viele):
|
||||
|
||||
| Spalte | Typ | Regel |
|
||||
| --- | --- | --- |
|
||||
| `id` | uuid | |
|
||||
| `owner_user_id` | uuid | FK `users(id) ON DELETE CASCADE`, aus `req.account.uid` (ADR 0001). **Nicht** der Benutzername, siehe „Besitz und Umbenennen“ |
|
||||
| `label` | text | Anzeigename, 1–80 Zeichen |
|
||||
| `repo_url` | text | `https://host[:port]/pfad(.git)`, ohne Benutzerinfo, ohne Query/Fragment |
|
||||
| `auth_username` | text | Standard `git`. Gitea/Forgejo/GitHub/GitLab akzeptieren einen PAT als Passwort mit beliebigem bzw. eigenem Benutzernamen. Die Doku nennt pro Anbieter den passenden Wert |
|
||||
| `token_enc` | text | verschlüsselter PAT (Abschnitt 3), nie im Klartext gespeichert |
|
||||
| `default_branch` | text | Standard aus `ls-remote --symref HEAD`, sonst `main` |
|
||||
| `brew_dir` | text | Standardordner für neue Brews, Standard `brews` |
|
||||
| `assets_dir` | text | für ADR 0004, Standard `assets` |
|
||||
| `created_at`, `updated_at`, `last_verified_at` | timestamptz | |
|
||||
|
||||
Index: `(owner_user_id)`.
|
||||
|
||||
**Besitz und Umbenennen:** Eine Verbindung gehört einem `users`-Datensatz,
|
||||
nicht einem Namen. Damit gilt:
|
||||
|
||||
- Ein Rename über `PUT /api/user/rename` ändert nur `authors[]` der Brews
|
||||
und berührt `git_connections` und `brew_git_links` nie. Für OIDC-Sessions
|
||||
ist die Route ohnehin gesperrt (ADR 0001, Abschnitt 4, Punkt 5).
|
||||
- Ein Mitziehen von `owner` im Rename-Hook ist **verworfen**: Die
|
||||
Upstream-Route prüft nicht, ob der Aufrufer den alten Namen besitzt. Ein
|
||||
Mitziehen würde jedem angemeldeten Benutzer fremde Verbindungen samt PAT
|
||||
zuspielen.
|
||||
- Das Git-Backend steht deshalb **nur OIDC-Konten** zur Verfügung (nur sie
|
||||
haben eine `uid`). Alle Routen unter `/api/git/*` antworten ohne
|
||||
`req.account.uid` mit `403 { HBErrorCode: 'G07' }`. Ausgenommen sind
|
||||
`GET /api/git/brews/:editId` (Status) und `POST /api/git/brews/:editId/pull`:
|
||||
Sie verlangen nur das Bearbeitungsrecht am Brew nach Upstream-Regeln. naturalcrit-Konten
|
||||
haben keine stabile ID (der Name im JWT ändert sich beim Rename), ein PAT
|
||||
ließe sich ihnen nicht sicher zuordnen. Siehe Entscheidung F13.
|
||||
- Speichern eines verknüpften Brews ist davon nicht betroffen. Ein
|
||||
naturalcrit-Mitautor darf ihn wie bisher speichern, der Commit läuft mit
|
||||
dem Token des Verbindungsbesitzers (Abschnitt 5).
|
||||
|
||||
**`brew_git_links`** (höchstens eine pro Brew):
|
||||
|
||||
| Spalte | Typ | Regel |
|
||||
| --- | --- | --- |
|
||||
| `brew_id` | uuid | PK, FK `brews(id) ON DELETE CASCADE` |
|
||||
| `connection_id` | uuid | FK `git_connections(id) ON DELETE CASCADE` |
|
||||
| `branch` | text | per `git check-ref-format --branch` geprüft |
|
||||
| `path` | text | relativ, `/`-getrennt, kein `..`, kein führendes `/`, nicht unter `.git/`, ≤ 255 Zeichen, Endung `.md` |
|
||||
| `last_commit_sha` | text | Commit, der den Snapshot erzeugt bzw. übernommen hat |
|
||||
| `last_blob_sha` | text | Blob-ID der Datei in diesem Commit, Basis der Konflikterkennung |
|
||||
| `last_synced_at` | timestamptz | |
|
||||
| `last_error` | text? | letzter Fehlercode für die Statusanzeige |
|
||||
|
||||
Eindeutig: `(connection_id, branch, path)`, damit nicht zwei Brews dieselbe
|
||||
Datei beschreiben. Wird eine Verbindung gelöscht, fallen die Links weg, und
|
||||
die Brews bleiben als reine DB-Brews mit ihrem letzten Snapshot erhalten.
|
||||
|
||||
Mongo: Collections `gitconnections` und `brewgitlinks` mit denselben
|
||||
Feldern (camelCase). `brewId` ist der `_id`-String des Homebrew-Dokuments.
|
||||
Die Kaskade beim Löschen erledigt das Repository (`brews.deleteById` löscht
|
||||
Link und Assets mit).
|
||||
|
||||
### 3. Token-Verschlüsselung
|
||||
|
||||
- Algorithmus **AES-256-GCM** (`node:crypto`), 12 Byte zufälliger IV pro
|
||||
Verschlüsselung, 16 Byte Tag.
|
||||
- Schlüssel `HB_GIT_TOKEN_KEY`: 32 Byte, base64 (`openssl rand -base64 32`).
|
||||
**Fehlt er, ist das Git-Backend deaktiviert** (Warnung beim Start, die
|
||||
`/api/git/*`-Routen antworten mit 503). Es gibt keinen Rückfall auf
|
||||
`secret` oder `HB_SESSION_SECRET`.
|
||||
- Format: `v1.<kid>.<iv>.<ciphertext>.<tag>` (base64url). `kid` sind die
|
||||
ersten 8 Hex-Zeichen von `sha256(key)`. AAD ist `git-connection:<id>`. Ein
|
||||
Chiffrat lässt sich also nicht in eine andere Verbindung kopieren.
|
||||
- Rotation: `HB_GIT_TOKEN_KEYS_OLD` (kommagetrennt) ist nur zum
|
||||
Entschlüsseln da. Bei der nächsten Nutzung wird mit dem aktuellen Schlüssel
|
||||
neu verschlüsselt.
|
||||
- Der Token ist **write-only**. Die API gibt ihn nie zurück (nur
|
||||
`hasToken: true`). Er erscheint in keinem Log und keiner Fehlermeldung.
|
||||
Fehlertexte von `git` werden vor dem Loggen durch eine Funktion
|
||||
`redact(text, token)` gefiltert.
|
||||
|
||||
### 4. Git-Zugriff (providerneutral, ohne Arbeitskopie)
|
||||
|
||||
Modul `server/fork/git/`:
|
||||
|
||||
| Datei | Inhalt |
|
||||
| --- | --- |
|
||||
| `gitClient.js` | einzige Stelle, die `git` startet (`execFile`, nie Shell) |
|
||||
| `crypto.js` | Token ver- und entschlüsseln |
|
||||
| `urlPolicy.js` | URL- und Host-Prüfung (SSRF) |
|
||||
| `brewSync.js` | Laden, Speichern, Konflikte, Pull |
|
||||
| `routes.js` | `/api/git/*` |
|
||||
| `hooks.js` | Einhängepunkte für `homebrew.api.js` |
|
||||
| `locks.js` | prozesslokaler Mutex pro Brew und globales Limit |
|
||||
|
||||
Wir nutzen die **`git`-CLI** über Smart-HTTP. Das ist bei jedem Anbieter
|
||||
gleich, eine Anbieter-REST-API gibt es nicht. Jede Operation läuft in einem
|
||||
frischen Bare-Repo unter `HB_GIT_WORKDIR` (Standard `os.tmpdir()/hb-git`,
|
||||
Verzeichnis `0700`), das danach gelöscht wird.
|
||||
|
||||
Umgebung jedes `git`-Aufrufs (nichts davon in Argumenten oder Dateien):
|
||||
|
||||
```
|
||||
HOME=<tmpdir> GIT_CONFIG_NOSYSTEM=1 GIT_TERMINAL_PROMPT=0 GIT_ASKPASS=/bin/false
|
||||
GIT_CONFIG_COUNT=5
|
||||
GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0=Authorization: Basic <base64(auth_username:token)>
|
||||
GIT_CONFIG_KEY_1=protocol.allow GIT_CONFIG_VALUE_1=never
|
||||
GIT_CONFIG_KEY_2=protocol.https.allow GIT_CONFIG_VALUE_2=always
|
||||
GIT_CONFIG_KEY_3=http.followRedirects GIT_CONFIG_VALUE_3=false
|
||||
GIT_CONFIG_KEY_4=credential.helper GIT_CONFIG_VALUE_4=
|
||||
```
|
||||
|
||||
Ablauf **Lesen** (Datei und Blob-ID auf dem Branch):
|
||||
|
||||
```
|
||||
git init --bare -q <tmp>
|
||||
git -C <tmp> fetch --depth=1 --filter=blob:none <url> refs/heads/<branch>
|
||||
head=$(git -C <tmp> rev-parse FETCH_HEAD)
|
||||
blob=$(git -C <tmp> rev-parse "$head:<path>") # braucht nur Trees
|
||||
git -C <tmp> cat-file blob "$blob" # lädt genau diesen Blob nach
|
||||
```
|
||||
|
||||
Ablauf **Schreiben** (Commit auf `head` ohne Arbeitskopie):
|
||||
|
||||
```
|
||||
new=$(git -C <tmp> hash-object -w --stdin < datei)
|
||||
GIT_INDEX_FILE=<tmp>/idx git -C <tmp> read-tree "$head"
|
||||
GIT_INDEX_FILE=<tmp>/idx git -C <tmp> update-index --add --cacheinfo 100644,"$new","<path>"
|
||||
tree=$(GIT_INDEX_FILE=<tmp>/idx git -C <tmp> write-tree)
|
||||
commit=$(git -C <tmp> commit-tree "$tree" -p "$head" -m "<message>") # Autor über GIT_AUTHOR_*/GIT_COMMITTER_*
|
||||
git -C <tmp> push <url> "$commit:refs/heads/<branch>" # nie --force
|
||||
```
|
||||
|
||||
- Existiert der Branch noch nicht (leeres Repo oder neuer Branch), wird ein
|
||||
Root-Commit ohne `-p` erzeugt. Für einen neuen Branch in einem nicht leeren
|
||||
Repo setzt das Fork-Modul den Branch auf den Kopf von `default_branch` auf.
|
||||
- Ignoriert ein Server `--filter`, gibt `git` eine Warnung aus und lädt die
|
||||
Blobs des Kopf-Commits. Das ist funktional korrekt, nur langsamer.
|
||||
- Lokal mit git 2.53 gegen ein `file://`-Remote geprüft (23.11.2026): Der
|
||||
Fetch lädt nur Commit und Trees (4 Objekte, ein 200-KB-Blob im Repo wird
|
||||
nicht übertragen), `cat-file` lädt den Brew-Blob nach, der Push aus dem
|
||||
Shallow+Partial-Clone klappt, und ein veralteter Commit wird als
|
||||
Non-Fast-Forward abgelehnt.
|
||||
- **Vor M3-Start Pflicht-Spike über HTTPS:** Ada prüft dieselbe Folge
|
||||
inklusive Root-Commit gegen Gitea und GitHub. Weicht etwas ab, wird diese
|
||||
ADR angepasst, bevor die Umsetzung beginnt.
|
||||
- Commit-Identität: Autor = speichernder Benutzer (`displayName` oder
|
||||
`username`, E-Mail `<username>@users.noreply.<host aus HB_PUBLIC_URL>`).
|
||||
Committer = `HB_GIT_COMMITTER_NAME` / `HB_GIT_COMMITTER_EMAIL` (Standard
|
||||
`Homebrewery` / `homebrewery@<host>`). Nachricht:
|
||||
`Update <path> via Homebrewery` bzw. `Create <path> via Homebrewery`.
|
||||
- Grenzen: `HB_GIT_TIMEOUT_MS` (Standard 20000) pro Aufruf, dazu
|
||||
`GIT_HTTP_LOW_SPEED_LIMIT=1000` und `GIT_HTTP_LOW_SPEED_TIME=10`.
|
||||
`HB_GIT_MAX_FILE_BYTES` (Standard 5 MiB) für Brew-Dateien.
|
||||
`HB_GIT_MAX_CONCURRENCY` (Standard 2) gleichzeitige Git-Operationen pro
|
||||
Prozess (knapper VM-Speicher), weitere warten in einer Queue (max. 20, sonst
|
||||
503).
|
||||
|
||||
**SSRF-Schutz** (`urlPolicy.js`), vor jeder Operation:
|
||||
|
||||
1. Nur `https:` (Ausnahme `http:` bei `HB_GIT_ALLOW_HTTP=true`, nur für lokale
|
||||
Entwicklung), keine Benutzerinfo in der URL.
|
||||
2. Ist `HB_GIT_ALLOWED_HOSTS` gesetzt (kommagetrennt, `*.example.org`
|
||||
erlaubt), muss der Host passen.
|
||||
3. Sonst wird der Host per `dns.lookup(all)` aufgelöst. Ist eine Adresse
|
||||
Loopback, privat (RFC 1918, ULA), Link-Local, CGNAT oder unspezifiziert,
|
||||
wird abgebrochen. Ausnahme: `HB_GIT_ALLOW_PRIVATE=true`, z. B. für eine
|
||||
Gitea-Instanz im selben Compose-Netz.
|
||||
4. Restrisiko DNS-Rebinding zwischen Prüfung und `git`-Verbindung. In
|
||||
Produktion wird deshalb `HB_GIT_ALLOWED_HOSTS` empfohlen.
|
||||
|
||||
### 5. Brew ↔ Repo/Branch/Pfad, Speichern und Konflikte
|
||||
|
||||
**Anlegen und Verknüpfen** (Fork-Routen, keine Upstream-Änderung):
|
||||
|
||||
| Route | Wirkung |
|
||||
| --- | --- |
|
||||
| `POST /api/git/brews` `{ connectionId, branch?, path?, brew }` | Neuer Brew: `api.beforeNewSave`, Datei per Root- oder Normal-Commit anlegen. Pfad-Standard `<brew_dir>/<slug(title)>.md`. Ist die Datei schon vorhanden, folgt 409 `G06` |
|
||||
| `POST /api/git/brews/import` `{ connectionId, branch, path }` | Vorhandene Datei lesen, mit `splitTextStyleAndMetadata` zerlegen, Brew + Link anlegen |
|
||||
| `POST /api/git/brews/:editId/link` `{ connectionId, branch, path }` | Bestehenden DB-Brew nach Git schreiben und verknüpfen. Nicht erlaubt für Google-Drive-Brews (400) |
|
||||
| `DELETE /api/git/brews/:editId/link` | Verknüpfung lösen. Der Brew bleibt als DB-Brew, die Datei im Repo bleibt |
|
||||
| `GET /api/git/brews/:editId` | Status: Repo-URL, Branch, Pfad, `lastCommitSha`, `lastSyncedAt`, `lastError` |
|
||||
| `POST /api/git/brews/:editId/pull` | Remote-Stand in den Snapshot übernehmen (überschreibt den DB-Stand) |
|
||||
|
||||
Rechte: Verknüpfen, Lösen und Verbindungen verwalten darf nur der
|
||||
**Besitzer der Verbindung** (`owner_user_id === req.account.uid`), und er
|
||||
muss Besitzer des Brews sein (`authors[0] === req.account.username`). Speichern dürfen alle, die den Brew laut Upstream-Regeln
|
||||
bearbeiten dürfen. Der Commit läuft dann mit dem Token des
|
||||
Verbindungsbesitzers.
|
||||
|
||||
**Speichern** (`PUT /api/update/:id`, Upstream-Route): Hook
|
||||
`gitHooks.beforeBrewSave({ brew, req, res })` in `updateBrew`, direkt vor dem
|
||||
Google-Drive-Block. Ablauf bei verknüpftem Brew, unter Mutex pro Brew:
|
||||
|
||||
1. Wurde `saveToGoogle` angefragt: 400, ein Brew ist entweder Git oder Drive.
|
||||
2. Remote lesen (nur `head` und `blob`, ohne Inhalt).
|
||||
3. `blob === last_blob_sha`, oder Query `gitOverwrite=<blob>` passt zum
|
||||
aktuellen `blob`: neuen Commit auf `head` bauen und pushen. Andere
|
||||
Dateien im Repo dürfen sich geändert haben, das ist kein Konflikt.
|
||||
4. Push wegen Non-Fast-Forward abgelehnt: zurück zu Schritt 2, höchstens
|
||||
3 Versuche, dann 503 `G05`.
|
||||
5. `blob !== last_blob_sha` ohne passendes `gitOverwrite`: **Konflikt**,
|
||||
Antwort `409 { HBErrorCode: 'G01', remoteCommitSha, remoteBlobSha }`.
|
||||
Weder Git noch DB werden geändert.
|
||||
6. Nach erfolgreichem Push setzt der Hook `ctx.git = { commit, blob }`.
|
||||
Upstream speichert die DB wie gewohnt. Danach aktualisiert
|
||||
`gitHooks.afterBrewSave(ctx)` den Link (`last_commit_sha`,
|
||||
`last_blob_sha`, `last_synced_at`, `last_error = null`).
|
||||
7. Fehler bei Auth/Netz (401/403 → `G02`, 404 Repo/Branch → `G03`, Timeout →
|
||||
`G04`): Antwort 502/504 mit Code. Die DB wird nicht geändert, der Client
|
||||
behält seinen ungespeicherten Stand (Upstream-Verhalten bei Save-Fehlern).
|
||||
|
||||
Schlägt der DB-Save nach erfolgreichem Push fehl, ist Git dem Snapshot
|
||||
voraus. Beim nächsten Öffnen erkennt der Abgleich (unten) einen fremden Blob
|
||||
und übernimmt ihn. Der Zustand heilt sich also selbst.
|
||||
|
||||
**Konfliktdialog** (Client, `G01`): drei Optionen.
|
||||
|
||||
- „Remote-Version laden“: `POST …/pull`, dann Seite neu laden. Eigene
|
||||
Änderungen gehen verloren, vorher wird angeboten, sie über den
|
||||
Upstream-Download zu sichern.
|
||||
- „Meine Version behalten“: erneuter Save mit `?gitOverwrite=<remoteBlobSha>`.
|
||||
Das erzeugt einen normalen Commit auf dem neuen Stand, kein Force-Push, die
|
||||
Remote-Änderung bleibt in der Historie.
|
||||
- „Abbrechen“.
|
||||
|
||||
Ein automatischer Drei-Wege-Merge (mit `@sanity/diff-match-patch`, schon
|
||||
Abhängigkeit) ist ausdrücklich **nicht** Teil von M3.
|
||||
|
||||
**Abgleich beim Öffnen:** Fork-Middleware auf `GET /edit/:id`, registriert vor
|
||||
`pageRoutes`. Sie bestimmt die `editId` über `api.getId(req)` (die ID kann ein
|
||||
Google-Präfix tragen) und liest Remote `blob`. Weicht er von `last_blob_sha` ab,
|
||||
übernimmt sie den Remote-Stand in den Snapshot (Metadaten über
|
||||
`splitTextStyleAndMetadata`, `version + 1`, Link aktualisieren) und ruft dann
|
||||
`next()` auf. Die Upstream-Route lädt den aktualisierten Brew. Ist Git nicht
|
||||
erreichbar, öffnet sich der Snapshot, `last_error` wird gesetzt, und die
|
||||
Git-Statusanzeige warnt. Gerade dann soll der Nutzer trotzdem lesen können.
|
||||
|
||||
Damit ein langsamer Git-Server das Öffnen nicht blockiert, hat dieser Pfad
|
||||
ein **eigenes Zeitbudget** `HB_GIT_OPEN_TIMEOUT_MS` (Standard `4000`, erlaubt
|
||||
`1000`–`HB_GIT_TIMEOUT_MS`):
|
||||
|
||||
- Das Budget gilt für den **ganzen** Abgleich: Warten in der
|
||||
Concurrency-Queue, `fetch`, `rev-parse` und gegebenenfalls `cat-file`.
|
||||
`gitClient.js` bekommt dafür einen `AbortSignal` und beendet laufende
|
||||
`git`-Prozesse bei Abbruch mit `SIGKILL`. Danach wird das temporäre
|
||||
Bare-Repo gelöscht.
|
||||
- Bei Überschreitung ändert die Middleware weder Snapshot noch
|
||||
`last_blob_sha`. Sie setzt `last_error = 'G04'`, loggt eine Warnung und
|
||||
ruft `next()` auf. Der Editor öffnet den Snapshot, die Git-Statusanzeige
|
||||
zeigt „Git nicht erreichbar, angezeigt wird der zuletzt gespeicherte
|
||||
Stand“ mit dem Button „Pull“.
|
||||
- Das ist ungefährlich: Der nächste Save liest Remote mit dem normalen
|
||||
`HB_GIT_TIMEOUT_MS`. Hat sich die Datei inzwischen geändert, greift der
|
||||
Konflikt `G01` (Schritt 5). Ein Remote-Stand geht also nicht verloren.
|
||||
- Der Abgleich beim Öffnen wird nicht wiederholt (kein Retry innerhalb des
|
||||
Budgets), und der Mutex pro Brew wird mit demselben Budget angefordert.
|
||||
|
||||
**Pull und offene Editor-Tabs:** `POST …/pull` und der Abgleich beim Öffnen
|
||||
erhöhen `version`. Ein zweiter, schon offener Editor-Tab desselben Brews
|
||||
läuft beim nächsten Save in die Upstream-Versionsprüfung (`409`, Hinweis zum
|
||||
Neuladen). Das ist gewolltes Upstream-Verhalten, der Fork ändert daran
|
||||
nichts.
|
||||
|
||||
**Löschen (F9, Umsetzung #20):** Der Fork greift in `deleteBrew` (Upstream)
|
||||
nur ein, wenn Upstream den Brew wirklich löscht, also wenn `authors` nach dem
|
||||
Entfernen des Aufrufers leer ist (letzter Autor oder Brew ohne Autoren).
|
||||
Dann gilt unter dem Brew-Mutex wie beim Speichern:
|
||||
|
||||
1. Die verknüpfte Datei wird per Commit aus dem Repo entfernt (Nachricht
|
||||
`Delete <pfad> via Homebrewery`, Autor wie beim Speichern, Token des
|
||||
Verbindungsbesitzers). Basis der Konfliktprüfung ist `last_blob_sha`.
|
||||
Weicht der Stand im Repo davon ab, gibt es `G01` und es wird nichts
|
||||
gelöscht. Nach „Pull“ oder erneutem Öffnen kann der Nutzer es noch einmal
|
||||
versuchen.
|
||||
2. Danach löscht Upstream DB-Brew, Link und Assets (Repository-Kaskade).
|
||||
|
||||
- Schlägt der Commit fehl (Git nicht erreichbar, Token ungültig, Konflikt),
|
||||
wird nichts gelöscht und der Nutzer sieht den Fehler.
|
||||
- Fehlen die Datei oder der Branch im Repo schon, wird ohne Commit gelöscht.
|
||||
- Klappt der Commit, aber das Löschen in der DB nicht, bleibt der Brew ohne
|
||||
Datei stehen. Beim nächsten Öffnen meldet der Abgleich `G03`.
|
||||
- Bilder des Brews (ADR 0004) bleiben vorerst im Repo, weil andere Brews
|
||||
sie referenzieren können.
|
||||
- Bleiben andere Autoren übrig, entfernt Upstream nur den Eintrag des
|
||||
Aufrufers und die Datei bleibt stehen. Ist der Aufrufer der
|
||||
Verbindungsbesitzer (`req.account.uid = git_connections.owner_user_id`),
|
||||
wird zusätzlich die Verknüpfung gelöst (Datei bleibt). Sonst würden die
|
||||
übrigen Autoren weiter mit dem Token von jemandem committen, der kein
|
||||
Autor mehr ist. Upstream macht es bei Google Drive genauso
|
||||
(`shouldDeleteGoogleBrew`).
|
||||
- Umsetzung: Hooks `beforeBrewDelete`/`afterBrewDelete` (`server/fork/git/hooks.js`),
|
||||
Einhängepunkt in `deleteBrew` (`// [fork] ADR-0003`). Der Delete-Commit entfernt
|
||||
den Eintrag über `update-index --index-info` (Modus 0), weil das Bare-Repo
|
||||
keine Arbeitskopie hat.
|
||||
|
||||
### 6. Teilen per Snapshot (#9)
|
||||
|
||||
- Ausgeliefert wird der DB-Brew, also der zuletzt **über die App
|
||||
gespeicherte** oder beim Öffnen bzw. per Pull übernommene Stand. Die
|
||||
Share-Routen machen keinen Git-Zugriff und brauchen kein Token.
|
||||
- Commits, die außerhalb der App gemacht werden, erscheinen im Share-Link
|
||||
erst, wenn der Brew im Editor geöffnet oder `pull` ausgelöst wird.
|
||||
- Bilder: siehe ADR 0004. Auch dort gilt der Snapshot.
|
||||
- #9 besteht damit aus Tests (Share, Fetch, CSS, Metadaten, Download für
|
||||
Git-Brews ohne Git-Zugriff, Git per Mock unerreichbar) und dem
|
||||
Pull-Button in der Git-Statusanzeige.
|
||||
|
||||
### 7. Client
|
||||
|
||||
Neue Dateien unter `client/fork/git/`:
|
||||
|
||||
- `GitConnectionsPanel.jsx`: Verbindungen anlegen, testen
|
||||
(`POST /api/git/connections/:id/test` → `ls-remote --heads`), bearbeiten,
|
||||
löschen. Das Token-Feld ist nur ein Eingabefeld und wird nie vorbefüllt.
|
||||
- `GitNavItem.jsx`: im Editor-Navbar Status (Branch, Pfad, kurzer SHA,
|
||||
Fehler), Pull, Verknüpfen/Lösen, „Neu in Git“.
|
||||
- `GitErrorNavItem.jsx`: Konfliktdialog und Fehlertexte für `G01`–`G07`.
|
||||
|
||||
Verbindungs-API: `GET/POST /api/git/connections`,
|
||||
`PATCH/DELETE /api/git/connections/:id`, `POST …/:id/test`,
|
||||
`GET …/:id/branches`, `GET …/:id/files?branch=&dir=` (für den Import:
|
||||
`ls-tree` mit Filter auf `*.md`). Alle `/api/git/*`-Routen nutzen
|
||||
`checkClientVersion` und verlangen Login.
|
||||
|
||||
### Konfiguration
|
||||
|
||||
| Variable | Standard | Bedeutung |
|
||||
| --- | --- | --- |
|
||||
| `HB_GIT_TOKEN_KEY` | – | aktiviert das Feature, 32 Byte base64 |
|
||||
| `HB_GIT_TOKEN_KEYS_OLD` | – | alte Schlüssel zum Entschlüsseln |
|
||||
| `HB_GIT_ALLOWED_HOSTS` | – | Host-Allowlist |
|
||||
| `HB_GIT_ALLOW_PRIVATE` | `false` | private Ziele erlauben |
|
||||
| `HB_GIT_ALLOW_HTTP` | `false` | nur für Entwicklung |
|
||||
| `HB_GIT_WORKDIR` | `os.tmpdir()/hb-git` | temporäre Bare-Repos |
|
||||
| `HB_GIT_TIMEOUT_MS` | `20000` | pro `git`-Aufruf |
|
||||
| `HB_GIT_OPEN_TIMEOUT_MS` | `4000` | Gesamtbudget für den Abgleich beim Öffnen von `GET /edit/:id` |
|
||||
| `HB_GIT_MAX_FILE_BYTES` | `5242880` | Brew-Datei |
|
||||
| `HB_GIT_MAX_CONCURRENCY` | `2` | gleichzeitige Operationen |
|
||||
| `HB_GIT_COMMITTER_NAME` / `_EMAIL` | `Homebrewery` / `homebrewery@<host>` | |
|
||||
|
||||
### Tests
|
||||
|
||||
- Unit: `crypto.js` (Roundtrip, falsche AAD, Rotation), `urlPolicy.js`
|
||||
(alle Adressklassen), Pfad- und Branch-Validierung, `redact`.
|
||||
- Integration ohne Netz: Die Jest-Suite startet ein lokales Remote, nämlich
|
||||
`git http-backend` hinter einem kleinen Node-HTTP-Server mit Basic-Auth-Prüfung
|
||||
(`tests/fork/git-http-test-server.js`, Remote mit
|
||||
`uploadpack.allowFilter=true` und `http.receivepack=true`). Fälle: Lesen,
|
||||
Commit, Root-Commit, fremder Commit auf anderer Datei (kein Konflikt),
|
||||
fremder Commit auf gleicher Datei (`G01`), `gitOverwrite`, Push-Rennen,
|
||||
falscher Token (`G02`), Abgleich beim Öffnen mit hängendem Server
|
||||
(Test-Server antwortet nicht: Editor-Seite kommt nach höchstens
|
||||
`HB_GIT_OPEN_TIMEOUT_MS` + 500 ms mit dem Snapshot, `last_error = 'G04'`,
|
||||
kein `git`-Prozess bleibt übrig). Die Policy wird dafür mit `HB_GIT_ALLOW_HTTP` und
|
||||
`HB_GIT_ALLOW_PRIVATE` gelockert.
|
||||
- Besitz (API, supertest): Verwaltungsrouten mit naturalcrit-Session → 403
|
||||
`G07`, Status und Pull mit Bearbeitungsrecht → 200. Ein Rename über
|
||||
`PUT /api/user/rename` mit naturalcrit-Session lässt `git_connections` und
|
||||
`brew_git_links` unverändert (Contract-Fälle dazu siehe ADR 0002,
|
||||
Abschnitt 5).
|
||||
- Manuell bzw. in CI optional: gegen die Gitea-Instanz aus dem Compose-Setup (#3).
|
||||
|
||||
## Betroffene Upstream-Dateien
|
||||
|
||||
| Datei | Änderung |
|
||||
| --- | --- |
|
||||
| `server/app.js` | `app.use(forkGit.createRouter(…))` neben dem Auth-Router (ADR 0001); enthält `/api/git/*` und die Middleware für `GET /edit/:id` |
|
||||
| `server/homebrew.api.js` | in `updateBrew`: `beforeBrewSave` vor dem Google-Block, `afterBrewSave` nach dem DB-Save (je 1–3 Zeilen) |
|
||||
| `client/homebrew/pages/basePages/editPage/editorPage.jsx` | `<GitNavItem>` im Navbar, eine Zeile |
|
||||
| `client/homebrew/navbar/error-navitem.jsx` | Codes mit `G` an `GitErrorNavItem` weiterreichen, vor der 409-Behandlung |
|
||||
| `client/homebrew/pages/accountPage/accountPage.jsx` | `<GitConnectionsPanel>` einhängen |
|
||||
|
||||
## Alternativen
|
||||
|
||||
| Alternative | Warum verworfen |
|
||||
| --- | --- |
|
||||
| Anbieter-REST-APIs (GitHub Contents API, Gitea/GitLab-Pendants) | Nicht providerneutral, drei Implementierungen. Die Vorgabe ist Git über HTTPS |
|
||||
| `isomorphic-git` (reines JS) | Kein Partial-Clone (`--filter`), lädt bei großen Repos (Bilder, ADR 0004) alle Blobs des Kopf-Commits in den Speicher. `git` ist im Image schon vorhanden |
|
||||
| Dauerhafte Arbeitskopie pro Verbindung | Schneller bei vielen Saves, aber Plattenplatz, Aufräumen, Sperren, verwaiste Zustände. Optimierung später möglich (Cache-Bare-Repo pro `repo_url`) |
|
||||
| Token in der Remote-URL (`https://user:token@host/…`) | Landet in Prozessliste, Fehlermeldungen und ggf. `FETCH_HEAD` |
|
||||
| Snapshot nur bei „Teilen“ erzeugen, sonst nur Git | Share würde vom Zeitpunkt des Teilens abhängen, und Theme-Bundles, Vault und Metadaten bräuchten Git-Zugriff |
|
||||
| Share liest live aus Git (mit Cache) | Widerspricht der Vorgabe „zuletzt gespeicherter Stand“. Externe Ausfälle würden Share-Links brechen |
|
||||
| `owner` als Benutzername, beim Rename mitgezogen | Die Upstream-Route `/api/user/rename` prüft den alten Namen nicht. Mitziehen würde fremde Verbindungen samt PAT an jeden angemeldeten Benutzer geben |
|
||||
| Git-Backend auch für naturalcrit-Konten, Besitz über den Namen | Nach einem Rename verliert der Besitzer seine Verbindungen, und es gibt keinen sicheren Weg, sie ihm wieder zuzuordnen |
|
||||
| Force-Push bei „Meine Version behalten“ | Zerstört fremde Commits |
|
||||
| Commits zusammenfassen per Amend + Force-Push | Siehe oben. Gefährlich bei geteilten Branches |
|
||||
|
||||
## Folgen
|
||||
|
||||
- Positiv: Teilen, Theme-Bundles, Vault und Download funktionieren für
|
||||
Git-Brews ohne Mehraufwand. Git-Ausfälle betreffen nur das Speichern.
|
||||
- Positiv: Kein Token verlässt den Server, keiner liegt im Klartext in der DB.
|
||||
- Negativ: Jeder Speichervorgang ist ein Commit. Mit Autosave (10 s) entstehen
|
||||
viele kleine Commits. Deshalb Autosave für Git-Brews auf 60 s (F6).
|
||||
- Negativ: Speichern dauert je nach Git-Server 1–3 s länger. Der Autosave
|
||||
merkt davon nichts, beim manuellen Speichern ist es spürbar.
|
||||
- Negativ: Mitautoren speichern mit dem Token des Verbindungsbesitzers.
|
||||
- Negativ: Verbindungen anlegen und Brews verknüpfen können nur OIDC-Konten.
|
||||
naturalcrit-Konten können verknüpfte Brews nur mitbearbeiten (F13).
|
||||
- Negativ: Ist Git beim Öffnen langsamer als `HB_GIT_OPEN_TIMEOUT_MS`, sieht
|
||||
der Nutzer zunächst den Snapshot und muss externe Änderungen per Pull
|
||||
holen.
|
||||
- Negativ: Nur ein App-Prozess (prozesslokaler Mutex). Mehrere Replikate
|
||||
bräuchten eine DB-Sperre.
|
||||
|
||||
## Entscheidungen (Florian, 2026-11-25)
|
||||
|
||||
- **F6 – Commit-Häufigkeit:** Jeder Save ist ein Commit. Für Git-Brews wird
|
||||
der Autosave auf 60 s gestellt.
|
||||
- **F7 – Erlaubte Git-Hosts:** Der Code erlaubt standardmäßig alle
|
||||
öffentlichen Hosts. Das eigene Compose-Setup setzt eine Allowlist über
|
||||
`HB_GIT_ALLOWED_HOSTS`.
|
||||
- **F8 – Externe Commits im Share-Link:** Es reicht, dass sie nach dem Öffnen
|
||||
im Editor bzw. nach „Pull“ sichtbar werden.
|
||||
- **F9 – Löschen:** **Abweichend vom Vorschlag:** Beim Löschen eines Git-Brews
|
||||
in der App wird die Datei im Repo per Commit mitgelöscht (siehe Abschnitt 5,
|
||||
„Löschen“). Nur „Verknüpfung lösen“ lässt die Datei im Repo.
|
||||
- **F13 – Git nur für OIDC-Konten:** Ja. Verbindungen hängen an `users.id`.
|
||||
naturalcrit-Konten können verknüpfte Brews nur mitbearbeiten.
|
||||
@@ -0,0 +1,175 @@
|
||||
# ADR 0004: Bild-Ablage im verbundenen Git-Repo
|
||||
|
||||
- Status: Angenommen (Entscheidungen Florian 2026-11-25, siehe Ende)
|
||||
- Datum: 2026-11-23
|
||||
- Umsetzung: M4, Issue #10
|
||||
- Abhängig von: ADR 0002 (Repositories), ADR 0003 (Git-Zugriff, Snapshot)
|
||||
- Basis: Analyse auf Upstream `73df298c`, gegen `6d219487` geprüft (seitdem nur `splitPane.jsx` und `listPage.jsx` geändert, beide hier nicht betroffen)
|
||||
|
||||
## Kontext
|
||||
|
||||
- Upstream hat **keinen Bild-Upload**. Bilder werden per externer URL in
|
||||
Markdown eingebunden (``). Selbst gehostet gibt es nur
|
||||
`/staticImages` aus einem Server-Verzeichnis (`hb_images` in `server/app.js`),
|
||||
ohne Upload.
|
||||
- Der Renderer läuft im Browser (`client/homebrew/brewRenderer/`), die Bilder
|
||||
lädt der Browser direkt. Relative Pfade im Markdown würden relativ zur
|
||||
Seiten-URL (`/share/<id>`) aufgelöst und zeigen deshalb nicht auf Dateien
|
||||
im Repo.
|
||||
- Vorgaben: Bilder landen im verbundenen Repo (z. B. `assets/`). Leser brauchen
|
||||
keinen Repo-Zugriff (Snapshot-Prinzip aus ADR 0003). Die App liefert die
|
||||
Bilder aus.
|
||||
|
||||
## Entscheidung
|
||||
|
||||
### 1. Geltungsbereich
|
||||
|
||||
Upload gibt es nur für **Git-verknüpfte Brews** (ADR 0003). Reine DB-Brews
|
||||
bekommen keinen Upload, ohne Repo gibt es keinen Ablageort. Die Funktion ist
|
||||
aktiv, wenn das Git-Backend aktiv ist (`HB_GIT_TOKEN_KEY` gesetzt) und
|
||||
`HB_ASSETS_ENABLED` nicht `false` ist.
|
||||
|
||||
### 2. Upload
|
||||
|
||||
`POST /api/git/brews/:editId/assets`
|
||||
|
||||
- Rechte: wie Speichern (Upstream-Regeln für `edit`), dazu `checkClientVersion`.
|
||||
Gesperrte Brews (`lock`) sind nicht erlaubt (423).
|
||||
- Body: **Rohdaten** (`express.raw`, Limit `HB_ASSET_MAX_BYTES`), Header
|
||||
`Content-Type` (Bild-MIME) und `X-HB-Filename` (Originalname,
|
||||
URL-kodiert). Kein Multipart, also keine neue Abhängigkeit wie `multer`.
|
||||
- Prüfungen in dieser Reihenfolge:
|
||||
1. Größe ≤ `HB_ASSET_MAX_BYTES` (Standard 5 MiB), sonst 413.
|
||||
2. Typ über **Magic Bytes** bestimmen, nicht über den Header. Erlaubt sind
|
||||
PNG, JPEG, GIF und WebP (`HB_ASSET_TYPES`, Standard
|
||||
`png,jpeg,gif,webp`). Die Prüfung ist eine eigene kleine Funktion in
|
||||
`server/fork/assets/sniff.js`. Weicht der Typ vom Header ab oder ist er
|
||||
nicht erlaubt: 415. **SVG ist ausgeschlossen**, weil es Skripte
|
||||
enthalten kann.
|
||||
3. Summe aller Assets des Brews + neue Datei ≤ `HB_ASSET_MAX_BYTES_PER_BREW`
|
||||
(Standard 50 MiB), sonst 413.
|
||||
- `sha256` über den Inhalt berechnen. Gibt es für diesen Brew schon ein Asset
|
||||
mit gleichem Hash, kommt das bestehende Asset mit 200 zurück, ohne Commit.
|
||||
- Repo-Pfad: `<assets_dir>/<slug(basename)>-<sha256[0..11]>.<ext>`.
|
||||
`assets_dir` kommt aus der Verbindung (Standard `assets`), `slug` bedeutet
|
||||
Kleinbuchstaben, `[a-z0-9-]`, max. 60 Zeichen, sonst `image`. `ext` folgt
|
||||
aus dem erkannten Typ. Inhaltsadressierte Pfade kollidieren praktisch
|
||||
nicht. Existiert die Datei auf dem Branch schon mit gleichem Blob, gibt es
|
||||
keinen Commit.
|
||||
- Commit wie in ADR 0003 Abschnitt 4 (`hash-object`, `update-index`,
|
||||
`commit-tree`, Push, Retry bei Non-Fast-Forward). Nachricht
|
||||
`Add asset <path> via Homebrewery`. Ein Asset-Upload ändert nicht
|
||||
`last_blob_sha` des Brews, Brew-Saves sehen ihn nicht als Konflikt.
|
||||
- Erst nach erfolgreichem Push wird der Snapshot-Datensatz gespeichert
|
||||
(Abschnitt 3). Antwort `201 { url, path, sha256, size, contentType }`.
|
||||
|
||||
### 3. Asset-Snapshot in der DB
|
||||
|
||||
Tabelle bzw. Collection **`brew_assets`**:
|
||||
|
||||
| Spalte | Typ | Regel |
|
||||
| --- | --- | --- |
|
||||
| `id` | uuid | |
|
||||
| `brew_id` | uuid | FK `brews(id) ON DELETE CASCADE` |
|
||||
| `sha256` | text | 64 Hex-Zeichen, eindeutig zusammen mit `brew_id` |
|
||||
| `repo_path` | text | Pfad im Repo |
|
||||
| `commit_sha` | text | Commit des Uploads |
|
||||
| `content_type` | text | aus Magic Bytes |
|
||||
| `size` | integer | Bytes |
|
||||
| `data` | bytea / Buffer | Inhalt |
|
||||
| `created_at` | timestamptz | |
|
||||
|
||||
Die Bilddaten liegen **zusätzlich** in der DB. Nur so kann die App sie ohne
|
||||
Git-Zugriff und ohne Token ausliefern, auch wenn das Repo nicht erreichbar
|
||||
ist (Snapshot-Prinzip). Mongo-Dokumentgröße: 5 MiB pro Asset liegt weit unter
|
||||
dem Limit von 16 MiB. Wer `HB_ASSET_MAX_BYTES` über 15 MiB setzt, bekommt
|
||||
unter Mongo einen Startfehler.
|
||||
|
||||
### 4. Auslieferung
|
||||
|
||||
`GET /git-assets/:shareId/:sha256.:ext`, eigener Router `server/fork/assets/delivery.js`,
|
||||
in `server/app.js` **vor** der Content-Negotiation-Middleware eingehängt
|
||||
(siehe „Betroffene Upstream-Dateien“). Er braucht weder Cookies noch Login.
|
||||
|
||||
- Asset über `shareId` → Brew → (`brew_id`, `sha256`) suchen. Fehlt es, folgt 404.
|
||||
Stimmt `ext` nicht zum `content_type`, ebenfalls 404.
|
||||
- Für gesperrte Brews (`lock`) gilt dasselbe wie für `/share` (Upstream-Fehler `51`).
|
||||
- Header: `Content-Type` aus der DB, `Content-Length`,
|
||||
`Cache-Control: public, max-age=31536000, immutable` (die URL ist
|
||||
inhaltsadressiert), `ETag: "<sha256>"`, `X-Content-Type-Options: nosniff`,
|
||||
`Content-Security-Policy: default-src 'none'; sandbox`,
|
||||
`Cross-Origin-Resource-Policy: same-site`.
|
||||
- Kein Login nötig, wie beim Share-Link. Wer die `shareId` kennt, sieht den
|
||||
Brew samt Bildern.
|
||||
|
||||
Im Markdown fügt der Client ``
|
||||
an der Cursor-Position ein. Der Pfad ist absolut zur App, damit Editor,
|
||||
Share-Seite, Druck und PDF ohne Renderer-Änderung funktionieren.
|
||||
|
||||
### 5. Client
|
||||
|
||||
- `client/fork/assets/AssetUploadButton.jsx`: Button im Editor (Snippet-Bar)
|
||||
mit Dateiauswahl. Dazu Drag-and-drop und Einfügen aus der Zwischenablage im
|
||||
Code-Editor. Sichtbar nur bei Git-verknüpften Brews. Fortschritt und
|
||||
Fehlertexte (413, 415, Git-Fehler `G02`–`G05`) erscheinen direkt am Button.
|
||||
- Eine Asset-Liste (Bilder des Brews mit „Einfügen“) ist optional. Ein
|
||||
Lösch-Button ist nicht Teil von M4 (siehe Folgen).
|
||||
|
||||
### Konfiguration
|
||||
|
||||
| Variable | Standard | Bedeutung |
|
||||
| --- | --- | --- |
|
||||
| `HB_ASSETS_ENABLED` | `true` (wenn Git aktiv) | Upload ein/aus |
|
||||
| `HB_ASSET_MAX_BYTES` | `5242880` (5 MiB) | pro Datei |
|
||||
| `HB_ASSET_MAX_BYTES_PER_BREW` | `52428800` (50 MiB) | Summe pro Brew |
|
||||
| `HB_ASSET_TYPES` | `png,jpeg,gif,webp` | erlaubte Typen (SVG nicht wählbar) |
|
||||
|
||||
### Tests
|
||||
|
||||
- Unit: `sniff.js` (je Typ ein Minimalbild, falscher Header, SVG, Datei
|
||||
abgeschnitten), Pfadbildung, Limits, Dedupe.
|
||||
- Integration mit dem lokalen Git-Remote aus ADR 0003: Upload → Commit im
|
||||
Remote vorhanden, Auslieferung mit korrekten Headern, Auslieferung bei
|
||||
nicht erreichbarem Remote (Snapshot), Brew löschen entfernt die Assets,
|
||||
Upload auf Nicht-Git-Brew ergibt 400.
|
||||
|
||||
## Betroffene Upstream-Dateien
|
||||
|
||||
| Datei | Änderung |
|
||||
| --- | --- |
|
||||
| `server/app.js` | `app.use(forkAssets.deliveryRouter(…))` **vor** `app.use(contentNegotiation)`, eine Zeile. Grund: `server/middleware/content-negotiation.js` beantwortet reine Bild-Requests (`Accept: image/*`, so fragt der Browser bei `<img>` an) außerhalb von `/staticImages` mit 406. Die Upload-Route hängt im Fork-Git-Router (ADR 0003). `bodyParser.json` greift nur bei JSON-Content-Type, die Bilddaten kommen also unverändert bei `express.raw` an |
|
||||
| `client/homebrew/editor/snippetbar/snippetbar.jsx` | `<AssetUploadButton>` einhängen, eine Zeile |
|
||||
| `client/homebrew/editor/editor.jsx` | Drop/Paste-Handler aus `client/fork/assets/` an den Code-Editor übergeben, 1–2 Zeilen |
|
||||
|
||||
## Alternativen
|
||||
|
||||
| Alternative | Warum verworfen |
|
||||
| --- | --- |
|
||||
| Bilder bei jeder Anfrage live aus Git lesen | Braucht für jede Anfrage das Token des Besitzers und einen Git-Fetch. Langsam und abhängig von der Erreichbarkeit des Repos, widerspricht dem Snapshot-Prinzip |
|
||||
| Datei-Cache auf einem Volume statt in der DB | Weiteres Volume, Backup und Konsistenz mit der DB getrennt. Die DB wächst bei 5 MiB pro Datei moderat. Ein Cache lässt sich später nachrüsten |
|
||||
| Relative Repo-Pfade im Markdown (`assets/x.png`) mit Umschreiben im Renderer | Repo-portabler (Vorschau in Gitea/GitHub), braucht aber Änderungen im Upstream-Renderer und im Druckpfad. Siehe Entscheidung F10 |
|
||||
| Raw-URL des Git-Anbieters (`https://host/…/raw/…`) einbetten | Nicht providerneutral, und private Repos sind für Leser nicht erreichbar |
|
||||
| Multipart mit `multer`/`busboy` | Weitere Abhängigkeit, und für eine Datei pro Request unnötig |
|
||||
| SVG erlauben | XSS-Risiko. Sicher nur mit Sanitizer oder Auslieferung als Download |
|
||||
| EXIF-Daten entfernen (`sharp`) | Native Abhängigkeit, Speicherbedarf. Siehe Folgen |
|
||||
|
||||
## Folgen
|
||||
|
||||
- Positiv: Bilder sind versioniert im Repo des Nutzers, werden ohne Repo-Zugriff
|
||||
ausgeliefert und lange gecacht.
|
||||
- Negativ: Bilder liegen doppelt vor (Repo und DB). Die DB wächst mit, die
|
||||
Limits deckeln das pro Brew.
|
||||
- Negativ: Brew-Dateien im Repo verweisen auf App-URLs (`/git-assets/…`) und
|
||||
zeigen in der Repo-Vorschau keine Bilder.
|
||||
- Negativ: Hochgeladene Fotos behalten ihre EXIF-Metadaten (z. B. GPS) und
|
||||
sind über den Share-Link öffentlich. Die Upload-UI weist darauf hin.
|
||||
- Negativ: Gelöschte Bilder bleiben in Repo und DB, solange der Brew
|
||||
existiert. Löschen bzw. Aufräumen kommt später.
|
||||
|
||||
## Entscheidungen (Florian, 2026-11-25)
|
||||
|
||||
- **F10 – URL-Form im Markdown:** App-URL `/git-assets/<shareId>/<hash>.<ext>`,
|
||||
keine Änderung am Renderer.
|
||||
- **F11 – Limits:** 5 MiB pro Bild, 50 MiB pro Brew, erlaubt PNG/JPEG/GIF/WebP.
|
||||
- **F12 – EXIF:** Ein Hinweis in der Upload-UI reicht. Metadaten werden nicht
|
||||
entfernt.
|
||||
@@ -0,0 +1,37 @@
|
||||
# Architecture Decision Records
|
||||
|
||||
Architekturentscheidungen des Forks `homebrewery-oidc`. Jede ADR beschreibt
|
||||
Kontext, Entscheidung, verworfene Alternativen und Folgen und nennt die
|
||||
Upstream-Dateien, die angefasst werden müssen.
|
||||
|
||||
| Nr. | Titel | Status | Umsetzung |
|
||||
| --- | --- | --- | --- |
|
||||
| [0001](0001-auth-oidc.md) | Authentifizierung über generisches OIDC | Angenommen | M1 (#6) |
|
||||
| [0002](0002-storage-mongo-postgres.md) | Repository-Schicht, Mongo **oder** PostgreSQL pro Instanz | Angenommen | M2 (#7) |
|
||||
| [0003](0003-git-backend-und-teilen.md) | Git-Backend über HTTPS + PAT, Teilen per Server-Snapshot | Angenommen | M3 (#8, #9) |
|
||||
| [0004](0004-bild-ablage-im-git-repo.md) | Bild-Ablage im verbundenen Git-Repo | Angenommen | M4 (#10) |
|
||||
|
||||
## Gemeinsame Leitlinien (gelten für alle ADRs)
|
||||
|
||||
1. **Upstream-Sync zuerst.** Fork-Code liegt in eigenen Verzeichnissen
|
||||
(`server/fork/`, `server/storage/`, `client/fork/`). Upstream-Dateien
|
||||
bekommen nur kleine Einhängepunkte (Import + Aufruf, ein Konfigurationsfeld),
|
||||
die in jeder ADR unter „Betroffene Upstream-Dateien“ aufgelistet sind. Jede
|
||||
solche Stelle wird mit dem Kommentar `// [fork] <ADR-Nr>` markiert, damit
|
||||
sie bei Merges aus `upstream` sofort auffällt.
|
||||
2. **Konfiguration statt Umbau.** Alle Fork-Funktionen sind über Umgebungsvariablen
|
||||
mit Präfix `HB_` schaltbar (nconf liest sie über `server/config.js` klein
|
||||
geschrieben, also `config.get('hb_oidc_issuer')`). Ohne Fork-Konfiguration
|
||||
verhält sich die App wie Upstream.
|
||||
3. **Keine Secrets im Repo.** Client-Secrets, Session-Schlüssel und der
|
||||
Token-Schlüssel kommen ausschließlich aus der Umgebung (Compose: `.env`,
|
||||
nicht eingecheckt).
|
||||
4. **Ein App-Container pro Instanz.** Sperren (z. B. pro Brew beim Git-Commit)
|
||||
sind prozesslokal. Mehrere App-Replikate sind nicht vorgesehen.
|
||||
|
||||
## Entscheidungen
|
||||
|
||||
Florian hat die offenen Fragen F1–F14 am 2026-11-25 beantwortet. Die
|
||||
Antworten stehen am Ende jeder ADR unter „Entscheidungen“. Abweichend von den
|
||||
Empfehlungen gilt **F9**: Beim Löschen eines Git-Brews wird die Datei im Repo
|
||||
per Commit mitgelöscht (ADR 0003).
|
||||
@@ -0,0 +1,86 @@
|
||||
# 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`) |
|
||||
| `HB_NATURALCRIT_RENAME` | nein | `off` | `PUT /api/user/rename` für naturalcrit-Sitzungen: `off` gesperrt, `signed` nur mit Nachweis (s. u.) |
|
||||
|
||||
Die App startet nicht, wenn `oidc` aktiv ist und Pflichtwerte fehlen.
|
||||
|
||||
Betrieb mit dem veröffentlichten Image (eigene Compose-Datei): Alle Variablen müssen unter `environment:`/`env_file:` stehen, nach
|
||||
Änderungen `docker compose up -d` statt `restart`. Vorlage: [docs/deploy/README.md](../deploy/README.md).
|
||||
|
||||
## 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`).
|
||||
|
||||
## Umbenennen mit naturalcrit-Sitzung (`HB_NATURALCRIT_RENAME`)
|
||||
|
||||
`PUT /api/user/rename` schreibt die Brews von `username` auf `newUsername` um. Die Upstream-Route prüft nicht, ob der
|
||||
Aufrufer den alten Namen besitzt. Der Fork lässt die Route deshalb nur mit Nachweis durch (ADR 0001, Abschnitt 7):
|
||||
|
||||
| Einstellung | Wirkung |
|
||||
| --- | --- |
|
||||
| `off` (Standard) | gesperrt: 403, `HBErrorCode: A02` |
|
||||
| `signed` | erlaubt, wenn `newUsername` der eigenen Sitzung gehört und der Body `oldSession` enthält: ein mit `SECRET` (HS256) signiertes `nc_session`-Token mit `username` = altem Namen. Sonst 403, `HBErrorCode: A03` |
|
||||
|
||||
Ohne Anmeldung antwortet die Route immer mit 403. Mit `signed` startet die App außerhalb lokaler Umgebungen nicht,
|
||||
solange `SECRET` der Standardwert `secret` ist. Einschränkung: naturalcrit.com schickt `oldSession` nicht mit.
|
||||
Nach einer Namensänderung dort lassen sich die Brews daher nur durch den Betreiber in der Datenbank umschreiben.
|
||||
|
||||
## 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).
|
||||
@@ -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).
|
||||
@@ -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.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Betrieb mit dem veröffentlichten Image
|
||||
|
||||
Für den Betrieb ohne Repo-Checkout: [`compose.yaml`](compose.yaml) (App + PostgreSQL 18, OIDC, Git-Backend,
|
||||
Bild-Upload) und [`env.example`](env.example). Das Dev-Compose im Repo-Root (`docker-compose.yml` +
|
||||
`docker-compose.override.yml`) baut das Image selbst und ist nur für die Entwicklung gedacht.
|
||||
|
||||
## Image
|
||||
|
||||
| Registry | Image | Tags |
|
||||
| --- | --- | --- |
|
||||
| Gitea | `git.morlana.online/f.weber/homebrewery-oidc` | `main`, `vX.Y.Z`, `latest` (nur Release), `sha-<7>` |
|
||||
| Docker Hub | `<DOCKER_HUB_USER>/homebrewery-oidc` | nur `vX.Y.Z` und `latest` |
|
||||
|
||||
Details zu CI und Tags: [FORK.md](../../FORK.md#ci-and-container-image). Das Image enthält keine Konfiguration oder Secrets.
|
||||
|
||||
## Einrichten
|
||||
|
||||
```bash
|
||||
mkdir homebrewery && cd homebrewery
|
||||
# compose.yaml und env.example aus docs/deploy/ hierher kopieren
|
||||
cp env.example .env # Werte eintragen
|
||||
docker compose config -q # prüft Syntax und Pflichtvariablen
|
||||
docker compose up -d
|
||||
docker compose logs homebrewery | head
|
||||
```
|
||||
|
||||
Der Redirect-URI beim IdP ist `<HB_PUBLIC_URL>/auth/oidc/callback` ([docs/auth](../auth/README.md)). TLS und Reverse
|
||||
Proxy (nginx/Traefik vor Port 8000) sind nicht Teil der Vorlage; `HB_PUBLIC_URL` muss die extern erreichbare
|
||||
`https://`-URL sein. Der App-Container verbindet sich beim Start mit dem IdP (Discovery) und mit PostgreSQL (Version ≥ 18).
|
||||
|
||||
## Wichtig: Variablen müssen im Container ankommen
|
||||
|
||||
Der Container sieht **nur** Variablen unter `environment:` (oder aus `env_file:`). Ein Eintrag in `.env` allein reicht
|
||||
nicht, er füllt nur die `${…}`-Platzhalter in der Compose-Datei. Wer eine eigene Compose-Datei schreibt, muss jede
|
||||
`HB_*`-Variable (insbesondere `HB_GIT_TOKEN_KEY`) dort ausdrücklich durchreichen. Die Vorlage tut das für alle
|
||||
Variablen aus [docs/auth](../auth/README.md), [docs/git](../git/README.md) und [docs/storage](../storage/README.md).
|
||||
|
||||
Nach jeder Änderung `docker compose up -d` ausführen: `docker compose restart` startet denselben Container mit der
|
||||
alten Umgebung neu und übernimmt Änderungen **nicht**.
|
||||
|
||||
## Git-Backend nachträglich einschalten
|
||||
|
||||
Jederzeit möglich, kein Erststart nötig: `HB_GIT_TOKEN_KEY` in `.env` setzen, `docker compose up -d`. Prüfung und
|
||||
Fehlersuche: [docs/git](../git/README.md#fehlersuche--nachträglich-aktivieren).
|
||||
@@ -0,0 +1,71 @@
|
||||
# Betriebs-Vorlage: veröffentlichtes Image + PostgreSQL 18, OIDC-Login, Git-Backend, Bild-Upload.
|
||||
# Siehe docs/deploy/README.md. Start:
|
||||
# cp env.example .env # Werte eintragen (Secrets nie einchecken)
|
||||
# docker compose up -d # nach jeder Änderung an .env erneut `up -d` (nicht `restart`)
|
||||
#
|
||||
# WICHTIG: Der Container sieht nur Variablen, die unter `environment:` stehen (oder per `env_file:` geladen werden).
|
||||
# Eine Variable in .env allein reicht NICHT: .env füllt nur die ${…}-Platzhalter in dieser Datei.
|
||||
services:
|
||||
homebrewery:
|
||||
# Gitea-Registry: git.morlana.online/f.weber/homebrewery-oidc:<tag> (main, vX.Y.Z, latest)
|
||||
# Docker Hub (nur Release-Tags): <DOCKER_HUB_USER>/homebrewery-oidc:vX.Y.Z
|
||||
image: ${HB_IMAGE:-git.morlana.online/f.weber/homebrewery-oidc:latest}
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "${APP_PORT:-8000}:8000"
|
||||
environment:
|
||||
# Storage (docs/storage/)
|
||||
HB_DB_DRIVER: postgres
|
||||
HB_POSTGRES_URL: postgres://${POSTGRES_USER:-homebrewery}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD setzen}@postgres:5432/${POSTGRES_DB:-homebrewery}
|
||||
# Auth (docs/auth/)
|
||||
HB_AUTH_PROVIDERS: oidc
|
||||
HB_PUBLIC_URL: ${HB_PUBLIC_URL:?HB_PUBLIC_URL setzen}
|
||||
HB_SESSION_SECRET: ${HB_SESSION_SECRET:?HB_SESSION_SECRET setzen (openssl rand -base64 48)}
|
||||
HB_OIDC_ISSUER: ${HB_OIDC_ISSUER:?HB_OIDC_ISSUER setzen}
|
||||
HB_OIDC_CLIENT_ID: ${HB_OIDC_CLIENT_ID:?HB_OIDC_CLIENT_ID setzen}
|
||||
HB_OIDC_CLIENT_SECRET: ${HB_OIDC_CLIENT_SECRET:?HB_OIDC_CLIENT_SECRET setzen}
|
||||
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_TTL: ${HB_SESSION_TTL:-}
|
||||
# Git-Backend (docs/git/). Leer = deaktiviert. Erzeugen: openssl rand -base64 32
|
||||
HB_GIT_TOKEN_KEY: ${HB_GIT_TOKEN_KEY:-}
|
||||
HB_GIT_TOKEN_KEYS_OLD: ${HB_GIT_TOKEN_KEYS_OLD:-}
|
||||
HB_GIT_ALLOWED_HOSTS: ${HB_GIT_ALLOWED_HOSTS:-}
|
||||
HB_GIT_ALLOW_PRIVATE: ${HB_GIT_ALLOW_PRIVATE:-}
|
||||
HB_GIT_ALLOW_HTTP: ${HB_GIT_ALLOW_HTTP:-}
|
||||
HB_GIT_TIMEOUT_MS: ${HB_GIT_TIMEOUT_MS:-}
|
||||
HB_GIT_OPEN_TIMEOUT_MS: ${HB_GIT_OPEN_TIMEOUT_MS:-}
|
||||
HB_GIT_MAX_FILE_BYTES: ${HB_GIT_MAX_FILE_BYTES:-}
|
||||
HB_GIT_MAX_CONCURRENCY: ${HB_GIT_MAX_CONCURRENCY:-}
|
||||
HB_GIT_WORKDIR: ${HB_GIT_WORKDIR:-}
|
||||
HB_GIT_COMMITTER_NAME: ${HB_GIT_COMMITTER_NAME:-}
|
||||
HB_GIT_COMMITTER_EMAIL: ${HB_GIT_COMMITTER_EMAIL:-}
|
||||
# Bild-Upload (ADR 0004, nur mit aktivem Git-Backend)
|
||||
HB_ASSETS_ENABLED: ${HB_ASSETS_ENABLED:-}
|
||||
HB_ASSET_MAX_BYTES: ${HB_ASSET_MAX_BYTES:-}
|
||||
HB_ASSET_MAX_BYTES_PER_BREW: ${HB_ASSET_MAX_BYTES_PER_BREW:-}
|
||||
HB_ASSET_TYPES: ${HB_ASSET_TYPES:-}
|
||||
|
||||
postgres:
|
||||
image: postgres:18
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-homebrewery}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-homebrewery}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD setzen}
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql # PostgreSQL 18: Daten liegen unter /var/lib/postgresql/18/…
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
@@ -0,0 +1,17 @@
|
||||
# Kopieren nach .env (neben compose.yaml). Keine Secrets einchecken.
|
||||
# HB_IMAGE=git.morlana.online/f.weber/homebrewery-oidc:v1.0.0
|
||||
APP_PORT=8000
|
||||
# Nur URL-sichere Zeichen (A-Z a-z 0-9 - _ . ~), da das Passwort in der Postgres-URL steht (z. B. openssl rand -hex 24)
|
||||
POSTGRES_PASSWORD=bitte-aendern
|
||||
|
||||
HB_PUBLIC_URL=https://brew.example.org
|
||||
# openssl rand -base64 48
|
||||
HB_SESSION_SECRET=bitte-aendern-mindestens-32-byte-zufall-0123456789
|
||||
HB_OIDC_ISSUER=https://auth.example.org/application/o/homebrewery/
|
||||
HB_OIDC_CLIENT_ID=homebrewery
|
||||
HB_OIDC_CLIENT_SECRET=bitte-aendern
|
||||
|
||||
# Git-Backend: leer = aus. Erzeugen: openssl rand -base64 32 (genau 32 Byte, sonst Startabbruch; Schlüssel sichern!)
|
||||
HB_GIT_TOKEN_KEY=
|
||||
# Optional: Allowlist erlaubter Git-Hosts (leer = alle öffentlichen Hosts erlaubt)
|
||||
# HB_GIT_ALLOWED_HOSTS=git.example.org
|
||||
@@ -0,0 +1,130 @@
|
||||
# homebrewery-oidc
|
||||
|
||||
[Homebrewery](https://github.com/naturalcrit/homebrewery) fork for self-hosting: **OIDC login** (Keycloak, authentik, any OpenID Connect provider), **PostgreSQL 18** (or MongoDB) storage, a **Git backend** (brews live in your own Git repositories) and **image upload** into those repositories.
|
||||
|
||||
- Source, issues, docs: [repository](https://git.morlana.online/f.weber/homebrewery-oidc), [README](https://git.morlana.online/f.weber/homebrewery-oidc/src/branch/main/README.md)
|
||||
- Fork overview and CI/tag details: [FORK.md](https://git.morlana.online/f.weber/homebrewery-oidc/src/branch/main/FORK.md)
|
||||
- Upstream: [naturalcrit/homebrewery](https://github.com/naturalcrit/homebrewery). License: MIT (see the [license file](https://git.morlana.online/f.weber/homebrewery-oidc/src/branch/main/license)).
|
||||
|
||||
The image contains no configuration or secrets. Everything is configured with environment variables at runtime. The app listens on port **8000**.
|
||||
|
||||
## Tags
|
||||
|
||||
| Tag | Meaning |
|
||||
| --- | --- |
|
||||
| `vX.Y.Z` | Release, e.g. `v1.0.0`. Pin this in production. |
|
||||
| `latest` | Newest release (never a pre-release or a development build). |
|
||||
|
||||
The same images are also published to the Gitea registry `git.morlana.online/f.weber/homebrewery-oidc` (additionally with `main` and `sha-<7>` development tags).
|
||||
|
||||
## Quick start (Docker Compose, PostgreSQL 18)
|
||||
|
||||
1. Create a directory and download the two template files:
|
||||
|
||||
```bash
|
||||
mkdir homebrewery && cd homebrewery
|
||||
curl -fsSLO https://git.morlana.online/f.weber/homebrewery-oidc/raw/branch/main/docs/deploy/compose.yaml
|
||||
curl -fsSL https://git.morlana.online/f.weber/homebrewery-oidc/raw/branch/main/docs/deploy/env.example -o .env
|
||||
```
|
||||
|
||||
(Both files are also linked from the [deployment guide](https://git.morlana.online/f.weber/homebrewery-oidc/src/branch/main/docs/deploy/README.md); that guide is in German, this page is the English summary.)
|
||||
|
||||
2. Edit `.env`. Required: `POSTGRES_PASSWORD`, `HB_PUBLIC_URL`, `HB_SESSION_SECRET`, `HB_OIDC_ISSUER`, `HB_OIDC_CLIENT_ID`, `HB_OIDC_CLIENT_SECRET`.
|
||||
Set `HB_IMAGE` to pin a release, e.g. `HB_IMAGE=<DOCKER_HUB_USER>/homebrewery-oidc:v1.0.0` (`docker pull <DOCKER_HUB_USER>/homebrewery-oidc:v1.0.0`). Without it the template uses the Gitea registry image `:latest`.
|
||||
Generate secrets with `openssl rand -base64 48` (session secret) and `openssl rand -hex 24` (database password: only URL-safe characters, it ends up in the Postgres URL).
|
||||
|
||||
3. Register the redirect URI `<HB_PUBLIC_URL>/auth/oidc/callback` at your identity provider (confidential client, `client_secret_basic`).
|
||||
|
||||
4. Start:
|
||||
|
||||
```bash
|
||||
docker compose config -q # validates syntax and required variables
|
||||
docker compose up -d
|
||||
docker compose logs homebrewery | head
|
||||
curl -I http://localhost:8000/ # HTTP 200 once started
|
||||
```
|
||||
|
||||
TLS and a reverse proxy (nginx, Traefik, Caddy in front of port 8000) are not part of the template. `HB_PUBLIC_URL` must be the externally reachable `https://` URL, without a trailing slash. On startup the app checks that the required OIDC values are present and well-formed and connects to PostgreSQL (version 18 or newer is required, otherwise it aborts with a clear message). The identity provider itself (OIDC discovery) is only contacted at the first login; if it is unreachable, login answers with 502 but the app keeps running. Database migrations run automatically.
|
||||
|
||||
**Important:** the container only sees variables listed under `environment:` (or loaded via `env_file:`). An entry in `.env` alone only fills the `${...}` placeholders of the Compose file. If you write your own Compose file, pass every `HB_*` variable explicitly, especially `HB_GIT_TOKEN_KEY`.
|
||||
|
||||
### MongoDB instead of PostgreSQL
|
||||
|
||||
Set `HB_DB_DRIVER=mongo` (the default when unset) and `MONGODB_URI=mongodb://mongodb:27017/homebrewery`, add a `mongo` service, and drop `HB_POSTGRES_URL`. Exactly one backend is active per instance; there is no data migration between them (single brews: download/import). Note that MongoDB 5+ needs a CPU with AVX.
|
||||
|
||||
## Configuration
|
||||
|
||||
All settings are environment variables. Full reference (German): [login](https://git.morlana.online/f.weber/homebrewery-oidc/src/branch/main/docs/auth/README.md), [database](https://git.morlana.online/f.weber/homebrewery-oidc/src/branch/main/docs/storage/README.md), [Git backend and image upload](https://git.morlana.online/f.weber/homebrewery-oidc/src/branch/main/docs/git/README.md).
|
||||
|
||||
### Storage
|
||||
|
||||
| Variable | Required | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `HB_DB_DRIVER` | no | `mongo` | `mongo` or `postgres` |
|
||||
| `HB_POSTGRES_URL` | with `postgres` | – | e.g. `postgres://user:pw@postgres:5432/homebrewery` |
|
||||
| `HB_POSTGRES_POOL_MAX` | no | `10` | connection pool size |
|
||||
| `MONGODB_URI` | with `mongo` | – | as upstream |
|
||||
|
||||
### Login (OIDC)
|
||||
|
||||
| Variable | Required | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `HB_AUTH_PROVIDERS` | no | `oidc,naturalcrit` if `HB_OIDC_ISSUER` is set, otherwise `naturalcrit` | `oidc`, `naturalcrit` (comma separated). Use `oidc` for OIDC only. With your own Compose file, set `HB_AUTH_PROVIDERS=oidc`: otherwise the app refuses to start while `SECRET` has its default value |
|
||||
| `HB_PUBLIC_URL` | with `oidc` | – | external URL, e.g. `https://brew.example.org` |
|
||||
| `HB_OIDC_ISSUER` | with `oidc` | – | issuer URL (discovery via `/.well-known/openid-configuration`) |
|
||||
| `HB_OIDC_CLIENT_ID` | with `oidc` | – | |
|
||||
| `HB_OIDC_CLIENT_SECRET` | with `oidc` | – | |
|
||||
| `HB_SESSION_SECRET` | with `oidc` | – | at least 32 bytes |
|
||||
| `HB_SESSION_TTL` | no | `7d` | fixed session lifetime (`7d`, `12h`, `3600`) |
|
||||
| `HB_OIDC_SCOPES` | no | `openid profile email` | |
|
||||
| `HB_OIDC_USERNAME_CLAIM` | no | `preferred_username` | source of the username on first login |
|
||||
| `HB_OIDC_LINK_BY_EMAIL` | no | `false` | bind a pre-created user to the verified IdP e-mail |
|
||||
| `HB_OIDC_END_SESSION` | no | `false` | also sign out at the IdP on logout |
|
||||
| `HB_OIDC_LABEL` | no | `Anmelden` | login button text |
|
||||
|
||||
The app refuses to start if `oidc` is active and a required value is missing.
|
||||
|
||||
### Git backend (optional)
|
||||
|
||||
Lets OIDC users link brews to their own Git repositories (HTTPS + personal access token). Disabled while `HB_GIT_TOKEN_KEY` is empty.
|
||||
|
||||
| Variable | Required | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `HB_GIT_TOKEN_KEY` | to enable | – | 32 bytes, base64 (`openssl rand -base64 32`). **Back it up**: without it, stored tokens are unusable |
|
||||
| `HB_GIT_TOKEN_KEYS_OLD` | no | – | old keys (comma separated), decrypt only, for key rotation |
|
||||
| `HB_GIT_ALLOWED_HOSTS` | no | – | host allowlist, e.g. `git.example.org,*.example.org`. Recommended in production |
|
||||
| `HB_GIT_ALLOW_PRIVATE` | no | `false` | allow private/loopback targets (e.g. Gitea in the same Compose network) |
|
||||
| `HB_GIT_ALLOW_HTTP` | no | `false` | allow `http://`, local development only |
|
||||
| `HB_GIT_WORKDIR` | no | `os.tmpdir()/hb-git` | temporary bare repos, deleted after each operation |
|
||||
| `HB_GIT_TIMEOUT_MS` | no | `20000` | per `git` call |
|
||||
| `HB_GIT_OPEN_TIMEOUT_MS` | no | `4000` | sync budget when opening the editor |
|
||||
| `HB_GIT_MAX_FILE_BYTES` | no | `5242880` | largest brew file |
|
||||
| `HB_GIT_MAX_CONCURRENCY` | no | `2` | concurrent Git operations per process |
|
||||
| `HB_GIT_COMMITTER_NAME` / `HB_GIT_COMMITTER_EMAIL` | no | `Homebrewery` / `homebrewery@<host of HB_PUBLIC_URL>` | committer (the author is the saving user) |
|
||||
|
||||
### Image upload (needs the Git backend)
|
||||
|
||||
| Variable | Required | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `HB_ASSETS_ENABLED` | no | `true` (if Git is active) | upload on/off |
|
||||
| `HB_ASSET_MAX_BYTES` | no | `5242880` | per file (MongoDB: at most 15 MiB) |
|
||||
| `HB_ASSET_MAX_BYTES_PER_BREW` | no | `52428800` | total per brew |
|
||||
| `HB_ASSET_TYPES` | no | `png,jpeg,gif,webp` | allowed types (SVG is never accepted) |
|
||||
|
||||
## Operations
|
||||
|
||||
- **Update / upgrade:** change the tag (or keep `latest`), then `docker compose pull && docker compose up -d`. Use `up -d`, **not** `restart`: `restart` reuses the old container with its old environment and ignores changes. Migrations run on startup; read the release notes before jumping several versions.
|
||||
- **Backup:** back up the database (`docker compose exec -T postgres pg_dump -U homebrewery homebrewery > backup.sql`, adjust user/db to your `.env`) and keep `HB_GIT_TOKEN_KEY` (and any old keys) in your secret store. Brews linked to Git are also in your repositories, but the database holds sharing snapshots, users and stored (encrypted) tokens.
|
||||
- **Key rotation:** set the new key as `HB_GIT_TOKEN_KEY`, move the previous one into `HB_GIT_TOKEN_KEYS_OLD` (comma separated), run `docker compose up -d`. Tokens are re-encrypted on next use; drop the old key only after all connections have been used.
|
||||
- **Logs:** `docker compose logs -f homebrewery`. Look for `Git-Backend aktiv (kid=...)` (on) or `Git-Backend deaktiviert: HB_GIT_TOKEN_KEY ist nicht gesetzt` (off). Logs never contain keys or tokens.
|
||||
- **Health:** the image has no dedicated health endpoint; `GET /` on port 8000 returning HTTP 200 means the app is up. The container exits at startup if the database is unusable or required OIDC values are missing or malformed (IdP reachability is only checked at the first login), so `restart: unless-stopped` shows a restart loop with the reason in the log.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **Git panel says "Git-Backend auf diesem Server nicht aktiviert" / API returns `503 G10`:** `HB_GIT_TOKEN_KEY` does not reach the container. Check `docker compose exec homebrewery printenv HB_GIT_TOKEN_KEY | wc -c` (a valid key prints 45; `0`, `1` (empty value) or an error means it is not set), make sure it is listed under `environment:`, then `docker compose up -d`.
|
||||
- **`403 G07`:** the session is not an OIDC account. Only OIDC users can link repositories.
|
||||
- **Start aborts with `HB_GIT_TOKEN_KEY muss 32 Byte (base64) lang sein`:** invalid key (also checked in `HB_GIT_TOKEN_KEYS_OLD`). Generate with `openssl rand -base64 32`.
|
||||
- **Start aborts about PostgreSQL:** the server must be version 18 or newer and `HB_POSTGRES_URL` must be set.
|
||||
- **Login redirect mismatch:** the IdP redirect URI must be exactly `<HB_PUBLIC_URL>/auth/oidc/callback`.
|
||||
|
||||
More error codes: Git backend `G01`-`G10` in the [Git guide](https://git.morlana.online/f.weber/homebrewery-oidc/src/branch/main/docs/git/README.md#fehlercodes), image upload `A01`-`A07` in its [upload section](https://git.morlana.online/f.weber/homebrewery-oidc/src/branch/main/docs/git/README.md#bild-upload-adr-0004). Note: the account rename endpoint reuses `A01`-`A03` with a different meaning, see the [auth guide](https://git.morlana.online/f.weber/homebrewery-oidc/src/branch/main/docs/auth/README.md) (guides are in German).
|
||||
@@ -0,0 +1,178 @@
|
||||
# Git-Backend: Brews in beliebigen Git-Repositories
|
||||
|
||||
Umsetzung von [ADR 0003](../adr/0003-git-backend-und-teilen.md) (Gitea #8). Funktioniert mit MongoDB und
|
||||
PostgreSQL und ist nur für **OIDC-Konten** verfügbar (Verbindungen gehören einem `users`-Datensatz,
|
||||
[ADR 0001](../adr/0001-auth-oidc.md)). naturalcrit-Konten können verknüpfte Brews mitbearbeiten und über
|
||||
Status/Pull ansehen, aber nichts selbst verknüpfen (`403 G07`).
|
||||
|
||||
## Einschalten
|
||||
|
||||
```bash
|
||||
openssl rand -base64 32 # → HB_GIT_TOKEN_KEY
|
||||
```
|
||||
|
||||
Ohne `HB_GIT_TOKEN_KEY` ist das Backend deaktiviert (Warnung beim Start, Hinweis im Account-Panel, `/api/git/*` antwortet `503 G10`,
|
||||
gespeicherte Brews werden wie bisher nur in der DB gespeichert). Den Schlüssel **nicht verlieren**: Ohne ihn
|
||||
sind gespeicherte Tokens unbrauchbar (Nutzer müssen sie neu eintragen).
|
||||
|
||||
| Variable | Standard | Bedeutung |
|
||||
| --- | --- | --- |
|
||||
| `HB_GIT_TOKEN_KEY` | – | aktiviert das Feature, 32 Byte base64 |
|
||||
| `HB_GIT_TOKEN_KEYS_OLD` | – | alte Schlüssel (kommagetrennt), nur zum Entschlüsseln; bei der nächsten Nutzung wird neu verschlüsselt |
|
||||
| `HB_GIT_ALLOWED_HOSTS` | – | Host-Allowlist (`git.example.org,*.example.org`). Im Betrieb empfohlen |
|
||||
| `HB_GIT_ALLOW_PRIVATE` | `false` | private/Loopback-Ziele erlauben (z. B. Gitea im selben Compose-Netz) |
|
||||
| `HB_GIT_ALLOW_HTTP` | `false` | `http://` erlauben, nur für lokale Entwicklung |
|
||||
| `HB_GIT_WORKDIR` | `os.tmpdir()/hb-git` | temporäre Bare-Repos (`0700`, werden nach jeder Operation gelöscht) |
|
||||
| `HB_GIT_TIMEOUT_MS` | `20000` | pro `git`-Aufruf |
|
||||
| `HB_GIT_OPEN_TIMEOUT_MS` | `4000` | Gesamtbudget für den Abgleich beim Öffnen des Editors (1000 bis `HB_GIT_TIMEOUT_MS`) |
|
||||
| `HB_GIT_MAX_FILE_BYTES` | `5242880` | größte Brew-Datei |
|
||||
| `HB_GIT_MAX_CONCURRENCY` | `2` | gleichzeitige Git-Operationen pro Prozess (weitere warten, max. 20, sonst `503 G05`) |
|
||||
| `HB_GIT_COMMITTER_NAME` / `_EMAIL` | `Homebrewery` / `homebrewery@<Host aus HB_PUBLIC_URL>` | Committer; Autor ist der speichernde Nutzer |
|
||||
|
||||
Für den Betrieb mit dem veröffentlichten Image siehe [docs/deploy](../deploy/README.md). Das Docker-Image enthält `git` bereits. Außerhalb von Docker muss `git` (≥ 2.30) im `PATH` liegen.
|
||||
|
||||
## Fehlersuche / nachträglich aktivieren
|
||||
|
||||
Das Backend lässt sich **jederzeit** einschalten, ein Erststart ist nicht nötig: `HB_GIT_TOKEN_KEY` setzen und den
|
||||
Prozess neu starten. Die Variable wird bei jedem Start gelesen, die Postgres-Migration `0002_git_backend` läuft immer mit.
|
||||
|
||||
Mit Docker Compose gilt: Nach einer Änderung der Umgebung `docker compose up -d` ausführen (erstellt den Container neu).
|
||||
`docker compose restart` startet den alten Container mit der **alten** Umgebung neu. Die Variable muss außerdem unter
|
||||
`environment:` (oder `env_file:`) des App-Service stehen, siehe [Betrieb mit dem veröffentlichten Image](../deploy/README.md).
|
||||
|
||||
Prüfen, in dieser Reihenfolge:
|
||||
|
||||
1. **Kommt der Schlüssel im Container an?** `docker compose exec <service> printenv HB_GIT_TOKEN_KEY | wc -c`: `0`, `1` (Variable gesetzt, aber leer) oder
|
||||
Fehler = nicht gesetzt; ein gültiger Schlüssel (32 Byte, base64) hat 45 Zeichen (44 + Zeilenumbruch).
|
||||
2. **Startlog** (`docker compose logs <service>`): `Git-Backend aktiv (kid=…, alte Schlüssel: n, Host-Allowlist: ja (n)|nein)` = an;
|
||||
`Git-Backend deaktiviert: HB_GIT_TOKEN_KEY ist nicht gesetzt` = aus. Der Log enthält nie den Schlüssel.
|
||||
3. **API**: `curl -i <HB_PUBLIC_URL>/api/git/connections`:
|
||||
`503` + `G10` = Backend aus (Schritt 1/2), `401` = nicht angemeldet, `403` + `G07` = Sitzung ohne OIDC-Konto,
|
||||
`200` = alles in Ordnung (für `403`/`200` mit Sitzungs-Cookie des Browsers).
|
||||
4. **Panel**: liegt ganz unten auf `/account` („Git-Verbindungen“) und erscheint nur für angemeldete **OIDC-Konten**.
|
||||
Ist das Backend aus, steht dort der Hinweis „Git-Backend auf diesem Server nicht aktiviert“, bei einer
|
||||
naturalcrit-Sitzung „Nur mit OIDC-Anmeldung verfügbar“. Ohne Anmeldung ist das Panel unsichtbar.
|
||||
|
||||
Ein ungültiger Schlüssel (nicht base64 oder ≠ 32 Byte, auch in `HB_GIT_TOKEN_KEYS_OLD`) **bricht den Start ab**
|
||||
(`HB_GIT_TOKEN_KEY muss 32 Byte (base64) lang sein`); der Container läuft dann in eine Neustart-Schleife, die Ursache steht im Log.
|
||||
|
||||
Schlüsselwechsel: neuen Schlüssel als `HB_GIT_TOKEN_KEY` setzen, den bisherigen in `HB_GIT_TOKEN_KEYS_OLD` (kommagetrennt)
|
||||
aufnehmen, `up -d`. Tokens werden bei der nächsten Nutzung mit dem neuen Schlüssel neu verschlüsselt; der alte Schlüssel
|
||||
darf erst entfallen, wenn alle Verbindungen genutzt wurden (die `kid` im Format `v1.<kid>.…` identifiziert den Schlüssel).
|
||||
|
||||
## Benutzung
|
||||
|
||||
1. **Verbindung anlegen** (Account-Seite → „Git-Verbindungen“): Bezeichnung, HTTPS-URL des Repos, Benutzername,
|
||||
Personal Access Token mit Schreibrecht auf das Repo. „Testen“ prüft Erreichbarkeit und Token.
|
||||
Der Token ist write-only: Die API gibt ihn nie zurück, er erscheint in keinem Log und keiner Fehlermeldung.
|
||||
2. **Brew verknüpfen** (Editor → Navbar „Git“): Verbindung, Branch und Pfad (`brews/mein-brew.md`) wählen. Der
|
||||
Brew wird dabei als Datei ins Repo geschrieben. Oder umgekehrt: Account-Seite → „Brews aus Repo importieren“.
|
||||
3. **Speichern** erzeugt pro Save einen Commit (auch Autosave; bei verknüpften Brews 60 s nach der letzten Änderung statt 10 s). Nie Force-Push.
|
||||
4. **Öffnen** holt den aktuellen Remote-Stand in den Snapshot. Ist der Git-Server nicht erreichbar (oder
|
||||
langsamer als `HB_GIT_OPEN_TIMEOUT_MS`), öffnet sich der zuletzt gespeicherte Stand und die Navbar warnt.
|
||||
5. **Konflikt** (`409 G01`): Die Datei wurde im Repo geändert. Dialog: „Meine Version behalten“ (neuer Commit
|
||||
auf dem neuen Stand, Historie bleibt), „Meine Version sichern“ (Download), „Remote-Version laden“ (Pull),
|
||||
„Abbrechen“. Änderungen an *anderen* Dateien sind kein Konflikt.
|
||||
|
||||
Teilen funktioniert unverändert und ohne Git-Zugriff: Ausgeliefert wird der zuletzt über die App gespeicherte
|
||||
oder per Öffnen/Pull übernommene Stand. Löschen eines Brews löscht die Datei im Repo **nicht**.
|
||||
|
||||
## Dateiformat
|
||||
|
||||
Exakt die Ausgabe von `mergeBrewText` (dieselbe Datei wie beim Upstream-Download): ```` ```metadata ```` (YAML),
|
||||
optional ```` ```css ```` und der Text. Nicht in der Datei: Autoren, `published`, Views, `shareId`/`editId`, Version.
|
||||
|
||||
## Anbieter
|
||||
|
||||
HTTPS + PAT mit Basic-Auth, ohne Anbieter-API. Als Benutzername passt bei allen `git` (beliebig), bei GitHub
|
||||
und Gitea auch der eigene Benutzername.
|
||||
|
||||
| Anbieter | Token | Benutzername |
|
||||
| --- | --- | --- |
|
||||
| Gitea / Forgejo | Einstellungen → Anwendungen → Zugriffstoken, Scope `write:repository` | beliebig / eigener |
|
||||
| GitHub | Fine-grained Token mit „Contents: Read and write“ auf dem Repo | beliebig / eigener |
|
||||
| GitLab | Project/Personal Access Token, Scope `write_repository` | `oauth2` oder eigener |
|
||||
|
||||
## Fehlercodes
|
||||
|
||||
| Code | HTTP | Bedeutung |
|
||||
| --- | --- | --- |
|
||||
| `G01` | 409 | Konflikt: Datei im Repo geändert (`remoteCommitSha`, `remoteBlobSha` in der Antwort) |
|
||||
| `G02` | 502 | Anmeldung am Git-Server fehlgeschlagen (Token ungültig/ohne Schreibrecht) |
|
||||
| `G03` | 502 | Repository, Branch oder Datei nicht gefunden |
|
||||
| `G04` | 504 | Git-Server nicht erreichbar oder zu langsam |
|
||||
| `G05` | 503 | Push-Rennen nach 3 Versuchen verloren oder Server ausgelastet |
|
||||
| `G06` | 409 | Datei existiert im Repo bereits (Anlegen/Verknüpfen) |
|
||||
| `G07` | 403 | Nur für OIDC-Konten |
|
||||
| `G08` | 400 | ungültige Eingabe (URL, Pfad, Branch, …) |
|
||||
| `G09` | 413 | Datei größer als `HB_GIT_MAX_FILE_BYTES` |
|
||||
| `G10` | 503 | Git-Backend nicht aktiviert |
|
||||
|
||||
G08–G10 sind Ergänzungen zur ADR.
|
||||
|
||||
## Sicherheit
|
||||
|
||||
- Token: AES-256-GCM, Format `v1.<kid>.<iv>.<ct>.<tag>`, AAD `git-connection:<id>`, nie im Klartext in der DB.
|
||||
- `git` startet nur über `execFile`/`spawn` ohne Shell; Zugangsdaten gehen per `GIT_CONFIG_*`-Umgebung
|
||||
(`http.extraHeader`) an den Prozess, nie in Argumente, URL oder Dateien. `credential.helper` ist leer,
|
||||
Redirects sind aus, nur `https` (bzw. `http` mit `HB_GIT_ALLOW_HTTP`).
|
||||
- SSRF-Schutz vor jeder Operation: nur `https://`, keine Benutzerinfo, Allowlist oder DNS-Auflösung mit
|
||||
Sperre für Loopback, private, Link-Local- und CGNAT-Adressen. Restrisiko DNS-Rebinding: im Betrieb
|
||||
`HB_GIT_ALLOWED_HOSTS` setzen.
|
||||
- Mitautoren speichern mit dem Token des Verbindungsbesitzers.
|
||||
- Nur ein App-Prozess (Mutex pro Brew ist prozesslokal).
|
||||
|
||||
## Abweichungen von ADR 0003
|
||||
|
||||
- Zusätzliche Codes `G08` (ungültige Eingabe), `G09` (Datei zu groß), `G10` (Feature aus).
|
||||
- `afterBrewSave(ctx, saved)` wird in jedem Fall aufgerufen (auch bei fehlgeschlagenem DB-Save), weil der
|
||||
Brew-Mutex von `beforeBrewSave` bis dahin gehalten wird; der Link wird nur bei Erfolg aktualisiert.
|
||||
- Datei im Repo nach externem Löschen: `gitOverwrite=none` bestätigt das Neuanlegen.
|
||||
- Abgleich beim Öffnen und Pull laden den Inhalt im selben Repo-Zugriff wie den Blob-Vergleich (ein zweites
|
||||
frisches Repo hätte den Blob nicht).
|
||||
- Die `git`-Prozesse laufen in eigener Prozessgruppe, damit Abbruch (Zeitbudget) auch `git-remote-http` beendet.
|
||||
- Spike (ADR: „vor M3-Start Pflicht“) gegen Gitea 1.24 über HTTP und lokalen `git http-backend` gelaufen
|
||||
(Root-Commit in leerem Repo, `--filter=blob:none`-Fetch mit Lazy-Blob, Push, Non-Fast-Forward-Ablehnung);
|
||||
nachvollziehbar mit `scripts/git-e2e-gitea.sh`. GitHub wurde nicht geprüft (kein Zugang in der Entwicklungs-VM),
|
||||
das Protokoll ist identisch.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
npx jest server/fork/git tests/fork/git-backend.test.js # ohne Datenbank: echtes git gegen lokalen http-backend
|
||||
HB_TEST_POSTGRES_URL=… HB_TEST_MONGODB_URI=… npx jest server/storage tests/fork --runInBand # inkl. DB-Varianten
|
||||
```
|
||||
|
||||
`tests/fork/git-http-test-server.js` startet `git http-backend` hinter einem Node-Server mit Basic-Auth
|
||||
(Remote mit `uploadpack.allowFilter` und `http.receivepack`). Gegen eine echte Gitea-Instanz (Wegwerf-Container): `scripts/git-e2e-gitea.sh`; gegen ein beliebiges
|
||||
Remote (GitHub, GitLab, …): `GIT_E2E_URL=… GIT_E2E_USER=… GIT_E2E_TOKEN=… node scripts/git-e2e.mjs`.
|
||||
|
||||
## Teilen (Snapshot, ADR 0003 §6)
|
||||
|
||||
Share-, Fetch-, CSS-, Metadaten-, Quelltext- und Download-Routen liefern den DB-Snapshot und greifen nie auf Git
|
||||
zu. Leser brauchen weder Konto noch Repo-Zugriff und sehen weder Token noch Repo-URL oder Pfad (auch bei privaten
|
||||
Repos). Der Snapshot wird bei jedem erfolgreichen Speichern, Pull und Abgleich beim Öffnen aktualisiert. Sein
|
||||
Zeitpunkt (`updatedAt`) steht im Share-Link-Metadatenmenü („vor … “) und im Git-Menü des Editors als „Teilen-Stand“
|
||||
(`snapshotAt` in `GET /api/git/brews/:editId`). Commits außerhalb der App erscheinen erst nach Öffnen im Editor oder Pull.
|
||||
|
||||
## Bild-Upload (ADR 0004)
|
||||
|
||||
Nur für Git-verknüpfte Brews. `POST /api/git/brews/:editId/assets` (Rohdaten, `Content-Type` = Bild-MIME,
|
||||
`X-HB-Filename` = URL-kodierter Name) legt das Bild unter `<assets_dir>/<slug>-<sha256[0..11]>.<ext>` per Commit im Repo ab
|
||||
und speichert einen Snapshot in `brew_assets`. Antwort `201 { url, path, sha256, size, contentType, markdown }`
|
||||
(`200` bei bereits vorhandenem Inhalt). Ausgeliefert wird über `GET /git-assets/:shareId/:sha256.:ext` ohne Login und ohne Git-Zugriff.
|
||||
Der Typ wird per Magic Bytes bestimmt (PNG, JPEG, GIF, WebP; SVG nie).
|
||||
|
||||
| Variable | Standard | Bedeutung |
|
||||
| --- | --- | --- |
|
||||
| `HB_ASSETS_ENABLED` | `true` (wenn Git aktiv) | Upload ein/aus |
|
||||
| `HB_ASSET_MAX_BYTES` | `5242880` | pro Datei (Mongo: höchstens 15 MiB, sonst Startfehler) |
|
||||
| `HB_ASSET_MAX_BYTES_PER_BREW` | `52428800` | Summe pro Brew |
|
||||
| `HB_ASSET_TYPES` | `png,jpeg,gif,webp` | erlaubte Typen |
|
||||
|
||||
Fehlercodes: `A01` zu groß (413), `A02` Typ nicht erlaubt oder passt nicht zum Inhalt (415), `A03` Brew-Limit (413),
|
||||
`A04` Brew gesperrt (423), `A05` Brew nicht mit Git verknüpft (400), `A06` leerer Upload (400), `A07` Upload aus (503);
|
||||
dazu Git-Fehler `G02`–`G05`. Im Editor: Bild-Button in der Snippet-Bar, Drag-and-drop und Einfügen aus der Zwischenablage.
|
||||
Hinweis in der UI: EXIF-Daten bleiben erhalten, Bilder sind über den Teilen-Link öffentlich.
|
||||
Tests: `npx jest server/fork/assets tests/fork/assets.test.js tests/fork/assetClient.test.js`; die Storage-Contract-Suite
|
||||
(`server/storage/contract/assets.contract.js`) läuft mit `HB_TEST_POSTGRES_URL` bzw. `HB_TEST_MONGODB_URI`.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Storage: MongoDB oder PostgreSQL pro Instanz
|
||||
|
||||
Umsetzung von [ADR 0002](../adr/0002-storage-mongo-postgres.md) (Gitea #7). Pro Instanz ist **genau ein**
|
||||
Backend aktiv. Einen Datenumzug zwischen den Backends gibt es nicht (einzelne Brews: Download/Import).
|
||||
|
||||
## Konfiguration
|
||||
|
||||
| Variable | Bedeutung |
|
||||
| --- | --- |
|
||||
| `HB_DB_DRIVER` | `mongo` (Standard) oder `postgres` |
|
||||
| `MONGODB_URI` | wie Upstream (nur bei `mongo`) |
|
||||
| `HB_POSTGRES_URL` | z. B. `postgres://hb:…@postgres:5432/homebrewery` (Pflicht bei `postgres`) |
|
||||
| `HB_POSTGRES_POOL_MAX` | Pool-Größe, Standard `10` |
|
||||
|
||||
Beim Start wird nur das gewählte Backend verbunden (bei `postgres` verbindet sich Mongoose nicht). Fehlt
|
||||
`HB_POSTGRES_URL` oder ist der Server älter als PostgreSQL 18 (`server_version_num` < 180000), bricht der Start mit
|
||||
klarer Meldung ab. Die Migrationen (`server/storage/postgres/migrations/`) laufen beim Start automatisch
|
||||
(Kysely-Migrator mit Lock-Tabelle, bei Fehler Abbruch).
|
||||
|
||||
## Compose
|
||||
|
||||
```bash
|
||||
# Standard (Mongo, wie bisher)
|
||||
docker compose up --build
|
||||
|
||||
# PostgreSQL 18, ganz ohne Mongo: Profil `postgres`, Service `homebrewery-pg`
|
||||
docker compose --profile postgres up --build homebrewery-pg
|
||||
```
|
||||
|
||||
Die Service-Namen gehören dazu: Mit `--profile postgres up` ohne Namen startet Compose zusätzlich die
|
||||
profillosen Services `homebrewery` und `mongodb` (beide auf `APP_PORT`).
|
||||
|
||||
Für den Betrieb mit dem veröffentlichten Image (PostgreSQL 18, ohne Repo-Checkout): [docs/deploy/README.md](../deploy/README.md).
|
||||
|
||||
## Repository-Schicht
|
||||
|
||||
`server/storage/` – `getStorage()` liefert `{ brews, notifications, users }` (`gitConnections`, `brewGitLinks`,
|
||||
`brewAssets` kommen mit M3/M4). Alle Methoden sind `async` und liefern plain objects mit `id`, `text` immer
|
||||
entpackt, nie `textBin`. Nicht gefunden: `findBy…` liefert `null`.
|
||||
|
||||
Abweichungen von ADR 0002 (Details beim Umsetzen ergeben):
|
||||
|
||||
- `searchPublished(params)` liefert `{ brews, total }`; `total` nur mit `withTotal: true`, Brews nicht mit
|
||||
`limit: 0` (für `/api/vault/total`).
|
||||
- Sperren: `setLock(shareId, lock, { overwrite })`, `removeLock`, `requestReview`, `removeReviewRequest` liefern
|
||||
`{ result, brew }` (`'locked' | 'not-found' | 'already-locked'` usw.), damit die Fehlercodes der Admin-API
|
||||
unverändert bleiben und die Prüfung atomar ist (PG: eine Transaktion mit `FOR UPDATE`).
|
||||
- Notifications: `list()`, `create(data)`, `deleteByDismissKey(key)`; das Feld heißt jetzt `id` statt `_id`.
|
||||
- `/admin/clean/script/:id` läuft über Repository und `updateBrew` und funktioniert damit auch unter PG
|
||||
(ADR: 501). Nur `cleanupJunk`, `cleanupLost`, `finduncompressed` und `compress` antworten unter PG mit `501`.
|
||||
- Die Upstream-Modelle (`homebrew.model.js`, `notifications.model.js`, `db.js`) sind unverändert.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
# Postgres (frisches Schema test_<random> je Suite, wird danach gelöscht)
|
||||
HB_TEST_POSTGRES_URL=postgres://postgres:pw@127.0.0.1:5432/postgres npm run test:storage
|
||||
# Mongo (frische DB test_<random>)
|
||||
HB_TEST_MONGODB_URI=mongodb://127.0.0.1:27017 npm run test:storage
|
||||
```
|
||||
|
||||
Ohne die Variablen überspringen sich die Specs mit Warnung. `npm test` läuft weiter ohne Datenbank.
|
||||
Beide Variablen gleichzeitig sind erlaubt. Die CI (`storage`-Job, Matrix `mongo`/`postgres`) setzt je eine.
|
||||
|
||||
Hinweise zu Mongo unter Jest: Der Mongo-Treiber braucht dort `runtimeAdapters: { os }` (sonst sendet er keine
|
||||
Client-Metadaten und der Server lehnt den Handshake ab; die Specs setzen das). `Model.init()`/`syncIndexes()` auf
|
||||
`Homebrew` scheitert auf aktuellen Servern am Upstream-Index `{ lock: 1, sparse: true }`; die Specs legen die
|
||||
nötigen Indizes selbst an. MongoDB ≥ 5 braucht eine CPU mit AVX; auf Hosts ohne AVX hilft lokal `mongo:4.4`.
|
||||
Generated
+501
@@ -46,7 +46,9 @@
|
||||
"hash-wasm": "^4.12.0",
|
||||
"idb-keyval": "^6.2.5",
|
||||
"js-yaml": "^5.5.0",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"jwt-simple": "^0.6.1",
|
||||
"kysely": "^0.29.9",
|
||||
"less": "^4.9.1",
|
||||
"lodash": "^4.18.1",
|
||||
"marked-hbfm": "^1.0.3",
|
||||
@@ -56,6 +58,8 @@
|
||||
"nanoid": "6.0.2",
|
||||
"nconf": "^0.13.0",
|
||||
"node": "^26.13.0",
|
||||
"openid-client": "^6.9.1",
|
||||
"pg": "^8.23.1",
|
||||
"prettier": "^3.9.10",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
@@ -76,6 +80,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 +6451,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 +6755,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 +6821,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 +6837,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 +8650,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 +10946,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 +11119,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 +11196,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 +11228,133 @@
|
||||
"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/kysely": {
|
||||
"version": "0.29.9",
|
||||
"resolved": "https://registry.npmjs.org/kysely/-/kysely-0.29.9.tgz",
|
||||
"integrity": "sha512-K48ErswC3MlIcBqR0pYIIEl+n9rIgwxgzaM1FxKHMXn7egxr1NHj7bCeF98mXl9A3/QoL5I7mo5S/mLXgeDgGA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/less": {
|
||||
"version": "4.9.1",
|
||||
"resolved": "https://registry.npmjs.org/less/-/less-4.9.1.tgz",
|
||||
@@ -11443,12 +11709,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 +12579,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 +12702,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 +12754,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",
|
||||
@@ -12663,6 +13008,95 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/pg": {
|
||||
"version": "8.23.1",
|
||||
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
|
||||
"integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-connection-string": "^2.14.1",
|
||||
"pg-pool": "^3.14.0",
|
||||
"pg-protocol": "^1.16.1",
|
||||
"pg-types": "2.2.0",
|
||||
"pgpass": "1.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"pg-cloudflare": "^1.4.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"pg-native": ">=3.0.1"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"pg-native": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/pg-cloudflare": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
|
||||
"integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/pg-connection-string": {
|
||||
"version": "2.14.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
|
||||
"integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-int8": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pg-pool": {
|
||||
"version": "3.14.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
|
||||
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"pg": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pg-protocol": {
|
||||
"version": "1.16.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
|
||||
"integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-types": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-int8": "1.0.1",
|
||||
"postgres-array": "~2.0.0",
|
||||
"postgres-bytea": "~1.0.0",
|
||||
"postgres-date": "~1.0.4",
|
||||
"postgres-interval": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/pgpass": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"split2": "^4.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
@@ -12831,6 +13265,45 @@
|
||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-array": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-bytea": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
|
||||
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-date": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-interval": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"xtend": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prelude-ls": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
|
||||
@@ -13801,6 +14274,15 @@
|
||||
"memory-pager": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/split2": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
||||
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">= 10.x"
|
||||
}
|
||||
},
|
||||
"node_modules/sprintf-js": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
|
||||
@@ -14744,6 +15226,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",
|
||||
@@ -15492,6 +15984,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/xtend": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "5.0.8",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
|
||||
|
||||
+7
-1
@@ -28,6 +28,7 @@
|
||||
"test:api-unit:notifications": "jest \"server/.*.spec.js\" -t \"Notifications\" --verbose",
|
||||
"test:content-negotiation": "jest \"server/middleware/.*.spec.js\" --verbose",
|
||||
"test:static-content": "jest \"tests/routes/static-content.test.js\" --verbose",
|
||||
"test:storage": "jest server/storage tests/fork --runInBand",
|
||||
"test:coverage": "jest --coverage --silent --runInBand",
|
||||
"test:dev": "jest --verbose --watch",
|
||||
"test:basic": "jest tests/markdown/basic.test.js --verbose",
|
||||
@@ -61,7 +62,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|kysely)/)"
|
||||
],
|
||||
"transform": {
|
||||
"^.+\\.[jt]s$": "babel-jest",
|
||||
@@ -125,7 +126,9 @@
|
||||
"hash-wasm": "^4.12.0",
|
||||
"idb-keyval": "^6.2.5",
|
||||
"js-yaml": "^5.5.0",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"jwt-simple": "^0.6.1",
|
||||
"kysely": "^0.29.9",
|
||||
"less": "^4.9.1",
|
||||
"lodash": "^4.18.1",
|
||||
"marked-hbfm": "^1.0.3",
|
||||
@@ -135,6 +138,8 @@
|
||||
"nanoid": "6.0.2",
|
||||
"nconf": "^0.13.0",
|
||||
"node": "^26.13.0",
|
||||
"openid-client": "^6.9.1",
|
||||
"pg": "^8.23.1",
|
||||
"prettier": "^3.9.10",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
@@ -155,6 +160,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",
|
||||
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# Startet eine Wegwerf-Gitea-Instanz (Docker, SQLite), legt Benutzer, Token und Repo an und führt
|
||||
# scripts/git-e2e.mjs dagegen aus. Container wird am Ende gestoppt. Nur Dev-Zugangsdaten.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
NAME=hb-e2e-gitea
|
||||
PORT=${GITEA_E2E_PORT:-3300}
|
||||
IMAGE=${GITEA_IMAGE:-gitea/gitea:1.24}
|
||||
PASS="e2e-$(openssl rand -hex 8)"
|
||||
cleanup() { docker rm -f "$NAME" >/dev/null 2>&1 || true; }
|
||||
trap cleanup EXIT
|
||||
cleanup
|
||||
docker run -d --name "$NAME" --memory 400m -p "127.0.0.1:${PORT}:3000" \
|
||||
-e GITEA__database__DB_TYPE=sqlite3 -e GITEA__security__INSTALL_LOCK=true \
|
||||
-e GITEA__server__ROOT_URL="http://127.0.0.1:${PORT}/" -e GITEA__service__DISABLE_REGISTRATION=true "$IMAGE" >/dev/null
|
||||
for _ in $(seq 1 60); do curl -fs "http://127.0.0.1:${PORT}/api/healthz" >/dev/null && break; sleep 2; done
|
||||
docker exec -u git "$NAME" gitea admin user create --admin --username tester --password "$PASS" --email tester@example.test --must-change-password=false >/dev/null
|
||||
TOKEN=$(curl -fs -u "tester:$PASS" -H 'Content-Type: application/json' -X POST "http://127.0.0.1:${PORT}/api/v1/users/tester/tokens" \
|
||||
-d '{"name":"e2e","scopes":["write:repository","write:user"]}' | sed -n 's/.*"sha1":"\([^"]*\)".*/\1/p')
|
||||
curl -fs -u "tester:$PASS" -H 'Content-Type: application/json' -X POST "http://127.0.0.1:${PORT}/api/v1/user/repos" -d '{"name":"hb-e2e"}' >/dev/null
|
||||
GIT_E2E_URL="http://127.0.0.1:${PORT}/tester/hb-e2e.git" GIT_E2E_USER=tester GIT_E2E_TOKEN="$TOKEN" \
|
||||
GIT_E2E_ALLOW_HTTP=true GIT_E2E_ALLOW_PRIVATE=true node scripts/git-e2e.mjs
|
||||
@@ -0,0 +1,104 @@
|
||||
// E2E-Prüfung des Git-Backends gegen ein echtes Remote (Gitea, Forgejo, GitHub, GitLab, lokales Remote).
|
||||
// Nutzung: GIT_E2E_URL=https://host/owner/repo.git GIT_E2E_USER=name GIT_E2E_TOKEN=… node scripts/git-e2e.mjs
|
||||
// (lokale/private Ziele: GIT_E2E_ALLOW_PRIVATE=true, http://: GIT_E2E_ALLOW_HTTP=true). Das Repo darf leer sein.
|
||||
// Es werden nur Dateien unter hb-e2e-<zeit>/ angelegt. Der Token wird nie ausgegeben.
|
||||
import crypto from 'crypto';
|
||||
import os from 'os';
|
||||
import api from '../server/homebrew.api.js';
|
||||
import { splitTextStyleAndMetadata } from '../shared/helpers.js';
|
||||
import { readGitConfig } from '../server/fork/git/config.js';
|
||||
import { createGitService } from '../server/fork/git/brewSync.js';
|
||||
import { createMemoryStorage } from '../tests/fork/git-memory-storage.js';
|
||||
|
||||
const { GIT_E2E_URL: url, GIT_E2E_USER: user = 'git', GIT_E2E_TOKEN: token } = process.env;
|
||||
if(!url || !token) { console.error('GIT_E2E_URL und GIT_E2E_TOKEN setzen.'); process.exit(2); }
|
||||
|
||||
const cfg = { ...readGitConfig({ HB_GIT_TOKEN_KEY: crypto.randomBytes(32).toString('base64'), HB_PUBLIC_URL: 'https://hb.example.test', HB_GIT_WORKDIR: `${os.tmpdir()}/hb-git-e2e` }),
|
||||
allowHttp: process.env.GIT_E2E_ALLOW_HTTP === 'true', allowPrivate: process.env.GIT_E2E_ALLOW_PRIVATE === 'true', timeoutMs: 60000 };
|
||||
const storage = createMemoryStorage();
|
||||
const quiet = { warn: (...a)=>console.log(' [warn]', ...a), error: console.error, log: ()=>{} };
|
||||
const svc = createGitService({ cfg, getStorage: ()=>storage, api, splitTextStyleAndMetadata, logger: quiet });
|
||||
|
||||
let failed = 0;
|
||||
const step = async (name, fn)=>{
|
||||
process.stdout.write(`- ${name} … `);
|
||||
try { const r = await fn(); console.log('ok'); return r; } catch (err) { failed++; console.log(`FEHLER ${err.HBErrorCode ?? ''} ${err.message}`); }
|
||||
};
|
||||
const expectCode = async (code, fn)=>{
|
||||
try { await fn(); } catch (err) { if(err.HBErrorCode === code) return err; throw new Error(`erwartet ${code}, erhalten ${err.HBErrorCode ?? err.message}`); }
|
||||
throw new Error(`erwartet ${code}, aber kein Fehler`);
|
||||
};
|
||||
const assert = (cond, msg)=>{ if(!cond) throw new Error(msg); };
|
||||
|
||||
const dir = `hb-e2e-${Date.now()}`;
|
||||
const alice = await storage.users.create({ username: 'e2e', displayName: 'E2E Tester' });
|
||||
const account = { username: 'e2e', uid: alice.id };
|
||||
const author = { name: 'E2E Tester', email: 'e2e@users.noreply.hb.example.test' };
|
||||
|
||||
const conn = await step('Verbindung anlegen und testen', async ()=>{
|
||||
const c = await svc.createConnection(account, { label: 'e2e', repoUrl: url, authUsername: user, token });
|
||||
assert(c.hasToken && !JSON.stringify(c).includes(token), 'Token in Antwort');
|
||||
const t = await svc.testConnection(account, c.id);
|
||||
console.log(`(Standard-Branch ${t.defaultBranch}, ${t.branchCount} Branches) `);
|
||||
return c;
|
||||
});
|
||||
if(!conn) process.exit(1);
|
||||
const stored = await storage.gitConnections.findById(conn.id);
|
||||
|
||||
const brew = await step('Brew anlegen (Commit)', ()=>svc.createBrew(account, { connectionId: conn.id, path: `${dir}/a.md`, brew: { title: 'E2E Brew', text: 'Version 1', renderer: 'V3' } }));
|
||||
const save = async (text, query = {}, who = account)=>{
|
||||
const current = await storage.brews.findByEditId(brew.editId);
|
||||
const res = { code: undefined, status(c) { this.code = c; return this; }, json(b) { this.body = b; return this; } };
|
||||
const ctx = await svc.beforeBrewSave({ brew: { ...current, text }, req: { query, account: who }, res });
|
||||
if(ctx) await svc.afterBrewSave(ctx, await storage.brews.update({ ...current, text, version: current.version + 1 }));
|
||||
return { ctx, res };
|
||||
};
|
||||
const link = ()=>storage.brewGitLinks.findByBrewId(brew.id);
|
||||
|
||||
await step('Speichern erzeugt neuen Commit', async ()=>{
|
||||
const before = (await link()).lastCommitSha;
|
||||
const { ctx } = await save('Version 2');
|
||||
assert(ctx?.git?.commit && ctx.git.commit !== before, 'kein neuer Commit');
|
||||
});
|
||||
await step('Laden holt den Remote-Stand (Pull)', async ()=>{
|
||||
const l = await link();
|
||||
const conn2 = await storage.gitConnections.findById(conn.id);
|
||||
const state = await svc.readRemote(conn2, { branch: l.branch, filePath: l.path });
|
||||
assert(state.content.includes('Version 2'), 'Inhalt fehlt');
|
||||
assert(state.blob === l.lastBlobSha, 'Blob weicht ab');
|
||||
});
|
||||
await step('Fremder Commit auf derselben Datei → Konflikt G01', async ()=>{
|
||||
const l = await link();
|
||||
await svc.commitContent(await storage.gitConnections.findById(conn.id), { branch: l.branch, filePath: l.path, content: 'Extern geändert', expectedBlob: l.lastBlobSha, author: { name: 'Extern', email: 'x@example.test' } });
|
||||
const { ctx, res } = await save('Meine Version');
|
||||
assert(ctx === null && res.code === 409 && res.body.HBErrorCode === 'G01', 'kein Konflikt');
|
||||
globalThis.remoteBlob = res.body.remoteBlobSha;
|
||||
});
|
||||
await step('„Meine Version behalten“ (gitOverwrite) schreibt normalen Commit', async ()=>{
|
||||
const { ctx, res } = await save('Meine Version', { gitOverwrite: globalThis.remoteBlob });
|
||||
assert(ctx?.git && res.code === undefined, 'Overwrite fehlgeschlagen');
|
||||
});
|
||||
await step('Pull übernimmt externe Änderung in den Snapshot', async ()=>{
|
||||
const l = await link();
|
||||
await svc.commitContent(await storage.gitConnections.findById(conn.id), { branch: l.branch, filePath: l.path, content: '```metadata\ntitle: Extern 2\n```\n\nVon außen\n', expectedBlob: l.lastBlobSha, author });
|
||||
await svc.pull(account, brew.editId);
|
||||
const b = await storage.brews.findByEditId(brew.editId);
|
||||
assert(b.title === 'Extern 2' && b.text.includes('Von außen'), 'Snapshot nicht aktualisiert');
|
||||
});
|
||||
await step('Neuer Branch in nicht leerem Repo', async ()=>{
|
||||
const b2 = await svc.createBrew(account, { connectionId: conn.id, branch: `hb-e2e-${Date.now()}`, path: `${dir}/b.md`, brew: { title: 'Branch Brew', text: 'x' } });
|
||||
assert(b2.editId, 'kein Brew');
|
||||
});
|
||||
await step('Dateiliste und Import', async ()=>{
|
||||
const files = await svc.listFiles(account, conn.id, { branch: (await link()).branch, dir });
|
||||
assert(files.files.includes(`${dir}/a.md`), 'Datei fehlt in der Liste');
|
||||
const imported = await svc.importBrew(account, { connectionId: conn.id, branch: (await link()).branch, path: `${dir}/a.md` }).catch((e)=>e);
|
||||
assert(imported.HBErrorCode === 'G06', 'Doppel-Import nicht abgelehnt');
|
||||
});
|
||||
await step('Falscher Token → G02 ohne Token in der Meldung', async ()=>{
|
||||
await storage.gitConnections.update(conn.id, { tokenEnc: (await import('../server/fork/git/crypto.js')).createTokenCrypto({ key: cfg.key }).encrypt('falsch-xyz', conn.id) });
|
||||
const err = await expectCode('G02', ()=>svc.testConnection(account, conn.id));
|
||||
assert(!JSON.stringify(err.toBody()).includes(token) && !JSON.stringify(err.toBody()).includes('falsch-xyz'), 'Token in Fehlermeldung');
|
||||
});
|
||||
console.log(failed ? `\n${failed} Schritt(e) fehlgeschlagen` : `\nAlles ok (Dateien unter ${dir}/)`);
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -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('&', '&');
|
||||
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);
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
+53
-111
@@ -1,6 +1,6 @@
|
||||
/*eslint max-lines: ["warn", {"max": 500, "skipBlankLines": true, "skipComments": true}]*/
|
||||
import { model as HomebrewModel } from './homebrew.model.js';
|
||||
import { model as NotificationModel } from './notifications.model.js';
|
||||
import { getStorage } from './storage/index.js';
|
||||
import express from 'express';
|
||||
import Moment from 'moment';
|
||||
import zlib from 'zlib';
|
||||
@@ -35,6 +35,12 @@ export default function createAdminApi(vite) {
|
||||
return next();
|
||||
}
|
||||
throw { HBErrorCode: '52', code: 401, message: 'Access denied' };
|
||||
},
|
||||
// [fork] ADR-0002: Wartungsjobs auf dem Mongo-Altformat (textBin) gibt es unter Postgres nicht
|
||||
mongoOnly : (req, res, next)=>{
|
||||
if(getStorage().driver !== 'mongo')
|
||||
return res.status(501).json({ error: 'Not implemented for the PostgreSQL storage backend' });
|
||||
return next();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -68,7 +74,7 @@ export default function createAdminApi(vite) {
|
||||
'text' : { '$exists': true }
|
||||
}).lean().limit(10000).select('_id');
|
||||
|
||||
router.get('/admin/cleanupJunk', mw.adminOnly, (req, res)=>{
|
||||
router.get('/admin/cleanupJunk', mw.adminOnly, mw.mongoOnly, (req, res)=>{
|
||||
HomebrewModel.aggregate(junkBrewsPipeline).option({ maxTimeMS: 60000 })
|
||||
.then((objs)=>res.json({ count: objs.length, brewCollection: objs }))
|
||||
.catch((error)=>{
|
||||
@@ -78,7 +84,7 @@ export default function createAdminApi(vite) {
|
||||
});
|
||||
|
||||
// Delete result of junkBrewsPipeline
|
||||
router.post('/admin/cleanupJunk', mw.adminOnly, (req, res)=>{
|
||||
router.post('/admin/cleanupJunk', mw.adminOnly, mw.mongoOnly, (req, res)=>{
|
||||
HomebrewModel.aggregate(junkBrewsPipeline).option({ maxTimeMS: 60000 })
|
||||
.then((docs)=>{
|
||||
const ids = docs.map((doc)=>doc._id);
|
||||
@@ -91,7 +97,7 @@ export default function createAdminApi(vite) {
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/admin/cleanupLost', mw.adminOnly, (req, res)=>{
|
||||
router.get('/admin/cleanupLost', mw.adminOnly, mw.mongoOnly, (req, res)=>{
|
||||
HomebrewModel.aggregate(lostBrewsPipeline).option({ maxTimeMS: 60000 })
|
||||
.then((objs)=>res.json({ count: objs.length, brewCollection: objs }))
|
||||
.catch((error)=>{
|
||||
@@ -101,7 +107,7 @@ export default function createAdminApi(vite) {
|
||||
});
|
||||
|
||||
// Delete result of lostBrewsPipeline
|
||||
router.post('/admin/cleanupLost', mw.adminOnly, (req, res)=>{
|
||||
router.post('/admin/cleanupLost', mw.adminOnly, mw.mongoOnly, (req, res)=>{
|
||||
HomebrewModel.aggregate(lostBrewsPipeline).option({ maxTimeMS: 60000 })
|
||||
.then((docs)=>{
|
||||
const ids = docs.map((doc)=>doc._id);
|
||||
@@ -120,7 +126,7 @@ export default function createAdminApi(vite) {
|
||||
});
|
||||
|
||||
/* Find 50 brews that aren't compressed yet */
|
||||
router.get('/admin/finduncompressed', mw.adminOnly, (req, res)=>{
|
||||
router.get('/admin/finduncompressed', mw.adminOnly, mw.mongoOnly, (req, res)=>{
|
||||
const query = uncompressedBrewQuery.clone();
|
||||
|
||||
query.exec()
|
||||
@@ -158,17 +164,15 @@ export default function createAdminApi(vite) {
|
||||
/* Get list of a user's documents */
|
||||
router.get('/admin/user/list/:user', mw.adminOnly, async (req, res)=>{
|
||||
const username = req.params.user;
|
||||
const fields = { _id: 0, text: 0, textBin: 0 }; // Remove unnecessary fields from document lists
|
||||
|
||||
console.log(`[ADMIN: ${req.account?.username || 'Not Logged In'}] Get brew list for ${username}`);
|
||||
|
||||
const brews = await HomebrewModel.getByUser(username, true, fields);
|
||||
const brews = await getStorage().brews.listByAuthor(username, { includeUnpublished: true }); // [fork] ADR-0002 (ohne text)
|
||||
|
||||
return res.json(brews);
|
||||
});
|
||||
|
||||
/* Compresses the "text" field of a brew to binary */
|
||||
router.put('/admin/compress/:id', (req, res)=>{
|
||||
router.put('/admin/compress/:id', mw.mongoOnly, (req, res)=>{
|
||||
HomebrewModel.findOne({ _id: req.params.id })
|
||||
.then((brew)=>{
|
||||
if(!brew)
|
||||
@@ -190,8 +194,9 @@ export default function createAdminApi(vite) {
|
||||
|
||||
router.get('/admin/stats', mw.adminOnly, async (req, res)=>{
|
||||
try {
|
||||
const totalBrewsCount = await HomebrewModel.countDocuments({});
|
||||
const publishedBrewsCount = await HomebrewModel.countDocuments({ published: true });
|
||||
// [fork] ADR-0002
|
||||
const totalBrewsCount = await getStorage().brews.countAll();
|
||||
const publishedBrewsCount = await getStorage().brews.countPublished();
|
||||
|
||||
return res.json({
|
||||
totalBrews : totalBrewsCount,
|
||||
@@ -207,10 +212,8 @@ export default function createAdminApi(vite) {
|
||||
|
||||
router.get('/api/lock/count', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
|
||||
const countLocksQuery = {
|
||||
lock : { $exists: true }
|
||||
};
|
||||
const count = await HomebrewModel.countDocuments(countLocksQuery)
|
||||
// [fork] ADR-0002
|
||||
const count = await getStorage().brews.countLocked()
|
||||
.catch((error)=>{
|
||||
throw { name: 'Lock Count Error', message: 'Unable to get lock count', status: 500, HBErrorCode: '61', error };
|
||||
});
|
||||
@@ -220,23 +223,8 @@ export default function createAdminApi(vite) {
|
||||
}));
|
||||
|
||||
router.get('/api/locks', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
const countLocksPipeline = [
|
||||
{
|
||||
$match :
|
||||
{
|
||||
'lock' : { '$exists': 1 }
|
||||
},
|
||||
},
|
||||
{
|
||||
$project : {
|
||||
shareId : 1,
|
||||
editId : 1,
|
||||
title : 1,
|
||||
lock : 1
|
||||
}
|
||||
}
|
||||
];
|
||||
const lockedDocuments = await HomebrewModel.aggregate(countLocksPipeline)
|
||||
// [fork] ADR-0002
|
||||
const lockedDocuments = await getStorage().brews.listLocked()
|
||||
.catch((error)=>{
|
||||
throw { name: 'Can Not Get Locked Brews', message: 'Unable to get locked brew collection', status: 500, HBErrorCode: '68', error };
|
||||
});
|
||||
@@ -252,73 +240,43 @@ export default function createAdminApi(vite) {
|
||||
|
||||
lock.applied = new Date;
|
||||
|
||||
const filter = {
|
||||
shareId : req.params.id
|
||||
};
|
||||
|
||||
const brew = await HomebrewModel.findOne(filter);
|
||||
|
||||
if(!brew) throw { name: 'Brew Not Found', message: 'Cannot find brew to lock', shareId: req.params.id, status: 500, HBErrorCode: '63' };
|
||||
|
||||
if(brew.lock && !lock.overwrite) {
|
||||
throw { name: 'Already Locked', message: 'Lock already exists on brew', shareId: req.params.id, title: brew.title, status: 500, HBErrorCode: '64' };
|
||||
}
|
||||
|
||||
const overwrite = !!lock.overwrite;
|
||||
lock.overwrite = undefined;
|
||||
|
||||
brew.lock = lock;
|
||||
brew.markModified('lock');
|
||||
|
||||
await brew.save()
|
||||
// [fork] ADR-0002
|
||||
const { result, brew } = await getStorage().brews.setLock(req.params.id, lock, { overwrite })
|
||||
.catch((error)=>{
|
||||
throw { name: 'Lock Error', message: 'Unable to set lock', shareId: req.params.id, status: 500, HBErrorCode: '62', error };
|
||||
});
|
||||
|
||||
if(result === 'not-found') throw { name: 'Brew Not Found', message: 'Cannot find brew to lock', shareId: req.params.id, status: 500, HBErrorCode: '63' };
|
||||
|
||||
if(result === 'already-locked') {
|
||||
throw { name: 'Already Locked', message: 'Lock already exists on brew', shareId: req.params.id, title: brew.title, status: 500, HBErrorCode: '64' };
|
||||
}
|
||||
|
||||
return res.json({ name: 'LOCKED', message: `Lock applied to brew ID ${brew.shareId} - ${brew.title}`, ...lock });
|
||||
|
||||
}));
|
||||
|
||||
router.put('/api/unlock/:id', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
|
||||
const filter = {
|
||||
shareId : req.params.id
|
||||
};
|
||||
|
||||
const brew = await HomebrewModel.findOne(filter);
|
||||
|
||||
if(!brew) throw { name: 'Brew Not Found', message: 'Cannot find brew to unlock', shareId: req.params.id, status: 500, HBErrorCode: '66' };
|
||||
|
||||
if(!brew.lock) throw { name: 'Not Locked', message: 'Cannot unlock as brew is not locked', shareId: req.params.id, status: 500, HBErrorCode: '67' };
|
||||
|
||||
brew.lock = undefined;
|
||||
brew.markModified('lock');
|
||||
|
||||
await brew.save()
|
||||
// [fork] ADR-0002
|
||||
const { result } = await getStorage().brews.removeLock(req.params.id)
|
||||
.catch((error)=>{
|
||||
throw { name: 'Cannot Unlock', message: 'Unable to clear lock', shareId: req.params.id, status: 500, HBErrorCode: '65', error };
|
||||
});
|
||||
|
||||
if(result === 'not-found') throw { name: 'Brew Not Found', message: 'Cannot find brew to unlock', shareId: req.params.id, status: 500, HBErrorCode: '66' };
|
||||
|
||||
if(result === 'not-locked') throw { name: 'Not Locked', message: 'Cannot unlock as brew is not locked', shareId: req.params.id, status: 500, HBErrorCode: '67' };
|
||||
|
||||
return res.json({ name: 'Unlocked', message: `Lock removed from brew ID ${req.params.id}` });
|
||||
}));
|
||||
|
||||
router.get('/api/lock/reviews', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
const countReviewsPipeline = [
|
||||
{
|
||||
$match :
|
||||
{
|
||||
'lock.reviewRequested' : { '$exists': 1 }
|
||||
},
|
||||
},
|
||||
{
|
||||
$project : {
|
||||
shareId : 1,
|
||||
editId : 1,
|
||||
title : 1,
|
||||
lock : 1
|
||||
}
|
||||
}
|
||||
];
|
||||
const reviewDocuments = await HomebrewModel.aggregate(countReviewsPipeline)
|
||||
// [fork] ADR-0002
|
||||
const reviewDocuments = await getStorage().brews.listReviewRequests()
|
||||
.catch((error)=>{
|
||||
throw { name: 'Can Not Get Reviews', message: 'Unable to get review collection', status: 500, HBErrorCode: '68', error };
|
||||
});
|
||||
@@ -331,48 +289,32 @@ export default function createAdminApi(vite) {
|
||||
router.put('/api/lock/review/request/:id', asyncHandler(async (req, res)=>{
|
||||
// === This route is NOT Admin only ===
|
||||
// Any user can request a review of their document
|
||||
const filter = {
|
||||
shareId : req.params.id,
|
||||
lock : { $exists: 1 }
|
||||
};
|
||||
|
||||
const brew = await HomebrewModel.findOne(filter);
|
||||
if(!brew) { throw { name: 'Brew Not Found', message: `Cannot find a locked brew with ID ${req.params.id}`, code: 500, HBErrorCode: '70' }; };
|
||||
|
||||
if(brew.lock.reviewRequested){
|
||||
throw { name: 'Review Already Requested', message: `Review already requested for brew ${brew.shareId} - ${brew.title}`, code: 500, HBErrorCode: '71' };
|
||||
};
|
||||
|
||||
brew.lock.reviewRequested = new Date();
|
||||
brew.markModified('lock');
|
||||
|
||||
await brew.save()
|
||||
// [fork] ADR-0002
|
||||
const { result, brew } = await getStorage().brews.requestReview(req.params.id)
|
||||
.catch((error)=>{
|
||||
throw { name: 'Can Not Set Review Request', message: `Unable to set request for review on brew ID ${req.params.id}`, code: 500, HBErrorCode: '69', error };
|
||||
});
|
||||
|
||||
if(result === 'not-found') { throw { name: 'Brew Not Found', message: `Cannot find a locked brew with ID ${req.params.id}`, code: 500, HBErrorCode: '70' }; };
|
||||
|
||||
if(result === 'already-requested') {
|
||||
throw { name: 'Review Already Requested', message: `Review already requested for brew ${brew.shareId} - ${brew.title}`, code: 500, HBErrorCode: '71' };
|
||||
};
|
||||
|
||||
return res.json({ name: 'Review Requested', message: `Review requested on brew ID ${brew.shareId} - ${brew.title}` });
|
||||
|
||||
}));
|
||||
|
||||
router.put('/api/lock/review/remove/:id', mw.adminOnly, asyncHandler(async (req, res)=>{
|
||||
|
||||
const filter = {
|
||||
shareId : req.params.id,
|
||||
'lock.reviewRequested' : { $exists: 1 }
|
||||
};
|
||||
|
||||
const brew = await HomebrewModel.findOne(filter);
|
||||
if(!brew) { throw { name: 'Can Not Clear Review Request', message: `Brew ID ${req.params.id} does not have a review pending!`, HBErrorCode: '73' }; };
|
||||
|
||||
brew.lock.reviewRequested = undefined;
|
||||
brew.markModified('lock');
|
||||
|
||||
await brew.save()
|
||||
// [fork] ADR-0002
|
||||
const { result, brew } = await getStorage().brews.removeReviewRequest(req.params.id)
|
||||
.catch((error)=>{
|
||||
throw { name: 'Can Not Clear Review Request', message: `Unable to remove request for review on brew ID ${req.params.id}`, HBErrorCode: '72', error };
|
||||
});
|
||||
|
||||
if(result === 'not-found') { throw { name: 'Can Not Clear Review Request', message: `Brew ID ${req.params.id} does not have a review pending!`, HBErrorCode: '73' }; };
|
||||
|
||||
return res.json({ name: 'Review Request Cleared', message: `Review request removed for brew ID ${brew.shareId} - ${brew.title}` });
|
||||
|
||||
}));
|
||||
@@ -381,7 +323,7 @@ export default function createAdminApi(vite) {
|
||||
|
||||
router.get('/admin/notification/all', async (req, res, next)=>{
|
||||
try {
|
||||
const notifications = await NotificationModel.getAll();
|
||||
const notifications = await getStorage().notifications.list(); // [fork] ADR-0002
|
||||
return res.json(notifications);
|
||||
|
||||
} catch (error) {
|
||||
@@ -392,7 +334,7 @@ export default function createAdminApi(vite) {
|
||||
|
||||
router.post('/admin/notification/add', mw.adminOnly, async (req, res, next)=>{
|
||||
try {
|
||||
const notification = await NotificationModel.addNotification(req.body);
|
||||
const notification = await getStorage().notifications.create(req.body); // [fork] ADR-0002
|
||||
return res.status(201).json(notification);
|
||||
} catch (error) {
|
||||
console.log('Error adding notification: ', error.message);
|
||||
@@ -402,7 +344,7 @@ export default function createAdminApi(vite) {
|
||||
|
||||
router.delete('/admin/notification/delete/:id', mw.adminOnly, async (req, res, next)=>{
|
||||
try {
|
||||
const notification = await NotificationModel.deleteNotification(req.params.id);
|
||||
const notification = await getStorage().notifications.deleteByDismissKey(req.params.id); // [fork] ADR-0002
|
||||
return res.json(notification);
|
||||
} catch (error) {
|
||||
console.error('Error deleting notification: { key: ', req.params.id, ' error: ', error.message, ' }');
|
||||
|
||||
@@ -56,7 +56,7 @@ describe('Tests for admin api', ()=>{
|
||||
|
||||
const savedNotification = {
|
||||
...inputNotification,
|
||||
_id : expect.any(String),
|
||||
id : expect.any(String),
|
||||
createdAt : expect.any(String),
|
||||
startAt : inputNotification.startAt,
|
||||
stopAt : inputNotification.stopAt
|
||||
|
||||
+22
-13
@@ -25,7 +25,6 @@ import pageRoutes from './page-routes.js';
|
||||
|
||||
import serveCompressedStaticAssets from './static-assets.mv.js';
|
||||
import asyncHandler from 'express-async-handler';
|
||||
import { model as HomebrewModel } from './homebrew.model.js';
|
||||
|
||||
//==== Middleware Imports ====//
|
||||
import contentNegotiation from './middleware/content-negotiation.js';
|
||||
@@ -35,6 +34,11 @@ 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 { createGitBackend } from './fork/git/index.js';
|
||||
import { createAssetsDeliveryRouter } from './fork/assets/index.js';
|
||||
|
||||
import cors from 'cors';
|
||||
|
||||
export default async function createApp(vite) {
|
||||
@@ -45,6 +49,7 @@ export default async function createApp(vite) {
|
||||
const isLocalEnvironment = config.get('local_environments').includes(nodeEnv);
|
||||
|
||||
const sanitizeBrew = (brew, accessType)=>{
|
||||
brew.id = undefined;
|
||||
brew._id = undefined;
|
||||
brew.__v = undefined;
|
||||
if(accessType !== 'edit' && accessType !== 'shareAuthor') {
|
||||
@@ -60,6 +65,7 @@ export default async function createApp(vite) {
|
||||
}
|
||||
|
||||
app.use('/', serveCompressedStaticAssets('build'));
|
||||
app.use(createAssetsDeliveryRouter({ getStorage })); // Fork (ADR 0004): vor Content-Negotiation, <img> sendet Accept: image/*
|
||||
app.use(contentNegotiation);
|
||||
app.use(bodyParser.json({ limit: '25mb' }));
|
||||
app.use(cookieParser());
|
||||
@@ -112,6 +118,17 @@ 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 : (name)=>getStorage().brews.existsAuthor(name)
|
||||
}));
|
||||
|
||||
// Fork: Git-Backend (ADR 0003): /api/git/* und Abgleich bei GET /edit/:id, vor pageRoutes
|
||||
app.use(createGitBackend({ getStorage, api, splitTextStyleAndMetadata }).router);
|
||||
|
||||
app.use(homebrewApi);
|
||||
app.use(adminApi(vite));
|
||||
app.use(vaultApi);
|
||||
@@ -129,7 +146,6 @@ export default async function createApp(vite) {
|
||||
|
||||
app.use(pageRoutes({
|
||||
defaultMetaTags,
|
||||
HomebrewModel,
|
||||
sanitizeBrew,
|
||||
}));
|
||||
|
||||
@@ -177,16 +193,8 @@ export default async function createApp(vite) {
|
||||
if(!ownAccount)
|
||||
return res.status(403).json({ error: 'Must be logged in to change your username' });
|
||||
try {
|
||||
const brews = await HomebrewModel.getByUser(username, true, ['authors']);
|
||||
const renamePromises = brews.map(async (brew)=>{
|
||||
const updatedAuthors = brew.authors.map((author)=>author === username ? newUsername : author
|
||||
);
|
||||
return HomebrewModel.updateOne(
|
||||
{ _id: brew._id },
|
||||
{ $set: { authors: updatedAuthors } }
|
||||
);
|
||||
});
|
||||
await Promise.all(renamePromises);
|
||||
// [fork] ADR-0002
|
||||
await getStorage().brews.renameAuthor(username, newUsername);
|
||||
|
||||
return res.json({ success: true, message: `Brews for ${username} renamed to ${newUsername}.` });
|
||||
} catch (error) {
|
||||
@@ -231,7 +239,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,
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { sniffImageType, typeFromMime } from './sniff.js';
|
||||
import { readAssetsConfig } from './config.js';
|
||||
import { slugifyBasename, buildRepoPath, altText, assetUrl } from './paths.js';
|
||||
import { PNG, GIF, JPEG, WEBP, SVG } from '../../../tests/fork/image-fixtures.js';
|
||||
|
||||
describe('sniffImageType (ADR 0004 §2)', ()=>{
|
||||
test.each([['png', PNG], ['gif', GIF], ['jpeg', JPEG], ['webp', WEBP]])('erkennt %s', (type, buf)=>{
|
||||
expect(sniffImageType(buf)).toBe(type);
|
||||
});
|
||||
test('SVG, Text, leere und fremde Dateien ergeben null', ()=>{
|
||||
expect(sniffImageType(SVG)).toBeNull();
|
||||
expect(sniffImageType(Buffer.from('hallo'))).toBeNull();
|
||||
expect(sniffImageType(Buffer.alloc(0))).toBeNull();
|
||||
expect(sniffImageType(Buffer.from('%PDF-1.4 ....'))).toBeNull();
|
||||
expect(sniffImageType(null)).toBeNull();
|
||||
});
|
||||
test.each([['png', PNG], ['gif', GIF], ['jpeg', JPEG], ['webp', WEBP]])('abgeschnittenes %s ergibt null', (type, buf)=>{
|
||||
expect(sniffImageType(buf.subarray(0, buf.length - 6))).toBeNull();
|
||||
expect(sniffImageType(buf.subarray(0, 4))).toBeNull();
|
||||
});
|
||||
test('JPEG mit Füllbytes nach dem EOI-Marker bleibt gültig', ()=>{
|
||||
expect(sniffImageType(Buffer.concat([JPEG, Buffer.alloc(8)]))).toBe('jpeg');
|
||||
});
|
||||
test('Typ aus Header: Parameter und Aliasse', ()=>{
|
||||
expect(typeFromMime('image/PNG; charset=binary')).toBe('png');
|
||||
expect(typeFromMime('image/jpg')).toBe('jpeg');
|
||||
expect(typeFromMime('image/svg+xml')).toBeNull();
|
||||
expect(typeFromMime(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Konfiguration', ()=>{
|
||||
test('Standardwerte', ()=>{
|
||||
expect(readAssetsConfig({})).toEqual({ enabled: true, maxBytes: 5242880, maxBytesPerBrew: 52428800, types: ['png', 'jpeg', 'gif', 'webp'] });
|
||||
});
|
||||
test('ohne Git-Backend oder mit HB_ASSETS_ENABLED=false deaktiviert', ()=>{
|
||||
expect(readAssetsConfig({}, { gitEnabled: false }).enabled).toBe(false);
|
||||
expect(readAssetsConfig({ HB_ASSETS_ENABLED: 'false' }).enabled).toBe(false);
|
||||
});
|
||||
test('Limits und Typen sind konfigurierbar, jpg ist Alias, Duplikate fallen weg', ()=>{
|
||||
expect(readAssetsConfig({ HB_ASSET_MAX_BYTES: '1000', HB_ASSET_MAX_BYTES_PER_BREW: '5000', HB_ASSET_TYPES: 'png, jpg,jpeg' }))
|
||||
.toMatchObject({ maxBytes: 1000, maxBytesPerBrew: 5000, types: ['png', 'jpeg'] });
|
||||
});
|
||||
test('Leeres HB_ASSET_TYPES (Compose-Vorlage setzt "") gilt als nicht gesetzt', ()=>{
|
||||
expect(readAssetsConfig({ HB_ASSET_TYPES: '' }).types).toEqual(['png', 'jpeg', 'gif', 'webp']);
|
||||
expect(readAssetsConfig({ HB_ASSET_TYPES: ' ' }).types).toEqual(['png', 'jpeg', 'gif', 'webp']);
|
||||
});
|
||||
test('SVG und Unsinn sind Startfehler', ()=>{
|
||||
expect(()=>readAssetsConfig({ HB_ASSET_TYPES: 'png,svg' })).toThrow(/svg/i);
|
||||
expect(()=>readAssetsConfig({ HB_ASSET_TYPES: ',' })).toThrow(/leer/);
|
||||
expect(()=>readAssetsConfig({ HB_ASSET_MAX_BYTES: 'viel' })).toThrow(/HB_ASSET_MAX_BYTES/);
|
||||
expect(()=>readAssetsConfig({ HB_ASSET_MAX_BYTES: '0' })).toThrow(/HB_ASSET_MAX_BYTES/);
|
||||
});
|
||||
test('Mongo: mehr als 15 MiB pro Datei ist ein Startfehler, Postgres nicht', ()=>{
|
||||
const env = { HB_ASSET_MAX_BYTES: String(16 * 1024 * 1024) };
|
||||
expect(()=>readAssetsConfig(env, { driver: 'mongo' })).toThrow(/15 MiB/);
|
||||
expect(readAssetsConfig(env, { driver: 'postgres' }).maxBytes).toBe(16 * 1024 * 1024);
|
||||
expect(readAssetsConfig({ HB_ASSET_MAX_BYTES: String(15 * 1024 * 1024) }, { driver: 'mongo' }).maxBytes).toBe(15 * 1024 * 1024);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pfadbildung (ADR 0004 §2)', ()=>{
|
||||
const sha = 'abcdef0123456789'.repeat(4);
|
||||
test('Slug: Kleinbuchstaben, [a-z0-9-], max. 60 Zeichen, sonst "image"', ()=>{
|
||||
expect(slugifyBasename('Mein Bild (1).PNG')).toBe('mein-bild-1');
|
||||
expect(slugifyBasename(encodeURIComponent('Größe Ärger.jpg'))).toBe('gro-e-arger');
|
||||
expect(slugifyBasename('../../etc/passwd.png')).toBe('passwd');
|
||||
expect(slugifyBasename(`${'a'.repeat(100)}.png`)).toHaveLength(60);
|
||||
expect(slugifyBasename('日本語.png')).toBe('image');
|
||||
expect(slugifyBasename('')).toBe('image');
|
||||
expect(slugifyBasename(undefined)).toBe('image');
|
||||
expect(slugifyBasename('%E0%A4%A.png')).toMatch(/^[a-z0-9-]+$/);
|
||||
});
|
||||
test('Pfad = <assets_dir>/<slug>-<sha[0..11]>.<ext>, Endung aus erkanntem Typ', ()=>{
|
||||
expect(buildRepoPath({ assetsDir: 'assets', filename: 'Karte.jpeg', sha256: sha, type: 'png' })).toBe('assets/karte-abcdef012345.png');
|
||||
expect(buildRepoPath({ assetsDir: 'bilder/neu/', filename: 'x', sha256: sha, type: 'jpeg' })).toBe('bilder/neu/x-abcdef012345.jpg');
|
||||
expect(buildRepoPath({ assetsDir: '', filename: 'x', sha256: sha, type: 'gif' })).toBe('x-abcdef012345.gif');
|
||||
});
|
||||
test('Alt-Text ohne Markdown-Sonderzeichen, URL und Markdown-Form', ()=>{
|
||||
expect(altText('Karte [final] (2)_x.png')).toBe('Karte final 2 x');
|
||||
expect(altText(undefined)).toBe('Bild');
|
||||
expect(assetUrl('share123', sha, 'jpeg')).toBe(`/git-assets/share123/${sha}.jpg`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
// Konfiguration der Bild-Ablage (ADR 0004, "Konfiguration"), ausschließlich aus Umgebungsvariablen.
|
||||
const MIB = 1024 * 1024;
|
||||
const MONGO_MAX_ASSET_BYTES = 15 * MIB; // Dokumentlimit 16 MiB, Rest für Metadaten (ADR 0004 §3)
|
||||
|
||||
// SVG ist bewusst nicht wählbar (Skripte, ADR 0004 §2).
|
||||
export const KNOWN_TYPES = {
|
||||
png : { mime: 'image/png', ext: 'png' },
|
||||
jpeg : { mime: 'image/jpeg', ext: 'jpg' },
|
||||
gif : { mime: 'image/gif', ext: 'gif' },
|
||||
webp : { mime: 'image/webp', ext: 'webp' }
|
||||
};
|
||||
|
||||
const bool = (v, def)=>{
|
||||
if(v === undefined || v === null || v === '') return def;
|
||||
return ['1', 'true', 'yes', 'on'].includes(String(v).trim().toLowerCase());
|
||||
};
|
||||
|
||||
const bytes = (v, def, name)=>{
|
||||
if(v === undefined || v === null || String(v).trim() === '') return def;
|
||||
const n = Number(String(v).trim());
|
||||
if(!Number.isInteger(n) || n < 1) throw new Error(`${name} muss eine positive ganze Zahl (Bytes) sein`);
|
||||
return n;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {object} env
|
||||
* @param {{ gitEnabled?: boolean, driver?: string }} ctx
|
||||
*/
|
||||
export const readAssetsConfig = (env = process.env, { gitEnabled = true, driver } = {})=>{
|
||||
const maxBytes = bytes(env.HB_ASSET_MAX_BYTES, 5 * MIB, 'HB_ASSET_MAX_BYTES');
|
||||
const maxBytesPerBrew = bytes(env.HB_ASSET_MAX_BYTES_PER_BREW, 50 * MIB, 'HB_ASSET_MAX_BYTES_PER_BREW');
|
||||
if(driver === 'mongo' && maxBytes > MONGO_MAX_ASSET_BYTES)
|
||||
throw new Error('HB_ASSET_MAX_BYTES darf mit MongoDB höchstens 15 MiB (15728640) betragen (Dokumentlimit 16 MiB).');
|
||||
|
||||
const rawTypes = String(env.HB_ASSET_TYPES ?? '').trim() || 'png,jpeg,gif,webp';
|
||||
const names = rawTypes.split(',').map((s)=>s.trim().toLowerCase().replace(/^jpg$/, 'jpeg')).filter(Boolean);
|
||||
const unknown = names.filter((n)=>!KNOWN_TYPES[n]);
|
||||
if(unknown.length) throw new Error(`HB_ASSET_TYPES enthält nicht unterstützte Typen: ${unknown.join(', ')} (erlaubt: ${Object.keys(KNOWN_TYPES).join(', ')}; SVG ist ausgeschlossen)`);
|
||||
if(!names.length) throw new Error('HB_ASSET_TYPES darf nicht leer sein');
|
||||
|
||||
return {
|
||||
enabled : gitEnabled && bool(env.HB_ASSETS_ENABLED, true),
|
||||
maxBytes,
|
||||
maxBytesPerBrew,
|
||||
types : [...new Set(names)]
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import express from 'express';
|
||||
import asyncHandler from 'express-async-handler';
|
||||
import { typeForExt, mimeFor } from './paths.js';
|
||||
|
||||
// GET /git-assets/:shareId/:sha256.:ext (ADR 0004 §4). Kein Login, keine Cookies: wer die shareId kennt,
|
||||
// sieht den Brew samt Bildern. Muss VOR der Content-Negotiation-Middleware hängen (Accept: image/* → 406).
|
||||
const FILE = /^([0-9a-f]{64})\.([a-z0-9]{1,5})$/;
|
||||
|
||||
export const createAssetsDeliveryRouter = ({ getStorage, logger = console })=>{
|
||||
const router = express.Router();
|
||||
|
||||
const notFound = (res)=>res.status(404).set('Cache-Control', 'no-store').type('text/plain').send('Nicht gefunden');
|
||||
|
||||
router.get('/git-assets/:shareId/:file', asyncHandler(async (req, res)=>{
|
||||
const m = FILE.exec(req.params.file);
|
||||
const type = m && typeForExt(m[2]);
|
||||
if(!type || !/^[A-Za-z0-9_-]{1,64}$/.test(req.params.shareId)) return notFound(res);
|
||||
const sha256 = m[1];
|
||||
|
||||
let brew; let asset;
|
||||
try {
|
||||
brew = await getStorage().brews.findByShareId(req.params.shareId);
|
||||
if(!brew) return notFound(res);
|
||||
asset = await getStorage().brewAssets.findByBrewAndHash(brew.id, sha256, { withData: true });
|
||||
} catch (err) {
|
||||
logger.error?.('[assets] Auslieferung:', err?.message);
|
||||
return res.status(503).set('Cache-Control', 'no-store').type('text/plain').send('Datenbank nicht erreichbar');
|
||||
}
|
||||
if(!asset || asset.contentType !== mimeFor(type)) return notFound(res);
|
||||
|
||||
// Gesperrte Brews: wie /share (Upstream-Fehler 51)
|
||||
if(brew.lock) return res.status(403).set('Cache-Control', 'no-store').json({ HBErrorCode: '51', message: brew.lock.shareMessage ?? 'Dieser Brew ist gesperrt.' });
|
||||
|
||||
const etag = `"${asset.sha256}"`;
|
||||
res.set({
|
||||
'Content-Type' : asset.contentType,
|
||||
'Cache-Control' : 'public, max-age=31536000, immutable',
|
||||
'ETag' : etag,
|
||||
'X-Content-Type-Options' : 'nosniff',
|
||||
'Content-Security-Policy' : 'default-src \'none\'; sandbox',
|
||||
'Cross-Origin-Resource-Policy' : 'same-site'
|
||||
});
|
||||
if(req.get('if-none-match')?.split(',').map((s)=>s.trim().replace(/^W\//, '')).some((t)=>t === etag || t === '*')) return res.status(304).end();
|
||||
res.set('Content-Length', String(asset.data.length));
|
||||
if(req.method === 'HEAD') return res.end();
|
||||
res.end(asset.data);
|
||||
}));
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import { GitError } from '../git/errors.js';
|
||||
|
||||
// Fehlercodes der Bild-Ablage (ADR 0004). Git-Fehler (G02–G05, G08) kommen unverändert aus dem Git-Backend.
|
||||
export const ASSET_ERRORS = {
|
||||
A01 : { status: 413, message: 'Das Bild ist zu groß.' },
|
||||
A02 : { status: 415, message: 'Dieser Dateityp ist nicht erlaubt.' },
|
||||
A03 : { status: 413, message: 'Das Speicherlimit für Bilder dieses Brews ist erreicht.' },
|
||||
A04 : { status: 423, message: 'Der Brew ist gesperrt, es können keine Bilder hochgeladen werden.' },
|
||||
A05 : { status: 400, message: 'Bilder können nur zu Brews hochgeladen werden, die mit einem Git-Repository verbunden sind.' },
|
||||
A06 : { status: 400, message: 'Es wurde keine Bilddatei übertragen.' },
|
||||
A07 : { status: 503, message: 'Der Bild-Upload ist auf diesem Server nicht aktiviert.' }
|
||||
};
|
||||
|
||||
export class AssetError extends GitError {
|
||||
constructor(code, message, extra = {}) {
|
||||
super(code, message ?? ASSET_ERRORS[code]?.message, { ...extra, status: extra.status ?? ASSET_ERRORS[code]?.status });
|
||||
this.name = 'AssetError';
|
||||
}
|
||||
}
|
||||
|
||||
export const formatBytes = (n)=>{
|
||||
if(n >= 1024 * 1024) return `${+(n / 1024 / 1024).toFixed(1)} MiB`;
|
||||
if(n >= 1024) return `${Math.round(n / 1024)} KiB`;
|
||||
return `${n} Byte`;
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import { readAssetsConfig } from './config.js';
|
||||
import { createAssetService } from './service.js';
|
||||
import { createAssetsRouter } from './routes.js';
|
||||
import { createAssetsDeliveryRouter } from './delivery.js';
|
||||
|
||||
export { readAssetsConfig, createAssetService, createAssetsRouter, createAssetsDeliveryRouter };
|
||||
|
||||
/**
|
||||
* Bild-Ablage (ADR 0004): Upload-Service samt Router. Die Auslieferung hängt separat vor der
|
||||
* Content-Negotiation (createAssetsDeliveryRouter).
|
||||
*/
|
||||
export const createAssetsBackend = ({ gitSvc, getStorage, env = process.env, logger = console })=>{
|
||||
let driver;
|
||||
try { driver = getStorage().driver; } catch { /* Storage noch nicht initialisiert: Treiberprüfung entfällt */ }
|
||||
const cfg = readAssetsConfig(env, { gitEnabled: gitSvc.enabled, driver });
|
||||
const service = createAssetService({ cfg, gitSvc, getStorage, logger });
|
||||
return { service, router: createAssetsRouter(service, { logger }) };
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
import { KNOWN_TYPES } from './config.js';
|
||||
|
||||
// Dateiname → Slug (ADR 0004 §2): Kleinbuchstaben, [a-z0-9-], max. 60 Zeichen, sonst "image".
|
||||
export const slugifyBasename = (filename)=>{
|
||||
let name = '';
|
||||
try { name = decodeURIComponent(String(filename ?? '')); } catch { name = String(filename ?? ''); }
|
||||
name = name.split(/[\\/]/).pop().replace(/\.[A-Za-z0-9]{1,5}$/, '');
|
||||
const slug = name.normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60).replace(/-+$/, '');
|
||||
return slug || 'image';
|
||||
};
|
||||
|
||||
export const extFor = (type)=>KNOWN_TYPES[type].ext;
|
||||
export const mimeFor = (type)=>KNOWN_TYPES[type].mime;
|
||||
export const typeForExt = (ext)=>Object.keys(KNOWN_TYPES).find((t)=>KNOWN_TYPES[t].ext === ext) ?? null;
|
||||
|
||||
// <assets_dir>/<slug>-<sha256[0..11]>.<ext>
|
||||
export const buildRepoPath = ({ assetsDir, filename, sha256, type })=>{
|
||||
const dir = String(assetsDir ?? 'assets').replace(/^\/+|\/+$/g, '');
|
||||
return `${dir ? `${dir}/` : ''}${slugifyBasename(filename)}-${sha256.slice(0, 12)}.${extFor(type)}`;
|
||||
};
|
||||
|
||||
// Anzeigename für das Markdown-Alt: Basisname ohne Endung, ohne Zeichen, die Markdown stören
|
||||
export const altText = (filename)=>{
|
||||
let name = '';
|
||||
try { name = decodeURIComponent(String(filename ?? '')); } catch { name = String(filename ?? ''); }
|
||||
return name.split(/[\\/]/).pop().replace(/\.[A-Za-z0-9]{1,5}$/, '').replace(/[[\]()<>\\`*_!]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 100) || 'Bild';
|
||||
};
|
||||
|
||||
export const assetUrl = (shareId, sha256, type)=>`/git-assets/${shareId}/${sha256}.${extFor(type)}`;
|
||||
@@ -0,0 +1,52 @@
|
||||
import express from 'express';
|
||||
import asyncHandler from 'express-async-handler';
|
||||
import checkClientVersion from '../../middleware/check-client-version.js';
|
||||
import dbCheck from '../../middleware/dbCheck.js';
|
||||
import { GitError } from '../git/errors.js';
|
||||
import { AssetError, formatBytes } from './errors.js';
|
||||
|
||||
// POST /api/git/brews/:editId/assets (ADR 0004 §2). Rohdaten statt Multipart:
|
||||
// Content-Type = Bild-MIME, X-HB-Filename = URL-kodierter Originalname.
|
||||
export const createAssetsRouter = (svc, { logger = console } = {})=>{
|
||||
const router = express.Router();
|
||||
const send = (res, status, body)=>res.status(status).json(body);
|
||||
|
||||
const gate = (req, res, next)=>{
|
||||
if(!svc.enabled) return send(res, 503, new AssetError('A07').toBody());
|
||||
next();
|
||||
};
|
||||
const requireAccount = (req, res, next)=>{
|
||||
if(!req.account) return send(res, 401, { HBErrorCode: '04', message: 'Nicht angemeldet.' });
|
||||
next();
|
||||
};
|
||||
|
||||
// Der Body-Parser antwortet bei Überschreitung selbst mit 413; wir wollen unseren JSON-Fehler
|
||||
const raw = (req, res, next)=>express.raw({ type: ()=>true, limit: svc.cfg.maxBytes })(req, res, (err)=>{
|
||||
if(!err) return next();
|
||||
if(err.type === 'entity.too.large')
|
||||
return send(res, 413, new AssetError('A01', `Das Bild ist zu groß. Erlaubt sind höchstens ${formatBytes(svc.cfg.maxBytes)}.`).toBody());
|
||||
return send(res, err.status ?? 400, new AssetError('A06', 'Das Bild konnte nicht gelesen werden.').toBody());
|
||||
});
|
||||
|
||||
router.get('/api/git/assets/config', (req, res)=>send(res, 200, svc.clientConfig()));
|
||||
|
||||
router.post('/api/git/brews/:editId/assets', dbCheck, checkClientVersion, gate, requireAccount, raw, asyncHandler(async (req, res)=>{
|
||||
try {
|
||||
const { created, asset, brew } = await svc.upload(req.account, req.params.editId, {
|
||||
body : req.body,
|
||||
contentType : req.get('content-type'),
|
||||
filename : req.get('x-hb-filename')
|
||||
});
|
||||
send(res, created ? 201 : 200, svc.toResponse(brew, asset));
|
||||
} catch (err) {
|
||||
if(err instanceof GitError || (err?.HBErrorCode && err?.status)) {
|
||||
if(err.detail) logger.warn?.(`[assets] ${req.method} ${req.path}: ${err.HBErrorCode} ${err.detail}`);
|
||||
return send(res, err.status, err.toBody ? err.toBody() : { HBErrorCode: err.HBErrorCode, message: err.message });
|
||||
}
|
||||
logger.error?.(`[assets] ${req.method} ${req.path}:`, err?.message);
|
||||
send(res, 500, { HBErrorCode: 'G05', message: 'Interner Fehler beim Hochladen.' });
|
||||
}
|
||||
}));
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import crypto from 'crypto';
|
||||
import { GitError } from '../git/errors.js';
|
||||
import { AssetError, formatBytes } from './errors.js';
|
||||
import { sniffImageType, typeFromMime } from './sniff.js';
|
||||
import { buildRepoPath, mimeFor, altText, assetUrl } from './paths.js';
|
||||
|
||||
// Upload von Bildern in das verbundene Repo (ADR 0004 §2). Nutzt die Git-Schicht aus ADR 0003.
|
||||
export const createAssetService = ({ cfg, gitSvc, getStorage, logger = console })=>{
|
||||
const storage = ()=>getStorage();
|
||||
|
||||
const result = (brew, asset)=>({
|
||||
url : assetUrl(brew.shareId, asset.sha256, typeFromMime(asset.contentType)),
|
||||
path : asset.repoPath,
|
||||
sha256 : asset.sha256,
|
||||
size : asset.size,
|
||||
contentType : asset.contentType,
|
||||
markdown : `)})`
|
||||
});
|
||||
|
||||
const svc = {
|
||||
enabled : cfg.enabled && gitSvc.enabled,
|
||||
cfg,
|
||||
|
||||
// Öffentliche Einstellungen für den Client (keine Geheimnisse)
|
||||
clientConfig() {
|
||||
return { enabled: svc.enabled, maxBytes: cfg.maxBytes, maxBytesPerBrew: cfg.maxBytesPerBrew, types: cfg.types };
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {object} account req.account
|
||||
* @param {string} editId
|
||||
* @param {{ body: Buffer, contentType?: string, filename?: string }} input
|
||||
* @returns {Promise<{ created: boolean, asset: object }>}
|
||||
*/
|
||||
async upload(account, editId, { body, contentType, filename }) {
|
||||
if(!svc.enabled) throw new AssetError('A07');
|
||||
const brew = await gitSvc.loadEditableBrew(editId, account);
|
||||
if(brew.lock) throw new AssetError('A04');
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) throw new AssetError('A05');
|
||||
const conn = await storage().gitConnections.findById(link.connectionId);
|
||||
if(!conn) throw new GitError('G08', 'Die Git-Verbindung dieses Brews existiert nicht mehr.');
|
||||
|
||||
if(!Buffer.isBuffer(body) || body.length === 0) throw new AssetError('A06');
|
||||
if(body.length > cfg.maxBytes)
|
||||
throw new AssetError('A01', `Das Bild ist zu groß (${formatBytes(body.length)}). Erlaubt sind höchstens ${formatBytes(cfg.maxBytes)}.`);
|
||||
|
||||
const type = sniffImageType(body);
|
||||
const declared = typeFromMime(contentType);
|
||||
if(!type || !cfg.types.includes(type))
|
||||
throw new AssetError('A02', `Dieser Dateityp ist nicht erlaubt. Erlaubt sind: ${cfg.types.join(', ').toUpperCase()}.`);
|
||||
if(declared !== type)
|
||||
throw new AssetError('A02', `Der Dateityp stimmt nicht mit dem Inhalt überein (erkannt: ${type.toUpperCase()}).`);
|
||||
|
||||
const sha256 = crypto.createHash('sha256').update(body).digest('hex');
|
||||
const author = await gitSvc.authorOf(account);
|
||||
|
||||
// Dedupe, Limitprüfung, Commit und Snapshot unter einem Lock pro Brew, sonst Race beim Brew-Limit
|
||||
return gitSvc.locks.withKey(brew.id, async ()=>{
|
||||
const existing = await storage().brewAssets.findByBrewAndHash(brew.id, sha256);
|
||||
if(existing) return { created: false, asset: { ...existing, filename }, brew };
|
||||
|
||||
const used = await storage().brewAssets.sumSizeByBrew(brew.id);
|
||||
if(used + body.length > cfg.maxBytesPerBrew)
|
||||
throw new AssetError('A03', `Das Speicherlimit für Bilder dieses Brews (${formatBytes(cfg.maxBytesPerBrew)}) wäre überschritten. Belegt: ${formatBytes(used)}.`);
|
||||
|
||||
const repoPath = buildRepoPath({ assetsDir: conn.assetsDir, filename, sha256, type });
|
||||
const { commit } = await gitSvc.commitContent(conn, {
|
||||
branch : link.branch,
|
||||
filePath : repoPath,
|
||||
content : body,
|
||||
author,
|
||||
message : `Add asset ${repoPath} via Homebrewery`,
|
||||
maxBytes : cfg.maxBytes,
|
||||
ignoreConflict : true // inhaltsadressierter Pfad: ein vorhandener Blob ist derselbe Inhalt
|
||||
});
|
||||
|
||||
// Snapshot erst nach erfolgreichem Push (ADR 0004 §2)
|
||||
const asset = await storage().brewAssets.create({ brewId: brew.id, sha256, repoPath, commitSha: commit, contentType: mimeFor(type), size: body.length, data: body });
|
||||
return { created: true, asset: { ...asset, filename }, brew };
|
||||
});
|
||||
},
|
||||
|
||||
toResponse : result
|
||||
};
|
||||
return svc;
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
// Bildtyp anhand der Magic Bytes bestimmen (ADR 0004 §2). Der Header des Clients zählt nicht.
|
||||
// Liefert 'png' | 'jpeg' | 'gif' | 'webp' oder null. Zu kurze oder abgeschnittene Dateien ergeben null.
|
||||
|
||||
const startsWith = (buf, bytes, offset = 0)=>buf.length >= offset + bytes.length && bytes.every((b, i)=>buf[offset + i] === b);
|
||||
const ascii = (buf, str, offset = 0)=>buf.length >= offset + str.length && buf.toString('latin1', offset, offset + str.length) === str;
|
||||
|
||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
||||
|
||||
const isPng = (buf)=>{
|
||||
if(!startsWith(buf, PNG_SIGNATURE) || !ascii(buf, 'IHDR', 12)) return false;
|
||||
// Schluss mit IEND-Chunk (12 Byte: Länge 0, "IEND", CRC), sonst abgeschnitten
|
||||
return buf.length >= 45 && ascii(buf, 'IEND', buf.length - 8);
|
||||
};
|
||||
|
||||
// EOI-Marker (FF D9) in den letzten 32 Byte: manche Kameras hängen Füllbytes an
|
||||
const isJpeg = (buf)=>{
|
||||
if(!startsWith(buf, [0xff, 0xd8, 0xff]) || buf.length < 4) return false;
|
||||
const tail = buf.subarray(Math.max(0, buf.length - 32));
|
||||
return tail.includes(Buffer.from([0xff, 0xd9]));
|
||||
};
|
||||
|
||||
const isGif = (buf)=>(ascii(buf, 'GIF87a') || ascii(buf, 'GIF89a')) && buf.length >= 14 && buf[buf.length - 1] === 0x3b;
|
||||
|
||||
const isWebp = (buf)=>{
|
||||
if(!ascii(buf, 'RIFF') || !ascii(buf, 'WEBP', 8) || buf.length < 20) return false;
|
||||
if(!['VP8 ', 'VP8L', 'VP8X'].some((f)=>ascii(buf, f, 12))) return false;
|
||||
// RIFF-Länge muss zur Dateigröße passen (ohne Padding-Byte), sonst abgeschnitten
|
||||
const declared = buf.readUInt32LE(4) + 8;
|
||||
return buf.length === declared || buf.length === declared + 1;
|
||||
};
|
||||
|
||||
export const sniffImageType = (buf)=>{
|
||||
if(!Buffer.isBuffer(buf) || buf.length === 0) return null;
|
||||
if(isPng(buf)) return 'png';
|
||||
if(isJpeg(buf)) return 'jpeg';
|
||||
if(isGif(buf)) return 'gif';
|
||||
if(isWebp(buf)) return 'webp';
|
||||
return null;
|
||||
};
|
||||
|
||||
// Content-Type-Header auf unseren Typnamen abbilden (ohne Parameter, jpg/pjpeg-Aliasse)
|
||||
export const typeFromMime = (mime)=>{
|
||||
const m = String(mime ?? '').split(';')[0].trim().toLowerCase();
|
||||
return { 'image/png': 'png', 'image/jpeg': 'jpeg', 'image/jpg': 'jpeg', 'image/pjpeg': 'jpeg', 'image/gif': 'gif', 'image/webp': 'webp' }[m] ?? null;
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,452 @@
|
||||
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(express.json());
|
||||
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 = req.body; 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', ()=>{
|
||||
const UPSTREAM_SECRET = 'eigenes-secret'; // wie in buildApp()
|
||||
const rename = (b, body)=>b.req('/api/user/rename', {
|
||||
method : 'PUT', headers : { 'content-type': 'application/json' }, body : JSON.stringify(body)
|
||||
});
|
||||
const ncBrowser = (username)=>{ const b = browser(); b.jar.nc_session = username; return b; };
|
||||
// nc_session-Token, wie naturalcrit es mit jwt-simple ausstellt (HS256, ohne exp)
|
||||
const ncToken = (username, secret = UPSTREAM_SECRET, opts = {})=>jwt.sign({ username, issued: new Date().toISOString() }, secret, { noTimestamp: true, ...opts });
|
||||
const expectDenied = async (res, code)=>{
|
||||
expect(res.status).toBe(403);
|
||||
const body = await res.json();
|
||||
if(code) expect(body.HBErrorCode).toBe(code); else expect(body.HBErrorCode).toBeUndefined();
|
||||
expect(renameCalled).toBe(false);
|
||||
};
|
||||
|
||||
test('OIDC-Session → 403 A01, Upstream-Route wird nicht erreicht', async ()=>{
|
||||
const { b } = await login('alice');
|
||||
await expectDenied(await rename(b, { username: 'victim', newUsername: 'alice' }), 'A01');
|
||||
});
|
||||
|
||||
test('OIDC-Session → 403 A01 auch mit HB_NATURALCRIT_RENAME=signed und gültigem Nachweis', async ()=>{
|
||||
buildApp({ HB_NATURALCRIT_RENAME: 'signed' });
|
||||
const { b } = await login('alice');
|
||||
await expectDenied(await rename(b, { username: 'old', newUsername: 'alice', oldSession: ncToken('old') }), 'A01');
|
||||
});
|
||||
|
||||
test.each([
|
||||
['Standard (oidc,naturalcrit)', {}],
|
||||
['nur oidc', { HB_AUTH_PROVIDERS: 'oidc' }],
|
||||
['nur naturalcrit, signed', { HB_AUTH_PROVIDERS: 'naturalcrit', HB_NATURALCRIT_RENAME: 'signed' }]
|
||||
])('ohne Anmeldung → 403 (%s)', async (name, env)=>{
|
||||
buildApp(env);
|
||||
await expectDenied(await rename(browser(), { username: 'victim', newUsername: 'mallory' }));
|
||||
});
|
||||
|
||||
test('nur oidc: nc_session zählt nicht als Anmeldung → 403', async ()=>{
|
||||
buildApp({ HB_AUTH_PROVIDERS: 'oidc', HB_NATURALCRIT_RENAME: 'signed' });
|
||||
await expectDenied(await rename(ncBrowser('carol'), { username: 'carol-alt', newUsername: 'carol', oldSession: ncToken('carol-alt') }));
|
||||
});
|
||||
|
||||
describe('naturalcrit, Standard HB_NATURALCRIT_RENAME=off', ()=>{
|
||||
test('fremder alter Name → 403 A02', async ()=>{
|
||||
await expectDenied(await rename(ncBrowser('mallory'), { username: 'victim', newUsername: 'mallory' }), 'A02');
|
||||
});
|
||||
|
||||
test('auch mit gültigem Nachweis → 403 A02 (Endpunkt gesperrt)', async ()=>{
|
||||
await expectDenied(await rename(ncBrowser('carol'), { username: 'carol-alt', newUsername: 'carol', oldSession: ncToken('carol-alt') }), 'A02');
|
||||
});
|
||||
});
|
||||
|
||||
describe('naturalcrit, HB_NATURALCRIT_RENAME=signed', ()=>{
|
||||
beforeEach(()=>buildApp({ HB_NATURALCRIT_RENAME: 'signed' }));
|
||||
|
||||
test('eigener Rename mit Nachweis → 200, Upstream-Route erhält den Body ohne Token', async ()=>{
|
||||
const res = await rename(ncBrowser('carol'), { username: 'carol-alt', newUsername: 'carol', oldSession: ncToken('carol-alt') });
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ upstream: true });
|
||||
expect(renameCalled).toEqual({ username: 'carol-alt', newUsername: 'carol' });
|
||||
});
|
||||
|
||||
test('fremder alter Name ohne Nachweis → 403 A03', async ()=>{
|
||||
await expectDenied(await rename(ncBrowser('mallory'), { username: 'victim', newUsername: 'mallory' }), 'A03');
|
||||
});
|
||||
|
||||
test('fremder alter Name mit eigenem Token als Nachweis → 403 A03', async ()=>{
|
||||
await expectDenied(await rename(ncBrowser('mallory'), { username: 'victim', newUsername: 'mallory', oldSession: ncToken('mallory') }), 'A03');
|
||||
});
|
||||
|
||||
test.each([
|
||||
['fremder Schlüssel', ()=>ncToken('victim', 'x'.repeat(40))],
|
||||
['alg HS512', ()=>ncToken('victim', UPSTREAM_SECRET, { algorithm: 'HS512' })],
|
||||
['unsigniert (alg none)', ()=>jwt.sign({ username: 'victim' }, null, { algorithm: 'none' })],
|
||||
['abgelaufen', ()=>ncToken('victim', UPSTREAM_SECRET, { expiresIn: -5 })],
|
||||
['kein String', ()=>({ username: 'victim' })],
|
||||
['Token ohne username', ()=>jwt.sign({ issued: 'x' }, UPSTREAM_SECRET)]
|
||||
])('ungültiger Nachweis (%s) → 403 A03', async (name, token)=>{
|
||||
await expectDenied(await rename(ncBrowser('mallory'), { username: 'victim', newUsername: 'mallory', oldSession: token() }), 'A03');
|
||||
});
|
||||
|
||||
test('newUsername gehört nicht zur Sitzung → 403 A03', async ()=>{
|
||||
await expectDenied(await rename(ncBrowser('mallory'), { username: 'mallory', newUsername: 'victim', oldSession: ncToken('mallory') }), 'A03');
|
||||
});
|
||||
|
||||
test('fehlende Felder → 400', async ()=>{
|
||||
const res = await rename(ncBrowser('carol'), { newUsername: 'carol' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(renameCalled).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
// Auth-Konfiguration ausschließlich aus Umgebungsvariablen (ADR 0001, "Konfiguration").
|
||||
const VALID_PROVIDERS = ['oidc', 'naturalcrit'];
|
||||
// PUT /api/user/rename für naturalcrit-Sitzungen (ADR 0001, Abschnitt 7)
|
||||
const VALID_NC_RENAME = ['off', 'signed'];
|
||||
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'
|
||||
},
|
||||
// PUT /api/user/rename für naturalcrit-Sitzungen; secret = Schlüssel der Upstream-nc_session (ADR 0001, Abschnitt 7)
|
||||
naturalcrit : {
|
||||
rename : (env.HB_NATURALCRIT_RENAME || 'off').trim().toLowerCase(),
|
||||
secret : upstreamSecret
|
||||
}
|
||||
};
|
||||
|
||||
if(!VALID_NC_RENAME.includes(config.naturalcrit.rename)) {
|
||||
throw new Error(`HB_NATURALCRIT_RENAME ungültig: "${env.HB_NATURALCRIT_RENAME}" (erlaubt: ${VALID_NC_RENAME.join(', ')})`);
|
||||
}
|
||||
// Mit dem Standard-"secret" ließe sich der Nachweis (ein signiertes nc_session-Token des alten Namens) fälschen
|
||||
if(config.naturalcrit.rename === 'signed' && providers.includes('naturalcrit') && !isLocal
|
||||
&& (!upstreamSecret || upstreamSecret === 'secret')) {
|
||||
throw new Error('HB_NATURALCRIT_RENAME=signed braucht ein eigenes Upstream-"secret" (Env SECRET), der Standardwert ist unsicher.');
|
||||
}
|
||||
|
||||
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
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
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('HB_NATURALCRIT_RENAME: Standard off, signed erlaubt, unbekannter Wert bricht ab', ()=>{
|
||||
expect(readAuthConfig({}).naturalcrit).toEqual({ rename: 'off', secret: undefined });
|
||||
expect(readAuthConfig({ HB_NATURALCRIT_RENAME: ' Signed ' }, own).naturalcrit).toEqual({ rename: 'signed', secret: 'eigenes-secret' });
|
||||
expect(()=>readAuthConfig({ HB_NATURALCRIT_RENAME: 'upstream' }, own)).toThrow(/HB_NATURALCRIT_RENAME ungültig/);
|
||||
});
|
||||
|
||||
test('HB_NATURALCRIT_RENAME=signed mit Standard-secret bricht außerhalb lokaler Umgebungen ab', ()=>{
|
||||
expect(()=>readAuthConfig({ HB_NATURALCRIT_RENAME: 'signed' }, { upstreamSecret: 'secret' })).toThrow(/eigenes Upstream-"secret"/);
|
||||
expect(()=>readAuthConfig({ HB_NATURALCRIT_RENAME: 'signed' })).toThrow(/eigenes Upstream-"secret"/);
|
||||
expect(readAuthConfig({ HB_NATURALCRIT_RENAME: 'signed' }, { upstreamSecret: 'secret', isLocal: true }).naturalcrit.rename).toBe('signed');
|
||||
// ohne naturalcrit-Provider ist der Modus wirkungslos und kein Startfehler
|
||||
expect(readAuthConfig({ ...base, HB_AUTH_PROVIDERS: 'oidc', HB_NATURALCRIT_RENAME: 'signed' }).naturalcrit.rename).toBe('signed');
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
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';
|
||||
import { renameGuard } from './rename.js';
|
||||
|
||||
export { readAuthConfig, clientConfig };
|
||||
|
||||
const esc = (s)=>String(s).replace(/[&<>"']/g, (c)=>({ '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''' }[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 absichern, bevor sie greift: OIDC gesperrt (A01), naturalcrit nur mit Nachweis (ADR 0001 §7)
|
||||
router.put('/api/user/rename', renameGuard(config));
|
||||
|
||||
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;
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
// Absicherung von PUT /api/user/rename (ADR 0001, Abschnitt 7).
|
||||
// Die Upstream-Route prüft nur, ob newUsername der eigenen Sitzung gehört, nicht aber den alten Namen.
|
||||
// Dieser Wächter läuft im Fork-Router vor der Upstream-Route und lässt nur nachgewiesene Umbenennungen durch.
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const deny = (res, error, HBErrorCode)=>res.status(403).json(HBErrorCode ? { error, HBErrorCode } : { error });
|
||||
|
||||
// Nachweis für den alten Namen: ein mit dem Upstream-"secret" signiertes nc_session-Token (HS256, wie jwt-simple)
|
||||
// mit username === alter Name. Wer es vorlegt, hatte eine Sitzung unter dem alten Namen und konnte dessen Brews
|
||||
// ohnehin bearbeiten; die Umbenennung gibt ihm also keine zusätzlichen Rechte.
|
||||
export const verifyOldNameProof = (token, oldUsername, secret)=>{
|
||||
if(typeof token !== 'string' || !token || !secret) return false;
|
||||
try {
|
||||
const payload = jwt.verify(token, secret, { algorithms: ['HS256'] });
|
||||
return typeof payload?.username === 'string' && payload.username === oldUsername;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {object} config Ergebnis von readAuthConfig()
|
||||
*/
|
||||
export const renameGuard = (config)=>(req, res, next)=>{
|
||||
const account = req.account;
|
||||
if(account?.provider === 'oidc') {
|
||||
return deny(res, 'Benutzernamen von OIDC-Konten sind unveränderlich.', 'A01');
|
||||
}
|
||||
if(!account?.username) {
|
||||
return deny(res, 'Must be logged in to change your username');
|
||||
}
|
||||
if(config.naturalcrit.rename !== 'signed') {
|
||||
return deny(res, 'Umbenennen ist auf dieser Instanz deaktiviert (HB_NATURALCRIT_RENAME=off).', 'A02');
|
||||
}
|
||||
|
||||
const { username, newUsername, oldSession } = req.body ?? {};
|
||||
if(typeof username !== 'string' || typeof newUsername !== 'string' || !username || !newUsername) {
|
||||
return res.status(400).json({ error: 'Username and newUsername are required.' });
|
||||
}
|
||||
if(newUsername !== account.username || !verifyOldNameProof(oldSession, username, config.naturalcrit.secret)) {
|
||||
return deny(res, 'Kein gültiger Nachweis für den alten Benutzernamen (oldSession).', 'A03');
|
||||
}
|
||||
delete req.body.oldSession; // Token nicht an die Upstream-Route und deren Logs weiterreichen
|
||||
next();
|
||||
};
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -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() }));
|
||||
});
|
||||
@@ -0,0 +1,518 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { GitError, redact } from './errors.js';
|
||||
import { createTokenCrypto } from './crypto.js';
|
||||
import { createGitClient } from './gitClient.js';
|
||||
import { createLocks } from './locks.js';
|
||||
import { assertUrlAllowed } from './urlPolicy.js';
|
||||
import { validatePath, validateDir, validateBranch, slugify } from './validate.js';
|
||||
|
||||
// Kernlogik des Git-Backends (ADR 0003 §5): Verbindungen, Laden, Speichern, Konflikte, Pull.
|
||||
|
||||
const MAX_PUSH_ATTEMPTS = 3;
|
||||
|
||||
const noreplyEmail = (username, host)=>`${String(username).replace(/[^A-Za-z0-9._-]+/g, '-')}@users.noreply.${host}`;
|
||||
|
||||
export const publicConnection = (conn)=>({
|
||||
id : conn.id,
|
||||
label : conn.label,
|
||||
repoUrl : conn.repoUrl,
|
||||
authUsername : conn.authUsername,
|
||||
hasToken : !!conn.tokenEnc,
|
||||
defaultBranch : conn.defaultBranch,
|
||||
brewDir : conn.brewDir,
|
||||
assetsDir : conn.assetsDir,
|
||||
createdAt : conn.createdAt,
|
||||
updatedAt : conn.updatedAt,
|
||||
lastVerifiedAt : conn.lastVerifiedAt
|
||||
});
|
||||
|
||||
const publicStatus = (link, conn, { isConnectionOwner = false, brew } = {})=>link ? {
|
||||
linked : true,
|
||||
connectionId : conn?.id,
|
||||
connectionLabel : conn?.label,
|
||||
repoUrl : conn?.repoUrl,
|
||||
branch : link.branch,
|
||||
path : link.path,
|
||||
lastCommitSha : link.lastCommitSha,
|
||||
lastSyncedAt : link.lastSyncedAt,
|
||||
lastError : link.lastError,
|
||||
snapshotAt : brew?.updatedAt ?? null, // Stand, den Share-Links ausliefern (ADR 0003 §6)
|
||||
isConnectionOwner
|
||||
} : { linked: false };
|
||||
|
||||
export const createGitService = ({ cfg, getStorage, api, splitTextStyleAndMetadata, client, locks, logger = console })=>{
|
||||
const tokenCrypto = cfg.enabled ? createTokenCrypto({ key: cfg.key, oldKeys: cfg.oldKeys }) : undefined;
|
||||
client ??= createGitClient(cfg);
|
||||
locks ??= createLocks({ maxConcurrency: cfg.maxConcurrency, maxQueue: cfg.maxQueue });
|
||||
|
||||
const storage = ()=>getStorage();
|
||||
const committer = { name: cfg.committerName, email: cfg.committerEmail };
|
||||
|
||||
const logGit = (what, err)=>logger.warn?.(`[git] ${what}: ${err?.HBErrorCode ?? ''} ${err?.detail ?? err?.message ?? err}`);
|
||||
|
||||
// --- Token ---
|
||||
const getToken = async (conn)=>{
|
||||
let res;
|
||||
try { res = tokenCrypto.decrypt(conn.tokenEnc, conn.id); } catch {
|
||||
throw new GitError('G02', 'Der gespeicherte Token kann nicht entschlüsselt werden. Bitte Token neu hinterlegen.');
|
||||
}
|
||||
if(res.rotate) {
|
||||
await storage().gitConnections.update(conn.id, { tokenEnc: tokenCrypto.encrypt(res.token, conn.id) })
|
||||
.catch((e)=>logGit('Token-Rotation fehlgeschlagen', e));
|
||||
}
|
||||
return res.token;
|
||||
};
|
||||
|
||||
// Operation gegen das Remote einer Verbindung unter globalem Limit
|
||||
const withConn = async (conn, fn, { signal } = {})=>{
|
||||
const token = await getToken(conn);
|
||||
return locks.withSlot(()=>client.withRepo({ repoUrl: conn.repoUrl, authUsername: conn.authUsername, token, signal }, fn), { signal });
|
||||
};
|
||||
|
||||
// --- Rechte ---
|
||||
const isBrewOwner = (brew, account)=>!!account && (brew.authors?.length === 0 || brew.authors?.[0] === account.username);
|
||||
const canEdit = (brew, account)=>!!account && (brew.authors?.length === 0
|
||||
|| brew.authors?.includes(account.username) || brew.invitedAuthors?.includes(account.username));
|
||||
|
||||
const requireUid = (account)=>{
|
||||
if(!account?.uid) throw new GitError('G07');
|
||||
return account.uid;
|
||||
};
|
||||
|
||||
const accessError = (account)=>account
|
||||
? Object.assign(new GitError('G08', 'Du bist kein Autor dieses Brews.', { status: 401 }), { HBErrorCode: '03' })
|
||||
: Object.assign(new GitError('G08', 'Nicht angemeldet.', { status: 401 }), { HBErrorCode: '04' });
|
||||
|
||||
const loadEditableBrew = async (editId, account)=>{
|
||||
const brew = await storage().brews.findByEditId(editId);
|
||||
if(!brew) throw new GitError('G08', 'Brew nicht gefunden.', { status: 404 });
|
||||
if(!canEdit(brew, account)) throw accessError(account);
|
||||
return brew;
|
||||
};
|
||||
|
||||
const authorOf = async (account)=>{
|
||||
let name = account?.username ?? 'Homebrewery';
|
||||
if(account?.uid) {
|
||||
const user = await storage().users.findById(account.uid).catch(()=>null);
|
||||
name = user?.displayName || account.username;
|
||||
}
|
||||
return { name, email: noreplyEmail(account?.username ?? 'homebrewery', cfg.noreplyHost) };
|
||||
};
|
||||
|
||||
// --- Verbindungen ---
|
||||
const parseConnectionInput = async (input, { partial })=>{
|
||||
const out = {};
|
||||
const str = (v)=>typeof v === 'string' ? v.trim() : v;
|
||||
if(!partial || input.label !== undefined) {
|
||||
const label = str(input.label);
|
||||
if(typeof label !== 'string' || label.length < 1 || label.length > 80) throw new GitError('G08', 'Die Bezeichnung muss 1–80 Zeichen lang sein.');
|
||||
out.label = label;
|
||||
}
|
||||
if(!partial || input.repoUrl !== undefined) {
|
||||
out.repoUrl = str(input.repoUrl);
|
||||
await assertUrlAllowed(out.repoUrl, cfg);
|
||||
}
|
||||
if(input.authUsername !== undefined || !partial) {
|
||||
const u = str(input.authUsername) || 'git';
|
||||
if(typeof u !== 'string' || u.length > 100 || u.includes(':') || /[\0-\x1f]/.test(u)) throw new GitError('G08', 'Ungültiger Benutzername für den Git-Server.');
|
||||
out.authUsername = u;
|
||||
}
|
||||
if(input.token !== undefined && input.token !== '') {
|
||||
if(typeof input.token !== 'string' || input.token.length > 2000 || /[\0-\x1f\s]/.test(input.token)) throw new GitError('G08', 'Ungültiger Token.');
|
||||
out.token = input.token;
|
||||
} else if(!partial) throw new GitError('G08', 'Der Token fehlt.');
|
||||
if(input.defaultBranch !== undefined && input.defaultBranch !== '') out.defaultBranch = await validateBranch(str(input.defaultBranch));
|
||||
if(input.brewDir !== undefined) out.brewDir = validateDir(str(input.brewDir));
|
||||
if(input.assetsDir !== undefined) out.assetsDir = validateDir(str(input.assetsDir));
|
||||
return out;
|
||||
};
|
||||
|
||||
const svc = {
|
||||
enabled : cfg.enabled,
|
||||
cfg,
|
||||
locks,
|
||||
canEdit,
|
||||
isBrewOwner,
|
||||
loadEditableBrew,
|
||||
authorOf,
|
||||
|
||||
async listConnections(account) {
|
||||
const uid = requireUid(account);
|
||||
return (await storage().gitConnections.listByOwner(uid)).map(publicConnection);
|
||||
},
|
||||
|
||||
async createConnection(account, input) {
|
||||
const uid = requireUid(account);
|
||||
const data = await parseConnectionInput(input ?? {}, { partial: false });
|
||||
const { token, ...rest } = data;
|
||||
const id = randomUUID();
|
||||
const conn = { id, ownerUserId: uid, ...rest, tokenEnc: tokenCrypto.encrypt(token, id) };
|
||||
// Standard-Branch aus dem Remote (best effort): Fehler hier verhindern das Anlegen nicht, der Test-Button zeigt sie
|
||||
let verified = false;
|
||||
if(!conn.defaultBranch) {
|
||||
conn.defaultBranch = 'main';
|
||||
try {
|
||||
const { defaultBranch } = await withConn(conn, (repo)=>client.lsRemote(repo));
|
||||
if(defaultBranch) conn.defaultBranch = defaultBranch;
|
||||
verified = true;
|
||||
} catch (err) { logGit('ls-remote beim Anlegen', err); }
|
||||
}
|
||||
if(verified) conn.lastVerifiedAt = new Date();
|
||||
return publicConnection(await storage().gitConnections.create(conn));
|
||||
},
|
||||
|
||||
async updateConnection(account, id, input) {
|
||||
const uid = requireUid(account);
|
||||
const existing = await storage().gitConnections.findByIdForOwner(id, uid);
|
||||
if(!existing) throw new GitError('G08', 'Verbindung nicht gefunden.', { status: 404 });
|
||||
const { token, ...patch } = await parseConnectionInput(input ?? {}, { partial: true });
|
||||
if(token) patch.tokenEnc = tokenCrypto.encrypt(token, existing.id);
|
||||
return publicConnection(await storage().gitConnections.update(existing.id, patch));
|
||||
},
|
||||
|
||||
async deleteConnection(account, id) {
|
||||
const uid = requireUid(account);
|
||||
const existing = await storage().gitConnections.findByIdForOwner(id, uid);
|
||||
if(!existing) throw new GitError('G08', 'Verbindung nicht gefunden.', { status: 404 });
|
||||
await storage().gitConnections.delete(existing.id);
|
||||
},
|
||||
|
||||
async ownedConnection(account, id) {
|
||||
const uid = requireUid(account);
|
||||
const conn = await storage().gitConnections.findByIdForOwner(id, uid);
|
||||
if(!conn) throw new GitError('G08', 'Verbindung nicht gefunden.', { status: 404 });
|
||||
return conn;
|
||||
},
|
||||
|
||||
async testConnection(account, id) {
|
||||
const conn = await svc.ownedConnection(account, id);
|
||||
const { defaultBranch, heads } = await withConn(conn, (repo)=>client.lsRemote(repo));
|
||||
await storage().gitConnections.update(conn.id, { lastVerifiedAt: new Date(), ...(defaultBranch && !conn.defaultBranch ? { defaultBranch } : {}) });
|
||||
return { ok: true, defaultBranch: defaultBranch ?? conn.defaultBranch, branchCount: heads.length };
|
||||
},
|
||||
|
||||
async listBranches(account, id) {
|
||||
const conn = await svc.ownedConnection(account, id);
|
||||
const { defaultBranch, heads } = await withConn(conn, (repo)=>client.lsRemote(repo));
|
||||
return { defaultBranch: defaultBranch ?? conn.defaultBranch, branches: heads.map((h)=>h.name).sort() };
|
||||
},
|
||||
|
||||
async listFiles(account, id, { branch, dir }) {
|
||||
const conn = await svc.ownedConnection(account, id);
|
||||
branch = await validateBranch(branch || conn.defaultBranch);
|
||||
dir = validateDir(dir ?? '');
|
||||
const files = await withConn(conn, async (repo)=>{
|
||||
const head = await client.fetchHead(repo, branch);
|
||||
if(!head) throw new GitError('G03');
|
||||
return client.listFiles(repo, head, dir);
|
||||
});
|
||||
return { branch, files };
|
||||
},
|
||||
|
||||
// --- Schreiben ---
|
||||
/**
|
||||
* Schreibt `content` per Commit in Datei `path` auf `branch` (Schritte 2–4 aus ADR 0003 §5).
|
||||
* `expectedBlob`: Blob-ID, die wir zuletzt gesehen haben (null: Datei soll neu sein).
|
||||
* `overwrite`: Blob-ID aus gitOverwrite (bewusstes Überschreiben des fremden Stands).
|
||||
*/
|
||||
async commitContent(conn, { branch, filePath, content, expectedBlob, overwrite, author, signal, message: customMessage, maxBytes = cfg.maxFileBytes, ignoreConflict = false }) {
|
||||
if(Buffer.byteLength(content) > maxBytes) throw new GitError('G09');
|
||||
for (let attempt = 1; attempt <= MAX_PUSH_ATTEMPTS; attempt++) {
|
||||
const result = await withConn(conn, async (repo)=>{
|
||||
const head = await client.fetchHead(repo, branch);
|
||||
let parent = head;
|
||||
if(!head && !(await client.isEmptyRemote(repo))) {
|
||||
// Neuer Branch in nicht leerem Repo: auf Kopf von default_branch aufsetzen
|
||||
parent = await client.fetchHead(repo, conn.defaultBranch);
|
||||
if(!parent) throw new GitError('G03', 'Der Standard-Branch der Verbindung existiert im Repository nicht.');
|
||||
}
|
||||
const remoteBlob = parent ? await client.blobAt(repo, parent, filePath) : null;
|
||||
if(!ignoreConflict && (remoteBlob ?? null) !== (expectedBlob ?? null) && overwrite !== (remoteBlob ?? 'none')) {
|
||||
if(expectedBlob === null && remoteBlob) throw new GitError('G06', undefined, { extra: { remoteCommitSha: parent, remoteBlobSha: remoteBlob } });
|
||||
throw new GitError('G01', undefined, { extra: { remoteCommitSha: parent, remoteBlobSha: remoteBlob } });
|
||||
}
|
||||
const message = customMessage ?? `${remoteBlob ? 'Update' : 'Create'} ${filePath} via Homebrewery`;
|
||||
const { commit, blob } = await client.buildCommit(repo, { parent, filePath, content, author, message, committer });
|
||||
if(head && blob === remoteBlob) return { commit: head, blob, unchanged: true };
|
||||
try {
|
||||
await client.push(repo, commit, branch);
|
||||
} catch (err) {
|
||||
if(err.kind === 'rejected') return { retry: true };
|
||||
throw err;
|
||||
}
|
||||
return { commit, blob };
|
||||
}, { signal });
|
||||
if(!result.retry) return result;
|
||||
}
|
||||
throw new GitError('G05');
|
||||
},
|
||||
|
||||
/**
|
||||
* Entfernt die Datei per Commit (ADR 0003 §5, "Löschen (F9)"). `expectedBlob`: `last_blob_sha`.
|
||||
* Fehlen Branch oder Datei schon, gibt es keinen Commit (`absent`). Abweichender Blob → G01.
|
||||
*/
|
||||
async deleteFile(conn, { branch, filePath, expectedBlob, author, signal }) {
|
||||
for (let attempt = 1; attempt <= MAX_PUSH_ATTEMPTS; attempt++) {
|
||||
const result = await withConn(conn, async (repo)=>{
|
||||
const head = await client.fetchHead(repo, branch);
|
||||
if(!head) return { absent: true };
|
||||
const remoteBlob = await client.blobAt(repo, head, filePath);
|
||||
if(!remoteBlob) return { absent: true };
|
||||
if(remoteBlob !== (expectedBlob ?? null)) throw new GitError('G01', undefined, { extra: { remoteCommitSha: head, remoteBlobSha: remoteBlob } });
|
||||
const commit = await client.buildDeleteCommit(repo, { parent: head, filePath, author, message: `Delete ${filePath} via Homebrewery`, committer });
|
||||
try {
|
||||
await client.push(repo, commit, branch);
|
||||
} catch (err) {
|
||||
if(err.kind === 'rejected') return { retry: true };
|
||||
throw err;
|
||||
}
|
||||
return { commit };
|
||||
}, { signal });
|
||||
if(!result.retry) return result;
|
||||
}
|
||||
throw new GitError('G05');
|
||||
},
|
||||
|
||||
// --- Lesen ---
|
||||
async readRemote(conn, { branch, filePath, signal, withContent = true }) {
|
||||
return withConn(conn, async (repo)=>{
|
||||
const head = await client.fetchHead(repo, branch);
|
||||
if(!head) return { head: null, blob: null, content: null };
|
||||
const blob = await client.blobAt(repo, head, filePath);
|
||||
const wantContent = typeof withContent === 'function' ? withContent(blob) : withContent;
|
||||
const content = blob && wantContent ? await client.readBlob(repo, blob) : null;
|
||||
return { head, blob, content };
|
||||
}, { signal });
|
||||
},
|
||||
|
||||
// Remote-Stand in den DB-Snapshot übernehmen (Pull und Abgleich beim Öffnen)
|
||||
async applyRemote(brew, link, { head, blob, content }) {
|
||||
const fields = { text: content.replaceAll('\r\n', '\n') };
|
||||
splitTextStyleAndMetadata(fields);
|
||||
const updated = {
|
||||
...brew,
|
||||
text : content.replaceAll('\r\n', '\n'),
|
||||
version : (brew.version || 1) + 1,
|
||||
updatedAt : new Date()
|
||||
};
|
||||
if(typeof fields.title === 'string' && fields.title.trim()) updated.title = fields.title.trim().slice(0, 100);
|
||||
if(typeof fields.description === 'string') updated.description = fields.description.trim();
|
||||
if(typeof fields.renderer === 'string') updated.renderer = fields.renderer;
|
||||
if(typeof fields.lang === 'string') updated.lang = fields.lang;
|
||||
const saved = await storage().brews.update(updated);
|
||||
await storage().brewGitLinks.update(brew.id, { lastCommitSha: head, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
|
||||
return saved;
|
||||
},
|
||||
|
||||
// --- Brews ---
|
||||
async createBrew(account, { connectionId, branch, path: filePath, brew }) {
|
||||
const conn = await svc.ownedConnection(account, connectionId);
|
||||
if(!brew || typeof brew.text !== 'string') throw new GitError('G08', 'Der Brew fehlt oder hat keinen Text.');
|
||||
delete brew.editId; delete brew.shareId; delete brew.googleId; delete brew.id; delete brew._id;
|
||||
branch = await validateBranch(branch || conn.defaultBranch);
|
||||
api.beforeNewSave(account, brew);
|
||||
filePath = validatePath(filePath || `${conn.brewDir ? `${conn.brewDir}/` : ''}${slugify(brew.title)}.md`);
|
||||
if(await storage().brewGitLinks.findByLocation(conn.id, branch, filePath)) throw new GitError('G06');
|
||||
const author = await authorOf(account);
|
||||
const { commit, blob } = await svc.commitContent(conn, { branch, filePath, content: brew.text, expectedBlob: null, author });
|
||||
const saved = await storage().brews.create({ ...brew, editId: nanoid(12), shareId: nanoid(12) }); // wie newBrew im Upstream
|
||||
await storage().brewGitLinks.upsert({ brewId: saved.id, connectionId: conn.id, branch, path: filePath, lastCommitSha: commit, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
|
||||
return saved;
|
||||
},
|
||||
|
||||
async importBrew(account, { connectionId, branch, path: filePath }) {
|
||||
const conn = await svc.ownedConnection(account, connectionId);
|
||||
branch = await validateBranch(branch || conn.defaultBranch);
|
||||
filePath = validatePath(filePath);
|
||||
if(await storage().brewGitLinks.findByLocation(conn.id, branch, filePath)) throw new GitError('G06', 'Die Datei ist bereits mit einem Brew verknüpft.');
|
||||
const { head, blob, content } = await svc.readRemote(conn, { branch, filePath });
|
||||
if(!blob) throw new GitError('G03');
|
||||
const brew = { text: content };
|
||||
splitTextStyleAndMetadata(brew);
|
||||
if(!brew.title) brew.title = filePath.split('/').pop().replace(/\.md$/, '');
|
||||
api.beforeNewSave(account, brew);
|
||||
const saved = await storage().brews.create({ ...brew, editId: nanoid(12), shareId: nanoid(12) });
|
||||
await storage().brewGitLinks.upsert({ brewId: saved.id, connectionId: conn.id, branch, path: filePath, lastCommitSha: head, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
|
||||
return saved;
|
||||
},
|
||||
|
||||
async linkBrew(account, editId, { connectionId, branch, path: filePath }) {
|
||||
const conn = await svc.ownedConnection(account, connectionId);
|
||||
const brew = await loadEditableBrew(editId, account);
|
||||
if(!isBrewOwner(brew, account)) throw new GitError('G08', 'Nur der Besitzer des Brews darf ihn verknüpfen.', { status: 403 });
|
||||
if(brew.googleId) throw new GitError('G08', 'Ein Brew liegt entweder in Google Drive oder in Git.');
|
||||
if(await storage().brewGitLinks.findByBrewId(brew.id)) throw new GitError('G08', 'Der Brew ist bereits mit einem Repository verknüpft.');
|
||||
branch = await validateBranch(branch || conn.defaultBranch);
|
||||
filePath = validatePath(filePath || `${conn.brewDir ? `${conn.brewDir}/` : ''}${slugify(brew.title)}.md`);
|
||||
if(await storage().brewGitLinks.findByLocation(conn.id, branch, filePath)) throw new GitError('G06');
|
||||
const author = await authorOf(account);
|
||||
return svc.locks.withKey(brew.id, async ()=>{
|
||||
const { commit, blob } = await svc.commitContent(conn, { branch, filePath, content: brew.text, expectedBlob: null, author });
|
||||
const link = await storage().brewGitLinks.upsert({ brewId: brew.id, connectionId: conn.id, branch, path: filePath, lastCommitSha: commit, lastBlobSha: blob, lastSyncedAt: new Date(), lastError: null });
|
||||
return publicStatus(link, conn, { isConnectionOwner: true, brew });
|
||||
});
|
||||
},
|
||||
|
||||
async unlinkBrew(account, editId) {
|
||||
const brew = await loadEditableBrew(editId, account);
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) return;
|
||||
const conn = await storage().gitConnections.findByIdForOwner(link.connectionId, requireUid(account));
|
||||
if(!conn || !isBrewOwner(brew, account)) throw new GitError('G07', 'Nur der Besitzer der Verbindung und des Brews darf die Verknüpfung lösen.');
|
||||
await storage().brewGitLinks.delete(brew.id);
|
||||
},
|
||||
|
||||
async status(account, editId) {
|
||||
const brew = await loadEditableBrew(editId, account);
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) return { linked: false };
|
||||
const conn = await storage().gitConnections.findById(link.connectionId);
|
||||
return publicStatus(link, conn, { isConnectionOwner: !!account.uid && conn?.ownerUserId === account.uid, brew });
|
||||
},
|
||||
|
||||
async pull(account, editId) {
|
||||
const first = await loadEditableBrew(editId, account);
|
||||
return svc.locks.withKey(first.id, async ()=>{
|
||||
// Brew und Link unter dem Lock neu lesen, damit ein gleichzeitiger Save nicht überschrieben wird
|
||||
const brew = await loadEditableBrew(editId, account);
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) throw new GitError('G08', 'Der Brew ist nicht mit Git verknüpft.');
|
||||
const conn = await storage().gitConnections.findById(link.connectionId);
|
||||
if(!conn) throw new GitError('G08', 'Die Verbindung existiert nicht mehr.');
|
||||
const state = await svc.readRemote(conn, { branch: link.branch, filePath: link.path }).catch(async (err)=>{
|
||||
await storage().brewGitLinks.update(brew.id, { lastError: err.HBErrorCode ?? 'G05' });
|
||||
throw err;
|
||||
});
|
||||
if(!state.blob) throw new GitError('G03');
|
||||
await svc.applyRemote(brew, link, state);
|
||||
return svc.status(account, editId);
|
||||
});
|
||||
},
|
||||
|
||||
// Abgleich beim Öffnen (Express-Middleware für GET /edit/:id), eigenes Zeitbudget
|
||||
openSyncMiddleware() {
|
||||
return async (req, res, next)=>{
|
||||
try {
|
||||
if(!cfg.enabled || !req.account) return next();
|
||||
let id;
|
||||
try { id = api.getId(req).id; } catch { return next(); }
|
||||
const brew = await storage().brews.findByEditId(id);
|
||||
if(!brew || !canEdit(brew, req.account)) return next();
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) return next();
|
||||
const conn = await storage().gitConnections.findById(link.connectionId);
|
||||
if(!conn) return next();
|
||||
|
||||
const signal = AbortSignal.timeout(cfg.openTimeoutMs);
|
||||
try {
|
||||
await locks.withKey(brew.id, async ()=>{
|
||||
const current = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
const fresh = await storage().brews.findByEditId(id);
|
||||
// Inhalt nur laden, wenn sich der Blob geändert hat (im selben Repo-Zugriff)
|
||||
const state = await svc.readRemote(conn, { branch: link.branch, filePath: link.path, signal, withContent: (blob)=>blob !== current.lastBlobSha });
|
||||
if(!state.blob) throw new GitError('G03');
|
||||
if(state.content !== null) {
|
||||
await svc.applyRemote(fresh, current, state);
|
||||
} else if(current.lastError) {
|
||||
await storage().brewGitLinks.update(brew.id, { lastError: null });
|
||||
}
|
||||
}, { signal });
|
||||
} catch (err) {
|
||||
const code = signal.aborted ? 'G04' : (err.HBErrorCode ?? 'G05');
|
||||
logGit(`Abgleich beim Öffnen von ${id} fehlgeschlagen`, err);
|
||||
await storage().brewGitLinks.update(brew.id, { lastError: code }).catch(()=>{});
|
||||
}
|
||||
} catch (err) {
|
||||
logGit('Abgleich beim Öffnen', err);
|
||||
}
|
||||
next();
|
||||
};
|
||||
},
|
||||
|
||||
// --- Hooks für updateBrew (ADR 0003 §5, "Speichern") ---
|
||||
// Liefert null, wenn bereits geantwortet wurde (Fehler), sonst ein Kontextobjekt.
|
||||
async beforeBrewSave({ brew, req, res }) {
|
||||
if(!cfg.enabled || !brew?.id) return {};
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) return {};
|
||||
const conn = await storage().gitConnections.findById(link.connectionId);
|
||||
if(!conn) return {};
|
||||
const fail = (err)=>{
|
||||
if(!(err instanceof GitError)) { logGit('Speichern', err); err = new GitError('G05', 'Speichern im Repository fehlgeschlagen.'); } else if(err.HBErrorCode !== 'G01') logGit(`Speichern von ${brew.editId}`, err);
|
||||
res.status(err.status).json(err.toBody());
|
||||
return null;
|
||||
};
|
||||
if(req.query?.saveToGoogle) return fail(new GitError('G08', 'Ein Brew liegt entweder in Google Drive oder in Git.'));
|
||||
|
||||
let release;
|
||||
try {
|
||||
// Mutex pro Brew, bis afterBrewSave ihn freigibt (Commit und DB-Save sind eine Einheit)
|
||||
release = await svc.locks.acquireKey(brew.id);
|
||||
const author = await authorOf(req.account);
|
||||
const overwrite = typeof req.query?.gitOverwrite === 'string' ? req.query.gitOverwrite : undefined;
|
||||
// Basis der Konflikterkennung unter dem Mutex frisch lesen (ein paralleler Save kann sie verschoben haben)
|
||||
const fresh = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
const result = await svc.commitContent(conn, { branch: fresh.branch, filePath: fresh.path, content: brew.text, expectedBlob: fresh.lastBlobSha, overwrite, author });
|
||||
return { link: fresh, git: { commit: result.commit, blob: result.blob }, release };
|
||||
} catch (err) {
|
||||
release?.();
|
||||
return fail(err);
|
||||
}
|
||||
},
|
||||
|
||||
// --- Hooks für deleteBrew (ADR 0003 §5, "Löschen (F9)") ---
|
||||
// Aufruf nach dem Entfernen des Aufrufers aus `brew.authors`. Liefert null, wenn bereits geantwortet wurde.
|
||||
async beforeBrewDelete({ brew, req, res }) {
|
||||
if(!cfg.enabled || !brew?.id) return {};
|
||||
const link = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!link) return {};
|
||||
const conn = await storage().gitConnections.findById(link.connectionId);
|
||||
if(!conn) return {};
|
||||
const account = req.account;
|
||||
if(brew.authors.length > 0) {
|
||||
// Mitautoren bleiben: Datei bleibt. Geht der Verbindungsbesitzer, wird die Verknüpfung gelöst (nach dem DB-Update).
|
||||
return { unlinkBrewId: !!account?.uid && conn.ownerUserId === account.uid ? brew.id : undefined };
|
||||
}
|
||||
let release;
|
||||
try {
|
||||
release = await svc.locks.acquireKey(brew.id);
|
||||
const fresh = await storage().brewGitLinks.findByBrewId(brew.id);
|
||||
if(!fresh) { release(); return {}; }
|
||||
await svc.deleteFile(conn, { branch: fresh.branch, filePath: fresh.path, expectedBlob: fresh.lastBlobSha, author: await authorOf(account) });
|
||||
return { release };
|
||||
} catch (err) {
|
||||
release?.();
|
||||
if(!(err instanceof GitError)) { logGit('Löschen', err); err = new GitError('G05', 'Löschen im Repository fehlgeschlagen.'); } else if(err.HBErrorCode !== 'G01') logGit(`Löschen von ${brew.editId}`, err);
|
||||
res.status(err.status).json({ ...err.toBody(), operation: 'delete' });
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
async afterBrewDelete(ctx, ok) {
|
||||
try {
|
||||
if(ok && ctx?.unlinkBrewId) await storage().brewGitLinks.delete(ctx.unlinkBrewId);
|
||||
} catch (err) {
|
||||
logGit('Verknüpfung nach dem Löschen lösen', err);
|
||||
} finally {
|
||||
ctx?.release?.();
|
||||
}
|
||||
},
|
||||
|
||||
async afterBrewSave(ctx, saved) {
|
||||
if(!ctx?.git) return;
|
||||
try {
|
||||
if(saved) {
|
||||
await storage().brewGitLinks.update(ctx.link.brewId, { lastCommitSha: ctx.git.commit, lastBlobSha: ctx.git.blob, lastSyncedAt: new Date(), lastError: null });
|
||||
}
|
||||
} catch (err) {
|
||||
logGit('Link nach dem Speichern aktualisieren', err);
|
||||
} finally {
|
||||
ctx.release?.();
|
||||
}
|
||||
}
|
||||
};
|
||||
return svc;
|
||||
};
|
||||
|
||||
export { redact };
|
||||
@@ -0,0 +1,45 @@
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
|
||||
// Konfiguration des Git-Backends ausschließlich aus Umgebungsvariablen (ADR 0003, "Konfiguration").
|
||||
const bool = (v, def = false)=>{
|
||||
if(v === undefined || v === null || v === '') return def;
|
||||
return ['1', 'true', 'yes', 'on'].includes(String(v).trim().toLowerCase());
|
||||
};
|
||||
const int = (v, def, { min = 1, max = Number.MAX_SAFE_INTEGER } = {})=>{
|
||||
const n = parseInt(v, 10);
|
||||
return Number.isFinite(n) ? Math.min(Math.max(n, min), max) : def;
|
||||
};
|
||||
|
||||
export const parseKey = (value, name = 'HB_GIT_TOKEN_KEY')=>{
|
||||
const key = Buffer.from(String(value).trim(), 'base64');
|
||||
if(key.length !== 32) throw new Error(`${name} muss 32 Byte (base64) lang sein, z. B. openssl rand -base64 32`);
|
||||
return key;
|
||||
};
|
||||
|
||||
export const keyId = (key)=>crypto.createHash('sha256').update(key).digest('hex').slice(0, 8);
|
||||
|
||||
export const readGitConfig = (env = process.env)=>{
|
||||
const key = env.HB_GIT_TOKEN_KEY ? parseKey(env.HB_GIT_TOKEN_KEY) : undefined;
|
||||
const oldKeys = (env.HB_GIT_TOKEN_KEYS_OLD || '').split(',').map((s)=>s.trim()).filter(Boolean).map((k)=>parseKey(k, 'HB_GIT_TOKEN_KEYS_OLD'));
|
||||
const timeoutMs = int(env.HB_GIT_TIMEOUT_MS, 20000, { min: 1000 });
|
||||
const publicHost = (()=>{ try { return new URL(env.HB_PUBLIC_URL).hostname; } catch { return 'localhost'; } })();
|
||||
return {
|
||||
enabled : !!key,
|
||||
key,
|
||||
oldKeys,
|
||||
allowedHosts : (env.HB_GIT_ALLOWED_HOSTS || '').split(',').map((s)=>s.trim().toLowerCase()).filter(Boolean),
|
||||
allowPrivate : bool(env.HB_GIT_ALLOW_PRIVATE),
|
||||
allowHttp : bool(env.HB_GIT_ALLOW_HTTP),
|
||||
workdir : env.HB_GIT_WORKDIR || path.join(os.tmpdir(), 'hb-git'),
|
||||
timeoutMs,
|
||||
openTimeoutMs : int(env.HB_GIT_OPEN_TIMEOUT_MS, 4000, { min: 1000, max: timeoutMs }),
|
||||
maxFileBytes : int(env.HB_GIT_MAX_FILE_BYTES, 5 * 1024 * 1024),
|
||||
maxConcurrency : int(env.HB_GIT_MAX_CONCURRENCY, 2),
|
||||
maxQueue : 20,
|
||||
committerName : env.HB_GIT_COMMITTER_NAME || 'Homebrewery',
|
||||
committerEmail : env.HB_GIT_COMMITTER_EMAIL || `homebrewery@${publicHost}`,
|
||||
noreplyHost : publicHost
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import crypto from 'crypto';
|
||||
import { keyId } from './config.js';
|
||||
|
||||
// Token-Verschlüsselung (ADR 0003 §3): AES-256-GCM, Format v1.<kid>.<iv>.<ciphertext>.<tag> (base64url),
|
||||
// AAD = `git-connection:<id>`.
|
||||
const b64 = (buf)=>buf.toString('base64url');
|
||||
const unb64 = (s)=>Buffer.from(s, 'base64url');
|
||||
|
||||
export const createTokenCrypto = ({ key, oldKeys = [] })=>{
|
||||
if(!key) throw new Error('Kein Schlüssel für die Token-Verschlüsselung konfiguriert');
|
||||
const current = { kid: keyId(key), key };
|
||||
const all = new Map([[current.kid, key], ...oldKeys.map((k)=>[keyId(k), k])]);
|
||||
|
||||
return {
|
||||
encrypt(token, connectionId) {
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
||||
cipher.setAAD(Buffer.from(`git-connection:${connectionId}`));
|
||||
const ct = Buffer.concat([cipher.update(String(token), 'utf8'), cipher.final()]);
|
||||
return ['v1', current.kid, b64(iv), b64(ct), b64(cipher.getAuthTag())].join('.');
|
||||
},
|
||||
// → { token, rotate } (rotate: mit altem Schlüssel entschlüsselt, bitte neu verschlüsseln)
|
||||
decrypt(enc, connectionId) {
|
||||
const parts = String(enc).split('.');
|
||||
if(parts.length !== 5 || parts[0] !== 'v1') throw new Error('Unbekanntes Token-Format');
|
||||
const k = all.get(parts[1]);
|
||||
if(!k) throw new Error('Schlüssel zum Entschlüsseln nicht vorhanden');
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', k, unb64(parts[2]));
|
||||
decipher.setAAD(Buffer.from(`git-connection:${connectionId}`));
|
||||
decipher.setAuthTag(unb64(parts[4]));
|
||||
const token = Buffer.concat([decipher.update(unb64(parts[3])), decipher.final()]).toString('utf8');
|
||||
return { token, rotate: parts[1] !== current.kid };
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
// Fehlercodes des Git-Backends (ADR 0003). G01–G07 stehen in der ADR, G08–G10 sind Ergänzungen der Umsetzung.
|
||||
export const GIT_ERRORS = {
|
||||
G01 : { status: 409, message: 'Die Datei wurde im Repository geändert (Konflikt).' },
|
||||
G02 : { status: 502, message: 'Anmeldung am Git-Server fehlgeschlagen (Token ungültig oder ohne Schreibrecht).' },
|
||||
G03 : { status: 502, message: 'Repository, Branch oder Datei nicht gefunden.' },
|
||||
G04 : { status: 504, message: 'Der Git-Server ist nicht erreichbar oder zu langsam.' },
|
||||
G05 : { status: 503, message: 'Speichern im Repository nicht möglich (zu viele gleichzeitige Änderungen oder Server ausgelastet).' },
|
||||
G06 : { status: 409, message: 'Die Datei existiert im Repository bereits.' },
|
||||
G07 : { status: 403, message: 'Das Git-Backend steht nur Konten mit OIDC-Anmeldung zur Verfügung.' },
|
||||
G08 : { status: 400, message: 'Ungültige Eingabe.' },
|
||||
G09 : { status: 413, message: 'Die Datei ist zu groß.' },
|
||||
G10 : { status: 503, message: 'Das Git-Backend ist auf diesem Server nicht aktiviert (HB_GIT_TOKEN_KEY fehlt).' }
|
||||
};
|
||||
|
||||
export class GitError extends Error {
|
||||
constructor(code, message, extra = {}) {
|
||||
super(message ?? GIT_ERRORS[code]?.message ?? code);
|
||||
this.name = 'GitError';
|
||||
this.HBErrorCode = code;
|
||||
this.status = extra.status ?? GIT_ERRORS[code]?.status ?? 500;
|
||||
this.extra = extra.extra ?? {};
|
||||
}
|
||||
toBody() {
|
||||
return { HBErrorCode: this.HBErrorCode, message: this.message, ...this.extra };
|
||||
}
|
||||
}
|
||||
|
||||
// Entfernt Token (auch als Basic-Header) und Authorization-Header aus Text vor dem Loggen/Ausliefern.
|
||||
export const redact = (text, ...secrets)=>{
|
||||
let out = String(text ?? '');
|
||||
for (const secret of secrets.filter((s)=>s && String(s).length >= 3)) {
|
||||
const s = String(secret);
|
||||
out = out.split(s).join('***');
|
||||
out = out.split(Buffer.from(s).toString('base64')).join('***');
|
||||
}
|
||||
return out
|
||||
.replace(/(authorization:\s*(?:basic|bearer)\s+)\S+/gi, '$1***')
|
||||
.replace(/(https?:\/\/)[^\s/@]+@/gi, '$1***@');
|
||||
};
|
||||
@@ -0,0 +1,201 @@
|
||||
import crypto from 'crypto';
|
||||
import { readGitConfig, keyId } from './config.js';
|
||||
import { createTokenCrypto } from './crypto.js';
|
||||
import { assertUrlAllowed, parseRepoUrl, isPrivateAddress } from './urlPolicy.js';
|
||||
import { validatePath, validateBranch, validateDir, slugify } from './validate.js';
|
||||
import { redact, GitError } from './errors.js';
|
||||
import { createLocks, createSemaphore } from './locks.js';
|
||||
|
||||
const key = ()=>crypto.randomBytes(32);
|
||||
|
||||
describe('Token-Verschlüsselung (ADR 0003 §3)', ()=>{
|
||||
const k = key();
|
||||
const c = createTokenCrypto({ key: k });
|
||||
|
||||
test('Roundtrip, Format v1.<kid>.<iv>.<ct>.<tag>, zufälliger IV', ()=>{
|
||||
const enc = c.encrypt('ghp_geheim', 'conn-1');
|
||||
const parts = enc.split('.');
|
||||
expect(parts).toHaveLength(5);
|
||||
expect(parts[0]).toBe('v1');
|
||||
expect(parts[1]).toBe(keyId(k));
|
||||
expect(enc).not.toContain('ghp_geheim');
|
||||
expect(c.decrypt(enc, 'conn-1')).toEqual({ token: 'ghp_geheim', rotate: false });
|
||||
expect(c.encrypt('ghp_geheim', 'conn-1')).not.toBe(enc);
|
||||
});
|
||||
|
||||
test('falsche AAD (andere Verbindung) schlägt fehl', ()=>{
|
||||
const enc = c.encrypt('t', 'conn-1');
|
||||
expect(()=>c.decrypt(enc, 'conn-2')).toThrow();
|
||||
});
|
||||
|
||||
test('manipuliertes Chiffrat und unbekanntes Format schlagen fehl', ()=>{
|
||||
const enc = c.encrypt('t', 'conn-1').split('.');
|
||||
enc[3] = Buffer.from('xxxx').toString('base64url');
|
||||
expect(()=>c.decrypt(enc.join('.'), 'conn-1')).toThrow();
|
||||
expect(()=>c.decrypt('quatsch', 'conn-1')).toThrow();
|
||||
});
|
||||
|
||||
test('Rotation: alter Schlüssel entschlüsselt und meldet rotate', ()=>{
|
||||
const old = key();
|
||||
const enc = createTokenCrypto({ key: old }).encrypt('t', 'c');
|
||||
const rotated = createTokenCrypto({ key: k, oldKeys: [old] });
|
||||
expect(rotated.decrypt(enc, 'c')).toEqual({ token: 't', rotate: true });
|
||||
expect(()=>createTokenCrypto({ key: k }).decrypt(enc, 'c')).toThrow(/Schlüssel/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Konfiguration', ()=>{
|
||||
test('ohne HB_GIT_TOKEN_KEY deaktiviert', ()=>{
|
||||
expect(readGitConfig({}).enabled).toBe(false);
|
||||
});
|
||||
test('Schlüssel muss 32 Byte lang sein', ()=>{
|
||||
expect(()=>readGitConfig({ HB_GIT_TOKEN_KEY: Buffer.from('kurz').toString('base64') })).toThrow(/32 Byte/);
|
||||
expect(readGitConfig({ HB_GIT_TOKEN_KEY: key().toString('base64') }).enabled).toBe(true);
|
||||
});
|
||||
test('Standardwerte und Grenzen', ()=>{
|
||||
const cfg = readGitConfig({ HB_GIT_TOKEN_KEY: key().toString('base64'), HB_PUBLIC_URL: 'https://hb.example.test', HB_GIT_OPEN_TIMEOUT_MS: '999999' });
|
||||
expect(cfg).toMatchObject({ timeoutMs: 20000, openTimeoutMs: 20000, maxFileBytes: 5242880, maxConcurrency: 2, committerName: 'Homebrewery', committerEmail: 'homebrewery@hb.example.test', allowPrivate: false, allowHttp: false });
|
||||
expect(readGitConfig({ HB_GIT_OPEN_TIMEOUT_MS: '10' }).openTimeoutMs).toBe(1000);
|
||||
expect(readGitConfig({}).openTimeoutMs).toBe(4000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('URL-Policy (SSRF)', ()=>{
|
||||
const cfg = { allowedHosts: [], allowPrivate: false, allowHttp: false };
|
||||
const pub = async ()=>[{ address: '93.184.216.34' }];
|
||||
|
||||
test.each([
|
||||
['http://git.example.test/a/b', /https/],
|
||||
['https://user:pw@git.example.test/a/b', /Zugangsdaten/],
|
||||
['https://git.example.test/a/b?x=1', /Query/],
|
||||
['https://git.example.test/a/b#f', /Query/],
|
||||
['https://git.example.test/', /Pfad/],
|
||||
['ssh://git@git.example.test/a/b', /https/],
|
||||
['file:///etc/passwd', /https/],
|
||||
['kein url', /ungültig/]
|
||||
])('lehnt %s ab', async (url, msg)=>{
|
||||
await expect(assertUrlAllowed(url, cfg, { lookup: pub })).rejects.toThrow(msg);
|
||||
});
|
||||
|
||||
test('öffentlicher Host ist erlaubt', async ()=>{
|
||||
await expect(assertUrlAllowed('https://git.example.test:8443/a/b.git', cfg, { lookup: pub })).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
test.each(['127.0.0.1', '10.1.2.3', '172.16.0.1', '172.31.255.255', '192.168.1.1', '169.254.169.254', '100.64.0.1', '0.0.0.0', '::1', 'fd00::1', 'fe80::1', '::ffff:127.0.0.1', '::ffff:7f00:1', '::ffff:a9fe:a9fe', '::ffff:10.0.0.1', '0:0:0:0:0:ffff:7f00:1', '64:ff9b::7f00:1', '::7f00:1', '::a9fe:a9fe', '224.0.0.1'])('%s gilt als intern', (ip)=>{
|
||||
expect(isPrivateAddress(ip)).toBe(true);
|
||||
});
|
||||
test.each(['8.8.8.8', '93.184.216.34', '172.32.0.1', '2606:4700::1111'])('%s gilt als öffentlich', (ip)=>{
|
||||
expect(isPrivateAddress(ip)).toBe(false);
|
||||
});
|
||||
|
||||
test('Host, der auf interne Adresse auflöst, wird abgelehnt (auch gemischt)', async ()=>{
|
||||
const lookup = async ()=>[{ address: '93.184.216.34' }, { address: '10.0.0.5' }];
|
||||
await expect(assertUrlAllowed('https://evil.example.test/a/b', cfg, { lookup })).rejects.toThrow(/privat|intern/i);
|
||||
await expect(assertUrlAllowed('https://127.0.0.1/a/b', cfg, { lookup: pub })).rejects.toThrow();
|
||||
await expect(assertUrlAllowed('https://[::1]/a/b', cfg, { lookup: pub })).rejects.toThrow();
|
||||
});
|
||||
|
||||
test.each(['[::ffff:127.0.0.1]', '[::ffff:a9fe:a9fe]', '[::ffff:10.0.0.1]', '[64:ff9b::7f00:1]', '[::7f00:1]'])('IPv6-Literal %s in der URL wird abgelehnt', async (host)=>{
|
||||
await expect(assertUrlAllowed(`https://${host}/a/b.git`, cfg, { lookup: pub })).rejects.toMatchObject({ HBErrorCode: 'G08' });
|
||||
});
|
||||
|
||||
test('HB_GIT_ALLOW_PRIVATE erlaubt interne Ziele, HB_GIT_ALLOW_HTTP http://', async ()=>{
|
||||
await expect(assertUrlAllowed('http://127.0.0.1:3000/a/b', { ...cfg, allowPrivate: true, allowHttp: true })).resolves.toBeDefined();
|
||||
expect(()=>parseRepoUrl('http://x.test/a/b', { allowHttp: true })).not.toThrow();
|
||||
});
|
||||
|
||||
test('Allowlist: nur passende Hosts, Wildcard *.example.org', async ()=>{
|
||||
const c = { ...cfg, allowedHosts: ['github.com', '*.example.org'] };
|
||||
const never = async ()=>{ throw new Error('kein DNS nötig'); };
|
||||
await expect(assertUrlAllowed('https://github.com/a/b', c, { lookup: never })).resolves.toBeDefined();
|
||||
await expect(assertUrlAllowed('https://git.example.org/a/b', c, { lookup: never })).resolves.toBeDefined();
|
||||
await expect(assertUrlAllowed('https://example.org/a/b', c, { lookup: never })).rejects.toThrow(/nicht erlaubt/);
|
||||
await expect(assertUrlAllowed('https://evilgithub.com/a/b', c, { lookup: never })).rejects.toThrow(/nicht erlaubt/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pfad- und Branch-Validierung', ()=>{
|
||||
test.each(['brews/a.md', 'a.md', 'x/y/z.md'])('Pfad %s ok', (p)=>expect(validatePath(p)).toBe(p));
|
||||
test.each(['', '/abs.md', '../a.md', 'a/../b.md', 'a//b.md', 'a/./b.md', '.git/config.md', 'x/.git/a.md', 'a.txt', 'a\\b.md', `${'a'.repeat(256)}.md`, 'a\0.md'])('Pfad %j abgelehnt', (p)=>{
|
||||
expect(()=>validatePath(p)).toThrow(GitError);
|
||||
});
|
||||
test('Ordner', ()=>{
|
||||
expect(validateDir('brews/')).toBe('brews');
|
||||
expect(validateDir('')).toBe('');
|
||||
expect(()=>validateDir('../x')).toThrow();
|
||||
expect(()=>validateDir('/x')).toThrow();
|
||||
});
|
||||
test('Branch per git check-ref-format', async ()=>{
|
||||
await expect(validateBranch('main')).resolves.toBe('main');
|
||||
await expect(validateBranch('feature/x-1')).resolves.toBe('feature/x-1');
|
||||
for (const bad of ['', '-x', 'a..b', 'a b', 'a~1', 'a^', 'a:b', 'a?', 'a*', 'a[', 'x.lock', '@{-1}', '--upload-pack=evil', 'a//b', '/a']) {
|
||||
await expect(validateBranch(bad)).rejects.toBeInstanceOf(GitError);
|
||||
}
|
||||
});
|
||||
test('slugify', ()=>{
|
||||
expect(slugify('Dungeon Mäster: Teil 1!')).toBe('dungeon-master-teil-1');
|
||||
expect(slugify('')).toBe('brew');
|
||||
expect(slugify('../../etc')).toBe('etc');
|
||||
});
|
||||
});
|
||||
|
||||
describe('redact', ()=>{
|
||||
test('entfernt Token, Basic-Header und Userinfo', ()=>{
|
||||
const token = 'ghp_abcdef123456';
|
||||
const basic = Buffer.from(`git:${token}`).toString('base64');
|
||||
const text = `fatal: x ${token} Authorization: Basic ${basic} https://git:${token}@host/a ${Buffer.from(token).toString('base64')}`;
|
||||
const out = redact(text, token);
|
||||
expect(out).not.toContain(token);
|
||||
expect(out).not.toContain(basic);
|
||||
expect(out).not.toContain(Buffer.from(token).toString('base64'));
|
||||
expect(out).not.toMatch(/Basic [A-Za-z0-9+/=]{8,}/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Locks', ()=>{
|
||||
test('Concurrency-Limit und Queue-Limit (503/G05)', async ()=>{
|
||||
const sem = createSemaphore(1, 1);
|
||||
const r1 = await sem.acquire();
|
||||
const p2 = sem.acquire();
|
||||
await expect(sem.acquire()).rejects.toMatchObject({ HBErrorCode: 'G05' });
|
||||
r1();
|
||||
(await p2)();
|
||||
expect(sem.active).toBe(0);
|
||||
});
|
||||
|
||||
test('Warten wird per AbortSignal abgebrochen (G04)', async ()=>{
|
||||
const sem = createSemaphore(1);
|
||||
const r1 = await sem.acquire();
|
||||
const ac = new AbortController();
|
||||
const p = sem.acquire(ac.signal);
|
||||
ac.abort();
|
||||
await expect(p).rejects.toMatchObject({ HBErrorCode: 'G04' });
|
||||
r1();
|
||||
(await sem.acquire())();
|
||||
expect(sem.waiting).toBe(0);
|
||||
});
|
||||
|
||||
test('Mutex pro Brew serialisiert, verschiedene Brews laufen parallel, Schlüssel werden aufgeräumt', async ()=>{
|
||||
const locks = createLocks();
|
||||
const order = [];
|
||||
const task = (name, ms)=>locks.withKey('brew-1', async ()=>{ order.push(`start ${name}`); await new Promise((r)=>setTimeout(r, ms)); order.push(`end ${name}`); });
|
||||
await Promise.all([task('a', 30), task('b', 1)]);
|
||||
expect(order).toEqual(['start a', 'end a', 'start b', 'end b']);
|
||||
let parallel = 0; let max = 0;
|
||||
await Promise.all(['x', 'y'].map((k)=>locks.withKey(k, async ()=>{ max = Math.max(max, ++parallel); await new Promise((r)=>setTimeout(r, 20)); parallel--; })));
|
||||
expect(max).toBe(2);
|
||||
expect(locks.keyCount).toBe(0);
|
||||
});
|
||||
|
||||
test('acquireKey/release hält den Mutex über mehrere Schritte', async ()=>{
|
||||
const locks = createLocks();
|
||||
const release = await locks.acquireKey('k');
|
||||
let got = false;
|
||||
const p = locks.withKey('k', async ()=>{ got = true; });
|
||||
await new Promise((r)=>setTimeout(r, 10));
|
||||
expect(got).toBe(false);
|
||||
release(); release();
|
||||
await p;
|
||||
expect(got).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,215 @@
|
||||
import { spawn } from 'child_process';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
import { GitError, redact } from './errors.js';
|
||||
import { assertUrlAllowed } from './urlPolicy.js';
|
||||
|
||||
// Einzige Stelle, die `git` startet (execFile, nie Shell). Jede Operation läuft in einem frischen
|
||||
// Bare-Repo unter HB_GIT_WORKDIR, das danach gelöscht wird (ADR 0003 §4).
|
||||
|
||||
const clean = (s)=>String(s ?? '').replace(/[\0-\x1f<>]/g, '').trim();
|
||||
|
||||
const classify = (stderr)=>{
|
||||
const s = String(stderr);
|
||||
if(/couldn't find remote ref/i.test(s)) return 'no-ref';
|
||||
if(/Authentication failed|HTTP Basic: Access denied|could not read (Username|Password)|returned error: (401|403)|Invalid username or password|Permission denied|remote: .*(denied|forbidden|not allowed)/i.test(s)) return 'G02';
|
||||
if(/returned error: 404|not found|does not appear to be a git repository|repository .* does not exist/i.test(s)) return 'G03';
|
||||
if(/non-fast-forward|\[rejected\]|fetch first|stale info|failed to push some refs|cannot lock ref|reference already exists/i.test(s)) return 'rejected';
|
||||
if(/Could not resolve host|Failed to connect|Connection (refused|reset|timed out)|SSL|Operation too slow|timed out|Empty reply|unable to access/i.test(s)) return 'G04';
|
||||
return 'other';
|
||||
};
|
||||
|
||||
export const createGitClient = (cfg, { lookup, gitBinary = 'git' } = {})=>{
|
||||
const baseEnv = (tmp, repoUrl, authUsername, token)=>{
|
||||
const u = new URL(repoUrl);
|
||||
const entries = [
|
||||
['http.extraHeader', `Authorization: Basic ${Buffer.from(`${authUsername || 'git'}:${token}`).toString('base64')}`],
|
||||
['protocol.allow', 'never'],
|
||||
['protocol.https.allow', 'always'],
|
||||
['http.followRedirects', 'false'],
|
||||
['credential.helper', '']
|
||||
];
|
||||
if(u.protocol === 'http:') entries.push(['protocol.http.allow', 'always']);
|
||||
const env = {
|
||||
PATH : process.env.PATH,
|
||||
HOME : tmp,
|
||||
LC_ALL : 'C',
|
||||
GIT_CONFIG_NOSYSTEM : '1',
|
||||
GIT_CONFIG_GLOBAL : '/dev/null',
|
||||
GIT_TERMINAL_PROMPT : '0',
|
||||
GIT_ASKPASS : '/bin/false',
|
||||
GIT_HTTP_LOW_SPEED_LIMIT : '1000',
|
||||
GIT_HTTP_LOW_SPEED_TIME : '10',
|
||||
GIT_CONFIG_COUNT : String(entries.length)
|
||||
};
|
||||
entries.forEach(([k, v], i)=>{ env[`GIT_CONFIG_KEY_${i}`] = k; env[`GIT_CONFIG_VALUE_${i}`] = v; });
|
||||
return env;
|
||||
};
|
||||
|
||||
/**
|
||||
* Öffnet ein temporäres Bare-Repo und ruft fn(repo) auf. `signal` (AbortSignal) bricht laufende
|
||||
* git-Prozesse mit SIGKILL ab, danach wird das Verzeichnis gelöscht.
|
||||
*/
|
||||
const withRepo = async ({ repoUrl, authUsername, token, signal }, fn)=>{
|
||||
await assertUrlAllowed(repoUrl, cfg, { lookup });
|
||||
await fs.mkdir(cfg.workdir, { recursive: true, mode: 0o700 });
|
||||
const tmp = await fs.mkdtemp(path.join(cfg.workdir, 'op-'));
|
||||
const dir = path.join(tmp, 'repo.git');
|
||||
const env = baseEnv(tmp, repoUrl, authUsername, token);
|
||||
const secrets = [token];
|
||||
|
||||
const run = (args, { input, extraEnv, binary = false, maxBytes = 1024 * 1024, cwd = dir } = {})=>new Promise((resolve, reject)=>{
|
||||
if(signal?.aborted) return reject(new GitError('G04'));
|
||||
let aborted = false;
|
||||
let overflow = false;
|
||||
// Eigene Prozessgruppe (execFile reicht `detached` nicht durch): git startet git-remote-http als
|
||||
// Kindprozess, der beim Abbruch mit sterben muss.
|
||||
const child = spawn(gitBinary, args, { cwd, env: { ...env, ...extraEnv }, detached: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
||||
const kill = ()=>{
|
||||
try { process.kill(-child.pid, 'SIGKILL'); } catch { try { child.kill('SIGKILL'); } catch { /* schon beendet */ } }
|
||||
};
|
||||
const out = []; let outBytes = 0;
|
||||
const err = []; let errBytes = 0;
|
||||
child.stdout.on('data', (c)=>{
|
||||
outBytes += c.length;
|
||||
if(outBytes > maxBytes) { overflow = true; kill(); return; }
|
||||
out.push(c);
|
||||
});
|
||||
child.stderr.on('data', (c)=>{ errBytes += c.length; if(errBytes < 64 * 1024) err.push(c); });
|
||||
child.stdin.on('error', ()=>{});
|
||||
const onAbort = ()=>{ aborted = true; kill(); };
|
||||
// Kein AbortSignal.any/timeout: deren Quellsignale werden nur schwach gehalten
|
||||
const timer = setTimeout(onAbort, cfg.timeoutMs);
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
const done = ()=>{ clearTimeout(timer); signal?.removeEventListener('abort', onAbort); };
|
||||
child.on('error', (e)=>{
|
||||
done();
|
||||
reject(new GitError('G05', `git konnte nicht gestartet werden: ${e.code ?? e.message}`));
|
||||
});
|
||||
child.on('close', (code)=>{
|
||||
done();
|
||||
if(aborted) return reject(new GitError('G04'));
|
||||
if(overflow) return reject(new GitError('G09'));
|
||||
const stdout = Buffer.concat(out);
|
||||
if(code === 0) return resolve(binary ? stdout : stdout.toString('utf8'));
|
||||
const text = redact(Buffer.concat(err).toString('utf8'), ...secrets);
|
||||
const kind = classify(text);
|
||||
const known = ['G02', 'G03', 'G04'].includes(kind);
|
||||
const e = new GitError(known ? kind : 'G05', known ? undefined : 'Git-Operation fehlgeschlagen.');
|
||||
e.kind = kind;
|
||||
e.detail = text.slice(0, 2000); // nur für das Server-Log, nie an den Client
|
||||
reject(e);
|
||||
});
|
||||
if(input !== undefined) child.stdin.end(input); else child.stdin.end();
|
||||
});
|
||||
|
||||
try {
|
||||
await run(['init', '--bare', '-q', dir], { cwd: tmp });
|
||||
const idx = path.join(tmp, 'idx');
|
||||
const repo = {
|
||||
run,
|
||||
async str(args, opts) { return String(await run(args, opts)).trim(); },
|
||||
idx,
|
||||
url : repoUrl
|
||||
};
|
||||
return await fn(repo);
|
||||
} finally {
|
||||
await fs.rm(tmp, { recursive: true, force: true }).catch(()=>{});
|
||||
}
|
||||
};
|
||||
|
||||
// --- Operationen auf einem geöffneten Repo ---
|
||||
|
||||
// Holt die Spitze von refs/heads/<branch> (nur Commit und Trees). null, wenn der Branch fehlt.
|
||||
const fetchHead = async (repo, branch)=>{
|
||||
try {
|
||||
await repo.run(['fetch', '-q', '--depth=1', '--filter=blob:none', '--no-tags', repo.url, `refs/heads/${branch}`]);
|
||||
} catch (err) {
|
||||
if(err.kind === 'no-ref') return null;
|
||||
throw err;
|
||||
}
|
||||
return repo.str(['rev-parse', '--verify', 'FETCH_HEAD^{commit}']);
|
||||
};
|
||||
|
||||
const isEmptyRemote = async (repo)=>{
|
||||
const out = await repo.str(['ls-remote', '--heads', repo.url]);
|
||||
return out === '';
|
||||
};
|
||||
|
||||
// Blob-ID der Datei im Commit (null: Datei fehlt)
|
||||
const blobAt = async (repo, head, filePath)=>{
|
||||
if(!head) return null;
|
||||
let sha;
|
||||
try { sha = await repo.str(['rev-parse', '--verify', `${head}:${filePath}`]); } catch { return null; }
|
||||
const type = await repo.str(['cat-file', '-t', sha]);
|
||||
if(type !== 'blob') throw new (GitError)('G08', 'Der Pfad zeigt auf einen Ordner, nicht auf eine Datei.');
|
||||
return sha;
|
||||
};
|
||||
|
||||
const readBlob = async (repo, sha)=>{
|
||||
const buf = await repo.run(['cat-file', 'blob', sha], { binary: true, maxBytes: cfg.maxFileBytes + 1 });
|
||||
if(buf.length > cfg.maxFileBytes) throw new GitError('G09');
|
||||
return buf.toString('utf8');
|
||||
};
|
||||
|
||||
const commitTree = async (repo, { parent, tree, author, message, committer })=>repo.str(['commit-tree', tree, ...(parent ? ['-p', parent] : []), '-m', message], {
|
||||
extraEnv : {
|
||||
GIT_AUTHOR_NAME : clean(author.name) || 'Homebrewery',
|
||||
GIT_AUTHOR_EMAIL : clean(author.email) || committer.email,
|
||||
GIT_COMMITTER_NAME : committer.name,
|
||||
GIT_COMMITTER_EMAIL : committer.email
|
||||
}
|
||||
});
|
||||
|
||||
// Baut einen Commit ohne Arbeitskopie. parent === null → Root-Commit.
|
||||
const buildCommit = async (repo, { parent, filePath, content, author, message, committer })=>{
|
||||
const blob = await repo.str(['hash-object', '-w', '--stdin'], { input: content });
|
||||
const extraEnv = { GIT_INDEX_FILE: repo.idx };
|
||||
if(parent) await repo.run(['read-tree', parent], { extraEnv });
|
||||
await repo.run(['update-index', '--add', '--cacheinfo', `100644,${blob},${filePath}`], { extraEnv });
|
||||
const tree = await repo.str(['write-tree'], { extraEnv });
|
||||
const commit = await commitTree(repo, { parent, tree, author, message, committer });
|
||||
return { commit, blob };
|
||||
};
|
||||
|
||||
// Commit, der die Datei entfernt (ADR 0003 §5, Löschen). parent muss gesetzt sein.
|
||||
const buildDeleteCommit = async (repo, { parent, filePath, author, message, committer })=>{
|
||||
const extraEnv = { GIT_INDEX_FILE: repo.idx };
|
||||
await repo.run(['read-tree', parent], { extraEnv });
|
||||
// Modus 0 entfernt den Eintrag (--force-remove bräuchte eine Arbeitskopie). -z: Pfad wird nicht C-quotiert gelesen.
|
||||
await repo.run(['update-index', '-z', '--index-info'], { extraEnv, input: `0 ${'0'.repeat(40)}\t${filePath}\0` });
|
||||
const tree = await repo.str(['write-tree'], { extraEnv });
|
||||
return commitTree(repo, { parent, tree, author, message, committer });
|
||||
};
|
||||
|
||||
// Push ohne --force. Wirft e.kind === 'rejected' bei Non-Fast-Forward.
|
||||
const push = async (repo, commit, branch)=>{
|
||||
await repo.run(['push', '-q', repo.url, `${commit}:refs/heads/${branch}`]);
|
||||
};
|
||||
|
||||
const lsRemote = async (repo)=>{
|
||||
const out = await repo.str(['ls-remote', '--symref', repo.url, 'HEAD', 'refs/heads/*']);
|
||||
let defaultBranch;
|
||||
const heads = [];
|
||||
for (const line of out.split('\n').filter(Boolean)) {
|
||||
const sym = /^ref: refs\/heads\/(\S+)\tHEAD$/.exec(line);
|
||||
if(sym) { defaultBranch = sym[1]; continue; }
|
||||
const m = /^([0-9a-f]{40,64})\trefs\/heads\/(.+)$/.exec(line);
|
||||
if(m) heads.push({ name: m[2], sha: m[1] });
|
||||
}
|
||||
return { defaultBranch, heads };
|
||||
};
|
||||
|
||||
// Dateien (*.md) in einem Ordner des Branch-Kopfs
|
||||
const listFiles = async (repo, head, dir)=>{
|
||||
const spec = dir ? `${head}:${dir}` : head;
|
||||
let out;
|
||||
try { out = await repo.str(['ls-tree', '-r', '--name-only', spec]); } catch { return []; }
|
||||
return out.split('\n').filter((f)=>f.endsWith('.md')).map((f)=>dir ? `${dir}/${f}` : f);
|
||||
};
|
||||
|
||||
return { withRepo, fetchHead, isEmptyRemote, blobAt, readBlob, buildCommit, buildDeleteCommit, push, lsRemote, listFiles };
|
||||
};
|
||||
|
||||
export const randomId = ()=>crypto.randomBytes(8).toString('hex');
|
||||
@@ -0,0 +1,19 @@
|
||||
// Einhängepunkte für homebrew.api.js (ADR 0003 §5). Ohne konfigurierten Service (Git-Backend aus, Unit-Specs)
|
||||
// sind alle Hooks wirkungslos, damit die Upstream-Datei nur zwei Zeilen braucht.
|
||||
let service;
|
||||
|
||||
export const configureGitHooks = (svc)=>{ service = svc; };
|
||||
|
||||
// → null: Antwort wurde bereits gesendet (Fehler, z. B. Konflikt G01); sonst Kontext (ggf. leer)
|
||||
export const beforeBrewSave = async (args)=>service ? service.beforeBrewSave(args) : {};
|
||||
|
||||
// `saved` ist das Ergebnis des DB-Saves (falsy bei Fehler). Gibt den Brew-Mutex in jedem Fall frei.
|
||||
export const afterBrewSave = async (ctx, saved)=>{ if(service) await service.afterBrewSave(ctx, saved); };
|
||||
|
||||
// Löschen (F9): vor dem DB-Löschen, nachdem der Aufrufer aus `brew.authors` entfernt wurde. → null: schon geantwortet.
|
||||
export const beforeBrewDelete = async (args)=>service ? service.beforeBrewDelete(args) : {};
|
||||
|
||||
// `ok`: DB-Änderung gelungen. Gibt den Brew-Mutex in jedem Fall frei.
|
||||
export const afterBrewDelete = async (ctx, ok)=>{ if(service) await service.afterBrewDelete(ctx, ok); };
|
||||
|
||||
export default { configureGitHooks, beforeBrewSave, afterBrewSave, beforeBrewDelete, afterBrewDelete };
|
||||
@@ -0,0 +1,26 @@
|
||||
import { readGitConfig, keyId } from './config.js';
|
||||
import { createGitService } from './brewSync.js';
|
||||
import { createGitRouter } from './routes.js';
|
||||
import { configureGitHooks } from './hooks.js';
|
||||
import express from 'express';
|
||||
import { createAssetsBackend } from '../assets/index.js';
|
||||
|
||||
export { readGitConfig, createGitService, createGitRouter, configureGitHooks };
|
||||
|
||||
/**
|
||||
* Hängt das Git-Backend ein: Service anlegen, Hooks setzen, Router liefern.
|
||||
* @param {{ getStorage: ()=>object, api: object, splitTextStyleAndMetadata: Function, env?: object, logger?: object }} deps
|
||||
*/
|
||||
export const createGitBackend = ({ getStorage, api, splitTextStyleAndMetadata, env = process.env, logger = console })=>{
|
||||
const cfg = readGitConfig(env);
|
||||
if(!cfg.enabled) logger.warn?.('Git-Backend deaktiviert: HB_GIT_TOKEN_KEY ist nicht gesetzt (openssl rand -base64 32).');
|
||||
else logger.info?.(`Git-Backend aktiv (kid=${keyId(cfg.key)}, alte Schlüssel: ${cfg.oldKeys.length}, Host-Allowlist: ${cfg.allowedHosts.length ? `ja (${cfg.allowedHosts.length})` : 'nein'}).`);
|
||||
const service = createGitService({ cfg, getStorage, api, splitTextStyleAndMetadata, logger });
|
||||
configureGitHooks(cfg.enabled ? service : undefined);
|
||||
// Bild-Upload (ADR 0004) hängt vor dem Git-Router, damit POST …/assets die rohen Bilddaten selbst liest
|
||||
const assets = createAssetsBackend({ gitSvc: service, getStorage, env, logger });
|
||||
const router = express.Router();
|
||||
router.use(assets.router);
|
||||
router.use(createGitRouter(service, { logger }));
|
||||
return { service, assets: assets.service, router };
|
||||
};
|
||||
@@ -0,0 +1,72 @@
|
||||
import { GitError } from './errors.js';
|
||||
|
||||
// Zählender Semaphor mit begrenzter Warteschlange und Abbruch per AbortSignal.
|
||||
export const createSemaphore = (max, maxQueue = Infinity)=>{
|
||||
let active = 0;
|
||||
const queue = [];
|
||||
const release = ()=>{
|
||||
const next = queue.shift();
|
||||
if(next) { next.grant(); } else { active--; }
|
||||
};
|
||||
return {
|
||||
get active() { return active; },
|
||||
get waiting() { return queue.length; },
|
||||
acquire(signal) {
|
||||
if(signal?.aborted) return Promise.reject(new GitError('G04'));
|
||||
if(active < max) { active++; return Promise.resolve(release); }
|
||||
if(queue.length >= maxQueue) return Promise.reject(new GitError('G05', 'Der Server ist mit Git-Operationen ausgelastet, bitte später erneut versuchen.'));
|
||||
return new Promise((resolve, reject)=>{
|
||||
const entry = {
|
||||
grant : ()=>{ signal?.removeEventListener('abort', onAbort); resolve(release); }
|
||||
};
|
||||
const onAbort = ()=>{
|
||||
const i = queue.indexOf(entry);
|
||||
if(i >= 0) queue.splice(i, 1);
|
||||
reject(new GitError('G04'));
|
||||
};
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
queue.push(entry);
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Globales Limit (HB_GIT_MAX_CONCURRENCY) und Mutex pro Brew (prozesslokal).
|
||||
export const createLocks = ({ maxConcurrency = 2, maxQueue = 20 } = {})=>{
|
||||
const global = createSemaphore(maxConcurrency, maxQueue);
|
||||
const perKey = new Map();
|
||||
|
||||
const locks = {
|
||||
global,
|
||||
async withSlot(fn, { signal } = {}) {
|
||||
const release = await global.acquire(signal);
|
||||
try { return await fn(); } finally { release(); }
|
||||
},
|
||||
// Mutex pro Schlüssel; liefert release() für Fälle, in denen er über mehrere Schritte gehalten wird
|
||||
async acquireKey(key, { signal } = {}) {
|
||||
let entry = perKey.get(key);
|
||||
if(!entry) { entry = { sem: createSemaphore(1), users: 0 }; perKey.set(key, entry); }
|
||||
entry.users++;
|
||||
let release;
|
||||
try {
|
||||
release = await entry.sem.acquire(signal);
|
||||
} catch (err) {
|
||||
if(--entry.users === 0) perKey.delete(key);
|
||||
throw err;
|
||||
}
|
||||
let released = false;
|
||||
return ()=>{
|
||||
if(released) return;
|
||||
released = true;
|
||||
release();
|
||||
if(--entry.users === 0) perKey.delete(key);
|
||||
};
|
||||
},
|
||||
async withKey(key, fn, { signal } = {}) {
|
||||
const release = await locks.acquireKey(key, { signal });
|
||||
try { return await fn(); } finally { release(); }
|
||||
},
|
||||
get keyCount() { return perKey.size; }
|
||||
};
|
||||
return locks;
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
import express from 'express';
|
||||
import asyncHandler from 'express-async-handler';
|
||||
import checkClientVersion from '../../middleware/check-client-version.js';
|
||||
import dbCheck from '../../middleware/dbCheck.js';
|
||||
import { GitError } from './errors.js';
|
||||
import { publicConnection } from './brewSync.js';
|
||||
|
||||
// /api/git/* (ADR 0003 §4, §5, §7). Verwaltungsrouten verlangen ein OIDC-Konto (req.account.uid);
|
||||
// Status und Pull verlangen nur das Bearbeitungsrecht am Brew.
|
||||
export const createGitRouter = (svc, { logger = console } = {})=>{
|
||||
const router = express.Router();
|
||||
|
||||
const send = (res, status, body)=>res.status(status).json(body);
|
||||
|
||||
const requireEnabled = (req, res, next)=>{
|
||||
if(!svc.enabled) return send(res, 503, new GitError('G10').toBody());
|
||||
next();
|
||||
};
|
||||
const requireOidc = (req, res, next)=>{
|
||||
if(!req.account?.uid) return send(res, 403, new GitError('G07').toBody());
|
||||
next();
|
||||
};
|
||||
const requireAccount = (req, res, next)=>{
|
||||
if(!req.account) return send(res, 401, { HBErrorCode: '04', message: 'Nicht angemeldet.' });
|
||||
next();
|
||||
};
|
||||
const handle = (fn)=>asyncHandler(async (req, res)=>{
|
||||
try {
|
||||
await fn(req, res);
|
||||
} catch (err) {
|
||||
if(err instanceof GitError || (err?.HBErrorCode && err?.status)) {
|
||||
if(err.detail) logger.warn?.(`[git] ${req.method} ${req.path}: ${err.HBErrorCode} ${err.detail}`);
|
||||
return send(res, err.status, err.toBody ? err.toBody() : { HBErrorCode: err.HBErrorCode, message: err.message });
|
||||
}
|
||||
logger.error?.(`[git] ${req.method} ${req.path}:`, err?.message);
|
||||
send(res, 500, { HBErrorCode: 'G05', message: 'Interner Fehler im Git-Backend.' });
|
||||
}
|
||||
});
|
||||
|
||||
router.use('/api/git', dbCheck, checkClientVersion, requireEnabled);
|
||||
|
||||
// Verbindungen
|
||||
router.get('/api/git/connections', requireOidc, handle(async (req, res)=>send(res, 200, await svc.listConnections(req.account))));
|
||||
router.post('/api/git/connections', requireOidc, handle(async (req, res)=>send(res, 201, await svc.createConnection(req.account, req.body))));
|
||||
router.patch('/api/git/connections/:id', requireOidc, handle(async (req, res)=>send(res, 200, await svc.updateConnection(req.account, req.params.id, req.body))));
|
||||
router.delete('/api/git/connections/:id', requireOidc, handle(async (req, res)=>{ await svc.deleteConnection(req.account, req.params.id); res.status(204).end(); }));
|
||||
router.post('/api/git/connections/:id/test', requireOidc, handle(async (req, res)=>send(res, 200, await svc.testConnection(req.account, req.params.id))));
|
||||
router.get('/api/git/connections/:id/branches', requireOidc, handle(async (req, res)=>send(res, 200, await svc.listBranches(req.account, req.params.id))));
|
||||
router.get('/api/git/connections/:id/files', requireOidc, handle(async (req, res)=>send(res, 200, await svc.listFiles(req.account, req.params.id, { branch: req.query.branch, dir: req.query.dir }))));
|
||||
|
||||
// Brews
|
||||
router.post('/api/git/brews', requireOidc, handle(async (req, res)=>send(res, 200, await svc.createBrew(req.account, req.body ?? {}))));
|
||||
router.post('/api/git/brews/import', requireOidc, handle(async (req, res)=>send(res, 200, await svc.importBrew(req.account, req.body ?? {}))));
|
||||
router.post('/api/git/brews/:editId/link', requireOidc, handle(async (req, res)=>send(res, 200, await svc.linkBrew(req.account, req.params.editId, req.body ?? {}))));
|
||||
router.delete('/api/git/brews/:editId/link', requireOidc, handle(async (req, res)=>{ await svc.unlinkBrew(req.account, req.params.editId); res.status(204).end(); }));
|
||||
router.get('/api/git/brews/:editId', requireAccount, handle(async (req, res)=>send(res, 200, await svc.status(req.account, req.params.editId))));
|
||||
router.post('/api/git/brews/:editId/pull', requireAccount, handle(async (req, res)=>send(res, 200, await svc.pull(req.account, req.params.editId))));
|
||||
|
||||
// Abgleich beim Öffnen, muss vor pageRoutes registriert sein
|
||||
router.get('/edit/:id', svc.openSyncMiddleware());
|
||||
|
||||
return router;
|
||||
};
|
||||
|
||||
export { publicConnection };
|
||||
@@ -0,0 +1,61 @@
|
||||
import dns from 'dns';
|
||||
import net from 'net';
|
||||
import { GitError } from './errors.js';
|
||||
|
||||
// URL- und Host-Prüfung (ADR 0003 §4, SSRF-Schutz).
|
||||
|
||||
export const parseRepoUrl = (value, { allowHttp = false } = {})=>{
|
||||
let u;
|
||||
try { u = new URL(String(value)); } catch { throw new GitError('G08', 'Die Repository-URL ist ungültig.'); }
|
||||
const okProtocol = u.protocol === 'https:' || (allowHttp && u.protocol === 'http:');
|
||||
if(!okProtocol) throw new GitError('G08', 'Nur https://-URLs sind erlaubt.');
|
||||
if(u.username || u.password) throw new GitError('G08', 'Die URL darf keine Zugangsdaten enthalten.');
|
||||
if(u.search || u.hash) throw new GitError('G08', 'Die URL darf keine Query oder kein Fragment enthalten.');
|
||||
if(!u.hostname || u.pathname === '/' || u.pathname === '') throw new GitError('G08', 'Die URL muss einen Repository-Pfad enthalten.');
|
||||
if(String(value).length > 500) throw new GitError('G08', 'Die URL ist zu lang.');
|
||||
return u;
|
||||
};
|
||||
|
||||
const hostMatches = (host, pattern)=>pattern.startsWith('*.') ? host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1 : host === pattern;
|
||||
|
||||
const blocked = new net.BlockList();
|
||||
[
|
||||
['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16],
|
||||
['172.16.0.0', 12], ['192.0.0.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['224.0.0.0', 3]
|
||||
].forEach(([n, p])=>blocked.addSubnet(n, p, 'ipv4'));
|
||||
[
|
||||
['::', 96], // IPv4-kompatibel (::a.b.c.d), schließt :: und ::1 ein
|
||||
['::1', 128], ['fc00::', 7], ['fe80::', 10], ['ff00::', 8],
|
||||
['64:ff9b::', 96], // NAT64
|
||||
['2002::', 16] // 6to4
|
||||
].forEach(([n, p])=>blocked.addSubnet(n, p, 'ipv6'));
|
||||
// IPv4-gemappte Adressen (::ffff:a.b.c.d, auch als ::ffff:7f00:1) prüft BlockList selbst gegen die IPv4-Regeln.
|
||||
|
||||
export const isPrivateAddress = (address)=>{
|
||||
const ip = String(address).toLowerCase().replace(/^\[|\]$/g, '').split('%')[0];
|
||||
if(net.isIPv4(ip)) return blocked.check(ip, 'ipv4');
|
||||
if(net.isIPv6(ip)) return blocked.check(ip, 'ipv6');
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wirft G08, wenn die URL nicht erlaubt ist. `lookup` ist für Tests austauschbar.
|
||||
*/
|
||||
export const assertUrlAllowed = async (value, cfg, { lookup = dns.promises.lookup } = {})=>{
|
||||
const u = parseRepoUrl(value, cfg);
|
||||
const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
||||
if(cfg.allowedHosts?.length) {
|
||||
if(!cfg.allowedHosts.some((p)=>hostMatches(host, p)))
|
||||
throw new GitError('G08', 'Dieser Git-Host ist auf dieser Instanz nicht erlaubt.');
|
||||
return u;
|
||||
}
|
||||
if(cfg.allowPrivate) return u;
|
||||
let addrs;
|
||||
if(net.isIP(host)) addrs = [{ address: host }];
|
||||
else {
|
||||
try { addrs = await lookup(host, { all: true }); } catch { throw new GitError('G04', 'Der Git-Host konnte nicht aufgelöst werden.'); }
|
||||
}
|
||||
if(!addrs.length || addrs.some((a)=>isPrivateAddress(a.address)))
|
||||
throw new GitError('G08', 'Interne oder private Adressen sind als Git-Ziel nicht erlaubt.');
|
||||
return u;
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import { execFile } from 'child_process';
|
||||
import { GitError } from './errors.js';
|
||||
|
||||
// Pfad- und Branch-Validierung (ADR 0003 §2).
|
||||
export const validatePath = (p)=>{
|
||||
const bad = (msg)=>{ throw new GitError('G08', `Ungültiger Pfad: ${msg}`); };
|
||||
if(typeof p !== 'string' || !p) bad('leer');
|
||||
if(p.length > 255) bad('länger als 255 Zeichen');
|
||||
if(p.startsWith('/') || p.includes('\\') || /[\0-\x1f]/.test(p)) bad('nur relative Pfade mit / erlaubt');
|
||||
const parts = p.split('/');
|
||||
if(parts.some((s)=>s === '' || s === '.' || s === '..')) bad('kein .., . oder leere Segmente');
|
||||
if(parts[0].toLowerCase() === '.git' || parts.some((s)=>s.toLowerCase() === '.git')) bad('nicht unter .git');
|
||||
if(!p.endsWith('.md')) bad('Endung .md erforderlich');
|
||||
return p;
|
||||
};
|
||||
|
||||
// Ordner (ohne Endung-Pflicht), für brewDir/assetsDir und Dateilisten
|
||||
export const validateDir = (d)=>{
|
||||
if(d === '' || d === undefined || d === null) return '';
|
||||
if(typeof d !== 'string' || d.length > 255 || d.startsWith('/') || d.includes('\\') || /[\0-\x1f]/.test(d))
|
||||
throw new GitError('G08', 'Ungültiger Ordner.');
|
||||
const parts = d.replace(/\/+$/, '').split('/');
|
||||
if(parts.some((s)=>s === '' || s === '.' || s === '..' || s.toLowerCase() === '.git'))
|
||||
throw new GitError('G08', 'Ungültiger Ordner.');
|
||||
return parts.join('/');
|
||||
};
|
||||
|
||||
// `git check-ref-format` auf refs/heads/<name> (nicht --branch: das expandiert z. B. "@{-1}").
|
||||
export const validateBranch = (name)=>new Promise((resolve, reject)=>{
|
||||
const bad = ()=>reject(new GitError('G08', 'Ungültiger Branch-Name.'));
|
||||
if(typeof name !== 'string' || !name || name.length > 255 || name.startsWith('-') || /[\0-\x1f]/.test(name)) return bad();
|
||||
execFile('git', ['check-ref-format', `refs/heads/${name}`], { timeout: 5000 }, (err)=>err ? bad() : resolve(name));
|
||||
});
|
||||
|
||||
export const slugify = (title)=>{
|
||||
const s = String(title || '').normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
|
||||
return s || 'brew';
|
||||
};
|
||||
+64
-51
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable max-lines */
|
||||
import _ from 'lodash';
|
||||
import { model as HomebrewModel } from './homebrew.model.js';
|
||||
import { getStorage } from './storage/index.js';
|
||||
import express from 'express';
|
||||
import GoogleActions from './googleActions.js';
|
||||
import { hbfm } from 'marked-hbfm';
|
||||
@@ -13,6 +13,7 @@ import { splitTextStyleAndMetadata,
|
||||
brewSnippetsToJSON, debugTextMismatch } from '../shared/helpers.js';
|
||||
import checkClientVersion from './middleware/check-client-version.js';
|
||||
import dbCheck from './middleware/dbCheck.js';
|
||||
import { beforeBrewSave as gitBeforeBrewSave, afterBrewSave as gitAfterBrewSave, beforeBrewDelete as gitBeforeBrewDelete, afterBrewDelete as gitAfterBrewDelete } from './fork/git/hooks.js'; // [fork] ADR-0003
|
||||
|
||||
|
||||
const router = express.Router();
|
||||
@@ -96,7 +97,8 @@ const api = {
|
||||
|
||||
const userThemes = {};
|
||||
|
||||
const brews = await HomebrewModel.getByUser(username, true, fields, { tags: { $in: ['meta:theme', 'meta:Theme'] } });
|
||||
// [fork] ADR-0002
|
||||
const brews = await getStorage().brews.listByAuthor(username, { includeUnpublished: true, fields, tagsAny: ['meta:theme', 'meta:Theme'] });
|
||||
|
||||
for (const brew of brews) {
|
||||
userThemes[brew.renderer] ??= {};
|
||||
@@ -120,20 +122,23 @@ const api = {
|
||||
let { id, googleId } = api.getId(req);
|
||||
|
||||
const accessMap = {
|
||||
edit : { editId: id },
|
||||
share : { shareId: id },
|
||||
admin : { $or: [{ editId: id }, { shareId: id }] }
|
||||
edit : (brewId)=>getStorage().brews.findByEditId(brewId),
|
||||
share : (brewId)=>getStorage().brews.findByShareId(brewId),
|
||||
admin : (brewId)=>getStorage().brews.findByEditOrShareId(brewId)
|
||||
};
|
||||
|
||||
// Try to find the document in the Homebrewery database -- if it doesn't exist, that's fine.
|
||||
let stub = await HomebrewModel.get(accessMap[accessType])
|
||||
// [fork] ADR-0002
|
||||
let stub = await accessMap[accessType](id)
|
||||
.catch((err)=>{
|
||||
if(googleId)
|
||||
console.warn(`Unable to find document stub for ${accessType}Id ${id}`);
|
||||
else
|
||||
console.warn(err);
|
||||
console.warn(err);
|
||||
});
|
||||
stub = stub?.toObject();
|
||||
if(!stub) {
|
||||
if(googleId)
|
||||
console.warn(`Unable to find document stub for ${accessType}Id ${id}`);
|
||||
else
|
||||
console.warn(`Unable to find brew for ${accessType}Id ${id}`);
|
||||
}
|
||||
googleId ??= stub?.googleId;
|
||||
|
||||
const isOwner = (accessType == 'edit' && (!stub || stub?.authors?.length === 0)) || stub?.authors?.[0] === req.account?.username;
|
||||
@@ -219,13 +224,13 @@ const api = {
|
||||
.slice(0, MAX_TITLE_LENGTH);
|
||||
},
|
||||
excludePropsFromUpdate : (brew)=>{ //Remove props that should not update/overwrite when editing
|
||||
return _.omit(brew, ['_id', 'views', 'lastViewed']);
|
||||
return _.omit(brew, ['id', '_id', 'views', 'lastViewed']);
|
||||
},
|
||||
excludeGoogleProps : (brew)=>{ //Remove props that should not be saved to Google (only stored to Homebrewery stub)
|
||||
return _.omit(brew, ['version', 'tags', 'systems', 'published', 'authors', 'invitedAuthors', 'owner', 'views', 'thumbnail']);
|
||||
},
|
||||
excludeStubProps : (brew)=>{ //Remove props that should not be saved to stub-only brews
|
||||
brew.text = brew.textBin = undefined; // Can't use _.omit because this brew is a Mongoose object
|
||||
brew.text = brew.textBin = undefined; // Direkte Zuweisung statt _.omit: die Felder müssen als `undefined` erhalten bleiben (Stub)
|
||||
return brew;
|
||||
},
|
||||
beforeNewSave : (account, brew)=>{
|
||||
@@ -256,9 +261,7 @@ const api = {
|
||||
|
||||
api.beforeNewSave(req.account, brew);
|
||||
|
||||
let newHomebrew = new HomebrewModel(brew);
|
||||
newHomebrew.editId = nanoid(12);
|
||||
newHomebrew.shareId = nanoid(12);
|
||||
let newHomebrew = { ...brew, editId: nanoid(12), shareId: nanoid(12) };
|
||||
|
||||
let googleId, saved;
|
||||
if(saveToGoogle) {
|
||||
@@ -268,14 +271,14 @@ const api = {
|
||||
newHomebrew = api.excludeStubProps(newHomebrew);
|
||||
newHomebrew.googleId = googleId;
|
||||
}
|
||||
|
||||
saved = await newHomebrew.save()
|
||||
|
||||
// [fork] ADR-0002
|
||||
saved = await getStorage().brews.create(newHomebrew)
|
||||
.catch((err)=>{
|
||||
console.error(err, err.toString(), err.stack);
|
||||
throw { name: 'BrewSave Error', message: `Error while creating new brew, ${err.toString()}`, status: 500, HBErrorCode: '06' };
|
||||
});
|
||||
if(!saved) return;
|
||||
saved = saved.toObject();
|
||||
|
||||
res.status(200).send(saved);
|
||||
},
|
||||
@@ -398,18 +401,20 @@ const api = {
|
||||
brew.invitedAuthors = _.uniq(_.filter(brew.invitedAuthors, (a)=>req.account.username !== a));
|
||||
}
|
||||
|
||||
// [fork] ADR-0003: Git-Commit vor dem DB-Save; bei null wurde schon geantwortet (z. B. Konflikt G01)
|
||||
const gitCtx = await gitBeforeBrewSave({ brew, req, res });
|
||||
if(!gitCtx) return;
|
||||
|
||||
//=====----- Update to or remove from Google Drive -----=========//
|
||||
const originalGoogleId = brew.googleId;
|
||||
const { saveToGoogle, removeFromGoogle } = req.query;
|
||||
|
||||
if(brew.googleId && removeFromGoogle) { // If removing from google, remove the brew's googleId
|
||||
brew.googleId = undefined;
|
||||
}
|
||||
else if(!brew.googleId && saveToGoogle) { // If adding to google, create new google document and record the googleId
|
||||
} else if(!brew.googleId && saveToGoogle) { // If adding to google, create new google document and record the googleId
|
||||
brew.googleId = await api.newGoogleBrew(req.account, brew, res);
|
||||
if(!brew.googleId) return;
|
||||
}
|
||||
else if(brew.googleId) { // If already on google, update the google brew
|
||||
} else if(brew.googleId) { // If already on google, update the google brew
|
||||
const updated = await GoogleActions.updateGoogleBrew(api.excludeGoogleProps(brew), req.ip);
|
||||
if(!updated) return;
|
||||
}
|
||||
@@ -420,17 +425,18 @@ const api = {
|
||||
brew = api.excludeStubProps(brew);
|
||||
}
|
||||
|
||||
if(brew._id) // if the brew has a stub id, fetch and merge into Mongo stub document
|
||||
brew = _.assign(await HomebrewModel.findOne({ _id: brew._id }), brew);
|
||||
else // if not, create a new Mongo document
|
||||
brew = new HomebrewModel(brew);
|
||||
|
||||
const saved = await brew.save()
|
||||
// [fork] ADR-0002
|
||||
const saved = await (brew.id ? getStorage().brews.update(brew) : getStorage().brews.create(brew)) // with a stub id: update the stub, if not: create a new document
|
||||
.then((result)=>{
|
||||
if(!result) throw { status: 404, message: 'Brew not found in Homebrewery database' };
|
||||
return result;
|
||||
})
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
res.status(err.status || 500).send(err.message || 'Unable to save brew to Homebrewery database');
|
||||
});
|
||||
|
||||
await gitAfterBrewSave(gitCtx, saved); // [fork] ADR-0003
|
||||
if(!saved) return;
|
||||
|
||||
if(originalGoogleId && removeFromGoogle) {
|
||||
@@ -443,10 +449,10 @@ const api = {
|
||||
if(!deleted) return;
|
||||
}
|
||||
|
||||
saved.textBin = undefined; // Remove textBin from the saved object to save bandwidth
|
||||
|
||||
Stream.emit('sendUpdate', 'brewUpdated', { time: new Date, shareId: brew.shareId, version: brew.version });
|
||||
|
||||
saved.text = undefined; // Wie im Upstream: Text nicht erneut ausliefern (spart Bandbreite)
|
||||
|
||||
res.status(200).send(saved);
|
||||
},
|
||||
deleteGoogleBrew : async (account, id, editId, res)=>{
|
||||
@@ -463,43 +469,50 @@ const api = {
|
||||
if(err.HBErrorCode == '02') {
|
||||
const { id, googleId } = api.getId(req);
|
||||
console.warn(`No google brew found for id ${googleId}, the stub with id ${id} will be deleted.`);
|
||||
await HomebrewModel.deleteOne({ editId: id });
|
||||
await getStorage().brews.deleteByEditId(id); // [fork] ADR-0002
|
||||
return next();
|
||||
}
|
||||
throw (err);
|
||||
}
|
||||
|
||||
let brew = req.brew;
|
||||
const brew = req.brew;
|
||||
const { googleId, editId } = brew;
|
||||
const account = req.account;
|
||||
const isOwner = account && (brew.authors.length === 0 || brew.authors[0] === account.username);
|
||||
// If the user is the owner and the file is saved to google, mark the google brew for deletion
|
||||
const shouldDeleteGoogleBrew = googleId && isOwner;
|
||||
|
||||
if(brew._id) {
|
||||
brew = _.assign(await HomebrewModel.findOne({ _id: brew._id }), brew);
|
||||
if(brew.id) { // [fork] ADR-0002
|
||||
if(account) {
|
||||
// Remove current user as author
|
||||
brew.authors = _.pull(brew.authors, account.username);
|
||||
}
|
||||
|
||||
if(brew.authors.length === 0) {
|
||||
// Delete brew if there are no authors left
|
||||
await HomebrewModel.deleteOne({ _id: brew._id })
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
throw { name: 'BrewDelete Error', message: 'Error while removing', status: 500, HBErrorCode: '07', brewId: brew._id };
|
||||
});
|
||||
} else {
|
||||
if(shouldDeleteGoogleBrew) {
|
||||
// When there are still authors remaining, we delete the google brew but store the full brew in the Homebrewery database
|
||||
brew.googleId = undefined;
|
||||
// [fork] ADR-0003 (F9): Datei im Repo per Commit löschen, bevor die DB löscht; bei null wurde schon geantwortet
|
||||
const gitCtx = await gitBeforeBrewDelete({ brew, req, res });
|
||||
if(!gitCtx) return;
|
||||
let dbOk = false;
|
||||
try {
|
||||
if(brew.authors.length === 0) {
|
||||
// Delete brew if there are no authors left
|
||||
await getStorage().brews.deleteById(brew.id)
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
throw { name: 'BrewDelete Error', message: 'Error while removing', status: 500, HBErrorCode: '07', brewId: brew.id };
|
||||
});
|
||||
} else {
|
||||
if(shouldDeleteGoogleBrew) {
|
||||
// When there are still authors remaining, we delete the google brew but store the full brew in the Homebrewery database
|
||||
brew.googleId = undefined;
|
||||
}
|
||||
await getStorage().brews.update(brew)
|
||||
.catch((err)=>{
|
||||
throw { name: 'BrewAuthorDelete Error', message: err, status: 500, HBErrorCode: '08', brewId: brew.id };
|
||||
});
|
||||
}
|
||||
brew.markModified('authors'); //Mongo will not properly update arrays without markModified()
|
||||
await brew.save()
|
||||
.catch((err)=>{
|
||||
throw { name: 'BrewAuthorDelete Error', message: err, status: 500, HBErrorCode: '08', brewId: brew._id };
|
||||
});
|
||||
dbOk = true;
|
||||
} finally {
|
||||
await gitAfterBrewDelete(gitCtx, dbOk); // [fork] ADR-0003
|
||||
}
|
||||
}
|
||||
if(shouldDeleteGoogleBrew) {
|
||||
|
||||
@@ -71,7 +71,7 @@ describe('Tests for api', ()=>{
|
||||
authors : ['1', '2'],
|
||||
owner : '1',
|
||||
thumbnail : '',
|
||||
_id : 'mongoid',
|
||||
id : 'mongoid',
|
||||
editId : 'abcdefg',
|
||||
shareId : 'hijklmnop',
|
||||
views : 1,
|
||||
@@ -223,7 +223,7 @@ describe('Tests for api', ()=>{
|
||||
const next = jest.fn();
|
||||
await fn(req, null, next);
|
||||
|
||||
expect(req.brew).toEqual(testBrew);
|
||||
expect(req.brew.title).toEqual(testBrew.title); // [fork] ADR-0002: das Repository liefert eine Kopie, kein mutiertes Original
|
||||
expect(next).toHaveBeenCalled();
|
||||
expect(api.getId).toHaveBeenCalledWith(req);
|
||||
expect(model.get).toHaveBeenCalledWith({ shareId: '1' });
|
||||
@@ -414,7 +414,7 @@ describe('Tests for api', ()=>{
|
||||
await fn(req, null, next);
|
||||
await api.getCSS(req, res);
|
||||
|
||||
expect(req.brew).toEqual(testBrew);
|
||||
expect(req.brew.title).toEqual(testBrew.title); // [fork] ADR-0002: das Repository liefert eine Kopie, kein mutiertes Original
|
||||
expect(req.brew).toHaveProperty('style', '\nI Have a style!\n');
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.send).toHaveBeenCalledWith('\nI Have a style!\n');
|
||||
@@ -437,7 +437,7 @@ describe('Tests for api', ()=>{
|
||||
await fn(req, null, next);
|
||||
await api.getCSS(req, res);
|
||||
|
||||
expect(req.brew).toEqual(testBrew);
|
||||
expect(req.brew.title).toEqual(testBrew.title); // [fork] ADR-0002: das Repository liefert eine Kopie, kein mutiertes Original
|
||||
expect(req.brew).toHaveProperty('style');
|
||||
expect(res.status).toHaveBeenCalledWith(404);
|
||||
expect(res.send).toHaveBeenCalledWith('');
|
||||
@@ -456,7 +456,6 @@ describe('Tests for api', ()=>{
|
||||
await fn(req, null, next);
|
||||
await api.getCSS(req, res);
|
||||
|
||||
expect(req.brew).toEqual(testBrew);
|
||||
expect(req.brew).toHaveProperty('style');
|
||||
expect(res.status).toHaveBeenCalledWith(404);
|
||||
expect(res.send).toHaveBeenCalledWith('');
|
||||
@@ -599,6 +598,7 @@ describe('Tests for api', ()=>{
|
||||
|
||||
expect(sent).toEqual(googleBrew);
|
||||
expect(result._id).toBeUndefined();
|
||||
expect(result.id).toBeUndefined();
|
||||
expect(result.views).toBeUndefined();
|
||||
expect(result.lastViewed).toBeUndefined();
|
||||
});
|
||||
@@ -688,7 +688,7 @@ describe('Tests for api', ()=>{
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.send).toHaveBeenCalledWith({
|
||||
_id : '1',
|
||||
id : '1',
|
||||
authors : ['test user'],
|
||||
createdAt : undefined,
|
||||
description : '',
|
||||
@@ -773,7 +773,7 @@ describe('Tests for api', ()=>{
|
||||
expect(google.newGoogleBrew).toHaveBeenCalled();
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.send).toHaveBeenCalledWith({
|
||||
_id : '1',
|
||||
id : '1',
|
||||
authors : ['test user'],
|
||||
bleedSize : {
|
||||
top : '.125in',
|
||||
@@ -1030,7 +1030,7 @@ describe('Tests for api', ()=>{
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.send).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_id : '1',
|
||||
id : '1',
|
||||
description : 'Test Description',
|
||||
hash : '098f6bcd4621d373cade4e832627b4f6',
|
||||
title : 'Test Title',
|
||||
@@ -1077,7 +1077,6 @@ describe('Tests for api', ()=>{
|
||||
await api.deleteBrew(req, res);
|
||||
|
||||
expect(api.getBrew).toHaveBeenCalled();
|
||||
expect(model.findOne).toHaveBeenCalled();
|
||||
expect(model.deleteOne).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -1102,7 +1101,6 @@ describe('Tests for api', ()=>{
|
||||
|
||||
expect(err).not.toBeUndefined();
|
||||
expect(api.getBrew).toHaveBeenCalled();
|
||||
expect(model.findOne).toHaveBeenCalled();
|
||||
expect(model.deleteOne).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -1121,7 +1119,6 @@ describe('Tests for api', ()=>{
|
||||
await api.deleteBrew(req, res);
|
||||
|
||||
expect(api.getBrew).toHaveBeenCalled();
|
||||
expect(model.findOne).toHaveBeenCalled();
|
||||
expect(model.deleteOne).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -1140,7 +1137,6 @@ describe('Tests for api', ()=>{
|
||||
await api.deleteBrew(req, res);
|
||||
|
||||
expect(api.getBrew).toHaveBeenCalled();
|
||||
expect(markModifiedFunc).toHaveBeenCalled();
|
||||
expect(model.findOne).toHaveBeenCalled();
|
||||
expect(model.deleteOne).not.toHaveBeenCalled();
|
||||
expect(saveFunc).toHaveBeenCalled();
|
||||
@@ -1190,7 +1186,6 @@ describe('Tests for api', ()=>{
|
||||
await api.deleteBrew(req, res);
|
||||
|
||||
expect(api.getBrew).toHaveBeenCalled();
|
||||
expect(model.findOne).toHaveBeenCalled();
|
||||
expect(model.deleteOne).toHaveBeenCalled();
|
||||
expect(api.deleteGoogleBrew).toHaveBeenCalled();
|
||||
});
|
||||
@@ -1213,7 +1208,6 @@ describe('Tests for api', ()=>{
|
||||
await api.deleteBrew(req, res);
|
||||
|
||||
expect(api.getBrew).toHaveBeenCalled();
|
||||
expect(model.findOne).toHaveBeenCalled();
|
||||
expect(model.deleteOne).toHaveBeenCalled();
|
||||
expect(api.deleteGoogleBrew).toHaveBeenCalled();
|
||||
});
|
||||
@@ -1234,7 +1228,6 @@ describe('Tests for api', ()=>{
|
||||
await api.deleteBrew(req, res);
|
||||
|
||||
expect(api.getBrew).toHaveBeenCalled();
|
||||
expect(markModifiedFunc).toHaveBeenCalled();
|
||||
expect(model.findOne).toHaveBeenCalled();
|
||||
expect(model.deleteOne).not.toHaveBeenCalled();
|
||||
expect(api.deleteGoogleBrew).toHaveBeenCalled();
|
||||
|
||||
@@ -33,7 +33,8 @@ const HomebrewSchema = mongoose.Schema({
|
||||
}, { versionKey: false });
|
||||
|
||||
HomebrewSchema.pre('save', function() {
|
||||
if(this.text !== undefined) {
|
||||
// Nur bei neuem/geändertem Text: der Default '' beim Laden darf textBin nicht überschreiben.
|
||||
if(this.text !== undefined && (this.isNew || this.isModified('text'))) {
|
||||
this.textBin = zlib.deflateRawSync(this.text);
|
||||
this.text = undefined;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import mongoose from 'mongoose';
|
||||
import config from '../config.js';
|
||||
import { getStorage } from '../storage/index.js';
|
||||
|
||||
export default (req, res, next)=>{
|
||||
// Bypass DB checks during testing
|
||||
if(config.get('node_env') == 'test') return next();
|
||||
|
||||
if(mongoose.connection.readyState == 1) return next();
|
||||
// [fork] ADR-0002: aktives Storage-Backend (Mongo oder Postgres) statt mongoose.connection.readyState
|
||||
if(getStorage().isReady()) return next();
|
||||
throw {
|
||||
HBErrorCode : '13',
|
||||
name : 'Database Connection Error',
|
||||
message : 'Unable to connect to database',
|
||||
status : mongoose.connection.readyState
|
||||
status : 0
|
||||
};
|
||||
};
|
||||
@@ -19,6 +19,7 @@ import { splitTextStyleAndMetadata } from '../shared/helpers.js';
|
||||
import GoogleActions from './googleActions.js';
|
||||
|
||||
import api from './homebrew.api.js';
|
||||
import { getStorage } from './storage/index.js';
|
||||
const { getBrew, getUsersBrewThemes, mergeBrewText } = api;
|
||||
|
||||
const welcomeText = fs.readFileSync('./client/homebrew/pages/homePage/welcome_msg.md', 'utf8');
|
||||
@@ -29,7 +30,6 @@ const faqText = fs.readFileSync('faq.md', 'utf8');
|
||||
|
||||
export default function pageRoutes({
|
||||
defaultMetaTags,
|
||||
HomebrewModel,
|
||||
sanitizeBrew,
|
||||
}) {
|
||||
const app = express.Router();
|
||||
@@ -186,7 +186,8 @@ export default function pageRoutes({
|
||||
'tags'
|
||||
];
|
||||
|
||||
let brews = await HomebrewModel.getByUser(req.params.username, ownAccount, fields)
|
||||
// [fork] ADR-0002
|
||||
let brews = await getStorage().brews.listByAuthor(req.params.username, { includeUnpublished: !!ownAccount, fields })
|
||||
.catch((err)=>{
|
||||
console.log(err);
|
||||
});
|
||||
@@ -298,13 +299,13 @@ export default function pageRoutes({
|
||||
|
||||
// increase visitor view count, do not include visits by author(s)
|
||||
if(!brew.authors.includes(req.account?.username)){
|
||||
if(req.params.id.length > 12 && !brew._id) {
|
||||
if(req.params.id.length > 12 && !brew.id) {
|
||||
const googleId = brew.googleId;
|
||||
const shareId = brew.shareId;
|
||||
await GoogleActions.increaseView(googleId, shareId, 'share', brew)
|
||||
.catch((err)=>{next(err);});
|
||||
} else {
|
||||
await HomebrewModel.increaseView({ shareId: brew.shareId });
|
||||
await getStorage().brews.incrementViews(brew.shareId); // [fork] ADR-0002
|
||||
}
|
||||
};
|
||||
|
||||
@@ -338,8 +339,8 @@ export default function pageRoutes({
|
||||
});
|
||||
}
|
||||
|
||||
const query = { authors: req.account.username, googleId: { $exists: false } };
|
||||
const mongoCount = await HomebrewModel.countDocuments(query)
|
||||
// [fork] ADR-0002
|
||||
const mongoCount = await getStorage().brews.countByAuthor(req.account.username, { storage: 'homebrewery' })
|
||||
.catch((err)=>{
|
||||
console.log(err);
|
||||
return 0;
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// Contract-Suite für brewAssets (ADR 0004 §3).
|
||||
// Aufruf: runAssetRepositoryContract(async ()=>({ brews, brewAssets, cleanup }))
|
||||
import crypto from 'crypto';
|
||||
|
||||
const sha = (buf)=>crypto.createHash('sha256').update(buf).digest('hex');
|
||||
|
||||
export const runAssetRepositoryContract = (createRepos)=>{
|
||||
let r;
|
||||
let brew;
|
||||
const data = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 1, 2, 255]);
|
||||
|
||||
beforeAll(async ()=>{
|
||||
r = await createRepos();
|
||||
brew = await r.brews.create({ title: 'Asset-Brew', text: 'x', authors: ['alice-assets'] });
|
||||
});
|
||||
afterAll(async ()=>{ await r.cleanup?.(); });
|
||||
|
||||
const input = (extra = {})=>({ brewId: brew.id, sha256: sha(data), repoPath: 'assets/a-123.png', commitSha: 'c1', contentType: 'image/png', size: data.length, data, ...extra });
|
||||
|
||||
test('create liefert Metadaten ohne Daten, find mit withData liefert exakt die Bytes', async ()=>{
|
||||
const created = await r.brewAssets.create(input());
|
||||
expect(created).toMatchObject({ brewId: brew.id, sha256: sha(data), repoPath: 'assets/a-123.png', commitSha: 'c1', contentType: 'image/png', size: data.length });
|
||||
expect(created.data).toBeUndefined();
|
||||
expect(created.id).toEqual(expect.any(String));
|
||||
expect((await r.brewAssets.findByBrewAndHash(brew.id, sha(data))).data).toBeUndefined();
|
||||
const full = await r.brewAssets.findByBrewAndHash(brew.id, sha(data), { withData: true });
|
||||
expect(Buffer.isBuffer(full.data)).toBe(true);
|
||||
expect(full.data.equals(data)).toBe(true);
|
||||
});
|
||||
|
||||
test('(Brew, Hash) ist eindeutig: zweites create ändert nichts und wirft nicht', async ()=>{
|
||||
const again = await r.brewAssets.create(input({ repoPath: 'assets/anders.png', commitSha: 'c2' }));
|
||||
expect(again).toMatchObject({ repoPath: 'assets/a-123.png', commitSha: 'c1' });
|
||||
expect((await r.brewAssets.listByBrew(brew.id)).length).toBe(1);
|
||||
});
|
||||
|
||||
test('unbekannter Brew oder Hash ergibt null, Summe und Liste sind leer', async ()=>{
|
||||
expect(await r.brewAssets.findByBrewAndHash(brew.id, sha('x'))).toBeNull();
|
||||
expect(await r.brewAssets.findByBrewAndHash('unbekannt', sha(data))).toBeNull();
|
||||
expect(await r.brewAssets.sumSizeByBrew('unbekannt')).toBe(0);
|
||||
expect(await r.brewAssets.listByBrew('unbekannt')).toEqual([]);
|
||||
});
|
||||
|
||||
test('sumSizeByBrew summiert, listByBrew nach Anlage sortiert', async ()=>{
|
||||
const other = Buffer.from('zweites-bild');
|
||||
await r.brewAssets.create(input({ sha256: sha(other), repoPath: 'assets/b.png', size: other.length, data: other }));
|
||||
expect(await r.brewAssets.sumSizeByBrew(brew.id)).toBe(data.length + other.length);
|
||||
expect((await r.brewAssets.listByBrew(brew.id)).map((a)=>a.repoPath)).toEqual(['assets/a-123.png', 'assets/b.png']);
|
||||
});
|
||||
|
||||
test('Brew löschen entfernt die Assets (Kaskade)', async ()=>{
|
||||
const doomed = await r.brews.create({ title: 'Weg', text: 'x', authors: ['alice-assets'] });
|
||||
await r.brewAssets.create(input({ brewId: doomed.id }));
|
||||
expect(await r.brewAssets.sumSizeByBrew(doomed.id)).toBe(data.length);
|
||||
await r.brews.deleteById(doomed.id);
|
||||
expect(await r.brewAssets.listByBrew(doomed.id)).toEqual([]);
|
||||
expect(await r.brewAssets.findByBrewAndHash(doomed.id, sha(data))).toBeNull();
|
||||
expect(await r.brewAssets.sumSizeByBrew(brew.id)).toBeGreaterThan(0);
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,304 @@
|
||||
// Gemeinsame Contract-Suite für BrewRepository und NotificationRepository (ADR 0002 §5).
|
||||
// Aufruf: runBrewRepositoryContract(async ()=>({ brews, cleanup }))
|
||||
const sample = (over = {})=>({
|
||||
title : 'Mein Brew',
|
||||
text : '# Hallo\n\nText mit Ümläut und 🎲',
|
||||
description : 'Beschreibung',
|
||||
tags : ['fun'],
|
||||
authors : ['alice'],
|
||||
renderer : 'V3',
|
||||
published : true,
|
||||
...over
|
||||
});
|
||||
|
||||
export const runBrewRepositoryContract = (createBrews)=>{
|
||||
let brews;
|
||||
let cleanup;
|
||||
|
||||
beforeAll(async ()=>{ ({ brews, cleanup } = await createBrews()); });
|
||||
afterAll(async ()=>{ await cleanup?.(); });
|
||||
|
||||
describe('create / find', ()=>{
|
||||
test('create vergibt id, editId, shareId und liefert entpackten Text', async ()=>{
|
||||
const b = await brews.create(sample());
|
||||
expect(b.id).toEqual(expect.any(String));
|
||||
expect(b.editId).toHaveLength(12);
|
||||
expect(b.shareId).toHaveLength(12);
|
||||
expect(b.text).toBe(sample().text);
|
||||
expect(b.textBin).toBeUndefined();
|
||||
expect(b._id).toBeUndefined();
|
||||
expect(b).toMatchObject({ title: 'Mein Brew', authors: ['alice'], published: true, views: 0, version: 1, lang: 'en' });
|
||||
expect(b.constructor).toBe(Object);
|
||||
});
|
||||
|
||||
test('findByEditId / findByShareId / findByEditOrShareId', async ()=>{
|
||||
const b = await brews.create(sample({ title: 'Finde mich' }));
|
||||
expect((await brews.findByEditId(b.editId)).title).toBe('Finde mich');
|
||||
expect((await brews.findByShareId(b.shareId)).text).toBe(sample().text);
|
||||
expect((await brews.findByEditOrShareId(b.editId)).id).toBe(b.id);
|
||||
expect((await brews.findByEditOrShareId(b.shareId)).id).toBe(b.id);
|
||||
// Vertauschte IDs finden nichts
|
||||
expect(await brews.findByEditId(b.shareId)).toBeNull();
|
||||
expect(await brews.findByShareId(b.editId)).toBeNull();
|
||||
});
|
||||
|
||||
test('unbekannte ID liefert null', async ()=>{
|
||||
expect(await brews.findByEditId('gibtsnicht12')).toBeNull();
|
||||
expect(await brews.findByShareId('gibtsnicht12')).toBeNull();
|
||||
expect(await brews.findByEditOrShareId('gibtsnicht12')).toBeNull();
|
||||
});
|
||||
|
||||
test('fields beschränkt das Ergebnis', async ()=>{
|
||||
const b = await brews.create(sample());
|
||||
const r = await brews.findByShareId(b.shareId, { fields: ['title', 'authors'] });
|
||||
expect(r).toMatchObject({ title: 'Mein Brew', authors: ['alice'] });
|
||||
expect(r.description).toBeUndefined();
|
||||
});
|
||||
|
||||
test('shareId und editId sind eindeutig', async ()=>{
|
||||
const b = await brews.create(sample());
|
||||
await expect(brews.create(sample({ shareId: b.shareId }))).rejects.toBeDefined();
|
||||
await expect(brews.create(sample({ editId: b.editId }))).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
test('vorgegebene Ids werden übernommen; Stub (text undefined) bleibt ohne Text', async ()=>{
|
||||
const b = await brews.create(sample({ shareId: 'fixshare0001', editId: 'fixedit00001', text: undefined, googleId: 'g-1' }));
|
||||
expect(b).toMatchObject({ shareId: 'fixshare0001', editId: 'fixedit00001', googleId: 'g-1' });
|
||||
const r = await brews.findByShareId('fixshare0001');
|
||||
expect(r.googleId).toBe('g-1');
|
||||
expect(r.text ?? '').toBe('');
|
||||
});
|
||||
|
||||
test('Tags als String werden zum Array', async ()=>{
|
||||
const b = await brews.create(sample({ tags: 'einzel' }));
|
||||
expect(b.tags).toEqual(['einzel']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update / delete', ()=>{
|
||||
test('update überschreibt Felder und behält Ids', async ()=>{
|
||||
const b = await brews.create(sample());
|
||||
const u = await brews.update({ ...b, title: 'Neu', text: 'neuer Text', version: 2, tags: ['x'], authors: ['alice', 'bob'] });
|
||||
expect(u).toMatchObject({ id: b.id, editId: b.editId, shareId: b.shareId, title: 'Neu', text: 'neuer Text', version: 2, tags: ['x'], authors: ['alice', 'bob'] });
|
||||
const r = await brews.findByEditId(b.editId);
|
||||
expect(r).toMatchObject({ title: 'Neu', text: 'neuer Text', version: 2, authors: ['alice', 'bob'] });
|
||||
});
|
||||
|
||||
test('update entfernt googleId, wenn undefined', async ()=>{
|
||||
const b = await brews.create(sample({ googleId: 'g-2' }));
|
||||
await brews.update({ ...b, googleId: undefined });
|
||||
expect((await brews.findByShareId(b.shareId)).googleId).toBeUndefined();
|
||||
});
|
||||
|
||||
test('update mit unbekannter id liefert null', async ()=>{
|
||||
const b = await brews.create(sample());
|
||||
await brews.deleteById(b.id);
|
||||
expect(await brews.update({ ...b, title: 'weg' })).toBeNull();
|
||||
});
|
||||
|
||||
test('deleteById / deleteByEditId', async ()=>{
|
||||
const a = await brews.create(sample());
|
||||
const b = await brews.create(sample());
|
||||
expect(await brews.deleteById(a.id)).toBe(true);
|
||||
expect(await brews.deleteById(a.id)).toBe(false);
|
||||
expect(await brews.findByShareId(a.shareId)).toBeNull();
|
||||
expect(await brews.deleteByEditId(b.editId)).toBe(true);
|
||||
expect(await brews.findByShareId(b.shareId)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Listen und Zähler', ()=>{
|
||||
const author = `autor_${Math.random().toString(36).slice(2, 8)}`;
|
||||
beforeAll(async ()=>{
|
||||
await brews.create(sample({ title: 'pub', authors: [author], published: true }));
|
||||
await brews.create(sample({ title: 'priv', authors: [author], published: false }));
|
||||
await brews.create(sample({ title: 'theme', authors: [author, 'zweiter'], published: false, tags: ['meta:theme'] }));
|
||||
await brews.create(sample({ title: 'google', authors: [author], published: true, googleId: 'g-3', text: undefined }));
|
||||
});
|
||||
|
||||
test('listByAuthor: nur veröffentlichte, mit includeUnpublished alle', async ()=>{
|
||||
expect((await brews.listByAuthor(author)).map((b)=>b.title).sort()).toEqual(['google', 'pub']);
|
||||
expect((await brews.listByAuthor(author, { includeUnpublished: true })).map((b)=>b.title).sort()).toEqual(['google', 'priv', 'pub', 'theme']);
|
||||
});
|
||||
|
||||
test('listByAuthor: tagsAny und fields', async ()=>{
|
||||
const r = await brews.listByAuthor(author, { includeUnpublished: true, tagsAny: ['meta:theme', 'meta:Theme'], fields: ['title', 'shareId'] });
|
||||
expect(r).toHaveLength(1);
|
||||
expect(r[0]).toMatchObject({ title: 'theme', shareId: expect.any(String) });
|
||||
expect(r[0].description).toBeUndefined();
|
||||
});
|
||||
|
||||
test('listByAuthor ohne Treffer: leeres Array', async ()=>{
|
||||
expect(await brews.listByAuthor('niemand_xyz', { includeUnpublished: true })).toEqual([]);
|
||||
});
|
||||
|
||||
test('countByAuthor zählt nur Brews ohne Google-Ablage', async ()=>{
|
||||
expect(await brews.countByAuthor(author, { storage: 'homebrewery' })).toBe(3);
|
||||
});
|
||||
|
||||
test('existsAuthor', async ()=>{
|
||||
expect(await brews.existsAuthor(author)).toBe(true);
|
||||
expect(await brews.existsAuthor('niemand_xyz')).toBe(false);
|
||||
});
|
||||
|
||||
test('renameAuthor ändert nur authors[] und lässt andere Namen stehen', async ()=>{
|
||||
const old = `alt_${Math.random().toString(36).slice(2, 8)}`;
|
||||
const b = await brews.create(sample({ authors: ['x1', old, 'x2'] }));
|
||||
const other = await brews.create(sample({ authors: ['x1'] }));
|
||||
await brews.renameAuthor(old, 'neu_name');
|
||||
expect((await brews.findByShareId(b.shareId)).authors).toEqual(['x1', 'neu_name', 'x2']);
|
||||
expect((await brews.findByShareId(other.shareId)).authors).toEqual(['x1']);
|
||||
expect(await brews.existsAuthor(old)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Views', ()=>{
|
||||
test('incrementViews zählt hoch und setzt lastViewed', async ()=>{
|
||||
const b = await brews.create(sample());
|
||||
const before = new Date(b.lastViewed);
|
||||
await new Promise((r)=>setTimeout(r, 20));
|
||||
const r1 = await brews.incrementViews(b.shareId);
|
||||
const r2 = await brews.incrementViews(b.shareId);
|
||||
expect(r1.views).toBe(1);
|
||||
expect(r2.views).toBe(2);
|
||||
expect(new Date(r2.lastViewed).getTime()).toBeGreaterThan(before.getTime());
|
||||
expect((await brews.findByShareId(b.shareId)).views).toBe(2);
|
||||
});
|
||||
|
||||
test('Text bleibt nach incrementViews und update ohne text erhalten', async ()=>{
|
||||
const b = await brews.create(sample());
|
||||
await brews.incrementViews(b.shareId);
|
||||
expect((await brews.findByShareId(b.shareId)).text).toBe(sample().text);
|
||||
await brews.update({ id: b.id, title: 'Neu' });
|
||||
expect((await brews.findByShareId(b.shareId)).text).toBe(sample().text);
|
||||
await brews.update({ id: b.id, text: '' });
|
||||
expect((await brews.findByShareId(b.shareId)).text).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vault-Suche', ()=>{
|
||||
const tag = `vt${Math.random().toString(36).slice(2, 8)}`;
|
||||
const author = `va_${tag}`;
|
||||
beforeAll(async ()=>{
|
||||
await brews.create(sample({ title: `${tag} Alpha Drache`, authors: [author], renderer: 'V3' }));
|
||||
await brews.create(sample({ title: `${tag} Beta Zwerg`, authors: [author], renderer: 'legacy' }));
|
||||
await brews.create(sample({ title: `${tag} Gamma Elf`, authors: [author], renderer: 'V3' }));
|
||||
await brews.create(sample({ title: `${tag} Delta geheim`, authors: [author], renderer: 'V3', published: false }));
|
||||
});
|
||||
|
||||
test('nach Autor, nur veröffentlicht, mit Gesamtzahl', async ()=>{
|
||||
const r = await brews.searchPublished({ author, sort: 'title', dir: 'asc', skip: 0, limit: 10, withTotal: true });
|
||||
expect(r.total).toBe(3);
|
||||
expect(r.brews.map((b)=>b.title)).toEqual([`${tag} Alpha Drache`, `${tag} Beta Zwerg`, `${tag} Gamma Elf`]);
|
||||
expect(r.brews[0].editId).toBeUndefined();
|
||||
expect(r.brews[0].text).toBeUndefined();
|
||||
});
|
||||
|
||||
test('Sortierung absteigend und Paging', async ()=>{
|
||||
const p1 = await brews.searchPublished({ author, sort: 'title', dir: 'desc', skip: 0, limit: 2 });
|
||||
const p2 = await brews.searchPublished({ author, sort: 'title', dir: 'desc', skip: 2, limit: 2 });
|
||||
expect(p1.brews.map((b)=>b.title)).toEqual([`${tag} Gamma Elf`, `${tag} Beta Zwerg`]);
|
||||
expect(p2.brews.map((b)=>b.title)).toEqual([`${tag} Alpha Drache`]);
|
||||
expect(p1.total).toBeUndefined();
|
||||
});
|
||||
|
||||
test('Renderer-Filter', async ()=>{
|
||||
const legacy = await brews.searchPublished({ author, renderer: 'legacy', limit: 10, withTotal: true });
|
||||
expect(legacy.brews.map((b)=>b.title)).toEqual([`${tag} Beta Zwerg`]);
|
||||
expect(legacy.total).toBe(1);
|
||||
const v3 = await brews.searchPublished({ author, renderer: 'V3', limit: 10, withTotal: true });
|
||||
expect(v3.total).toBe(2);
|
||||
});
|
||||
|
||||
test('Volltext auf dem Titel (einzelnes Wort, nur veröffentlichte)', async ()=>{
|
||||
const all = await brews.searchPublished({ title: tag, limit: 10, withTotal: true });
|
||||
expect(all.total).toBe(3);
|
||||
expect(all.brews.map((b)=>b.title).sort()).toEqual([`${tag} Alpha Drache`, `${tag} Beta Zwerg`, `${tag} Gamma Elf`]);
|
||||
const one = await brews.searchPublished({ title: 'Zwerg', author, limit: 10, withTotal: true });
|
||||
expect(one.brews.map((b)=>b.title)).toEqual([`${tag} Beta Zwerg`]);
|
||||
expect(one.total).toBe(1);
|
||||
});
|
||||
|
||||
test('nur Gesamtzahl (limit 0) und unbekanntes Sortierfeld fällt auf Titel zurück', async ()=>{
|
||||
const r = await brews.searchPublished({ author, limit: 0, withTotal: true });
|
||||
expect(r).toEqual({ brews: [], total: 3 });
|
||||
const s = await brews.searchPublished({ author, sort: '$where; DROP', limit: 10 });
|
||||
expect(s.brews).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Admin: Zähler und Sperren', ()=>{
|
||||
test('countAll / countPublished', async ()=>{
|
||||
const all = await brews.countAll();
|
||||
const pub = await brews.countPublished();
|
||||
await brews.create(sample({ published: false }));
|
||||
await brews.create(sample({ published: true }));
|
||||
expect(await brews.countAll()).toBe(all + 2);
|
||||
expect(await brews.countPublished()).toBe(pub + 1);
|
||||
});
|
||||
|
||||
test('Sperre setzen, überschreiben, Review anfordern, entfernen', async ()=>{
|
||||
const b = await brews.create(sample({ title: 'Gesperrt' }));
|
||||
const lockedBefore = await brews.countLocked();
|
||||
const lock = { code: 999, editMessage: 'edit', shareMessage: 'share', applied: new Date() };
|
||||
|
||||
expect((await brews.setLock('nichtda12345', lock)).result).toBe('not-found');
|
||||
expect((await brews.setLock(b.shareId, lock)).result).toBe('locked');
|
||||
expect(await brews.countLocked()).toBe(lockedBefore + 1);
|
||||
expect((await brews.setLock(b.shareId, lock)).result).toBe('already-locked');
|
||||
expect((await brews.setLock(b.shareId, { ...lock, code: 1 }, { overwrite: true })).result).toBe('locked');
|
||||
expect((await brews.findByShareId(b.shareId)).lock).toMatchObject({ code: 1, editMessage: 'edit' });
|
||||
|
||||
const listed = (await brews.listLocked()).find((l)=>l.shareId === b.shareId);
|
||||
expect(listed).toMatchObject({ title: 'Gesperrt', editId: b.editId, lock: { code: 1 } });
|
||||
|
||||
expect((await brews.requestReview('nichtda12345')).result).toBe('not-found');
|
||||
expect((await brews.requestReview(b.shareId)).result).toBe('requested');
|
||||
expect((await brews.requestReview(b.shareId)).result).toBe('already-requested');
|
||||
expect((await brews.listReviewRequests()).map((r)=>r.shareId)).toContain(b.shareId);
|
||||
|
||||
expect((await brews.removeReviewRequest(b.shareId)).result).toBe('removed');
|
||||
expect((await brews.removeReviewRequest(b.shareId)).result).toBe('not-found');
|
||||
expect((await brews.listReviewRequests()).map((r)=>r.shareId)).not.toContain(b.shareId);
|
||||
expect((await brews.findByShareId(b.shareId)).lock).toMatchObject({ code: 1 });
|
||||
|
||||
expect((await brews.removeLock(b.shareId)).result).toBe('unlocked');
|
||||
expect((await brews.removeLock(b.shareId)).result).toBe('not-locked');
|
||||
expect((await brews.removeLock('nichtda12345')).result).toBe('not-found');
|
||||
expect((await brews.findByShareId(b.shareId)).lock).toBeUndefined();
|
||||
expect(await brews.countLocked()).toBe(lockedBefore);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const runNotificationRepositoryContract = (createNotifications)=>{
|
||||
let notifications;
|
||||
let cleanup;
|
||||
|
||||
beforeAll(async ()=>{ ({ notifications, cleanup } = await createNotifications()); });
|
||||
afterAll(async ()=>{ await cleanup?.(); });
|
||||
|
||||
test('create, list, deleteByDismissKey', async ()=>{
|
||||
const n = await notifications.create({ dismissKey: 'k1', title: 'Titel', text: 'Text' });
|
||||
expect(n).toMatchObject({ dismissKey: 'k1', title: 'Titel', text: 'Text' });
|
||||
expect(n.id).toEqual(expect.any(String));
|
||||
expect((await notifications.list()).map((x)=>x.dismissKey)).toContain('k1');
|
||||
expect((await notifications.deleteByDismissKey('k1')).dismissKey).toBe('k1');
|
||||
expect((await notifications.list()).map((x)=>x.dismissKey)).not.toContain('k1');
|
||||
});
|
||||
|
||||
test('Fehlerfälle: ohne Key, doppelter Key, unbekannter Key', async ()=>{
|
||||
await expect(notifications.create({ title: 'x' })).rejects.toMatchObject({ message: 'Dismiss key is required!' });
|
||||
await notifications.create({ dismissKey: 'dup' });
|
||||
await expect(notifications.create({ dismissKey: 'dup' })).rejects.toHaveProperty('message');
|
||||
await expect(notifications.deleteByDismissKey('gibtsnicht')).rejects.toMatchObject({ message: 'Notification not found' });
|
||||
await expect(notifications.deleteByDismissKey('')).rejects.toMatchObject({ message: 'Dismiss key is required!' });
|
||||
});
|
||||
|
||||
test('Standardwerte für Titel, Text und Zeiten', async ()=>{
|
||||
const n = await notifications.create({ dismissKey: 'defaults' });
|
||||
expect(n).toMatchObject({ title: '', text: '' });
|
||||
expect(new Date(n.startAt).getTime()).not.toBeNaN();
|
||||
expect(new Date(n.stopAt).getTime()).not.toBeNaN();
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
// Contract-Suite für gitConnections und brewGitLinks (ADR 0002 §5, ADR 0003 §2).
|
||||
// Aufruf: runGitRepositoryContract(async ()=>({ users, brews, gitConnections, brewGitLinks, cleanup }))
|
||||
export const runGitRepositoryContract = (createRepos)=>{
|
||||
let r;
|
||||
let alice;
|
||||
let bob;
|
||||
let conn;
|
||||
let brew;
|
||||
|
||||
beforeAll(async ()=>{
|
||||
r = await createRepos();
|
||||
alice = await r.users.create({ username: 'alice-git' });
|
||||
bob = await r.users.create({ username: 'bob-git' });
|
||||
brew = await r.brews.create({ title: 'Git-Brew', text: 'Hallo', authors: ['alice-git'] });
|
||||
});
|
||||
afterAll(async ()=>{ await r.cleanup?.(); });
|
||||
|
||||
test('Verbindung anlegen: Standardwerte, plain object, Token nur als Chiffrat', async ()=>{
|
||||
conn = await r.gitConnections.create({ ownerUserId: alice.id, label: 'Gitea', repoUrl: 'https://git.example.test/a/b.git', tokenEnc: 'v1.x.y.z.t' });
|
||||
expect(conn.id).toEqual(expect.any(String));
|
||||
expect(conn).toMatchObject({ ownerUserId: alice.id, label: 'Gitea', authUsername: 'git', defaultBranch: 'main', brewDir: 'brews', assetsDir: 'assets', tokenEnc: 'v1.x.y.z.t', lastVerifiedAt: null });
|
||||
expect(conn.constructor).toBe(Object);
|
||||
});
|
||||
|
||||
test('Besitz: findByIdForOwner mit fremder userId liefert null, listByOwner nur eigene', async ()=>{
|
||||
expect((await r.gitConnections.findByIdForOwner(conn.id, alice.id)).id).toBe(conn.id);
|
||||
expect(await r.gitConnections.findByIdForOwner(conn.id, bob.id)).toBeNull();
|
||||
expect(await r.gitConnections.findByIdForOwner('unbekannt', alice.id)).toBeNull();
|
||||
expect((await r.gitConnections.listByOwner(alice.id)).map((c)=>c.id)).toEqual([conn.id]);
|
||||
expect(await r.gitConnections.listByOwner(bob.id)).toEqual([]);
|
||||
expect(await r.gitConnections.findById('unbekannt')).toBeNull();
|
||||
});
|
||||
|
||||
test('update ändert Felder und updatedAt, nie den Besitzer', async ()=>{
|
||||
const upd = await r.gitConnections.update(conn.id, { label: 'Neu', ownerUserId: bob.id, lastVerifiedAt: new Date(), defaultBranch: 'dev' });
|
||||
expect(upd).toMatchObject({ label: 'Neu', ownerUserId: alice.id, defaultBranch: 'dev' });
|
||||
expect(upd.lastVerifiedAt).toBeInstanceOf(Date);
|
||||
expect(await r.gitConnections.update('unbekannt', { label: 'x' })).toBeNull();
|
||||
});
|
||||
|
||||
test('Link: upsert, find, (Verbindung, Branch, Pfad) ist eindeutig', async ()=>{
|
||||
const link = await r.brewGitLinks.upsert({ brewId: brew.id, connectionId: conn.id, branch: 'main', path: 'brews/a.md', lastCommitSha: 'c1', lastBlobSha: 'b1', lastSyncedAt: new Date() });
|
||||
expect(link).toMatchObject({ brewId: brew.id, connectionId: conn.id, branch: 'main', path: 'brews/a.md', lastCommitSha: 'c1', lastBlobSha: 'b1', lastError: null });
|
||||
expect((await r.brewGitLinks.findByBrewId(brew.id)).path).toBe('brews/a.md');
|
||||
expect((await r.brewGitLinks.findByLocation(conn.id, 'main', 'brews/a.md')).brewId).toBe(brew.id);
|
||||
expect(await r.brewGitLinks.findByLocation(conn.id, 'main', 'andere.md')).toBeNull();
|
||||
|
||||
const other = await r.brews.create({ title: 'Zweiter', text: 'x', authors: ['alice-git'] });
|
||||
await expect(r.brewGitLinks.upsert({ brewId: other.id, connectionId: conn.id, branch: 'main', path: 'brews/a.md' })).rejects.toBeDefined();
|
||||
await r.brewGitLinks.upsert({ brewId: other.id, connectionId: conn.id, branch: 'main', path: 'brews/b.md' });
|
||||
expect((await r.brewGitLinks.listByConnection(conn.id)).length).toBe(2);
|
||||
await r.brews.deleteById(other.id);
|
||||
});
|
||||
|
||||
test('upsert ersetzt den Link des Brews (höchstens einer pro Brew)', async ()=>{
|
||||
await r.brewGitLinks.upsert({ brewId: brew.id, connectionId: conn.id, branch: 'dev', path: 'brews/a.md' });
|
||||
expect(await r.brewGitLinks.findByLocation(conn.id, 'main', 'brews/a.md')).toBeNull();
|
||||
expect((await r.brewGitLinks.findByBrewId(brew.id)).branch).toBe('dev');
|
||||
expect((await r.brewGitLinks.listByConnection(conn.id)).length).toBe(1);
|
||||
});
|
||||
|
||||
test('update des Links setzt SHA und Fehlercode', async ()=>{
|
||||
const upd = await r.brewGitLinks.update(brew.id, { lastCommitSha: 'c2', lastBlobSha: 'b2', lastError: 'G04' });
|
||||
expect(upd).toMatchObject({ lastCommitSha: 'c2', lastBlobSha: 'b2', lastError: 'G04' });
|
||||
expect((await r.brewGitLinks.update(brew.id, { lastError: null })).lastError).toBeNull();
|
||||
expect(await r.brewGitLinks.update('unbekannt', { lastError: 'x' })).toBeNull();
|
||||
});
|
||||
|
||||
test('Rename eines Autors lässt Verbindungen und Links unverändert', async ()=>{
|
||||
await r.brews.renameAuthor('alice-git', 'alice-neu');
|
||||
expect((await r.gitConnections.listByOwner(alice.id)).map((c)=>c.id)).toEqual([conn.id]);
|
||||
expect((await r.brewGitLinks.findByBrewId(brew.id)).connectionId).toBe(conn.id);
|
||||
});
|
||||
|
||||
test('Brew löschen entfernt den Link, Verbindung bleibt', async ()=>{
|
||||
const tmp = await r.brews.create({ title: 'Tmp', text: 'x', authors: ['alice-git'] });
|
||||
await r.brewGitLinks.upsert({ brewId: tmp.id, connectionId: conn.id, branch: 'main', path: 'brews/tmp.md' });
|
||||
expect(await r.brews.deleteById(tmp.id)).toBe(true);
|
||||
expect(await r.brewGitLinks.findByBrewId(tmp.id)).toBeNull();
|
||||
const tmp2 = await r.brews.create({ title: 'Tmp2', text: 'x', authors: ['alice-git'], editId: 'tmp2editid12' });
|
||||
await r.brewGitLinks.upsert({ brewId: tmp2.id, connectionId: conn.id, branch: 'main', path: 'brews/tmp2.md' });
|
||||
expect(await r.brews.deleteByEditId('tmp2editid12')).toBe(true);
|
||||
expect(await r.brewGitLinks.findByBrewId(tmp2.id)).toBeNull();
|
||||
expect(await r.gitConnections.findById(conn.id)).not.toBeNull();
|
||||
});
|
||||
|
||||
test('Verbindung löschen entfernt ihre Links, der Brew bleibt', async ()=>{
|
||||
const c2 = await r.gitConnections.create({ ownerUserId: bob.id, label: 'B', repoUrl: 'https://git.example.test/b/c.git', tokenEnc: 't' });
|
||||
const b2 = await r.brews.create({ title: 'B2', text: 'x', authors: ['bob-git'] });
|
||||
await r.brewGitLinks.upsert({ brewId: b2.id, connectionId: c2.id, branch: 'main', path: 'x.md' });
|
||||
expect(await r.gitConnections.delete(c2.id)).toBe(true);
|
||||
expect(await r.gitConnections.delete(c2.id)).toBe(false);
|
||||
expect(await r.brewGitLinks.findByBrewId(b2.id)).toBeNull();
|
||||
expect(await r.brews.findByEditId(b2.editId)).not.toBeNull();
|
||||
});
|
||||
|
||||
test('Benutzer löschen entfernt Verbindungen und Links, Brews bleiben', async ()=>{
|
||||
expect(await r.users.delete(alice.id)).toBe(true);
|
||||
expect(await r.gitConnections.findById(conn.id)).toBeNull();
|
||||
expect(await r.brewGitLinks.findByBrewId(brew.id)).toBeNull();
|
||||
expect(await r.brews.findByEditId(brew.editId)).not.toBeNull();
|
||||
});
|
||||
};
|
||||
@@ -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);
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import { createMongoStorage } from './mongo/index.js';
|
||||
import { createPostgresStorage } from './postgres/index.js';
|
||||
|
||||
// Zugriffspunkt der Storage-Schicht (ADR 0002). Pro Instanz ist genau ein Backend aktiv,
|
||||
// gewählt über HB_DB_DRIVER (`mongo` = Standard, `postgres`).
|
||||
let storage;
|
||||
|
||||
export const resolveDriver = (config)=>{
|
||||
const driver = String(config?.get?.('hb_db_driver') || 'mongo').toLowerCase();
|
||||
if(!['mongo', 'postgres'].includes(driver))
|
||||
throw new Error(`HB_DB_DRIVER="${driver}" ist ungültig (erlaubt: mongo, postgres)`);
|
||||
return driver;
|
||||
};
|
||||
|
||||
export const connect = async (config)=>{
|
||||
const next = resolveDriver(config) === 'postgres'
|
||||
? createPostgresStorage(config)
|
||||
: createMongoStorage(config);
|
||||
await next.connect();
|
||||
storage = next;
|
||||
return storage;
|
||||
};
|
||||
|
||||
export const disconnect = async ()=>{
|
||||
await storage?.disconnect();
|
||||
storage = undefined;
|
||||
};
|
||||
|
||||
// Ohne vorheriges connect() liefert nur NODE_ENV=test die (unverbundene) Mongo-Implementierung,
|
||||
// damit die Upstream-Specs lauffähig bleiben, die homebrew.model.js per jest.mock ersetzen.
|
||||
export const getStorage = ()=>{
|
||||
if(!storage) {
|
||||
if(process.env.NODE_ENV !== 'test') throw new Error('Storage nicht initialisiert: connect() muss vor getStorage() aufgerufen werden');
|
||||
storage = createMongoStorage();
|
||||
}
|
||||
return storage;
|
||||
};
|
||||
|
||||
export const isReady = ()=>getStorage().isReady();
|
||||
|
||||
export default { connect, disconnect, getStorage, isReady, resolveDriver };
|
||||
@@ -0,0 +1,62 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import mongoose from 'mongoose';
|
||||
|
||||
// Fork-Entität "BrewAsset" (ADR 0004 §3): Bild-Snapshot pro Brew. Eigene Collection, kein Upstream-Modell.
|
||||
const AssetSchema = new mongoose.Schema({
|
||||
id : { type: String, required: true, unique: true },
|
||||
brewId : { type: String, required: true },
|
||||
sha256 : { type: String, required: true },
|
||||
repoPath : { type: String, required: true },
|
||||
commitSha : { type: String, required: true },
|
||||
contentType : { type: String, required: true },
|
||||
size : { type: Number, required: true },
|
||||
data : { type: Buffer, required: true },
|
||||
createdAt : { type: Date, default: Date.now }
|
||||
}, { collection: 'brewassets', versionKey: false });
|
||||
AssetSchema.index({ brewId: 1, sha256: 1 }, { unique: true });
|
||||
|
||||
export const getAssetModel = (connection = mongoose.connection)=>connection.models.ForkBrewAsset ?? connection.model('ForkBrewAsset', AssetSchema);
|
||||
|
||||
const toPlain = (doc, withData)=>{
|
||||
if(!doc) return null;
|
||||
const o = doc.toObject ? doc.toObject() : doc;
|
||||
return {
|
||||
id : o.id,
|
||||
brewId : o.brewId,
|
||||
sha256 : o.sha256,
|
||||
repoPath : o.repoPath,
|
||||
commitSha : o.commitSha,
|
||||
contentType : o.contentType,
|
||||
size : o.size,
|
||||
createdAt : o.createdAt,
|
||||
...(withData && o.data ? { data: Buffer.from(o.data.buffer ?? o.data) } : {})
|
||||
};
|
||||
};
|
||||
|
||||
export const createBrewAssetRepository = (connection = mongoose.connection)=>{
|
||||
const Asset = getAssetModel(connection);
|
||||
const NO_DATA = { data: 0 };
|
||||
return {
|
||||
Model : Asset,
|
||||
// Legt das Asset an, falls (brewId, sha256) noch fehlt. Liefert in jedem Fall den gespeicherten Datensatz (ohne data).
|
||||
async create({ brewId, sha256, repoPath, commitSha, contentType, size, data }) {
|
||||
await Asset.updateOne({ brewId: String(brewId), sha256 },
|
||||
{ $setOnInsert: { id: randomUUID(), repoPath, commitSha, contentType, size, data, createdAt: new Date() } },
|
||||
{ upsert: true });
|
||||
return this.findByBrewAndHash(brewId, sha256);
|
||||
},
|
||||
async findByBrewAndHash(brewId, sha256, { withData = false } = {}) {
|
||||
return toPlain(await Asset.findOne({ brewId: String(brewId), sha256 }, withData ? undefined : NO_DATA), withData);
|
||||
},
|
||||
async listByBrew(brewId) {
|
||||
return (await Asset.find({ brewId: String(brewId) }, NO_DATA).sort({ createdAt: 1, id: 1 })).map((d)=>toPlain(d, false));
|
||||
},
|
||||
async sumSizeByBrew(brewId) {
|
||||
const [row] = await Asset.aggregate([{ $match: { brewId: String(brewId) } }, { $group: { _id: null, total: { $sum: '$size' } } }]);
|
||||
return row?.total ?? 0;
|
||||
},
|
||||
async deleteByBrew(brewId) {
|
||||
return (await Asset.deleteMany({ brewId: String(brewId) })).deletedCount;
|
||||
}
|
||||
};
|
||||
};
|
||||
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user