Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e7ca2a1b50
|
||
|
|
adaa10a4dc
|
||
|
|
9183363ea1
|
||
|
|
448c67912f
|
||
|
|
06b7ad2c77
|
||
|
|
400411d736
|
||
|
|
84dd8e6bf4
|
||
|
|
bbfebc0095
|
||
|
|
23d9b83567
|
||
|
|
a55c403527
|
||
|
|
0bf80006df
|
||
|
|
66bb91cb3e
|
||
|
|
fb9f4b0345
|
||
|
|
6ff41ce8ec
|
||
|
|
fe278d465f
|
||
|
|
727a090bb7
|
||
|
|
d4724ac6de
|
||
|
|
6473d7108b
|
||
|
|
0880870a9f
|
||
|
|
7b159a0355
|
||
|
|
1703b3806a
|
||
|
|
8f06133181
|
||
|
|
efac56ba76
|
||
|
|
022ae1daef
|
||
|
|
8c112f50e6
|
||
|
|
a181ed3ebd | ||
|
|
86f9e963d2 | ||
|
|
23c94e01f6 |
No files matched your search
@@ -0,0 +1,74 @@
|
||||
# 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
|
||||
|
||||
# --- 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=
|
||||
@@ -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,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,168 @@
|
||||
# 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 |
|
||||
|
||||
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.
|
||||
|
||||
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,31 @@ 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).
|
||||
|
||||
### Running the application on FreeBSD or FreeNAS
|
||||
|
||||
Please see the docs here: [README.FreeBSD.md](./README.FREEBSD.md)
|
||||
|
||||
@@ -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,91 @@
|
||||
import './git.less';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { gitApi } from './gitApi.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 | off | ready
|
||||
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)=>{ if([403, 503].includes(err.status)) setState('off'); else { setFormError(err.message); setState('ready'); } });
|
||||
useEffect(()=>{ reload(); }, []);
|
||||
|
||||
if(state !== 'ready') return null; // Git-Backend deaktiviert oder kein OIDC-Konto
|
||||
|
||||
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,62 @@
|
||||
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') {
|
||||
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>;
|
||||
}
|
||||
|
||||
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,82 @@
|
||||
import './git.less';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
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); }, [status?.linked]);
|
||||
|
||||
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.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,35 @@
|
||||
@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; }
|
||||
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';
|
||||
@@ -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>
|
||||
<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,155 @@
|
||||
# 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:-}
|
||||
# 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:-}
|
||||
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 }]
|
||||
}
|
||||
]
|
||||
}
|
||||
+19
-16
@@ -1,6 +1,6 @@
|
||||
# ADR 0001: Authentifizierung über generisches OIDC
|
||||
|
||||
- Status: Vorgeschlagen
|
||||
- Status: Angenommen (Entscheidungen Florian 2026-11-25, siehe Ende)
|
||||
- Datum: 2026-11-23, überarbeitet 2026-11-25 (Review PR #12)
|
||||
- Umsetzung: M1, Issue #6
|
||||
- Basis: Analyse auf Upstream `73df298c`, gegen `6d219487` geprüft (seitdem nur `splitPane.jsx` und `listPage.jsx` geändert, beide hier nicht betroffen)
|
||||
@@ -157,6 +157,7 @@ Ablauf im Callback:
|
||||
(`{ 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
|
||||
@@ -289,20 +290,22 @@ bleiben unverändert.
|
||||
- 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 Frage F1.
|
||||
Siehe Entscheidung F1.
|
||||
|
||||
## Offene Fragen (Florian)
|
||||
## Entscheidungen (Florian, 2026-11-25)
|
||||
|
||||
- **F1 – Was heißt „bisherige Logins bleiben“?** Benutzername/Passwort und
|
||||
Google laufen bei Upstream über naturalcrit.com, nicht in dieser App. Eine
|
||||
eigene Instanz hat diese Logins nur, wenn wir zusätzlich den naturalcrit-
|
||||
Account-Server betreiben. *Empfehlung:* Den Codepfad (`naturalcrit`) behalten
|
||||
und abschaltbar machen, im eigenen Compose-Setup standardmäßig nur `oidc`
|
||||
aktivieren und keinen naturalcrit-Server betreiben. Ist das so gemeint, oder
|
||||
soll der Fork einen eigenen Passwort-Login bekommen?
|
||||
- **F2 – Session-Laufzeit:** 7 Tage fest, ohne Verlängerung. Passt das, oder
|
||||
lieber kürzer (z. B. 24 h) mit stillem Re-Login über den IdP?
|
||||
- **F3 – Bestehende Benutzernamen:** Gibt es eine bestehende Datenbank mit
|
||||
naturalcrit-Benutzernamen, deren Brews OIDC-Konten zugeordnet werden sollen?
|
||||
Falls nein, kann `HB_OIDC_LINK_BY_EMAIL` samt `POST /admin/users` auf später
|
||||
verschoben werden.
|
||||
- **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). Der Hinweis unter „Folgen“ gilt bis
|
||||
dahin.
|
||||
@@ -1,6 +1,6 @@
|
||||
# ADR 0002: Repository-Schicht, MongoDB **oder** PostgreSQL pro Instanz
|
||||
|
||||
- Status: Vorgeschlagen
|
||||
- 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)
|
||||
@@ -82,8 +82,8 @@ taucht außerhalb der Mongo-Implementierung nicht auf.
|
||||
| `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 })` → `{ brews, total }` | `vault.api.js` |
|
||||
| Admin: `countAll()`, `countPublished()`, `listLocked(…)`, `countLocked()`, `setLock(id, lock)`, `removeLock(id)`, `listReviewRequests()`, `removeReviewRequest(id)` | `admin.api.js` |
|
||||
| `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
|
||||
@@ -104,10 +104,12 @@ Upstream-Code heute aufruft (`HomebrewModel.get`, `getByUser`,
|
||||
Registry ersetzt. Die Upstream-Modelldateien bleiben **unverändert**.
|
||||
|
||||
**Admin-Wartungsjobs** (`cleanupJunk`, `cleanupLost`, `finduncompressed`,
|
||||
`compress`, `/admin/clean/script`) 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.
|
||||
`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
|
||||
|
||||
@@ -293,10 +295,10 @@ Unverändert: `server/homebrew.model.js`, `server/notifications.model.js`,
|
||||
- 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).
|
||||
|
||||
## Offene Fragen (Florian)
|
||||
## Entscheidungen (Florian, 2026-11-25)
|
||||
|
||||
- **F4 – Standard-Backend im Compose-Setup:** Empfehlung: `postgres`, weil
|
||||
das Ziel des Forks ist. Mongo bleibt als Option für Upstream-nahe Instanzen.
|
||||
Einverstanden?
|
||||
- **F5 – Admin-Wartungsjobs unter PG:** Reicht `501 Not Implemented` für
|
||||
`cleanupJunk`/`cleanupLost`/`compress`, oder braucht ihr sie auch unter PG?
|
||||
- **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`.
|
||||
@@ -1,6 +1,6 @@
|
||||
# ADR 0003: Git-Backend über HTTPS + PAT, Teilen per Server-Snapshot
|
||||
|
||||
- Status: Vorgeschlagen
|
||||
- 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)
|
||||
@@ -85,7 +85,7 @@ nicht einem Namen. Damit gilt:
|
||||
`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 Frage F13.
|
||||
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).
|
||||
@@ -314,8 +314,35 @@ 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:** `deleteBrew` (Upstream) löscht DB-Brew, Link und Assets
|
||||
(Repository-Kaskade). Die Datei im Repo wird **nicht** gelöscht.
|
||||
**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`).
|
||||
- Bis #20 umgesetzt ist, wird beim Löschen nur die Verknüpfung entfernt, die
|
||||
Datei bleibt im Repo.
|
||||
|
||||
### 6. Teilen per Snapshot (#9)
|
||||
|
||||
@@ -415,7 +442,7 @@ Verbindungs-API: `GET/POST /api/git/connections`,
|
||||
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. Siehe Frage F6.
|
||||
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.
|
||||
@@ -427,24 +454,17 @@ Verbindungs-API: `GET/POST /api/git/connections`,
|
||||
- Negativ: Nur ein App-Prozess (prozesslokaler Mutex). Mehrere Replikate
|
||||
bräuchten eine DB-Sperre.
|
||||
|
||||
## Offene Fragen (Florian)
|
||||
## Entscheidungen (Florian, 2026-11-25)
|
||||
|
||||
- **F6 – Commit-Häufigkeit:** Jeder Save = ein Commit (auch Autosave alle
|
||||
≥ 10 s). *Empfehlung:* so lassen und für Git-Brews den Autosave auf 60 s
|
||||
stellen (kleine Änderung in `editorPage.jsx`). Alternative wäre ein
|
||||
expliziter „Commit“-Button mit Autosave nur in die DB. Das widerspricht aber
|
||||
„Git führend“ und verkompliziert die Konfliktlogik.
|
||||
- **F7 – Erlaubte Git-Hosts:** Dürfen Nutzer beliebige öffentliche Hosts
|
||||
eintragen, oder soll die Instanz per `HB_GIT_ALLOWED_HOSTS` auf bestimmte
|
||||
Hosts (z. B. `git.morlana.online`, `github.com`) beschränkt sein?
|
||||
*Empfehlung:* Im eigenen Compose-Setup eine Allowlist setzen, der Code
|
||||
erlaubt standardmäßig alle öffentlichen Hosts.
|
||||
- **F8 – Externe Commits im Share-Link:** Reicht es, dass sie erst nach dem
|
||||
Öffnen im Editor bzw. nach „Pull“ sichtbar werden?
|
||||
- **F9 – Löschen:** Beim Löschen eines Git-Brews in der App bleibt die Datei
|
||||
im Repo. Einverstanden?
|
||||
- **F13 – Git nur für OIDC-Konten:** Verbindungen hängen an `users.id`, also
|
||||
können nur OIDC-Konten sie anlegen. naturalcrit-Konten können verknüpfte
|
||||
Brews mitbearbeiten, aber nichts selbst verknüpfen. Einverstanden?
|
||||
*Empfehlung:* ja. Mit der Empfehlung zu F1 (nur `oidc` im eigenen Setup)
|
||||
betrifft das niemanden.
|
||||
- **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.
|
||||
@@ -1,6 +1,6 @@
|
||||
# ADR 0004: Bild-Ablage im verbundenen Git-Repo
|
||||
|
||||
- Status: Vorgeschlagen
|
||||
- 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)
|
||||
@@ -147,7 +147,7 @@ Share-Seite, Druck und PDF ohne Renderer-Änderung funktionieren.
|
||||
| --- | --- |
|
||||
| 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 Frage F10 |
|
||||
| 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 |
|
||||
@@ -166,12 +166,10 @@ Share-Seite, Druck und PDF ohne Renderer-Änderung funktionieren.
|
||||
- Negativ: Gelöschte Bilder bleiben in Repo und DB, solange der Brew
|
||||
existiert. Löschen bzw. Aufräumen kommt später.
|
||||
|
||||
## Offene Fragen (Florian)
|
||||
## Entscheidungen (Florian, 2026-11-25)
|
||||
|
||||
- **F10 – URL-Form im Markdown:** App-URL `/git-assets/<shareId>/<hash>.<ext>`
|
||||
(Empfehlung, keine Renderer-Änderung) oder relative Repo-Pfade, damit die
|
||||
Bilder auch in der Repo-Vorschau sichtbar sind (Renderer-Patch in Upstream-Code)?
|
||||
- **F11 – Limits:** 5 MiB pro Bild und 50 MiB pro Brew, erlaubt PNG/JPEG/GIF/WebP.
|
||||
Passt das?
|
||||
- **F12 – EXIF:** Reicht ein Hinweis in der UI, oder sollen Metadaten beim
|
||||
Upload entfernt werden (zusätzliche native Abhängigkeit, mehr Speicher)?
|
||||
- **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.
|
||||
+9
-8
@@ -6,10 +6,10 @@ Upstream-Dateien, die angefasst werden müssen.
|
||||
|
||||
| Nr. | Titel | Status | Umsetzung |
|
||||
| --- | --- | --- | --- |
|
||||
| [0001](0001-auth-oidc.md) | Authentifizierung über generisches OIDC | Vorgeschlagen | M1 (#6) |
|
||||
| [0002](0002-storage-mongo-postgres.md) | Repository-Schicht, Mongo **oder** PostgreSQL pro Instanz | Vorgeschlagen | M2 (#7) |
|
||||
| [0003](0003-git-backend-und-teilen.md) | Git-Backend über HTTPS + PAT, Teilen per Server-Snapshot | Vorgeschlagen | M3 (#8, #9) |
|
||||
| [0004](0004-bild-ablage-im-git-repo.md) | Bild-Ablage im verbundenen Git-Repo | Vorgeschlagen | M4 (#10) |
|
||||
| [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)
|
||||
|
||||
@@ -29,8 +29,9 @@ Upstream-Dateien, die angefasst werden müssen.
|
||||
4. **Ein App-Container pro Instanz.** Sperren (z. B. pro Brew beim Git-Commit)
|
||||
sind prozesslokal. Mehrere App-Replikate sind nicht vorgesehen.
|
||||
|
||||
## Fragen an Florian
|
||||
## Entscheidungen
|
||||
|
||||
Offene Grundsatzfragen stehen am Ende jeder ADR unter „Offene Fragen“ und
|
||||
gesammelt in der PR-Beschreibung. Bis zur Antwort gilt jeweils die dort
|
||||
genannte Empfehlung als Arbeitsannahme.
|
||||
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,68 @@
|
||||
# Login (OIDC) einrichten
|
||||
|
||||
Umsetzung von [ADR 0001](../adr/0001-auth-oidc.md). Der Login läuft über einen beliebigen
|
||||
OpenID-Connect-Provider (getestet mit Keycloak und authentik). Alles wird über
|
||||
Umgebungsvariablen konfiguriert, siehe `.env.example`.
|
||||
|
||||
## Schnellstart mit dem Compose-Setup
|
||||
|
||||
```sh
|
||||
cp .env.example .env # enthält Dev-Werte für Keycloak
|
||||
docker compose --profile keycloak up -d # Keycloak (Start dauert 1-2 Minuten)
|
||||
docker compose up --build -d # App mit OIDC-Login -> http://localhost:8000
|
||||
```
|
||||
|
||||
Mit authentik: `HB_OIDC_ISSUER` in `.env` auf die authentik-Zeile umstellen und
|
||||
`--profile authentik` verwenden. Testbenutzer in beiden: `testuser` / `testuser-dev`.
|
||||
Details: [keycloak.md](keycloak.md), [authentik.md](authentik.md).
|
||||
|
||||
## Variablen
|
||||
|
||||
| Variable | Pflicht | Standard | Bedeutung |
|
||||
| --- | --- | --- | --- |
|
||||
| `HB_AUTH_PROVIDERS` | nein | s. u. | `oidc`, `naturalcrit` (kommagetrennt) |
|
||||
| `HB_PUBLIC_URL` | bei `oidc` | – | z. B. `https://brew.example.org`, ohne `/` am Ende |
|
||||
| `HB_OIDC_ISSUER` | bei `oidc` | – | Issuer-URL (Discovery über `/.well-known/openid-configuration`) |
|
||||
| `HB_OIDC_CLIENT_ID` | bei `oidc` | – | |
|
||||
| `HB_OIDC_CLIENT_SECRET` | bei `oidc` | – | vertraulicher Client (`client_secret_basic`) |
|
||||
| `HB_OIDC_SCOPES` | nein | `openid profile email` | |
|
||||
| `HB_OIDC_USERNAME_CLAIM` | nein | `preferred_username` | Quelle des Benutzernamens bei Neuanlage |
|
||||
| `HB_OIDC_LINK_BY_EMAIL` | nein | `false` | verifizierte E-Mail an vorab angelegten Benutzer binden |
|
||||
| `HB_OIDC_END_SESSION` | nein | `false` | beim Logout auch am IdP abmelden |
|
||||
| `HB_OIDC_LABEL` | nein | `Anmelden` | Text des Login-Buttons |
|
||||
| `HB_SESSION_SECRET` | bei `oidc` | – | mindestens 32 Byte |
|
||||
| `HB_SESSION_TTL` | nein | `7d` | feste Session-Laufzeit (`7d`, `12h`, `3600`) |
|
||||
|
||||
Die App startet nicht, wenn `oidc` aktiv ist und Pflichtwerte fehlen.
|
||||
|
||||
## Login-Methoden ein-/ausschalten (`HB_AUTH_PROVIDERS`)
|
||||
|
||||
Der Redirect-URI beim IdP ist `${HB_PUBLIC_URL}/auth/oidc/callback`, der Post-Logout-URI `${HB_PUBLIC_URL}/`.
|
||||
|
||||
| Einstellung | Wirkung |
|
||||
| --- | --- |
|
||||
| nicht gesetzt, kein Issuer | Upstream-Verhalten: nur `naturalcrit` |
|
||||
| nicht gesetzt, `HB_OIDC_ISSUER` gesetzt | `oidc,naturalcrit`: Login-Link führt auf die Auswahlseite `/auth/login`. Außerhalb lokaler Umgebungen bricht der Start ab, solange das Upstream-`secret` (Env `SECRET`) der Standardwert `secret` ist, weil sich sonst `nc_session` fälschen ließe; `SECRET` setzen oder `HB_AUTH_PROVIDERS=oidc` |
|
||||
| `oidc` | nur OIDC. `nc_session` wird ignoriert, `POST /local/login` liefert 404, Google Drive als Speicherort entfällt |
|
||||
| `naturalcrit` | nur Alt-Login (Benutzername/Passwort und Google laufen bei Upstream über naturalcrit.com). `/auth/oidc/*` liefern 404, ein vorhandenes `hb_session` wird ignoriert |
|
||||
|
||||
Hinweis: Benutzername/Passwort- und Google-Login gehören bei Upstream zu naturalcrit.com und nicht zu dieser App
|
||||
(ADR 0001, Frage F1). Ein Abschalten bedeutet daher: die `nc_session` wird nicht mehr akzeptiert und
|
||||
die Login-Links verschwinden aus der Oberfläche.
|
||||
|
||||
## Kontozuordnung
|
||||
|
||||
- Der Benutzer ist über (`iss`, `sub`) eindeutig. Beim ersten Login wird ein Konto angelegt. Der Benutzername
|
||||
kommt aus `HB_OIDC_USERNAME_CLAIM` (Fallback: Teil der E-Mail vor dem `@`) und ist danach unveränderlich.
|
||||
Kollidiert er mit einem Benutzer oder einem Autor in bestehenden Brews, wird `-2`, `-3`, … angehängt.
|
||||
- Bestehende Namen aus `authors[]` werden nicht automatisch übernommen. Mit `HB_OIDC_LINK_BY_EMAIL=true` bindet der
|
||||
Login einen **vorab angelegten** Benutzer (ohne OIDC-Bindung) an die verifizierte E-Mail des IdP.
|
||||
Das Anlegen vorab angelegter Benutzer (`POST /admin/users`) ist nicht Teil von M1.
|
||||
- `PUT /api/user/rename` ist für OIDC-Sitzungen gesperrt (403, `HBErrorCode: A01`).
|
||||
|
||||
## Tests
|
||||
|
||||
- Automatisiert: `npx jest server/fork/auth` (Mock-IdP `oidc-provider` im Prozess, kein Container nötig).
|
||||
- Storage-Contract gegen Mongo: `HB_TEST_MONGODB_URI=mongodb://127.0.0.1:27017 npx jest server/storage`.
|
||||
- E2E gegen echten IdP und laufende App: `node scripts/oidc-e2e.mjs --idp keycloak|authentik`
|
||||
(siehe die jeweilige Anleitung).
|
||||
@@ -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,119 @@
|
||||
# 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, `/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 |
|
||||
|
||||
Das Docker-Image enthält `git` bereits. Außerhalb von Docker muss `git` (≥ 2.30) im `PATH` liegen.
|
||||
|
||||
## 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`.
|
||||
@@ -0,0 +1,66 @@
|
||||
# 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`).
|
||||
|
||||
## 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
|
||||
|
||||
+20
-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,10 @@ 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 cors from 'cors';
|
||||
|
||||
export default async function createApp(vite) {
|
||||
@@ -45,6 +48,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') {
|
||||
@@ -112,6 +116,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 +144,6 @@ export default async function createApp(vite) {
|
||||
|
||||
app.use(pageRoutes({
|
||||
defaultMetaTags,
|
||||
HomebrewModel,
|
||||
sanitizeBrew,
|
||||
}));
|
||||
|
||||
@@ -177,16 +191,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 +237,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,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,390 @@
|
||||
import http from 'http';
|
||||
import express from 'express';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { startIdp, loginAtIdp, CLIENT } from './testIdp.js';
|
||||
import { createMemoryUsers } from './testUsers.js';
|
||||
import { readAuthConfig, accountMiddleware, createAuthRouter } from './index.js';
|
||||
import { openTx, sealTx, SESSION_COOKIE, TX_COOKIE } from './session.js';
|
||||
|
||||
const SECRET = 's'.repeat(40);
|
||||
const ACCOUNTS = {
|
||||
alice : { preferred_username: 'alice', email: 'alice@example.test', email_verified: true, name: 'Alice A.' },
|
||||
bob : { preferred_username: 'bob', email: 'bob@example.test', email_verified: false }
|
||||
};
|
||||
|
||||
let appServer; let idp; let appUrl; let delegate; let users; let authors; let renameCalled;
|
||||
|
||||
const buildApp = (envOverrides = {}, depsOverrides = {})=>{
|
||||
const config = readAuthConfig({
|
||||
HB_PUBLIC_URL : appUrl, HB_OIDC_ISSUER : idp.issuer, HB_OIDC_CLIENT_ID : CLIENT.client_id,
|
||||
HB_OIDC_CLIENT_SECRET : CLIENT.client_secret, HB_SESSION_SECRET : SECRET, ...envOverrides
|
||||
}, { upstreamSecret: 'eigenes-secret' });
|
||||
const app = express();
|
||||
app.use(cookieParser());
|
||||
// Stand-in für die Upstream-Account-Middleware: nc_session-Cookie == Benutzername
|
||||
app.use((req, res, next)=>{ if(req.cookies.nc_session) req.account = { username: req.cookies.nc_session }; next(); });
|
||||
app.use(accountMiddleware(config));
|
||||
app.use(createAuthRouter(config, { getUsers: ()=>users, brewAuthorExists: async (n)=>authors.has(n), ...depsOverrides }));
|
||||
app.get('/whoami', (req, res)=>res.json(req.account ?? null));
|
||||
app.put('/api/user/rename', (req, res)=>{ renameCalled = true; res.json({ upstream: true }); });
|
||||
app.post('/local/login', (req, res)=>res.json('upstream-token'));
|
||||
app.get('/', (req, res)=>res.send('home'));
|
||||
delegate = app;
|
||||
return config;
|
||||
};
|
||||
|
||||
// Mini-Browser mit Cookie-Jar
|
||||
const browser = ()=>{
|
||||
const jar = {};
|
||||
const store = (res)=>{
|
||||
for (const c of res.headers.getSetCookie()) {
|
||||
const [kv, ...attrs] = c.split(';');
|
||||
const i = kv.indexOf('=');
|
||||
const name = kv.slice(0, i); const value = kv.slice(i + 1);
|
||||
if(!value || attrs.some((a)=>/expires=Thu, 01 Jan 1970/i.test(a))) delete jar[name]; else jar[name] = value;
|
||||
}
|
||||
};
|
||||
const req = async (path, init = {})=>{
|
||||
const res = await fetch(path.startsWith('http') ? path : `${appUrl}${path}`, {
|
||||
redirect : 'manual', ...init,
|
||||
headers : { cookie: Object.entries(jar).map(([k, v])=>`${k}=${v}`).join('; '), ...(init.headers || {}) }
|
||||
});
|
||||
store(res);
|
||||
return res;
|
||||
};
|
||||
return { jar, req };
|
||||
};
|
||||
|
||||
// Vollständiger Login; gibt { b, res (Callback-Antwort), authUrl }
|
||||
const login = async (sub, redirect = '/brews', b = browser())=>{
|
||||
const start = await b.req(`/auth/oidc/login?redirect=${encodeURIComponent(redirect)}`);
|
||||
const authUrl = start.headers.get('location');
|
||||
const { callbackUrl } = await loginAtIdp(authUrl, { login: sub });
|
||||
const res = await b.req(callbackUrl);
|
||||
return { b, res, authUrl, callbackUrl };
|
||||
};
|
||||
|
||||
beforeAll(async ()=>{
|
||||
jest.spyOn(console, 'warn').mockImplementation(()=>{});
|
||||
jest.spyOn(console, 'error').mockImplementation(()=>{});
|
||||
appServer = http.createServer((req, res)=>delegate(req, res));
|
||||
await new Promise((r)=>appServer.listen(0, '127.0.0.1', r));
|
||||
appUrl = `http://127.0.0.1:${appServer.address().port}`;
|
||||
idp = await startIdp({ accounts: ACCOUNTS, redirectUri: `${appUrl}/auth/oidc/callback` });
|
||||
});
|
||||
afterAll(async ()=>{
|
||||
await idp.close();
|
||||
await new Promise((r)=>{ appServer.closeAllConnections?.(); appServer.close(r); });
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
beforeEach(()=>{
|
||||
users = createMemoryUsers(); authors = new Set(); renameCalled = false;
|
||||
buildApp();
|
||||
});
|
||||
|
||||
describe('OIDC-Login (Authorization Code + PKCE) gegen Mock-IdP', ()=>{
|
||||
test('Login-Redirect enthält PKCE S256, state, nonce, Scopes und setzt das Tx-Cookie', async ()=>{
|
||||
const b = browser();
|
||||
const res = await b.req('/auth/oidc/login');
|
||||
expect(res.status).toBe(302);
|
||||
const u = new URL(res.headers.get('location'));
|
||||
expect(u.origin).toBe(idp.issuer);
|
||||
expect(u.searchParams.get('code_challenge_method')).toBe('S256');
|
||||
expect(u.searchParams.get('code_challenge')).toMatch(/^[\w-]{43}$/);
|
||||
expect(u.searchParams.get('state')).toHaveLength(43);
|
||||
expect(u.searchParams.get('nonce')).toHaveLength(43);
|
||||
expect(u.searchParams.get('scope')).toBe('openid profile email');
|
||||
expect(u.searchParams.get('redirect_uri')).toBe(`${appUrl}/auth/oidc/callback`);
|
||||
const setCookie = res.headers.getSetCookie().find((c)=>c.startsWith(TX_COOKIE));
|
||||
expect(setCookie).toMatch(/HttpOnly/i);
|
||||
expect(setCookie).toMatch(/SameSite=Lax/i);
|
||||
expect(setCookie).toMatch(/Path=\/auth\/oidc/);
|
||||
expect(setCookie).toMatch(/Max-Age=600/);
|
||||
expect(setCookie).not.toMatch(/Secure/i); // http-Testumgebung
|
||||
});
|
||||
|
||||
test('Erfolg: Konto angelegt, Session-Cookie, Weiterleitung, req.account gesetzt', async ()=>{
|
||||
const { b, res } = await login('alice', '/edit/xyz?a=1');
|
||||
expect(res.status).toBe(302);
|
||||
expect(res.headers.get('location')).toBe('/edit/xyz?a=1');
|
||||
const sessionCookie = res.headers.getSetCookie().find((c)=>c.startsWith(SESSION_COOKIE));
|
||||
expect(sessionCookie).toMatch(/HttpOnly/i);
|
||||
expect(sessionCookie).toMatch(/Path=\//);
|
||||
expect(b.jar[TX_COOKIE]).toBeUndefined(); // Transaktion verbraucht
|
||||
|
||||
expect(users.rows).toHaveLength(1);
|
||||
expect(users.rows[0]).toMatchObject({ username: 'alice', oidcIssuer: idp.issuer, oidcSub: 'alice', email: 'alice@example.test', emailVerified: true, displayName: 'Alice A.' });
|
||||
|
||||
const who = await (await b.req('/whoami')).json();
|
||||
expect(who).toEqual({ username: 'alice', uid: users.rows[0].id, provider: 'oidc' });
|
||||
|
||||
const claims = jwt.verify(b.jar[SESSION_COOKIE], SECRET, { algorithms: ['HS256'] });
|
||||
expect(claims).toMatchObject({ v: 1, username: 'alice', iss: idp.issuer, sub: 'alice' });
|
||||
expect(claims.exp - claims.iat).toBe(7 * 24 * 3600);
|
||||
});
|
||||
|
||||
test('erneuter Login erzeugt kein zweites Konto', async ()=>{
|
||||
await login('alice');
|
||||
await login('alice');
|
||||
expect(users.rows).toHaveLength(1);
|
||||
expect(users.rows[0].lastLoginAt).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
test('Namenskollision mit Brew-Autor: neues Konto bekommt Suffix', async ()=>{
|
||||
authors.add('alice');
|
||||
await login('alice');
|
||||
expect(users.rows[0].username).toBe('alice-2');
|
||||
});
|
||||
|
||||
test('E-Mail-Verknüpfung nur bei HB_OIDC_LINK_BY_EMAIL=true und verifizierter E-Mail', async ()=>{
|
||||
const pre = await users.create({ username: 'legacy-alice', email: 'alice@example.test' });
|
||||
await login('alice');
|
||||
expect(users.rows.map((r)=>r.username).sort()).toEqual(['alice', 'legacy-alice']);
|
||||
|
||||
users = createMemoryUsers();
|
||||
const pre2 = await users.create({ username: 'legacy-alice', email: 'alice@example.test' });
|
||||
buildApp({ HB_OIDC_LINK_BY_EMAIL: 'true' });
|
||||
await login('alice');
|
||||
expect(users.rows).toHaveLength(1);
|
||||
expect(users.rows[0]).toMatchObject({ id: pre2.id, username: 'legacy-alice', oidcSub: 'alice' });
|
||||
expect(pre.id).not.toBe(pre2.id);
|
||||
|
||||
users = createMemoryUsers();
|
||||
await users.create({ username: 'legacy-bob', email: 'bob@example.test' });
|
||||
await login('bob'); // E-Mail nicht verifiziert
|
||||
expect(users.rows.find((r)=>r.username === 'legacy-bob').oidcSub).toBeNull();
|
||||
});
|
||||
|
||||
test('eigener Anzeigename und Scopes über Umgebung', async ()=>{
|
||||
buildApp({ HB_OIDC_SCOPES: 'openid email', HB_OIDC_USERNAME_CLAIM: 'email' });
|
||||
const res = await browser().req('/auth/oidc/login');
|
||||
expect(new URL(res.headers.get('location')).searchParams.get('scope')).toBe('openid email');
|
||||
});
|
||||
|
||||
describe('Fehlerfälle im Callback', ()=>{
|
||||
const expectErrorPage = async (res, status)=>{
|
||||
expect(res.status).toBe(status);
|
||||
expect(res.headers.get('content-type')).toMatch(/html/);
|
||||
expect(await res.text()).toMatch(/Erneut anmelden/);
|
||||
};
|
||||
|
||||
test('ohne Transaktion → 400', async ()=>{
|
||||
const res = await browser().req('/auth/oidc/callback?code=abc&state=xyz');
|
||||
await expectErrorPage(res, 400);
|
||||
});
|
||||
|
||||
test('falscher state → 400, kein Konto, keine Session', async ()=>{
|
||||
const b = browser();
|
||||
const start = await b.req('/auth/oidc/login');
|
||||
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
||||
const u = new URL(callbackUrl);
|
||||
u.searchParams.set('state', 'manipuliert');
|
||||
const res = await b.req(u.href);
|
||||
await expectErrorPage(res, 400);
|
||||
expect(users.rows).toHaveLength(0);
|
||||
expect(b.jar[SESSION_COOKIE]).toBeUndefined();
|
||||
expect(b.jar[TX_COOKIE]).toBeUndefined();
|
||||
});
|
||||
|
||||
test('Transaktion nur einmal verwendbar (Replay)', async ()=>{
|
||||
const b = browser();
|
||||
const start = await b.req('/auth/oidc/login');
|
||||
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
||||
const txCookie = b.jar[TX_COOKIE];
|
||||
expect((await b.req(callbackUrl)).status).toBe(302);
|
||||
b.jar[TX_COOKIE] = txCookie; // Angreifer spielt Cookie + Code erneut ein
|
||||
const res = await b.req(callbackUrl);
|
||||
await expectErrorPage(res, 400); // Code ist beim IdP verbraucht
|
||||
expect(users.rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('abgelaufene Transaktion → 400', async ()=>{
|
||||
const b = browser();
|
||||
const start = await b.req('/auth/oidc/login');
|
||||
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
||||
const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }, { upstreamSecret: 'eigenes-secret' });
|
||||
const tx = openTx(config, b.jar[TX_COOKIE]);
|
||||
b.jar[TX_COOKIE] = sealTx(config, { ...tx, createdAt: Date.now() - 11 * 60 * 1000 });
|
||||
await expectErrorPage(await b.req(callbackUrl), 400);
|
||||
expect(users.rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('manipuliertes Tx-Cookie → 400', async ()=>{
|
||||
const b = browser();
|
||||
const start = await b.req('/auth/oidc/login');
|
||||
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
||||
b.jar[TX_COOKIE] = `${b.jar[TX_COOKIE].slice(0, -3)}AAA`;
|
||||
await expectErrorPage(await b.req(callbackUrl), 400);
|
||||
});
|
||||
|
||||
test('falscher nonce (ID-Token passt nicht zur Transaktion) → 400', async ()=>{
|
||||
const b = browser();
|
||||
const start = await b.req('/auth/oidc/login');
|
||||
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
||||
const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }, { upstreamSecret: 'eigenes-secret' });
|
||||
const tx = openTx(config, b.jar[TX_COOKIE]);
|
||||
b.jar[TX_COOKIE] = sealTx(config, { ...tx, nonce: 'anderer-nonce' });
|
||||
await expectErrorPage(await b.req(callbackUrl), 400);
|
||||
expect(users.rows).toHaveLength(0);
|
||||
expect(b.jar[SESSION_COOKIE]).toBeUndefined();
|
||||
});
|
||||
|
||||
test('falscher PKCE-Verifier → 400', async ()=>{
|
||||
const b = browser();
|
||||
const start = await b.req('/auth/oidc/login');
|
||||
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
||||
const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }, { upstreamSecret: 'eigenes-secret' });
|
||||
const tx = openTx(config, b.jar[TX_COOKIE]);
|
||||
b.jar[TX_COOKIE] = sealTx(config, { ...tx, codeVerifier: 'A'.repeat(43) });
|
||||
await expectErrorPage(await b.req(callbackUrl), 400);
|
||||
expect(users.rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('IdP meldet error=access_denied → 400 mit Hinweis', async ()=>{
|
||||
const b = browser();
|
||||
const start = await b.req('/auth/oidc/login');
|
||||
const state = new URL(start.headers.get('location')).searchParams.get('state');
|
||||
const res = await b.req(`/auth/oidc/callback?error=access_denied&state=${state}&iss=${encodeURIComponent(idp.issuer)}`);
|
||||
await expectErrorPage(res, 400);
|
||||
expect(users.rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('Code ungültig → 400', async ()=>{
|
||||
const b = browser();
|
||||
const start = await b.req('/auth/oidc/login');
|
||||
const state = new URL(start.headers.get('location')).searchParams.get('state');
|
||||
const res = await b.req(`/auth/oidc/callback?code=falsch&state=${state}&iss=${encodeURIComponent(idp.issuer)}`);
|
||||
await expectErrorPage(res, 400);
|
||||
});
|
||||
|
||||
test('Fehler im Konto-Mapping → 500 ohne Session', async ()=>{
|
||||
buildApp({}, { getUsers: ()=>({ findByOidc: async ()=>{ throw new Error('db down'); } }) });
|
||||
const { b, res } = await login('alice');
|
||||
await expectErrorPage(res, 500);
|
||||
expect(b.jar[SESSION_COOKIE]).toBeUndefined();
|
||||
});
|
||||
|
||||
test('IdP nicht erreichbar → 502, späterer Versuch klappt (Discovery nicht dauerhaft gecacht)', async ()=>{
|
||||
buildApp({ HB_OIDC_ISSUER: 'http://127.0.0.1:9' });
|
||||
const res = await browser().req('/auth/oidc/login');
|
||||
await expectErrorPage(res, 502);
|
||||
// anderer Router mit funktionierendem IdP
|
||||
buildApp();
|
||||
expect((await browser().req('/auth/oidc/login')).status).toBe(302);
|
||||
});
|
||||
});
|
||||
|
||||
describe('offene Weiterleitung', ()=>{
|
||||
test.each(['//evil.example', 'https://evil.example/x', '/\\evil.example', 'javascript:alert(1)'])('redirect=%s → /', async (redirect)=>{
|
||||
const { res } = await login('alice', redirect);
|
||||
expect(res.headers.get('location')).toBe('/');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Logout', ()=>{
|
||||
test('löscht das Session-Cookie und leitet auf / um', async ()=>{
|
||||
const { b } = await login('alice');
|
||||
const res = await b.req('/auth/logout');
|
||||
expect(res.status).toBe(302);
|
||||
expect(res.headers.get('location')).toBe('/');
|
||||
expect(b.jar[SESSION_COOKIE]).toBeUndefined();
|
||||
expect(await (await b.req('/whoami')).json()).toBeNull();
|
||||
});
|
||||
|
||||
test('mit HB_OIDC_END_SESSION=true Redirect zum end_session_endpoint des IdP', async ()=>{
|
||||
buildApp({ HB_OIDC_END_SESSION: 'true' });
|
||||
const { b } = await login('alice');
|
||||
const res = await b.req('/auth/logout');
|
||||
const loc = new URL(res.headers.get('location'));
|
||||
expect(loc.origin).toBe(idp.issuer);
|
||||
expect(loc.pathname).toBe('/session/end');
|
||||
expect(loc.searchParams.get('client_id')).toBe(CLIENT.client_id);
|
||||
expect(loc.searchParams.get('post_logout_redirect_uri')).toBe(`${appUrl}/`);
|
||||
expect(b.jar[SESSION_COOKIE]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Session-Gültigkeit', ()=>{
|
||||
test('abgelaufene und fremd signierte Sessions liefern kein Konto', async ()=>{
|
||||
const b = browser();
|
||||
const claims = { v: 1, uid: 'u', username: 'mallory', iss: 'i', sub: 's' };
|
||||
b.jar[SESSION_COOKIE] = jwt.sign(claims, SECRET, { expiresIn: -5 });
|
||||
expect(await (await b.req('/whoami')).json()).toBeNull();
|
||||
b.jar[SESSION_COOKIE] = jwt.sign(claims, 'x'.repeat(40), { expiresIn: 60 });
|
||||
expect(await (await b.req('/whoami')).json()).toBeNull();
|
||||
b.jar[SESSION_COOKIE] = jwt.sign(claims, SECRET, { expiresIn: 60 });
|
||||
expect((await (await b.req('/whoami')).json()).username).toBe('mallory');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PUT /api/user/rename', ()=>{
|
||||
test('OIDC-Session → 403 A01, Upstream-Route wird nicht erreicht', async ()=>{
|
||||
const { b } = await login('alice');
|
||||
const res = await b.req('/api/user/rename', {
|
||||
method : 'PUT', headers : { 'content-type': 'application/json' },
|
||||
body : JSON.stringify({ username: 'victim', newUsername: 'alice' })
|
||||
});
|
||||
expect(res.status).toBe(403);
|
||||
expect(await res.json()).toMatchObject({ HBErrorCode: 'A01' });
|
||||
expect(renameCalled).toBe(false);
|
||||
});
|
||||
|
||||
test('naturalcrit-Session → Upstream-Verhalten', async ()=>{
|
||||
const b = browser();
|
||||
b.jar.nc_session = 'carol';
|
||||
const res = await b.req('/api/user/rename', { method: 'PUT' });
|
||||
expect(await res.json()).toEqual({ upstream: true });
|
||||
expect(renameCalled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Alt-Logins abschaltbar (HB_AUTH_PROVIDERS)', ()=>{
|
||||
test('beide aktiv: nc_session gilt (mit provider), Auswahlseite, /local/login erreichbar', async ()=>{
|
||||
buildApp({ HB_AUTH_PROVIDERS: 'oidc,naturalcrit' });
|
||||
const b = browser();
|
||||
b.jar.nc_session = 'carol';
|
||||
expect(await (await b.req('/whoami')).json()).toEqual({ username: 'carol', provider: 'naturalcrit' });
|
||||
const chooser = await b.req('/auth/login?redirect=%2Fbrews');
|
||||
const html = await chooser.text();
|
||||
expect(html).toMatch(/\/auth\/oidc\/login\?redirect=%2Fbrews/);
|
||||
expect(html).toMatch(/naturalcrit\.com\/login/);
|
||||
expect((await b.req('/local/login', { method: 'POST' })).status).toBe(200);
|
||||
});
|
||||
|
||||
test('nur oidc: nc_session wird ignoriert, /local/login 404, /auth/login leitet direkt zum IdP-Login', async ()=>{
|
||||
buildApp({ HB_AUTH_PROVIDERS: 'oidc' });
|
||||
const b = browser();
|
||||
b.jar.nc_session = 'carol';
|
||||
expect(await (await b.req('/whoami')).json()).toBeNull();
|
||||
expect((await b.req('/local/login', { method: 'POST' })).status).toBe(404);
|
||||
const res = await b.req('/auth/login?redirect=%2Fx');
|
||||
expect(res.status).toBe(302);
|
||||
expect(res.headers.get('location')).toBe('/auth/oidc/login?redirect=%2Fx');
|
||||
// OIDC-Login funktioniert weiter
|
||||
const { b: b2 } = await login('alice');
|
||||
expect((await (await b2.req('/whoami')).json()).provider).toBe('oidc');
|
||||
});
|
||||
|
||||
test('nur naturalcrit: OIDC-Endpunkte gesperrt, hb_session wird ignoriert', async ()=>{
|
||||
buildApp({ HB_AUTH_PROVIDERS: 'naturalcrit' });
|
||||
const b = browser();
|
||||
expect((await b.req('/auth/oidc/login')).status).toBe(404);
|
||||
expect((await b.req('/auth/oidc/callback?code=x&state=y')).status).toBe(404);
|
||||
expect((await b.req('/auth/login')).status).toBe(404);
|
||||
b.jar[SESSION_COOKIE] = jwt.sign({ v: 1, uid: 'u', username: 'mallory', iss: 'i', sub: 's' }, SECRET, { expiresIn: 60 });
|
||||
b.jar.nc_session = 'carol';
|
||||
expect(await (await b.req('/whoami')).json()).toEqual({ username: 'carol', provider: 'naturalcrit' });
|
||||
expect((await b.req('/local/login', { method: 'POST' })).status).toBe(200);
|
||||
});
|
||||
|
||||
test('nur oidc: PUT /api/user/rename ohne OIDC-Session erreicht die Upstream-Route (dort greift die Kontoprüfung)', async ()=>{
|
||||
buildApp({ HB_AUTH_PROVIDERS: 'oidc' });
|
||||
const b = browser();
|
||||
b.jar.nc_session = 'carol';
|
||||
const res = await b.req('/api/user/rename', { method: 'PUT' });
|
||||
expect(renameCalled).toBe(true);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
// Auth-Konfiguration ausschließlich aus Umgebungsvariablen (ADR 0001, "Konfiguration").
|
||||
const VALID_PROVIDERS = ['oidc', 'naturalcrit'];
|
||||
const MIN_SECRET_BYTES = 32;
|
||||
|
||||
const bool = (v, def = false)=>{
|
||||
if(v === undefined || v === null || v === '') return def;
|
||||
return ['1', 'true', 'yes', 'on'].includes(String(v).trim().toLowerCase());
|
||||
};
|
||||
|
||||
// "7d", "12h", "30m", "90s", "604800" (Sekunden) -> Sekunden
|
||||
export const parseTtl = (value, def = 7 * 24 * 3600)=>{
|
||||
if(value === undefined || value === '') return def;
|
||||
const m = /^(\d+)\s*([smhdw]?)$/i.exec(String(value).trim());
|
||||
if(!m) throw new Error(`HB_SESSION_TTL ungültig: "${value}" (erwartet z. B. 7d, 12h, 3600)`);
|
||||
const mult = { '': 1, s: 1, m: 60, h: 3600, d: 86400, w: 604800 }[m[2].toLowerCase()];
|
||||
const seconds = Number(m[1]) * mult;
|
||||
if(seconds <= 0) throw new Error('HB_SESSION_TTL muss größer als 0 sein');
|
||||
return seconds;
|
||||
};
|
||||
|
||||
export const readAuthConfig = (env = process.env, { upstreamSecret, isLocal = false } = {})=>{
|
||||
const issuer = env.HB_OIDC_ISSUER || undefined;
|
||||
|
||||
let providers;
|
||||
if(env.HB_AUTH_PROVIDERS && env.HB_AUTH_PROVIDERS.trim()) {
|
||||
providers = [...new Set(env.HB_AUTH_PROVIDERS.split(',').map((p)=>p.trim().toLowerCase()).filter(Boolean))];
|
||||
const unknown = providers.filter((p)=>!VALID_PROVIDERS.includes(p));
|
||||
if(unknown.length) throw new Error(`HB_AUTH_PROVIDERS: unbekannte Werte ${unknown.join(', ')} (erlaubt: ${VALID_PROVIDERS.join(', ')})`);
|
||||
} else {
|
||||
providers = issuer ? ['oidc', 'naturalcrit'] : ['naturalcrit'];
|
||||
}
|
||||
|
||||
const publicUrl = (env.HB_PUBLIC_URL || '').replace(/\/+$/, '');
|
||||
const config = {
|
||||
providers,
|
||||
publicUrl,
|
||||
secureCookies : publicUrl.startsWith('https://'),
|
||||
sessionSecret : env.HB_SESSION_SECRET || undefined,
|
||||
sessionTtl : parseTtl(env.HB_SESSION_TTL),
|
||||
oidc : {
|
||||
issuer,
|
||||
clientId : env.HB_OIDC_CLIENT_ID || undefined,
|
||||
clientSecret : env.HB_OIDC_CLIENT_SECRET || undefined,
|
||||
scopes : (env.HB_OIDC_SCOPES || 'openid profile email').trim(),
|
||||
usernameClaim : env.HB_OIDC_USERNAME_CLAIM || 'preferred_username',
|
||||
linkByEmail : bool(env.HB_OIDC_LINK_BY_EMAIL),
|
||||
endSession : bool(env.HB_OIDC_END_SESSION),
|
||||
label : env.HB_OIDC_LABEL || 'Anmelden'
|
||||
}
|
||||
};
|
||||
|
||||
if(providers.includes('oidc')) {
|
||||
const required = {
|
||||
HB_OIDC_ISSUER : config.oidc.issuer,
|
||||
HB_OIDC_CLIENT_ID : config.oidc.clientId,
|
||||
HB_OIDC_CLIENT_SECRET : config.oidc.clientSecret,
|
||||
HB_PUBLIC_URL : config.publicUrl,
|
||||
HB_SESSION_SECRET : config.sessionSecret
|
||||
};
|
||||
const missing = Object.entries(required).filter(([, v])=>!v).map(([k])=>k);
|
||||
if(missing.length) throw new Error(`Auth-Provider "oidc" ist aktiv, aber es fehlen: ${missing.join(', ')}`);
|
||||
if(Buffer.byteLength(config.sessionSecret) < MIN_SECRET_BYTES) {
|
||||
throw new Error(`HB_SESSION_SECRET muss mindestens ${MIN_SECRET_BYTES} Byte lang sein`);
|
||||
}
|
||||
if(!/^https?:\/\//.test(config.publicUrl)) throw new Error('HB_PUBLIC_URL muss mit http:// oder https:// beginnen');
|
||||
let issuerUrl;
|
||||
try { issuerUrl = new URL(config.oidc.issuer); } catch { throw new Error('HB_OIDC_ISSUER ist keine gültige URL'); }
|
||||
// http://-Issuer nur im Dev-Setup (HB_PUBLIC_URL selbst http://), sonst läuft Discovery/JWKS/Token unverschlüsselt
|
||||
if(issuerUrl.protocol === 'http:' && config.publicUrl.startsWith('https://')) {
|
||||
throw new Error('HB_OIDC_ISSUER muss https:// verwenden, wenn HB_PUBLIC_URL https:// ist');
|
||||
}
|
||||
// Upstream-nc_session wird mit config "secret" signiert; Standardwert => Sitzung fälschbar
|
||||
if(providers.includes('naturalcrit') && !isLocal && (!upstreamSecret || upstreamSecret === 'secret')) {
|
||||
throw new Error('Auth: "naturalcrit" ist neben "oidc" aktiv, aber das Upstream-"secret" ist der Standardwert. Entweder SECRET setzen oder HB_AUTH_PROVIDERS=oidc.');
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
};
|
||||
|
||||
export const hasProvider = (config, name)=>config.providers.includes(name);
|
||||
|
||||
// Nur das, was der Client wissen darf (kein Secret)
|
||||
const loginUrlFor = (providers)=>{
|
||||
if(!providers.includes('oidc')) return null;
|
||||
return providers.includes('naturalcrit') ? '/auth/login' : '/auth/oidc/login';
|
||||
};
|
||||
|
||||
export const clientConfig = (config)=>({
|
||||
providers : config.providers,
|
||||
loginUrl : loginUrlFor(config.providers),
|
||||
logoutUrl : '/auth/logout',
|
||||
oidcLabel : config.oidc.label
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { readAuthConfig, parseTtl, clientConfig } from './config.js';
|
||||
|
||||
const base = {
|
||||
HB_PUBLIC_URL : 'https://brew.example.org/', HB_OIDC_ISSUER : 'https://idp.example/realms/x',
|
||||
HB_OIDC_CLIENT_ID : 'id', HB_OIDC_CLIENT_SECRET : 's', HB_SESSION_SECRET : 'x'.repeat(32)
|
||||
};
|
||||
|
||||
const own = { upstreamSecret: 'eigenes-secret' };
|
||||
|
||||
describe('Auth-Konfiguration', ()=>{
|
||||
test('Standard ohne Angaben: nur naturalcrit (Upstream-Verhalten)', ()=>{
|
||||
const c = readAuthConfig({});
|
||||
expect(c.providers).toEqual(['naturalcrit']);
|
||||
expect(clientConfig(c).loginUrl).toBeNull();
|
||||
});
|
||||
|
||||
test('Issuer gesetzt, Provider leer: oidc,naturalcrit mit Auswahlseite', ()=>{
|
||||
const c = readAuthConfig(base, own);
|
||||
expect(c.providers).toEqual(['oidc', 'naturalcrit']);
|
||||
expect(c.publicUrl).toBe('https://brew.example.org');
|
||||
expect(c.secureCookies).toBe(true);
|
||||
expect(clientConfig(c).loginUrl).toBe('/auth/login');
|
||||
expect(c.oidc).toMatchObject({ scopes: 'openid profile email', usernameClaim: 'preferred_username', linkByEmail: false, endSession: false, label: 'Anmelden' });
|
||||
});
|
||||
|
||||
test('nur oidc: direkter Login-Link', ()=>{
|
||||
const c = readAuthConfig({ ...base, HB_AUTH_PROVIDERS: 'oidc' });
|
||||
expect(c.providers).toEqual(['oidc']);
|
||||
expect(clientConfig(c).loginUrl).toBe('/auth/oidc/login');
|
||||
});
|
||||
|
||||
test('Startprüfung nennt fehlende Variablen', ()=>{
|
||||
expect(()=>readAuthConfig({ HB_AUTH_PROVIDERS: 'oidc' })).toThrow(/HB_OIDC_ISSUER.*HB_OIDC_CLIENT_ID.*HB_OIDC_CLIENT_SECRET.*HB_PUBLIC_URL.*HB_SESSION_SECRET/);
|
||||
});
|
||||
|
||||
test('zu kurzes Session-Secret und unbekannter Provider brechen ab', ()=>{
|
||||
expect(()=>readAuthConfig({ ...base, HB_SESSION_SECRET: 'kurz' }, own)).toThrow(/32 Byte/);
|
||||
expect(()=>readAuthConfig({ HB_AUTH_PROVIDERS: 'ldap' })).toThrow(/unbekannte/);
|
||||
});
|
||||
|
||||
test('http-URL: Cookies nicht Secure', ()=>{
|
||||
expect(readAuthConfig({ ...base, HB_PUBLIC_URL: 'http://localhost:8000' }, own).secureCookies).toBe(false);
|
||||
});
|
||||
|
||||
test('TTL-Formate', ()=>{
|
||||
expect(parseTtl('7d')).toBe(604800);
|
||||
expect(parseTtl('12h')).toBe(43200);
|
||||
expect(parseTtl('3600')).toBe(3600);
|
||||
expect(parseTtl(undefined)).toBe(604800);
|
||||
expect(()=>parseTtl('bald')).toThrow();
|
||||
expect(()=>parseTtl('0')).toThrow();
|
||||
});
|
||||
|
||||
test('Secret taucht nicht in der Client-Konfiguration auf', ()=>{
|
||||
expect(JSON.stringify(clientConfig(readAuthConfig(base, own)))).not.toMatch(/secret|"s"/i);
|
||||
});
|
||||
|
||||
describe('Upstream-secret (fälschbare nc_session)', ()=>{
|
||||
test('Abbruch bei oidc+naturalcrit, Standard-secret, nicht lokal', ()=>{
|
||||
expect(()=>readAuthConfig(base, { upstreamSecret: 'secret', isLocal: false })).toThrow(/Upstream-"secret".*HB_AUTH_PROVIDERS=oidc/);
|
||||
expect(()=>readAuthConfig(base, { upstreamSecret: '', isLocal: false })).toThrow(/Upstream-"secret"/);
|
||||
expect(()=>readAuthConfig(base)).toThrow(/Upstream-"secret"/);
|
||||
});
|
||||
|
||||
test('kein Abbruch: lokal, nur oidc oder eigenes secret', ()=>{
|
||||
expect(()=>readAuthConfig(base, { upstreamSecret: 'secret', isLocal: true })).not.toThrow();
|
||||
expect(()=>readAuthConfig({ ...base, HB_AUTH_PROVIDERS: 'oidc' }, { upstreamSecret: 'secret', isLocal: false })).not.toThrow();
|
||||
expect(()=>readAuthConfig(base, { upstreamSecret: 'eigenes-secret', isLocal: false })).not.toThrow();
|
||||
});
|
||||
|
||||
test('reiner Upstream-Modus bleibt unverändert', ()=>{
|
||||
expect(()=>readAuthConfig({}, { upstreamSecret: 'secret', isLocal: false })).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Issuer-Schema', ()=>{
|
||||
test('http-Issuer mit https-HB_PUBLIC_URL bricht ab', ()=>{
|
||||
expect(()=>readAuthConfig({ ...base, HB_OIDC_ISSUER: 'http://idp.example' }, own)).toThrow(/https:\/\//);
|
||||
});
|
||||
|
||||
test('http-Issuer mit http-HB_PUBLIC_URL ist erlaubt (Dev/Compose)', ()=>{
|
||||
expect(()=>readAuthConfig({ ...base, HB_OIDC_ISSUER: 'http://idp:8080', HB_PUBLIC_URL: 'http://localhost:8000' }, own)).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import express from 'express';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import { readAuthConfig, hasProvider, clientConfig } from './config.js';
|
||||
import { createOidcClient, OidcCallbackError } from './oidc.js';
|
||||
import { issueSession, readSession, clearSession, setTx, takeTx, safeRedirect } from './session.js';
|
||||
import { mapAccount } from './accountMapping.js';
|
||||
|
||||
export { readAuthConfig, clientConfig };
|
||||
|
||||
const esc = (s)=>String(s).replace(/[&<>"']/g, (c)=>({ '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''' }[c]));
|
||||
|
||||
const page = (title, body)=>`<!DOCTYPE html><html lang="de"><head><meta charset="utf-8"><title>${esc(title)}</title>`
|
||||
+ `<meta name="viewport" content="width=device-width,initial-scale=1">`
|
||||
+ `<style>body{font-family:sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem}a.btn{display:block;margin:.75rem 0;padding:.75rem 1rem;background:#0a7f6f;color:#fff;text-decoration:none;border-radius:4px;text-align:center}</style>`
|
||||
+ `</head><body><h1>${esc(title)}</h1>${body}</body></html>`;
|
||||
|
||||
const errorPage = (res, status, message, retryUrl = '/auth/oidc/login')=>{
|
||||
res.status(status).type('html').send(page('Anmeldung fehlgeschlagen',
|
||||
`<p>${esc(message)}</p><p><a href="${esc(retryUrl)}">Erneut anmelden</a></p>`));
|
||||
};
|
||||
|
||||
// Account-Middleware: läuft direkt nach der Upstream-Middleware und setzt req.account neu (ADR 0001 §3)
|
||||
export const accountMiddleware = (config)=>(req, res, next)=>{
|
||||
const session = hasProvider(config, 'oidc') ? readSession(req, config) : null;
|
||||
if(session) {
|
||||
req.account = { username: session.username, uid: session.uid, provider: 'oidc' };
|
||||
} else if(hasProvider(config, 'naturalcrit')) {
|
||||
if(req.account) req.account = { ...req.account, provider: 'naturalcrit' };
|
||||
} else {
|
||||
req.account = undefined;
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {object} config Ergebnis von readAuthConfig()
|
||||
* @param {{ getUsers: ()=>object, brewAuthorExists: (name:string)=>Promise<boolean>, oidcClient?: object }} deps
|
||||
*/
|
||||
export const createAuthRouter = (config, deps = {})=>{
|
||||
const router = express.Router();
|
||||
const oidcEnabled = hasProvider(config, 'oidc');
|
||||
const naturalcritEnabled = hasProvider(config, 'naturalcrit');
|
||||
const parseCookies = cookieParser();
|
||||
router.use((req, res, next)=>req.cookies ? next() : parseCookies(req, res, next));
|
||||
|
||||
// Upstream-Route sperren/umleiten, bevor sie greift
|
||||
router.put('/api/user/rename', (req, res, next)=>{
|
||||
if(req.account?.provider === 'oidc') {
|
||||
return res.status(403).json({
|
||||
error : 'Benutzernamen von OIDC-Konten sind unveränderlich.',
|
||||
HBErrorCode : 'A01'
|
||||
});
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
if(!naturalcritEnabled) {
|
||||
router.post('/local/login', (req, res)=>res.status(404).json({ error: 'Not found' }));
|
||||
}
|
||||
|
||||
router.get('/auth/logout', async (req, res)=>{
|
||||
const wasOidc = req.account?.provider === 'oidc';
|
||||
clearSession(res, config);
|
||||
if(wasOidc && oidcEnabled) {
|
||||
try {
|
||||
const url = await (deps.oidcClient ?? (deps.oidcClient = createOidcClient(config))).buildEndSessionUrl();
|
||||
if(url) return res.redirect(url);
|
||||
} catch (err) {
|
||||
console.warn('OIDC end_session nicht möglich:', err?.message);
|
||||
}
|
||||
}
|
||||
res.redirect('/');
|
||||
});
|
||||
|
||||
if(!oidcEnabled) {
|
||||
// Abgeschaltete Methode: Endpunkte gesperrt
|
||||
router.all('/auth/oidc/*splat', (req, res)=>res.status(404).json({ error: 'OIDC-Login ist deaktiviert.' }));
|
||||
router.get('/auth/login', (req, res)=>res.status(404).json({ error: 'Not found' }));
|
||||
return router;
|
||||
}
|
||||
|
||||
const oidc = deps.oidcClient ?? (deps.oidcClient = createOidcClient(config));
|
||||
|
||||
// Auswahlseite, wenn beide Provider aktiv sind
|
||||
router.get('/auth/login', (req, res)=>{
|
||||
const redirect = safeRedirect(req.query.redirect);
|
||||
if(!naturalcritEnabled) return res.redirect(`/auth/oidc/login?redirect=${encodeURIComponent(redirect)}`);
|
||||
const ncUrl = `https://www.naturalcrit.com/login?redirect=${encodeURIComponent(`${config.publicUrl}${redirect}`)}`;
|
||||
res.type('html').send(page('Anmelden',
|
||||
`<a class="btn" href="/auth/oidc/login?redirect=${encodeURIComponent(redirect)}">${esc(config.oidc.label)}</a>`
|
||||
+ `<a class="btn" href="${esc(ncUrl)}">NaturalCrit-Konto (Benutzername/Passwort, Google)</a>`));
|
||||
});
|
||||
|
||||
router.get('/auth/oidc/login', async (req, res)=>{
|
||||
try {
|
||||
const { url, tx } = await oidc.buildLogin(req.query.redirect);
|
||||
setTx(res, config, tx);
|
||||
res.redirect(url);
|
||||
} catch (err) {
|
||||
console.error('OIDC login:', err);
|
||||
if(err instanceof OidcCallbackError) return errorPage(res, err.status, err.message);
|
||||
errorPage(res, 500, 'Anmeldung nicht möglich.');
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/auth/oidc/callback', async (req, res)=>{
|
||||
const tx = takeTx(req, res, config);
|
||||
if(!tx) return errorPage(res, 400, 'Die Anmeldung ist abgelaufen oder wurde nicht von dieser Seite gestartet.');
|
||||
if(req.query.state !== tx.state) return errorPage(res, 400, 'Ungültiger Anmeldezustand (state).');
|
||||
|
||||
try {
|
||||
const identity = await oidc.handleCallback(tx, `${config.publicUrl}${req.originalUrl}`);
|
||||
const users = deps.getUsers();
|
||||
const user = await mapAccount(identity, {
|
||||
users,
|
||||
brewAuthorExists : deps.brewAuthorExists,
|
||||
usernameClaim : config.oidc.usernameClaim,
|
||||
linkByEmail : config.oidc.linkByEmail
|
||||
});
|
||||
issueSession(res, config, user, identity);
|
||||
res.redirect(safeRedirect(tx.redirect));
|
||||
} catch (err) {
|
||||
console.error('OIDC callback:', err?.cause ?? err);
|
||||
if(err instanceof OidcCallbackError) return errorPage(res, err.status, err.message);
|
||||
errorPage(res, 500, 'Die Anmeldung ist fehlgeschlagen.');
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -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,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,451 @@
|
||||
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 } = {})=>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,
|
||||
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,
|
||||
|
||||
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 }) {
|
||||
if(Buffer.byteLength(content) > cfg.maxFileBytes) 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((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 = `${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');
|
||||
},
|
||||
|
||||
// --- 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 });
|
||||
});
|
||||
},
|
||||
|
||||
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 });
|
||||
},
|
||||
|
||||
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);
|
||||
}
|
||||
},
|
||||
|
||||
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,203 @@
|
||||
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');
|
||||
};
|
||||
|
||||
// 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 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
|
||||
}
|
||||
});
|
||||
return { commit, blob };
|
||||
};
|
||||
|
||||
// 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, push, lsRemote, listFiles };
|
||||
};
|
||||
|
||||
export const randomId = ()=>crypto.randomBytes(8).toString('hex');
|
||||
@@ -0,0 +1,13 @@
|
||||
// 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); };
|
||||
|
||||
export default { configureGitHooks, beforeBrewSave, afterBrewSave };
|
||||
@@ -0,0 +1,18 @@
|
||||
import { readGitConfig } from './config.js';
|
||||
import { createGitService } from './brewSync.js';
|
||||
import { createGitRouter } from './routes.js';
|
||||
import { configureGitHooks } from './hooks.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).');
|
||||
const service = createGitService({ cfg, getStorage, api, splitTextStyleAndMetadata, logger });
|
||||
configureGitHooks(cfg.enabled ? service : undefined);
|
||||
return { service, router: createGitRouter(service, { logger }) };
|
||||
};
|
||||
@@ -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';
|
||||
};
|
||||
+44
-40
@@ -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 } 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,21 +469,20 @@ 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);
|
||||
@@ -485,20 +490,19 @@ const api = {
|
||||
|
||||
if(brew.authors.length === 0) {
|
||||
// Delete brew if there are no authors left
|
||||
await HomebrewModel.deleteOne({ _id: brew._id })
|
||||
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 };
|
||||
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;
|
||||
}
|
||||
brew.markModified('authors'); //Mongo will not properly update arrays without markModified()
|
||||
await brew.save()
|
||||
await getStorage().brews.update(brew)
|
||||
.catch((err)=>{
|
||||
throw { name: 'BrewAuthorDelete Error', message: err, status: 500, HBErrorCode: '08', brewId: brew._id };
|
||||
throw { name: 'BrewAuthorDelete Error', message: err, status: 500, HBErrorCode: '08', brewId: brew.id };
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,294 @@
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
|
||||
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,205 @@
|
||||
import _ from 'lodash';
|
||||
import mongoose from 'mongoose';
|
||||
import zlib from 'zlib';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { model as HomebrewModel } from '../../homebrew.model.js';
|
||||
import { getGitModels } from './git.js';
|
||||
|
||||
// BrewRepository (Mongo, ADR 0002): ruft exakt die Statics/Methoden auf, die der Upstream-Code
|
||||
// bisher direkt aufgerufen hat (HomebrewModel.get, getByUser, increaseView, findOne …).
|
||||
// Ergebnisse sind plain objects mit `id` (statt `_id`) und entpacktem `text` (kein `textBin`).
|
||||
|
||||
const toPlain = (docOrObj)=>{
|
||||
if(!docOrObj) return null;
|
||||
if(typeof docOrObj !== 'object') return docOrObj;
|
||||
const obj = docOrObj.toObject ? docOrObj.toObject() : { ...docOrObj };
|
||||
const { _id, __v, textBin, ...rest } = obj;
|
||||
if(textBin && rest.text === undefined) rest.text = zlib.inflateRawSync(Buffer.isBuffer(textBin) ? textBin : (textBin.buffer ?? textBin)).toString();
|
||||
return _id === undefined ? rest : { id: String(_id), ...rest };
|
||||
};
|
||||
|
||||
const withoutId = (brew)=>_.omit(brew, ['id', '_id']);
|
||||
|
||||
const RENDERER_QUERY = { legacy: { renderer: 'legacy' }, V3: { renderer: 'V3' } };
|
||||
|
||||
const searchQuery = ({ title, author, renderer })=>({
|
||||
$and : [
|
||||
{ published: true },
|
||||
RENDERER_QUERY[renderer] ?? {},
|
||||
title ? { $text: { $search: title, $caseSensitive: false } } : {},
|
||||
author ? { authors: author } : {}
|
||||
]
|
||||
});
|
||||
|
||||
const SORT_FIELDS = ['title', 'createdAt', 'updatedAt', 'lastViewed', 'views', 'pageCount', 'version'];
|
||||
|
||||
const lockProjection = { shareId: 1, editId: 1, title: 1, lock: 1 };
|
||||
|
||||
const mapIds = (docs)=>docs.map((doc)=>{
|
||||
if(typeof doc !== 'object' || doc === null) return doc;
|
||||
const { _id, ...rest } = doc;
|
||||
return _id === undefined ? rest : { id: String(_id), ...rest };
|
||||
});
|
||||
|
||||
const asProjection = (fields)=>fields && !Array.isArray(fields) ? Object.keys(fields).filter((k)=>fields[k]) : fields;
|
||||
|
||||
// Kaskade (ADR 0003 §2): beim Löschen eines Brews fällt seine Git-Verknüpfung weg.
|
||||
// Ohne Verbindung (Unit-Specs mit gemocktem Modell) gibt es nichts zu löschen.
|
||||
const connected = ()=>mongoose.connection.readyState === 1;
|
||||
const removeGitLink = async (brewId)=>{
|
||||
if(connected()) await getGitModels().Link.deleteOne({ brewId });
|
||||
};
|
||||
|
||||
export const createBrewRepository = ()=>{
|
||||
const find = async (query, fields)=>{
|
||||
const doc = await (fields ? HomebrewModel.get(query, asProjection(fields)) : HomebrewModel.get(query))
|
||||
.catch(()=>null);
|
||||
return toPlain(doc);
|
||||
};
|
||||
|
||||
return {
|
||||
async findByEditId(editId, { fields } = {}) { return find({ editId }, fields); },
|
||||
async findByShareId(shareId, { fields } = {}) { return find({ shareId }, fields); },
|
||||
async findByEditOrShareId(id) { return find({ $or: [{ editId: id }, { shareId: id }] }); },
|
||||
|
||||
async listByAuthor(username, { includeUnpublished = false, fields, tagsAny } = {}) {
|
||||
const filter = tagsAny ? { tags: { $in: tagsAny } } : null;
|
||||
const brews = fields
|
||||
? await HomebrewModel.getByUser(username, includeUnpublished, fields, filter)
|
||||
: await HomebrewModel.getByUser(username, includeUnpublished, { text: 0, textBin: 0 }, filter);
|
||||
return brews.map(toPlain);
|
||||
},
|
||||
|
||||
async countByAuthor(username, { storage = 'homebrewery' } = {}) {
|
||||
const query = { authors: username, ...(storage === 'homebrewery' ? { googleId: { $exists: false } } : {}) };
|
||||
return HomebrewModel.countDocuments(query);
|
||||
},
|
||||
|
||||
async existsAuthor(username) {
|
||||
return !!(await HomebrewModel.exists({ authors: username }));
|
||||
},
|
||||
|
||||
async create(brew) {
|
||||
const input = withoutId(brew);
|
||||
const doc = new HomebrewModel(input);
|
||||
doc.editId = input.editId ?? nanoid(12);
|
||||
doc.shareId = input.shareId ?? nanoid(12);
|
||||
// Explizit auf undefined gesetzte Felder (Stub-Brews: text) dürfen keine Schema-Defaults bekommen
|
||||
for (const key of Object.keys(input)) {
|
||||
if(input[key] === undefined) doc[key] = undefined;
|
||||
}
|
||||
const saved = await doc.save();
|
||||
const plain = toPlain(saved);
|
||||
if(input.text !== undefined) plain.text = input.text; // nach save() steckt der Text in textBin
|
||||
return plain;
|
||||
},
|
||||
|
||||
async update(brew) {
|
||||
if(!brew.id) throw new Error('BrewRepository.update braucht eine id');
|
||||
const doc = await HomebrewModel.findOne({ _id: brew.id });
|
||||
if(!doc) return null;
|
||||
const merged = _.assign(doc, withoutId(brew));
|
||||
const saved = await merged.save();
|
||||
const plain = toPlain(saved);
|
||||
if(brew.text !== undefined) plain.text = brew.text;
|
||||
return plain;
|
||||
},
|
||||
|
||||
async deleteById(id) {
|
||||
const res = await HomebrewModel.deleteOne({ _id: id });
|
||||
const deleted = (res?.deletedCount ?? 0) > 0;
|
||||
if(deleted) await removeGitLink(String(id));
|
||||
return deleted;
|
||||
},
|
||||
async deleteByEditId(editId) {
|
||||
const doc = connected() ? await HomebrewModel.findOne({ editId }, { _id: 1 }) : null;
|
||||
const res = await HomebrewModel.deleteOne({ editId });
|
||||
const deleted = (res?.deletedCount ?? 0) > 0;
|
||||
if(deleted && doc) await removeGitLink(String(doc._id));
|
||||
return deleted;
|
||||
},
|
||||
|
||||
async incrementViews(shareId) {
|
||||
return toPlain(await HomebrewModel.increaseView({ shareId }));
|
||||
},
|
||||
|
||||
async renameAuthor(oldName, newName) {
|
||||
const brews = await HomebrewModel.getByUser(oldName, true, ['authors']);
|
||||
await Promise.all(brews.map((brew)=>HomebrewModel.updateOne(
|
||||
{ _id: brew._id },
|
||||
{ $set: { authors: brew.authors.map((a)=>a === oldName ? newName : a) } }
|
||||
)));
|
||||
return brews.length;
|
||||
},
|
||||
|
||||
// { title, author, renderer: 'legacy'|'V3', sort, dir, skip, limit, withTotal }
|
||||
async searchPublished(params) {
|
||||
const { sort = 'title', dir = 'asc', skip = 0, limit = 20, withTotal = false } = params;
|
||||
const query = searchQuery(params);
|
||||
let brews = [];
|
||||
if(limit > 0) {
|
||||
const sortField = SORT_FIELDS.includes(sort) ? sort : 'title';
|
||||
const docs = await HomebrewModel.find(query, { editId: 0, googleId: 0, text: 0, textBin: 0, version: 0 })
|
||||
.sort({ [sortField]: dir === 'asc' ? 1 : -1 })
|
||||
.skip(skip)
|
||||
.limit(limit)
|
||||
.maxTimeMS(5000)
|
||||
.exec();
|
||||
brews = docs.map(toPlain);
|
||||
}
|
||||
const total = withTotal ? await HomebrewModel.countDocuments(query) : undefined;
|
||||
return { brews, total };
|
||||
},
|
||||
|
||||
// --- Admin ---
|
||||
async countAll() { return HomebrewModel.countDocuments({}); },
|
||||
async countPublished() { return HomebrewModel.countDocuments({ published: true }); },
|
||||
async countLocked() { return HomebrewModel.countDocuments({ lock: { $exists: true } }); },
|
||||
async listLocked() {
|
||||
return mapIds(await HomebrewModel.aggregate([{ $match: { lock: { $exists: 1 } } }, { $project: lockProjection }]));
|
||||
},
|
||||
async listReviewRequests() {
|
||||
return mapIds(await HomebrewModel.aggregate([{ $match: { 'lock.reviewRequested': { $exists: 1 } } }, { $project: lockProjection }]));
|
||||
},
|
||||
|
||||
// Ergebnis: { result, brew }; result ∈ 'locked' | 'not-found' | 'already-locked'
|
||||
async setLock(shareId, lock, { overwrite = false } = {}) {
|
||||
const doc = await HomebrewModel.findOne({ shareId });
|
||||
if(!doc) return { result: 'not-found' };
|
||||
if(doc.lock && !overwrite) return { result: 'already-locked', brew: toPlain(doc) };
|
||||
doc.lock = lock;
|
||||
doc.markModified('lock');
|
||||
await doc.save();
|
||||
return { result: 'locked', brew: toPlain(doc) };
|
||||
},
|
||||
// result ∈ 'unlocked' | 'not-found' | 'not-locked'
|
||||
async removeLock(shareId) {
|
||||
const doc = await HomebrewModel.findOne({ shareId });
|
||||
if(!doc) return { result: 'not-found' };
|
||||
if(!doc.lock) return { result: 'not-locked', brew: toPlain(doc) };
|
||||
doc.lock = undefined;
|
||||
doc.markModified('lock');
|
||||
await doc.save();
|
||||
return { result: 'unlocked', brew: toPlain(doc) };
|
||||
},
|
||||
// result ∈ 'requested' | 'not-found' | 'already-requested'
|
||||
async requestReview(shareId) {
|
||||
const doc = await HomebrewModel.findOne({ shareId, lock: { $exists: 1 } });
|
||||
if(!doc) return { result: 'not-found' };
|
||||
if(doc.lock.reviewRequested) return { result: 'already-requested', brew: toPlain(doc) };
|
||||
doc.lock.reviewRequested = new Date();
|
||||
doc.markModified('lock');
|
||||
await doc.save();
|
||||
return { result: 'requested', brew: toPlain(doc) };
|
||||
},
|
||||
// result ∈ 'removed' | 'not-found'
|
||||
async removeReviewRequest(shareId) {
|
||||
const doc = await HomebrewModel.findOne({ shareId, 'lock.reviewRequested': { $exists: 1 } });
|
||||
if(!doc) return { result: 'not-found' };
|
||||
doc.lock.reviewRequested = undefined;
|
||||
doc.markModified('lock');
|
||||
await doc.save();
|
||||
return { result: 'removed', brew: toPlain(doc) };
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,120 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import mongoose from 'mongoose';
|
||||
|
||||
// Fork-Entitäten "GitConnection" und "BrewGitLink" (ADR 0003 §2). Eigene Collections, keine Upstream-Modelle.
|
||||
const ConnectionSchema = new mongoose.Schema({
|
||||
id : { type: String, required: true, unique: true },
|
||||
ownerUserId : { type: String, required: true, index: true },
|
||||
label : { type: String, required: true },
|
||||
repoUrl : { type: String, required: true },
|
||||
authUsername : { type: String, default: 'git' },
|
||||
tokenEnc : { type: String, required: true },
|
||||
defaultBranch : { type: String, default: 'main' },
|
||||
brewDir : { type: String, default: 'brews' },
|
||||
assetsDir : { type: String, default: 'assets' },
|
||||
createdAt : { type: Date, default: Date.now },
|
||||
updatedAt : { type: Date, default: Date.now },
|
||||
lastVerifiedAt : { type: Date }
|
||||
}, { collection: 'gitconnections', versionKey: false });
|
||||
|
||||
const LinkSchema = new mongoose.Schema({
|
||||
brewId : { type: String, required: true, unique: true },
|
||||
connectionId : { type: String, required: true, index: true },
|
||||
branch : { type: String, required: true },
|
||||
path : { type: String, required: true },
|
||||
lastCommitSha : { type: String },
|
||||
lastBlobSha : { type: String },
|
||||
lastSyncedAt : { type: Date },
|
||||
lastError : { type: String }
|
||||
}, { collection: 'brewgitlinks', versionKey: false });
|
||||
LinkSchema.index({ connectionId: 1, branch: 1, path: 1 }, { unique: true });
|
||||
|
||||
export const getGitModels = (connection = mongoose.connection)=>({
|
||||
Connection : connection.models.ForkGitConnection ?? connection.model('ForkGitConnection', ConnectionSchema),
|
||||
Link : connection.models.ForkBrewGitLink ?? connection.model('ForkBrewGitLink', LinkSchema)
|
||||
});
|
||||
|
||||
const nul = (v)=>v ?? null;
|
||||
|
||||
const connToPlain = (doc)=>{
|
||||
if(!doc) return null;
|
||||
const o = doc.toObject ? doc.toObject() : doc;
|
||||
return {
|
||||
id : o.id,
|
||||
ownerUserId : o.ownerUserId,
|
||||
label : o.label,
|
||||
repoUrl : o.repoUrl,
|
||||
authUsername : o.authUsername,
|
||||
tokenEnc : o.tokenEnc,
|
||||
defaultBranch : o.defaultBranch,
|
||||
brewDir : o.brewDir,
|
||||
assetsDir : o.assetsDir,
|
||||
createdAt : o.createdAt,
|
||||
updatedAt : o.updatedAt,
|
||||
lastVerifiedAt : nul(o.lastVerifiedAt)
|
||||
};
|
||||
};
|
||||
|
||||
const linkToPlain = (doc)=>{
|
||||
if(!doc) return null;
|
||||
const o = doc.toObject ? doc.toObject() : doc;
|
||||
return {
|
||||
brewId : o.brewId,
|
||||
connectionId : o.connectionId,
|
||||
branch : o.branch,
|
||||
path : o.path,
|
||||
lastCommitSha : nul(o.lastCommitSha),
|
||||
lastBlobSha : nul(o.lastBlobSha),
|
||||
lastSyncedAt : nul(o.lastSyncedAt),
|
||||
lastError : nul(o.lastError)
|
||||
};
|
||||
};
|
||||
|
||||
const CONN_FIELDS = ['label', 'repoUrl', 'authUsername', 'tokenEnc', 'defaultBranch', 'brewDir', 'assetsDir', 'lastVerifiedAt'];
|
||||
const LINK_FIELDS = ['connectionId', 'branch', 'path', 'lastCommitSha', 'lastBlobSha', 'lastSyncedAt', 'lastError'];
|
||||
const pick = (obj, fields)=>Object.fromEntries(fields.filter((f)=>obj[f] !== undefined).map((f)=>[f, obj[f]]));
|
||||
|
||||
export const createGitConnectionRepository = (connection = mongoose.connection)=>{
|
||||
const { Connection, Link } = getGitModels(connection);
|
||||
return {
|
||||
Model : Connection,
|
||||
async create({ id, ownerUserId, ...rest }) {
|
||||
return connToPlain(await Connection.create({ id: id ?? randomUUID(), ownerUserId: String(ownerUserId), ...pick(rest, CONN_FIELDS) }));
|
||||
},
|
||||
async findById(id) { return connToPlain(await Connection.findOne({ id: String(id) })); },
|
||||
async findByIdForOwner(id, userId) {
|
||||
return connToPlain(await Connection.findOne({ id: String(id), ownerUserId: String(userId) }));
|
||||
},
|
||||
async listByOwner(userId) {
|
||||
return (await Connection.find({ ownerUserId: String(userId) }).sort({ createdAt: 1, id: 1 })).map(connToPlain);
|
||||
},
|
||||
async update(id, patch) {
|
||||
return connToPlain(await Connection.findOneAndUpdate({ id: String(id) }, { $set: { ...pick(patch, CONN_FIELDS), updatedAt: new Date() } }, { returnDocument: 'after' }));
|
||||
},
|
||||
async delete(id) {
|
||||
const res = await Connection.deleteOne({ id: String(id) });
|
||||
if(res.deletedCount > 0) await Link.deleteMany({ connectionId: String(id) });
|
||||
return res.deletedCount > 0;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export const createBrewGitLinkRepository = (connection = mongoose.connection)=>{
|
||||
const { Link } = getGitModels(connection);
|
||||
return {
|
||||
Model : Link,
|
||||
async upsert({ brewId, ...rest }) {
|
||||
return linkToPlain(await Link.findOneAndUpdate({ brewId: String(brewId) }, { $set: pick(rest, LINK_FIELDS) },
|
||||
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true }));
|
||||
},
|
||||
async findByBrewId(brewId) { return linkToPlain(await Link.findOne({ brewId: String(brewId) })); },
|
||||
async findByLocation(connectionId, branch, path) {
|
||||
return linkToPlain(await Link.findOne({ connectionId: String(connectionId), branch, path }));
|
||||
},
|
||||
async listByConnection(connectionId) { return (await Link.find({ connectionId: String(connectionId) })).map(linkToPlain); },
|
||||
async update(brewId, patch) {
|
||||
return linkToPlain(await Link.findOneAndUpdate({ brewId: String(brewId) }, { $set: pick(patch, LINK_FIELDS) }, { returnDocument: 'after' }));
|
||||
},
|
||||
async delete(brewId) { return (await Link.deleteOne({ brewId: String(brewId) })).deletedCount > 0; }
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
import mongoose from 'mongoose';
|
||||
import DB from '../../db.js';
|
||||
import { createUserRepository } from './users.js';
|
||||
import { createBrewRepository } from './brews.js';
|
||||
import { createNotificationRepository } from './notifications.js';
|
||||
import { createGitConnectionRepository, createBrewGitLinkRepository } from './git.js';
|
||||
|
||||
// Mongo-Implementierung der Storage-Schicht (ADR 0002). Ruft die Statics und Methoden der
|
||||
// unveränderten Upstream-Modelle (homebrew.model.js, notifications.model.js) auf.
|
||||
export const createMongoStorage = (config)=>{
|
||||
const brews = createBrewRepository();
|
||||
const notifications = createNotificationRepository();
|
||||
let users;
|
||||
let gitConnections;
|
||||
let brewGitLinks;
|
||||
return {
|
||||
driver : 'mongo',
|
||||
brews,
|
||||
notifications,
|
||||
async connect() {
|
||||
await DB.connect(config);
|
||||
if(!config.get('local_environments').includes(config.get('node_env'))) {
|
||||
await this.users.Model.syncIndexes(); // nur Fork-Modelle, nie Homebrew
|
||||
await this.gitConnections.Model.syncIndexes();
|
||||
await this.brewGitLinks.Model.syncIndexes();
|
||||
}
|
||||
},
|
||||
async disconnect() {
|
||||
await DB.disconnect();
|
||||
},
|
||||
isReady() {
|
||||
return mongoose.connection.readyState === 1;
|
||||
},
|
||||
get users() {
|
||||
users ??= createUserRepository();
|
||||
return users;
|
||||
},
|
||||
get gitConnections() {
|
||||
gitConnections ??= createGitConnectionRepository();
|
||||
return gitConnections;
|
||||
},
|
||||
get brewGitLinks() {
|
||||
brewGitLinks ??= createBrewGitLinkRepository();
|
||||
return brewGitLinks;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import { model as NotificationModel } from '../../notifications.model.js';
|
||||
|
||||
const toPlain = (doc)=>{
|
||||
if(!doc || typeof doc !== 'object') return doc;
|
||||
const { _id, ...rest } = doc.toObject ? doc.toObject() : { ...doc };
|
||||
return _id === undefined ? rest : { id: String(_id), ...rest };
|
||||
};
|
||||
|
||||
// NotificationRepository (Mongo): dünne Hülle um die Statics des Upstream-Modells.
|
||||
export const createNotificationRepository = ()=>({
|
||||
async list() {
|
||||
return (await NotificationModel.getAll()).map(toPlain);
|
||||
},
|
||||
async create(data) {
|
||||
return toPlain(await NotificationModel.addNotification(data));
|
||||
},
|
||||
async deleteByDismissKey(dismissKey) {
|
||||
return toPlain(await NotificationModel.deleteNotification(dismissKey));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import os from 'os';
|
||||
import mongoose from 'mongoose';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { createUserRepository } from './users.js';
|
||||
import { createBrewRepository } from './brews.js';
|
||||
import { createNotificationRepository } from './notifications.js';
|
||||
import { model as HomebrewModel } from '../../homebrew.model.js';
|
||||
import { model as NotificationModel } from '../../notifications.model.js';
|
||||
import { runUserRepositoryContract } from '../contract/users.contract.js';
|
||||
import { createGitConnectionRepository, createBrewGitLinkRepository } from './git.js';
|
||||
import { runGitRepositoryContract } from '../contract/git.contract.js';
|
||||
import { runBrewRepositoryContract, runNotificationRepositoryContract } from '../contract/brews.contract.js';
|
||||
|
||||
const uri = process.env.HB_TEST_MONGODB_URI;
|
||||
const suite = uri ? describe : describe.skip;
|
||||
// Unter Jest scheitert der dynamische import('os') des Mongo-Treibers; ohne Client-Metadaten lehnt der Server den Handshake ab.
|
||||
const driverOptions = { runtimeAdapters: { os } };
|
||||
|
||||
if(!uri) console.warn('HB_TEST_MONGODB_URI fehlt: Mongo-Storage-Contract-Tests werden übersprungen.');
|
||||
|
||||
suite('Mongo UserRepository (Contract)', ()=>{
|
||||
runUserRepositoryContract(async ()=>{
|
||||
const dbName = `test_${randomBytes(4).toString('hex')}`;
|
||||
const connection = await mongoose.createConnection(uri, { dbName, ...driverOptions }).asPromise();
|
||||
const users = createUserRepository(connection);
|
||||
await users.Model.init();
|
||||
return { users, cleanup: async ()=>{ await connection.dropDatabase(); await connection.close(); } };
|
||||
});
|
||||
});
|
||||
|
||||
// Brews und Notifications laufen über die globalen Upstream-Modelle (mongoose.connect).
|
||||
const connectGlobal = async ()=>{
|
||||
const dbName = `test_${randomBytes(4).toString('hex')}`;
|
||||
await mongoose.connect(uri, { dbName, ...driverOptions });
|
||||
// Nicht Model.init()/syncIndexes(): Upstream definiert `{ lock: 1, sparse: true }`, das neuere Mongo-Server ablehnen.
|
||||
await HomebrewModel.collection.createIndex({ shareId: 1 }, { unique: true });
|
||||
await HomebrewModel.collection.createIndex({ editId: 1 }, { unique: true });
|
||||
await HomebrewModel.collection.createIndex({ published: 1, title: 'text' });
|
||||
await NotificationModel.init();
|
||||
return async ()=>{ await mongoose.connection.dropDatabase(); await mongoose.disconnect(); };
|
||||
};
|
||||
|
||||
suite('Mongo BrewRepository (Contract)', ()=>{
|
||||
runBrewRepositoryContract(async ()=>({ brews: createBrewRepository(), cleanup: await connectGlobal() }));
|
||||
});
|
||||
|
||||
suite('Mongo NotificationRepository (Contract)', ()=>{
|
||||
runNotificationRepositoryContract(async ()=>({ notifications: createNotificationRepository(), cleanup: await connectGlobal() }));
|
||||
});
|
||||
|
||||
suite('Mongo Git-Repositories (Contract)', ()=>{
|
||||
runGitRepositoryContract(async ()=>{
|
||||
const cleanup = await connectGlobal();
|
||||
const users = createUserRepository();
|
||||
const gitConnections = createGitConnectionRepository();
|
||||
const brewGitLinks = createBrewGitLinkRepository();
|
||||
await users.Model.init();
|
||||
await gitConnections.Model.init();
|
||||
await brewGitLinks.Model.init();
|
||||
return { users, brews: createBrewRepository(), gitConnections, brewGitLinks, cleanup };
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import mongoose from 'mongoose';
|
||||
import { getGitModels } from './git.js';
|
||||
|
||||
// Fork-Entität "User" (ADR 0001 §4). Collection `users`, eigenes Schema, berührt keine Upstream-Modelle.
|
||||
const UserSchema = new mongoose.Schema({
|
||||
id : { type: String, required: true, unique: true },
|
||||
username : { type: String, required: true, unique: true },
|
||||
oidcIssuer : { type: String },
|
||||
oidcSub : { type: String },
|
||||
email : { type: String, index: true },
|
||||
emailVerified : { type: Boolean, default: false },
|
||||
displayName : { type: String },
|
||||
createdAt : { type: Date, default: Date.now },
|
||||
lastLoginAt : { type: Date }
|
||||
}, { collection: 'users', versionKey: false });
|
||||
|
||||
// (oidcIssuer, oidcSub) eindeutig, aber nur, wenn gesetzt (vorab angelegte Benutzer haben keine Bindung)
|
||||
UserSchema.index(
|
||||
{ oidcIssuer: 1, oidcSub: 1 },
|
||||
{ unique: true, partialFilterExpression: { oidcSub: { $type: 'string' } } }
|
||||
);
|
||||
|
||||
const toPlain = (doc)=>{
|
||||
if(!doc) return null;
|
||||
const o = doc.toObject ? doc.toObject() : doc;
|
||||
return {
|
||||
id : o.id,
|
||||
username : o.username,
|
||||
oidcIssuer : o.oidcIssuer ?? null,
|
||||
oidcSub : o.oidcSub ?? null,
|
||||
email : o.email ?? null,
|
||||
emailVerified : !!o.emailVerified,
|
||||
displayName : o.displayName ?? null,
|
||||
createdAt : o.createdAt,
|
||||
lastLoginAt : o.lastLoginAt ?? null
|
||||
};
|
||||
};
|
||||
|
||||
const clean = (obj)=>Object.fromEntries(Object.entries(obj).filter(([, v])=>v !== undefined));
|
||||
|
||||
export const createUserRepository = (connection = mongoose.connection)=>{
|
||||
const User = connection.models.ForkUser ?? connection.model('ForkUser', UserSchema);
|
||||
|
||||
return {
|
||||
Model : User,
|
||||
|
||||
async create({ username, oidcIssuer, oidcSub, email, emailVerified, displayName }) {
|
||||
const doc = await User.create(clean({
|
||||
id : randomUUID(),
|
||||
username,
|
||||
oidcIssuer,
|
||||
oidcSub,
|
||||
email : email ? String(email).toLowerCase() : undefined,
|
||||
emailVerified : !!emailVerified,
|
||||
displayName
|
||||
}));
|
||||
return toPlain(doc);
|
||||
},
|
||||
|
||||
async findById(id) {
|
||||
return toPlain(await User.findOne({ id }));
|
||||
},
|
||||
|
||||
async findByUsername(username) {
|
||||
return toPlain(await User.findOne({ username }));
|
||||
},
|
||||
|
||||
async usernameExists(username) {
|
||||
return !!(await User.exists({ username }));
|
||||
},
|
||||
|
||||
async findByOidc(issuer, sub) {
|
||||
return toPlain(await User.findOne({ oidcIssuer: issuer, oidcSub: sub }));
|
||||
},
|
||||
|
||||
// Vorab angelegte Benutzer (ohne OIDC-Bindung) mit dieser E-Mail
|
||||
async findUnlinkedByEmail(email) {
|
||||
const docs = await User.find({
|
||||
email : String(email).toLowerCase(),
|
||||
oidcSub : { $not: { $type: 'string' } }
|
||||
});
|
||||
return docs.map(toPlain);
|
||||
},
|
||||
|
||||
async update(id, patch) {
|
||||
const set = clean({ ...patch });
|
||||
delete set.id;
|
||||
delete set.username; // unveränderlich
|
||||
if(set.email) set.email = String(set.email).toLowerCase();
|
||||
return toPlain(await User.findOneAndUpdate({ id }, { $set: set }, { returnDocument: 'after' }));
|
||||
},
|
||||
|
||||
async delete(id) {
|
||||
const res = await User.deleteOne({ id });
|
||||
if(res.deletedCount > 0) {
|
||||
// Kaskade (ADR 0002 §5): Verbindungen des Benutzers samt Links entfernen, Brews bleiben
|
||||
const { Connection, Link } = getGitModels(connection);
|
||||
const ids = (await Connection.find({ ownerUserId: String(id) }, { id: 1 })).map((c)=>c.id);
|
||||
await Link.deleteMany({ connectionId: { $in: ids } });
|
||||
await Connection.deleteMany({ ownerUserId: String(id) });
|
||||
}
|
||||
return res.deletedCount > 0;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,167 @@
|
||||
import { sql } from 'kysely';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { brewToRow, rowToBrew, BREW_LIST_COLUMNS, BREW_SELECT_COLUMNS, columnFor } from './rows.js';
|
||||
|
||||
// BrewRepository (PostgreSQL, ADR 0002). Gleicher Vertrag wie mongo/brews.js.
|
||||
const SORT_FIELDS = ['title', 'createdAt', 'updatedAt', 'lastViewed', 'views', 'pageCount', 'version'];
|
||||
|
||||
export const createBrewRepository = (db)=>{
|
||||
const selectOne = async (where, { fields } = {})=>{
|
||||
const row = await db.selectFrom('brews').select(BREW_SELECT_COLUMNS.concat('id')).where(...where).executeTakeFirst();
|
||||
return rowToBrew(row, { fields });
|
||||
};
|
||||
|
||||
const searchWhere = ({ title, author, renderer })=>(qb)=>{
|
||||
qb = qb.where('published', '=', true);
|
||||
if(renderer) qb = qb.where('renderer', '=', renderer);
|
||||
if(title) qb = qb.where(sql`title_tsv @@ websearch_to_tsquery('simple', ${title})`);
|
||||
if(author) qb = qb.where(sql`authors @> ARRAY[${author}]::text[]`);
|
||||
return qb;
|
||||
};
|
||||
|
||||
// Lock-Operationen: Zeile sperren, prüfen, schreiben (eine Transaktion)
|
||||
const withLockedRow = (shareId, extraWhere, fn)=>db.transaction().execute(async (trx)=>{
|
||||
let qb = trx.selectFrom('brews').select(['id', 'share_id', 'title', 'lock']).where('share_id', '=', shareId).forUpdate();
|
||||
if(extraWhere) qb = extraWhere(qb);
|
||||
const row = await qb.executeTakeFirst();
|
||||
if(!row) return { result: 'not-found' };
|
||||
return fn(trx, row);
|
||||
});
|
||||
const lockBrewInfo = (row, lock)=>({ id: row.id, shareId: row.share_id, title: row.title, ...(lock ? { lock } : {}) });
|
||||
|
||||
return {
|
||||
async findByEditId(editId, opts) { return selectOne(['edit_id', '=', editId], opts); },
|
||||
async findByShareId(shareId, opts) { return selectOne(['share_id', '=', shareId], opts); },
|
||||
async findByEditOrShareId(id) {
|
||||
const row = await db.selectFrom('brews').select(BREW_SELECT_COLUMNS.concat('id'))
|
||||
.where((eb)=>eb.or([eb('edit_id', '=', id), eb('share_id', '=', id)])).executeTakeFirst();
|
||||
return rowToBrew(row);
|
||||
},
|
||||
|
||||
async listByAuthor(username, { includeUnpublished = false, fields, tagsAny } = {}) {
|
||||
let qb = db.selectFrom('brews').select(BREW_LIST_COLUMNS.concat('id'))
|
||||
.where(sql`authors @> ARRAY[${username}]::text[]`);
|
||||
if(!includeUnpublished) qb = qb.where('published', '=', true);
|
||||
if(tagsAny) qb = qb.where(sql`tags && ${tagsAny}::text[]`);
|
||||
return (await qb.execute()).map((row)=>rowToBrew(row, { fields }));
|
||||
},
|
||||
|
||||
async countByAuthor(username, { storage = 'homebrewery' } = {}) {
|
||||
let qb = db.selectFrom('brews').select(sql`count(*)::int`.as('n')).where(sql`authors @> ARRAY[${username}]::text[]`);
|
||||
if(storage === 'homebrewery') qb = qb.where('google_id', 'is', null);
|
||||
return (await qb.executeTakeFirst()).n;
|
||||
},
|
||||
|
||||
async existsAuthor(username) {
|
||||
const row = await db.selectFrom('brews').select('id').where(sql`authors @> ARRAY[${username}]::text[]`).limit(1).executeTakeFirst();
|
||||
return !!row;
|
||||
},
|
||||
|
||||
async create(brew) {
|
||||
const row = brewToRow(brew);
|
||||
row.share_id ??= nanoid(12);
|
||||
row.edit_id ??= nanoid(12);
|
||||
const inserted = await db.insertInto('brews').values(row).returningAll().executeTakeFirstOrThrow();
|
||||
return rowToBrew(inserted);
|
||||
},
|
||||
|
||||
async update(brew) {
|
||||
if(!brew.id) throw new Error('BrewRepository.update braucht eine id');
|
||||
const row = brewToRow(brew, 'update');
|
||||
const updated = Object.keys(row).length
|
||||
? await db.updateTable('brews').set(row).where('id', '=', brew.id).returningAll().executeTakeFirst()
|
||||
: await db.selectFrom('brews').selectAll().where('id', '=', brew.id).executeTakeFirst();
|
||||
return rowToBrew(updated);
|
||||
},
|
||||
|
||||
async deleteById(id) {
|
||||
const res = await db.deleteFrom('brews').where('id', '=', id).executeTakeFirst();
|
||||
return res.numDeletedRows > 0n;
|
||||
},
|
||||
async deleteByEditId(editId) {
|
||||
const res = await db.deleteFrom('brews').where('edit_id', '=', editId).executeTakeFirst();
|
||||
return res.numDeletedRows > 0n;
|
||||
},
|
||||
|
||||
async incrementViews(shareId) {
|
||||
const row = await db.updateTable('brews')
|
||||
.set({ views: sql`views + 1`, last_viewed: sql`now()` })
|
||||
.where('share_id', '=', shareId).returningAll().executeTakeFirst();
|
||||
return rowToBrew(row);
|
||||
},
|
||||
|
||||
async renameAuthor(oldName, newName) {
|
||||
const res = await db.updateTable('brews')
|
||||
.set({ authors: sql`array_replace(authors, ${oldName}, ${newName})` })
|
||||
.where(sql`authors @> ARRAY[${oldName}]::text[]`).executeTakeFirst();
|
||||
return Number(res.numUpdatedRows);
|
||||
},
|
||||
|
||||
async searchPublished(params) {
|
||||
const { sort = 'title', dir = 'asc', skip = 0, limit = 20, withTotal = false } = params;
|
||||
const where = searchWhere(params);
|
||||
let brews = [];
|
||||
if(limit > 0) {
|
||||
const sortField = SORT_FIELDS.includes(sort) ? sort : 'title';
|
||||
const columns = BREW_LIST_COLUMNS.filter((c)=>!['edit_id', 'google_id', 'version'].includes(c)).concat('id');
|
||||
const rows = await where(db.selectFrom('brews').select(columns))
|
||||
.orderBy(columnFor(sortField), dir === 'asc' ? 'asc' : 'desc').orderBy('id')
|
||||
.offset(skip).limit(limit).execute();
|
||||
brews = rows.map((row)=>rowToBrew(row));
|
||||
}
|
||||
const total = withTotal
|
||||
? (await where(db.selectFrom('brews').select(sql`count(*)::int`.as('n'))).executeTakeFirst()).n
|
||||
: undefined;
|
||||
return { brews, total };
|
||||
},
|
||||
|
||||
// --- Admin ---
|
||||
async countAll() { return (await db.selectFrom('brews').select(sql`count(*)::int`.as('n')).executeTakeFirst()).n; },
|
||||
async countPublished() {
|
||||
return (await db.selectFrom('brews').select(sql`count(*)::int`.as('n')).where('published', '=', true).executeTakeFirst()).n;
|
||||
},
|
||||
async countLocked() {
|
||||
return (await db.selectFrom('brews').select(sql`count(*)::int`.as('n')).where('lock', 'is not', null).executeTakeFirst()).n;
|
||||
},
|
||||
async listLocked() {
|
||||
const rows = await db.selectFrom('brews').select(['id', 'share_id', 'edit_id', 'title', 'lock']).where('lock', 'is not', null).execute();
|
||||
return rows.map((r)=>({ id: r.id, shareId: r.share_id, editId: r.edit_id, title: r.title, lock: r.lock }));
|
||||
},
|
||||
async listReviewRequests() {
|
||||
const rows = await db.selectFrom('brews').select(['id', 'share_id', 'edit_id', 'title', 'lock'])
|
||||
.where(sql`lock ? 'reviewRequested'`).execute();
|
||||
return rows.map((r)=>({ id: r.id, shareId: r.share_id, editId: r.edit_id, title: r.title, lock: r.lock }));
|
||||
},
|
||||
|
||||
async setLock(shareId, lock, { overwrite = false } = {}) {
|
||||
return withLockedRow(shareId, null, async (trx, row)=>{
|
||||
if(row.lock && !overwrite) return { result: 'already-locked', brew: lockBrewInfo(row, row.lock) };
|
||||
await trx.updateTable('brews').set({ lock: JSON.stringify(lock) }).where('id', '=', row.id).execute();
|
||||
return { result: 'locked', brew: lockBrewInfo(row, lock) };
|
||||
});
|
||||
},
|
||||
async removeLock(shareId) {
|
||||
return withLockedRow(shareId, null, async (trx, row)=>{
|
||||
if(!row.lock) return { result: 'not-locked', brew: lockBrewInfo(row) };
|
||||
await trx.updateTable('brews').set({ lock: null }).where('id', '=', row.id).execute();
|
||||
return { result: 'unlocked', brew: lockBrewInfo(row) };
|
||||
});
|
||||
},
|
||||
async requestReview(shareId) {
|
||||
return withLockedRow(shareId, (qb)=>qb.where('lock', 'is not', null), async (trx, row)=>{
|
||||
if(row.lock.reviewRequested) return { result: 'already-requested', brew: lockBrewInfo(row, row.lock) };
|
||||
const lock = { ...row.lock, reviewRequested: new Date() };
|
||||
await trx.updateTable('brews').set({ lock: JSON.stringify(lock) }).where('id', '=', row.id).execute();
|
||||
return { result: 'requested', brew: lockBrewInfo(row, lock) };
|
||||
});
|
||||
},
|
||||
async removeReviewRequest(shareId) {
|
||||
return withLockedRow(shareId, (qb)=>qb.where(sql`lock ? 'reviewRequested'`), async (trx, row)=>{
|
||||
const lock = { ...row.lock };
|
||||
delete lock.reviewRequested;
|
||||
await trx.updateTable('brews').set({ lock: JSON.stringify(lock) }).where('id', '=', row.id).execute();
|
||||
return { result: 'removed', brew: lockBrewInfo(row, lock) };
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
import pg from 'pg';
|
||||
import { Kysely, PostgresDialect } from 'kysely';
|
||||
import { Migrator } from 'kysely/migration';
|
||||
import migrations from './migrations/index.js';
|
||||
|
||||
export const MIN_SERVER_VERSION_NUM = 180000;
|
||||
|
||||
// Erzeugt Pool + Kysely-Instanz. `searchPath` (optional) setzt das Schema, z. B. für Tests.
|
||||
export const createDb = ({ url, poolMax = 10, searchPath })=>{
|
||||
const pool = new pg.Pool({
|
||||
connectionString : url,
|
||||
max : poolMax,
|
||||
...(searchPath ? { options: `-c search_path=${searchPath}` } : {})
|
||||
});
|
||||
const db = new Kysely({ dialect: new PostgresDialect({ pool }) });
|
||||
return { pool, db };
|
||||
};
|
||||
|
||||
export const checkServerVersion = async (pool)=>{
|
||||
const { rows } = await pool.query('SHOW server_version_num');
|
||||
const num = parseInt(rows[0].server_version_num, 10);
|
||||
if(num < MIN_SERVER_VERSION_NUM)
|
||||
throw new Error(`PostgreSQL ≥ 18 erforderlich, Server meldet server_version_num=${num}`);
|
||||
return num;
|
||||
};
|
||||
|
||||
// Kysely sperrt über die eigene Lock-Tabelle, parallele Starts migrieren nicht gleichzeitig.
|
||||
export const migrateToLatest = async (db)=>{
|
||||
const migrator = new Migrator({ db, provider: { getMigrations: async ()=>migrations } });
|
||||
const { error, results } = await migrator.migrateToLatest();
|
||||
for (const r of results ?? []) console.log(`Migration ${r.migrationName}: ${r.status}`);
|
||||
if(error) throw error;
|
||||
};
|
||||
@@ -0,0 +1,123 @@
|
||||
// Repositories für Git-Verbindungen und Brew-Verknüpfungen (PostgreSQL, ADR 0003 §2).
|
||||
// Gleicher Vertrag wie mongo/git.js. Ergebnisse: plain objects in camelCase.
|
||||
const UUID = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
const CONN = {
|
||||
label : 'label',
|
||||
repoUrl : 'repo_url',
|
||||
authUsername : 'auth_username',
|
||||
tokenEnc : 'token_enc',
|
||||
defaultBranch : 'default_branch',
|
||||
brewDir : 'brew_dir',
|
||||
assetsDir : 'assets_dir',
|
||||
lastVerifiedAt : 'last_verified_at'
|
||||
};
|
||||
const LINK = {
|
||||
connectionId : 'connection_id',
|
||||
branch : 'branch',
|
||||
path : 'path',
|
||||
lastCommitSha : 'last_commit_sha',
|
||||
lastBlobSha : 'last_blob_sha',
|
||||
lastSyncedAt : 'last_synced_at',
|
||||
lastError : 'last_error'
|
||||
};
|
||||
|
||||
const toRow = (map, patch)=>{
|
||||
const row = {};
|
||||
for (const [field, column] of Object.entries(map)) {
|
||||
if(patch[field] !== undefined) row[column] = patch[field];
|
||||
}
|
||||
return row;
|
||||
};
|
||||
|
||||
const rowToConnection = (r)=>!r ? null : ({
|
||||
id : r.id,
|
||||
ownerUserId : r.owner_user_id,
|
||||
label : r.label,
|
||||
repoUrl : r.repo_url,
|
||||
authUsername : r.auth_username,
|
||||
tokenEnc : r.token_enc,
|
||||
defaultBranch : r.default_branch,
|
||||
brewDir : r.brew_dir,
|
||||
assetsDir : r.assets_dir,
|
||||
createdAt : r.created_at,
|
||||
updatedAt : r.updated_at,
|
||||
lastVerifiedAt : r.last_verified_at ?? null
|
||||
});
|
||||
|
||||
const rowToLink = (r)=>!r ? null : ({
|
||||
brewId : r.brew_id,
|
||||
connectionId : r.connection_id,
|
||||
branch : r.branch,
|
||||
path : r.path,
|
||||
lastCommitSha : r.last_commit_sha ?? null,
|
||||
lastBlobSha : r.last_blob_sha ?? null,
|
||||
lastSyncedAt : r.last_synced_at ?? null,
|
||||
lastError : r.last_error ?? null
|
||||
});
|
||||
|
||||
export const createGitConnectionRepository = (db)=>({
|
||||
async create({ id, ownerUserId, ...rest }) {
|
||||
const values = { owner_user_id: ownerUserId, ...toRow(CONN, rest) };
|
||||
if(id) values.id = id;
|
||||
return rowToConnection(await db.insertInto('git_connections').values(values).returningAll().executeTakeFirstOrThrow());
|
||||
},
|
||||
async findById(id) {
|
||||
if(!UUID.test(String(id))) return null;
|
||||
return rowToConnection(await db.selectFrom('git_connections').selectAll().where('id', '=', id).executeTakeFirst());
|
||||
},
|
||||
async findByIdForOwner(id, userId) {
|
||||
if(!UUID.test(String(id)) || !UUID.test(String(userId))) return null;
|
||||
return rowToConnection(await db.selectFrom('git_connections').selectAll().where('id', '=', id).where('owner_user_id', '=', userId).executeTakeFirst());
|
||||
},
|
||||
async listByOwner(userId) {
|
||||
if(!UUID.test(String(userId))) return [];
|
||||
const rows = await db.selectFrom('git_connections').selectAll().where('owner_user_id', '=', userId).orderBy('created_at').orderBy('id').execute();
|
||||
return rows.map(rowToConnection);
|
||||
},
|
||||
async update(id, patch) {
|
||||
if(!UUID.test(String(id))) return null;
|
||||
const row = toRow(CONN, patch);
|
||||
if(!Object.keys(row).length) return this.findById(id);
|
||||
row.updated_at = new Date();
|
||||
return rowToConnection(await db.updateTable('git_connections').set(row).where('id', '=', id).returningAll().executeTakeFirst());
|
||||
},
|
||||
async delete(id) {
|
||||
if(!UUID.test(String(id))) return false;
|
||||
const res = await db.deleteFrom('git_connections').where('id', '=', id).executeTakeFirst();
|
||||
return res.numDeletedRows > 0n;
|
||||
}
|
||||
});
|
||||
|
||||
export const createBrewGitLinkRepository = (db)=>({
|
||||
// Legt den Link an oder ersetzt ihn (höchstens einer pro Brew)
|
||||
async upsert({ brewId, ...rest }) {
|
||||
const set = toRow(LINK, rest);
|
||||
return rowToLink(await db.insertInto('brew_git_links').values({ brew_id: brewId, ...set })
|
||||
.onConflict((oc)=>oc.column('brew_id').doUpdateSet(set)).returningAll().executeTakeFirstOrThrow());
|
||||
},
|
||||
async findByBrewId(brewId) {
|
||||
if(!UUID.test(String(brewId))) return null;
|
||||
return rowToLink(await db.selectFrom('brew_git_links').selectAll().where('brew_id', '=', brewId).executeTakeFirst());
|
||||
},
|
||||
async findByLocation(connectionId, branch, path) {
|
||||
if(!UUID.test(String(connectionId))) return null;
|
||||
return rowToLink(await db.selectFrom('brew_git_links').selectAll()
|
||||
.where('connection_id', '=', connectionId).where('branch', '=', branch).where('path', '=', path).executeTakeFirst());
|
||||
},
|
||||
async listByConnection(connectionId) {
|
||||
if(!UUID.test(String(connectionId))) return [];
|
||||
return (await db.selectFrom('brew_git_links').selectAll().where('connection_id', '=', connectionId).execute()).map(rowToLink);
|
||||
},
|
||||
async update(brewId, patch) {
|
||||
if(!UUID.test(String(brewId))) return null;
|
||||
const row = toRow(LINK, patch);
|
||||
if(!Object.keys(row).length) return this.findByBrewId(brewId);
|
||||
return rowToLink(await db.updateTable('brew_git_links').set(row).where('brew_id', '=', brewId).returningAll().executeTakeFirst());
|
||||
},
|
||||
async delete(brewId) {
|
||||
if(!UUID.test(String(brewId))) return false;
|
||||
const res = await db.deleteFrom('brew_git_links').where('brew_id', '=', brewId).executeTakeFirst();
|
||||
return res.numDeletedRows > 0n;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { createDb, checkServerVersion, migrateToLatest } from './db.js';
|
||||
import { createBrewRepository } from './brews.js';
|
||||
import { createNotificationRepository } from './notifications.js';
|
||||
import { createUserRepository } from './users.js';
|
||||
import { createGitConnectionRepository, createBrewGitLinkRepository } from './gitRepos.js';
|
||||
|
||||
// PostgreSQL-Implementierung der Storage-Schicht (ADR 0002). Kysely + pg, versionierte Migrationen
|
||||
// laufen beim Start (migrateToLatest). Konfiguration: HB_POSTGRES_URL, HB_POSTGRES_POOL_MAX.
|
||||
export const createPostgresStorage = (config, overrides = {})=>{
|
||||
let handle;
|
||||
let ready = false;
|
||||
const repos = {};
|
||||
|
||||
const build = (db)=>{
|
||||
repos.brews = createBrewRepository(db);
|
||||
repos.notifications = createNotificationRepository(db);
|
||||
repos.users = createUserRepository(db);
|
||||
repos.gitConnections = createGitConnectionRepository(db);
|
||||
repos.brewGitLinks = createBrewGitLinkRepository(db);
|
||||
};
|
||||
|
||||
return {
|
||||
driver : 'postgres',
|
||||
get brews() { return repos.brews; },
|
||||
get notifications() { return repos.notifications; },
|
||||
get users() { return repos.users; },
|
||||
get gitConnections() { return repos.gitConnections; },
|
||||
get brewGitLinks() { return repos.brewGitLinks; },
|
||||
get pool() { return handle?.pool; }, // nur für Tests
|
||||
async connect() {
|
||||
const url = overrides.url ?? config?.get('hb_postgres_url');
|
||||
if(!url) throw new Error('HB_DB_DRIVER=postgres, aber HB_POSTGRES_URL ist nicht gesetzt (z. B. postgres://hb:…@postgres:5432/homebrewery)');
|
||||
const poolMax = parseInt(overrides.poolMax ?? config?.get('hb_postgres_pool_max'), 10) || 10;
|
||||
handle = createDb({ url, poolMax, searchPath: overrides.searchPath });
|
||||
// Fehler idle Clients nur loggen: pg verwirft den Client, der Pool stellt neue Verbindungen selbst her.
|
||||
handle.pool.on('error', (err)=>{ console.error('PostgreSQL-Pool-Fehler:', err.message); });
|
||||
await checkServerVersion(handle.pool);
|
||||
await migrateToLatest(handle.db);
|
||||
build(handle.db);
|
||||
ready = true;
|
||||
},
|
||||
async disconnect() {
|
||||
ready = false;
|
||||
await handle?.db.destroy();
|
||||
handle = undefined;
|
||||
},
|
||||
isReady() {
|
||||
return ready;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
import { sql } from 'kysely';
|
||||
|
||||
// ADR 0002 §3. PostgreSQL ≥ 18 (uuidv7() ist eingebaut).
|
||||
export const up = async (db)=>{
|
||||
await 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 '',
|
||||
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
|
||||
)`.execute(db);
|
||||
await sql`CREATE INDEX brews_authors_gin ON brews USING gin (authors)`.execute(db);
|
||||
await sql`CREATE INDEX brews_tags_gin ON brews USING gin (tags)`.execute(db);
|
||||
await sql`CREATE INDEX brews_title_tsv_gin ON brews USING gin (title_tsv)`.execute(db);
|
||||
await sql`CREATE INDEX brews_published_updated ON brews (published, updated_at DESC)`.execute(db);
|
||||
await sql`CREATE INDEX brews_google_id ON brews (google_id) WHERE google_id IS NOT NULL`.execute(db);
|
||||
await sql`CREATE INDEX brews_lock ON brews ((lock IS NOT NULL)) WHERE lock IS NOT NULL`.execute(db);
|
||||
|
||||
await sql`
|
||||
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()
|
||||
)`.execute(db);
|
||||
|
||||
await sql`
|
||||
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)
|
||||
)`.execute(db);
|
||||
await sql`CREATE INDEX users_email ON users (email)`.execute(db);
|
||||
};
|
||||
|
||||
export const down = async (db)=>{
|
||||
await sql`DROP TABLE IF EXISTS users`.execute(db);
|
||||
await sql`DROP TABLE IF EXISTS notifications`.execute(db);
|
||||
await sql`DROP TABLE IF EXISTS brews`.execute(db);
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import { sql } from 'kysely';
|
||||
|
||||
// ADR 0003 §2: Git-Verbindungen (pro Benutzer) und Brew-Verknüpfungen.
|
||||
export const up = async (db)=>{
|
||||
await sql`
|
||||
CREATE TABLE git_connections (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
owner_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
label text NOT NULL,
|
||||
repo_url text NOT NULL,
|
||||
auth_username text NOT NULL DEFAULT 'git',
|
||||
token_enc text NOT NULL,
|
||||
default_branch text NOT NULL DEFAULT 'main',
|
||||
brew_dir text NOT NULL DEFAULT 'brews',
|
||||
assets_dir text NOT NULL DEFAULT 'assets',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_verified_at timestamptz
|
||||
)`.execute(db);
|
||||
await sql`CREATE INDEX git_connections_owner ON git_connections (owner_user_id)`.execute(db);
|
||||
|
||||
await sql`
|
||||
CREATE TABLE brew_git_links (
|
||||
brew_id uuid PRIMARY KEY REFERENCES brews(id) ON DELETE CASCADE,
|
||||
connection_id uuid NOT NULL REFERENCES git_connections(id) ON DELETE CASCADE,
|
||||
branch text NOT NULL,
|
||||
path text NOT NULL,
|
||||
last_commit_sha text,
|
||||
last_blob_sha text,
|
||||
last_synced_at timestamptz,
|
||||
last_error text,
|
||||
UNIQUE (connection_id, branch, path)
|
||||
)`.execute(db);
|
||||
};
|
||||
|
||||
export const down = async (db)=>{
|
||||
await sql`DROP TABLE IF EXISTS brew_git_links`.execute(db);
|
||||
await sql`DROP TABLE IF EXISTS git_connections`.execute(db);
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
// Statische Migrationsliste (kein Dateisystem-Scan, damit es mit Vite/Jest/Node gleich läuft).
|
||||
// Neue Migration: Datei `NNNN_beschreibung.js` mit up(db)/down(db) anlegen und hier eintragen.
|
||||
import * as m0001 from './0001_initial.js';
|
||||
import * as m0002 from './0002_git_backend.js';
|
||||
|
||||
export default {
|
||||
'0001_initial' : m0001,
|
||||
'0002_git_backend' : m0002
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
import { notificationToRow, rowToNotification } from './rows.js';
|
||||
|
||||
// NotificationRepository (PostgreSQL). Fehler haben wie im Upstream-Modell die Form { message }.
|
||||
export const createNotificationRepository = (db)=>({
|
||||
async list() {
|
||||
return (await db.selectFrom('notifications').selectAll().orderBy('created_at').orderBy('id').execute()).map(rowToNotification);
|
||||
},
|
||||
async create(data) {
|
||||
if(!data.dismissKey) throw { message: 'Dismiss key is required!' };
|
||||
try {
|
||||
const row = await db.insertInto('notifications').values(notificationToRow(data)).returningAll().executeTakeFirstOrThrow();
|
||||
return rowToNotification(row);
|
||||
} catch (err) {
|
||||
throw { message: err.message || 'Error saving notification' };
|
||||
}
|
||||
},
|
||||
async deleteByDismissKey(dismissKey) {
|
||||
if(!dismissKey) throw { message: 'Dismiss key is required!' };
|
||||
let row;
|
||||
try {
|
||||
row = await db.deleteFrom('notifications').where('dismiss_key', '=', dismissKey).returningAll().executeTakeFirst();
|
||||
} catch (err) {
|
||||
throw { message: err.message || 'Error deleting notification' };
|
||||
}
|
||||
if(!row) throw { message: 'Notification not found' };
|
||||
return rowToNotification(row);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import _ from 'lodash';
|
||||
|
||||
// Abbildung snake_case (PG) <-> camelCase (Repository), eine Funktion je Tabelle (ADR 0002 §3).
|
||||
const BREW_COLUMNS = {
|
||||
shareId : 'share_id',
|
||||
editId : 'edit_id',
|
||||
googleId : 'google_id',
|
||||
title : 'title',
|
||||
text : 'text',
|
||||
pageCount : 'page_count',
|
||||
description : 'description',
|
||||
tags : 'tags',
|
||||
systems : 'systems',
|
||||
lang : 'lang',
|
||||
renderer : 'renderer',
|
||||
authors : 'authors',
|
||||
invitedAuthors : 'invited_authors',
|
||||
published : 'published',
|
||||
thumbnail : 'thumbnail',
|
||||
createdAt : 'created_at',
|
||||
updatedAt : 'updated_at',
|
||||
lastViewed : 'last_viewed',
|
||||
views : 'views',
|
||||
version : 'version',
|
||||
lock : 'lock'
|
||||
};
|
||||
|
||||
const ARRAY_FIELDS = ['tags', 'systems', 'authors', 'invitedAuthors'];
|
||||
const INT_FIELDS = ['pageCount', 'views', 'version'];
|
||||
const DATE_FIELDS = ['createdAt', 'updatedAt', 'lastViewed'];
|
||||
// Spalten ohne NOT NULL: explizit `undefined` heißt "auf NULL setzen" (Mongo: $unset)
|
||||
const NULLABLE = ['googleId', 'systems', 'lock'];
|
||||
// NOT NULL mit Default: explizit `undefined` setzt den Default zurück (Stub-Brews: text)
|
||||
const RESET_TO_DEFAULT = { text: '' };
|
||||
|
||||
const invert = (map)=>Object.fromEntries(Object.entries(map).map(([k, v])=>[v, k]));
|
||||
const BREW_FIELDS_BY_COLUMN = invert(BREW_COLUMNS);
|
||||
|
||||
const toArray = (v)=>{
|
||||
if(Array.isArray(v)) return v;
|
||||
return (v === undefined || v === null || v === '') ? [] : [v];
|
||||
};
|
||||
|
||||
const coerce = (field, value)=>{
|
||||
if(ARRAY_FIELDS.includes(field)) return toArray(value);
|
||||
if(INT_FIELDS.includes(field)) return Number.isFinite(Number(value)) ? Math.trunc(Number(value)) : undefined;
|
||||
if(DATE_FIELDS.includes(field)) return value instanceof Date ? value : new Date(value);
|
||||
if(field === 'published') return !!value;
|
||||
return value;
|
||||
};
|
||||
|
||||
// mode 'insert': nur gesetzte Felder (Defaults greifen), 'update': undefined → NULL/Default
|
||||
export const brewToRow = (brew, mode = 'insert')=>{
|
||||
const row = {};
|
||||
for (const [field, column] of Object.entries(BREW_COLUMNS)) {
|
||||
if(!(field in brew)) continue;
|
||||
const value = brew[field];
|
||||
if(value === undefined || value === null) {
|
||||
if(mode !== 'update') continue;
|
||||
if(NULLABLE.includes(field)) row[column] = null;
|
||||
else if(field in RESET_TO_DEFAULT) row[column] = RESET_TO_DEFAULT[field];
|
||||
continue;
|
||||
}
|
||||
const coerced = coerce(field, value);
|
||||
if(coerced !== undefined) row[column] = coerced;
|
||||
}
|
||||
return row;
|
||||
};
|
||||
|
||||
export const rowToBrew = (row, { fields } = {})=>{
|
||||
if(!row) return null;
|
||||
const brew = { id: row.id };
|
||||
for (const [column, value] of Object.entries(row)) {
|
||||
const field = BREW_FIELDS_BY_COLUMN[column];
|
||||
if(!field) continue;
|
||||
if(NULLABLE.includes(field) && value === null) continue; // wie Mongo: Feld fehlt
|
||||
brew[field] = value;
|
||||
}
|
||||
return fields ? _.pick(brew, ['id', ...fields]) : brew;
|
||||
};
|
||||
|
||||
export const BREW_SELECT_COLUMNS = Object.values(BREW_COLUMNS);
|
||||
export const BREW_LIST_COLUMNS = BREW_SELECT_COLUMNS.filter((c)=>c !== 'text');
|
||||
export const columnFor = (field)=>BREW_COLUMNS[field];
|
||||
|
||||
// --- notifications ---
|
||||
export const notificationToRow = (n)=>{
|
||||
const row = { dismiss_key: n.dismissKey };
|
||||
for (const [field, column] of [['title', 'title'], ['text', 'text'], ['startAt', 'start_at'], ['stopAt', 'stop_at'], ['createdAt', 'created_at']])
|
||||
if(n[field] !== undefined && n[field] !== null) row[column] = n[field];
|
||||
return row;
|
||||
};
|
||||
export const rowToNotification = (r)=>(!r ? null : {
|
||||
id : r.id,
|
||||
dismissKey : r.dismiss_key,
|
||||
title : r.title,
|
||||
text : r.text,
|
||||
createdAt : r.created_at,
|
||||
startAt : r.start_at,
|
||||
stopAt : r.stop_at
|
||||
});
|
||||
|
||||
// --- users ---
|
||||
export const rowToUser = (r)=>(!r ? null : {
|
||||
id : r.id,
|
||||
username : r.username,
|
||||
oidcIssuer : r.oidc_issuer ?? null,
|
||||
oidcSub : r.oidc_sub ?? null,
|
||||
email : r.email ?? null,
|
||||
emailVerified : !!r.email_verified,
|
||||
displayName : r.display_name ?? null,
|
||||
createdAt : r.created_at,
|
||||
lastLoginAt : r.last_login_at ?? null
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { randomBytes } from 'crypto';
|
||||
import pg from 'pg';
|
||||
import { createPostgresStorage } from './index.js';
|
||||
import { runUserRepositoryContract } from '../contract/users.contract.js';
|
||||
import { runGitRepositoryContract } from '../contract/git.contract.js';
|
||||
import { runBrewRepositoryContract, runNotificationRepositoryContract } from '../contract/brews.contract.js';
|
||||
|
||||
const url = process.env.HB_TEST_POSTGRES_URL;
|
||||
const suite = url ? describe : describe.skip;
|
||||
if(!url) console.warn('HB_TEST_POSTGRES_URL fehlt: Postgres-Storage-Contract-Tests werden übersprungen.');
|
||||
|
||||
// Jede Suite bekommt ein frisches Schema test_<random> und räumt danach auf.
|
||||
const createStorage = async ()=>{
|
||||
const schema = `test_${randomBytes(4).toString('hex')}`;
|
||||
const admin = new pg.Client({ connectionString: url });
|
||||
await admin.connect();
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const storage = createPostgresStorage(undefined, { url, searchPath: schema, poolMax: 3 });
|
||||
await storage.connect();
|
||||
return {
|
||||
storage,
|
||||
cleanup : async ()=>{
|
||||
await storage.disconnect();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
suite('Postgres UserRepository (Contract)', ()=>{
|
||||
runUserRepositoryContract(async ()=>{
|
||||
const { storage, cleanup } = await createStorage();
|
||||
return { users: storage.users, cleanup };
|
||||
});
|
||||
});
|
||||
|
||||
suite('Postgres BrewRepository (Contract)', ()=>{
|
||||
runBrewRepositoryContract(async ()=>{
|
||||
const { storage, cleanup } = await createStorage();
|
||||
return { brews: storage.brews, cleanup };
|
||||
});
|
||||
});
|
||||
|
||||
suite('Postgres NotificationRepository (Contract)', ()=>{
|
||||
runNotificationRepositoryContract(async ()=>{
|
||||
const { storage, cleanup } = await createStorage();
|
||||
return { notifications: storage.notifications, cleanup };
|
||||
});
|
||||
});
|
||||
|
||||
suite('Postgres Git-Repositories (Contract)', ()=>{
|
||||
runGitRepositoryContract(async ()=>{
|
||||
const { storage, cleanup } = await createStorage();
|
||||
return { users: storage.users, brews: storage.brews, gitConnections: storage.gitConnections, brewGitLinks: storage.brewGitLinks, cleanup };
|
||||
});
|
||||
});
|
||||
|
||||
suite('Postgres Verbindung und Migrationen', ()=>{
|
||||
test('Start ohne HB_POSTGRES_URL bricht mit klarer Meldung ab', async ()=>{
|
||||
const storage = createPostgresStorage({ get: ()=>undefined });
|
||||
await expect(storage.connect()).rejects.toThrow(/HB_POSTGRES_URL/);
|
||||
});
|
||||
|
||||
test('Migrationen sind idempotent, isReady folgt connect/disconnect', async ()=>{
|
||||
const { storage, cleanup } = await createStorage();
|
||||
expect(storage.isReady()).toBe(true);
|
||||
await cleanup();
|
||||
expect(storage.isReady()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
suite('Postgres Pool-Fehler', ()=>{
|
||||
it('bleibt nach einem Idle-Client-Fehler bereit', async ()=>{
|
||||
const { storage, cleanup } = await createStorage();
|
||||
const spy = jest.spyOn(console, 'error').mockImplementation(()=>{});
|
||||
try {
|
||||
expect(storage.isReady()).toBe(true);
|
||||
storage.pool.emit('error', new Error('Verbindung verloren'));
|
||||
expect(storage.isReady()).toBe(true);
|
||||
expect(spy).toHaveBeenCalled();
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { rowToUser } from './rows.js';
|
||||
|
||||
// UserRepository (PostgreSQL), gleicher Vertrag wie mongo/users.js (ADR 0001 §4).
|
||||
const COLUMNS = { oidcIssuer: 'oidc_issuer', oidcSub: 'oidc_sub', email: 'email', emailVerified: 'email_verified', displayName: 'display_name', lastLoginAt: 'last_login_at' };
|
||||
|
||||
const toRow = (patch)=>{
|
||||
const row = {};
|
||||
for (const [field, column] of Object.entries(COLUMNS)) {
|
||||
if(patch[field] === undefined) continue;
|
||||
row[column] = field === 'email' && patch.email ? String(patch.email).toLowerCase() : patch[field];
|
||||
}
|
||||
if('emailVerified' in row) row.email_verified = !!row.email_verified;
|
||||
return row;
|
||||
};
|
||||
|
||||
export const createUserRepository = (db)=>({
|
||||
async create({ username, ...rest }) {
|
||||
const row = await db.insertInto('users').values({ username, ...toRow(rest) }).returningAll().executeTakeFirstOrThrow();
|
||||
return rowToUser(row);
|
||||
},
|
||||
async findById(id) {
|
||||
if(!/^[0-9a-f-]{36}$/i.test(String(id))) return null; // kein uuid → nicht vorhanden (statt SQL-Fehler)
|
||||
return rowToUser(await db.selectFrom('users').selectAll().where('id', '=', id).executeTakeFirst());
|
||||
},
|
||||
async findByUsername(username) {
|
||||
return rowToUser(await db.selectFrom('users').selectAll().where('username', '=', username).executeTakeFirst());
|
||||
},
|
||||
async usernameExists(username) {
|
||||
return !!(await db.selectFrom('users').select('id').where('username', '=', username).executeTakeFirst());
|
||||
},
|
||||
async findByOidc(issuer, sub) {
|
||||
return rowToUser(await db.selectFrom('users').selectAll().where('oidc_issuer', '=', issuer).where('oidc_sub', '=', sub).executeTakeFirst());
|
||||
},
|
||||
// Vorab angelegte Benutzer (ohne OIDC-Bindung) mit dieser E-Mail
|
||||
async findUnlinkedByEmail(email) {
|
||||
const rows = await db.selectFrom('users').selectAll().where('email', '=', String(email).toLowerCase()).where('oidc_sub', 'is', null).execute();
|
||||
return rows.map(rowToUser);
|
||||
},
|
||||
async update(id, patch) {
|
||||
if(!/^[0-9a-f-]{36}$/i.test(String(id))) return null;
|
||||
const row = toRow(patch);
|
||||
if(!Object.keys(row).length) return this.findById(id);
|
||||
return rowToUser(await db.updateTable('users').set(row).where('id', '=', id).returningAll().executeTakeFirst());
|
||||
},
|
||||
async delete(id) {
|
||||
if(!/^[0-9a-f-]{36}$/i.test(String(id))) return false;
|
||||
const res = await db.deleteFrom('users').where('id', '=', id).executeTakeFirst();
|
||||
return res.numDeletedRows > 0n;
|
||||
}
|
||||
});
|
||||
+10
-60
@@ -1,36 +1,18 @@
|
||||
import express from 'express';
|
||||
import asyncHandler from 'express-async-handler';
|
||||
import { model as HomebrewModel } from './homebrew.model.js';
|
||||
import { getStorage } from './storage/index.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const titleConditions = (title)=>{
|
||||
if(!title) return {};
|
||||
return {
|
||||
$text : {
|
||||
$search : title,
|
||||
$caseSensitive : false,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const authorConditions = (author)=>{
|
||||
if(!author) return {};
|
||||
return { authors: author };
|
||||
};
|
||||
|
||||
const rendererConditions = (legacy, v3)=>{
|
||||
// [fork] ADR-0002: Die Abfrage selbst liegt im BrewRepository (Mongo: $text, Postgres: tsvector).
|
||||
const rendererFilter = (legacy, v3)=>{
|
||||
if(legacy === 'true' && v3 !== 'true')
|
||||
return { renderer: 'legacy' };
|
||||
return 'legacy';
|
||||
|
||||
if(v3 === 'true' && legacy !== 'true')
|
||||
return { renderer: 'V3' };
|
||||
return 'V3';
|
||||
|
||||
return {}; // If all renderers selected, renderer field not needed in query for speed
|
||||
};
|
||||
|
||||
const sortConditions = (sort, dir)=>{
|
||||
return { [sort]: dir === 'asc' ? 1 : -1 };
|
||||
return undefined; // If all renderers selected, renderer field not needed in query for speed
|
||||
};
|
||||
|
||||
const findBrews = async (req, res)=>{
|
||||
@@ -42,30 +24,8 @@ const findBrews = async (req, res)=>{
|
||||
const sort = req.query.sort || 'title';
|
||||
const dir = req.query.dir || 'asc';
|
||||
|
||||
const combinedQuery = {
|
||||
$and : [
|
||||
{ published: true },
|
||||
rendererConditions(req.query.legacy, req.query.v3),
|
||||
titleConditions(title),
|
||||
authorConditions(author)
|
||||
],
|
||||
};
|
||||
|
||||
const projection = {
|
||||
editId : 0,
|
||||
googleId : 0,
|
||||
text : 0,
|
||||
textBin : 0,
|
||||
version : 0
|
||||
};
|
||||
|
||||
await HomebrewModel.find(combinedQuery, projection)
|
||||
.sort(sortConditions(sort, dir))
|
||||
.skip(skip)
|
||||
.limit(count)
|
||||
.maxTimeMS(5000)
|
||||
.exec()
|
||||
.then((brews)=>{
|
||||
await getStorage().brews.searchPublished({ title, author, renderer: rendererFilter(req.query.legacy, req.query.v3), sort, dir, skip, limit: count })
|
||||
.then(({ brews })=>{
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
const processedBrews = brews.map((brew)=>{
|
||||
@@ -84,18 +44,8 @@ const findTotal = async (req, res)=>{
|
||||
const title = req.query.title || '';
|
||||
const author = req.query.author || '';
|
||||
|
||||
const combinedQuery = {
|
||||
$and : [
|
||||
{ published: true },
|
||||
rendererConditions(req.query.legacy, req.query.v3),
|
||||
titleConditions(title),
|
||||
authorConditions(author)
|
||||
],
|
||||
};
|
||||
|
||||
await HomebrewModel.countDocuments(combinedQuery)
|
||||
.then((totalBrews)=>{
|
||||
console.log(`when returning, the total of brews is ${totalBrews} for the query ${JSON.stringify(combinedQuery)}`);
|
||||
await getStorage().brews.searchPublished({ title, author, renderer: rendererFilter(req.query.legacy, req.query.v3), limit: 0, withTotal: true })
|
||||
.then(({ total: totalBrews })=>{
|
||||
res.json({ totalBrews });
|
||||
})
|
||||
.catch((error)=>{
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// API-Smoke-Test (ADR 0002 §5): Neuanlage, Laden, Update, Teilen-Lookup, Löschen gegen das echte Backend.
|
||||
// Läuft pro konfiguriertem Backend: HB_TEST_POSTGRES_URL (postgres) bzw. HB_TEST_MONGODB_URI (mongo).
|
||||
import os from 'os';
|
||||
import { randomBytes } from 'crypto';
|
||||
import supertest from 'supertest';
|
||||
import pg from 'pg';
|
||||
import mongoose from 'mongoose';
|
||||
import { md5 } from 'hash-wasm';
|
||||
import { makePatches, stringifyPatches } from '@sanity/diff-match-patch';
|
||||
import createApp from '../../server/app.js';
|
||||
import storage from '../../server/storage/index.js';
|
||||
import packageJSON from '../../package.json' with { type: 'json' };
|
||||
|
||||
const backends = [
|
||||
{ driver: 'postgres', url: process.env.HB_TEST_POSTGRES_URL },
|
||||
{ driver: 'mongo', url: process.env.HB_TEST_MONGODB_URI }
|
||||
];
|
||||
|
||||
const auth = `Basic ${Buffer.from('admin:password3').toString('base64')}`;
|
||||
const version = { 'Homebrewery-Version': packageJSON.version };
|
||||
|
||||
for (const { driver, url } of backends) {
|
||||
const suite = url ? describe : describe.skip;
|
||||
if(!url) console.warn(`API-Smoke (${driver}): HB_TEST_${driver === 'postgres' ? 'POSTGRES_URL' : 'MONGODB_URI'} fehlt, übersprungen.`);
|
||||
|
||||
suite(`API-Smoke gegen ${driver}`, ()=>{
|
||||
let request;
|
||||
let cleanup;
|
||||
|
||||
beforeAll(async ()=>{
|
||||
const name = `test_${randomBytes(4).toString('hex')}`;
|
||||
const values = { hb_db_driver: driver, node_env: 'test', local_environments: ['local'] };
|
||||
if(driver === 'postgres') {
|
||||
const admin = new pg.Client({ connectionString: url });
|
||||
await admin.connect();
|
||||
await admin.query(`CREATE SCHEMA ${name}`);
|
||||
// Schema per search_path der Verbindung: hängt die URL-Option an
|
||||
values.hb_postgres_url = `${url}${url.includes('?') ? '&' : '?'}options=-c%20search_path%3D${name}`;
|
||||
cleanup = async ()=>{ await storage.disconnect(); await admin.query(`DROP SCHEMA ${name} CASCADE`); await admin.end(); };
|
||||
} else {
|
||||
values.mongodb_uri = url;
|
||||
cleanup = async ()=>{ await mongoose.connection.dropDatabase(); await storage.disconnect(); };
|
||||
}
|
||||
// Unter Jest scheitert der dynamische import('os') des Mongo-Treibers (Handshake ohne Metadaten)
|
||||
const connect = mongoose.connect.bind(mongoose);
|
||||
jest.spyOn(mongoose, 'connect').mockImplementation((u, o)=>connect(u, { ...o, dbName: name, runtimeAdapters: { os } }));
|
||||
await storage.connect({ get: (key)=>values[key] });
|
||||
request = supertest.agent(await createApp()).set('X-Forwarded-Proto', 'https');
|
||||
});
|
||||
afterAll(async ()=>{ await cleanup?.(); });
|
||||
|
||||
test('Neuanlage, Laden, Update, Löschen', async ()=>{
|
||||
// Neuanlage
|
||||
const created = await request.post('/api').set(version).send({ text: 'Hallo Smoke', title: 'Smoke Brew', tags: ['meta:theme'], renderer: 'V3' });
|
||||
expect(created.status).toBe(200);
|
||||
const { editId, shareId } = created.body;
|
||||
expect(editId).toHaveLength(12);
|
||||
expect(shareId).toHaveLength(12);
|
||||
|
||||
// Laden (Admin-Lookup per Edit- oder Share-ID)
|
||||
const byEdit = await request.get(`/admin/lookup/${editId}`).set('Authorization', auth);
|
||||
expect(byEdit.status).toBe(200);
|
||||
expect(byEdit.body).toMatchObject({ title: 'Smoke Brew', shareId, editId });
|
||||
const byShare = await request.get(`/admin/lookup/${shareId}`).set('Authorization', auth);
|
||||
expect(byShare.body.shareId).toBe(shareId);
|
||||
|
||||
// Teilen: Theme-Bundle lädt den Brew über die Share-ID
|
||||
const shared = await request.get(`/api/theme/V3/${shareId}`);
|
||||
expect(shared.status).toBe(200);
|
||||
|
||||
// Update mit Patches (wie der Editor)
|
||||
const loaded = byEdit.body;
|
||||
const oldText = loaded.text.normalize('NFC');
|
||||
const newText = `${oldText}\nZweite Zeile`;
|
||||
const updated = await request.put(`/api/update/${editId}`).set(version).send({
|
||||
...loaded,
|
||||
text : newText,
|
||||
hash : await md5(oldText),
|
||||
patches : stringifyPatches(makePatches(encodeURI(oldText), encodeURI(newText)))
|
||||
});
|
||||
expect(updated.status).toBe(200);
|
||||
expect(updated.body.version).toBe(2);
|
||||
const reloaded = await request.get(`/admin/lookup/${editId}`).set('Authorization', auth);
|
||||
expect(reloaded.body.version).toBe(2);
|
||||
expect(reloaded.body.text).toContain('Zweite Zeile');
|
||||
|
||||
// Löschen (anonymer Brew ohne Autoren)
|
||||
const removed = await request.get(`/api/remove/${editId}`).set(version);
|
||||
expect(removed.status).toBe(204);
|
||||
const gone = await request.get(`/admin/lookup/${editId}`).set('Authorization', auth);
|
||||
expect(gone.body.shareId).toBeUndefined(); // Fehlerseite statt Brew
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// Git-Backend gegen die echte App und echte Datenbank (ADR 0003): Speichern über PUT /api/update/:id,
|
||||
// Konflikt G01, gitOverwrite, Pull, Teilen ohne Git-Zugriff. Läuft je Backend, das konfiguriert ist:
|
||||
// HB_TEST_POSTGRES_URL bzw. HB_TEST_MONGODB_URI (wie api-smoke.test.js).
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
import supertest from 'supertest';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import pg from 'pg';
|
||||
import mongoose from 'mongoose';
|
||||
import { md5 } from 'hash-wasm';
|
||||
import { makePatches, stringifyPatches } from '@sanity/diff-match-patch';
|
||||
import createApp from '../../server/app.js';
|
||||
import storage from '../../server/storage/index.js';
|
||||
import packageJSON from '../../package.json' with { type: 'json' };
|
||||
import { startGitHttpServer } from './git-http-test-server.js';
|
||||
|
||||
const backends = [
|
||||
{ driver: 'postgres', url: process.env.HB_TEST_POSTGRES_URL },
|
||||
{ driver: 'mongo', url: process.env.HB_TEST_MONGODB_URI }
|
||||
];
|
||||
const version = { 'Homebrewery-Version': packageJSON.version };
|
||||
const SECRET = 's'.repeat(40);
|
||||
|
||||
for (const { driver, url } of backends) {
|
||||
const suite = url ? describe : describe.skip;
|
||||
if(!url) console.warn(`Git-Backend-DB-Test (${driver}): Datenbank-URL fehlt, übersprungen.`);
|
||||
|
||||
suite(`Git-Backend gegen ${driver}`, ()=>{
|
||||
let request; let cleanup; let remote; let workdir; let cookie; let user; let envBackup; let connectSpy;
|
||||
|
||||
beforeAll(async ()=>{
|
||||
envBackup = { ...process.env };
|
||||
workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'hb-git-work-'));
|
||||
Object.assign(process.env, {
|
||||
HB_AUTH_PROVIDERS : 'oidc', HB_OIDC_ISSUER : 'https://idp.example.test', HB_OIDC_CLIENT_ID : 'hb', HB_OIDC_CLIENT_SECRET : 'x',
|
||||
HB_PUBLIC_URL : 'http://localhost:8000', HB_SESSION_SECRET : SECRET,
|
||||
HB_GIT_TOKEN_KEY : randomBytes(32).toString('base64'), HB_GIT_ALLOW_HTTP : 'true', HB_GIT_ALLOW_PRIVATE : 'true', HB_GIT_WORKDIR : workdir
|
||||
});
|
||||
remote = await startGitHttpServer();
|
||||
|
||||
const name = `test_${randomBytes(4).toString('hex')}`;
|
||||
const values = { hb_db_driver: driver, node_env: 'test', local_environments: ['local'] };
|
||||
if(driver === 'postgres') {
|
||||
const admin = new pg.Client({ connectionString: url });
|
||||
await admin.connect();
|
||||
await admin.query(`CREATE SCHEMA ${name}`);
|
||||
values.hb_postgres_url = `${url}${url.includes('?') ? '&' : '?'}options=-c%20search_path%3D${name}`;
|
||||
cleanup = async ()=>{ await storage.disconnect(); await admin.query(`DROP SCHEMA ${name} CASCADE`); await admin.end(); };
|
||||
} else {
|
||||
values.mongodb_uri = url;
|
||||
cleanup = async ()=>{ await mongoose.connection.dropDatabase(); await storage.disconnect(); };
|
||||
}
|
||||
const connect = mongoose.connect.bind(mongoose);
|
||||
connectSpy = jest.spyOn(mongoose, 'connect').mockImplementation((u, o)=>connect(u, { ...o, dbName: name, runtimeAdapters: { os } }));
|
||||
await storage.connect({ get: (key)=>values[key] });
|
||||
if(driver === 'mongo') {
|
||||
const { model } = await import('../../server/homebrew.model.js');
|
||||
await model.collection.createIndex({ shareId: 1 }, { unique: true });
|
||||
await model.collection.createIndex({ editId: 1 }, { unique: true });
|
||||
const git = storage.getStorage();
|
||||
await git.users.Model.init(); await git.gitConnections.Model.init(); await git.brewGitLinks.Model.init();
|
||||
}
|
||||
user = await storage.getStorage().users.create({ username: 'alice-git', displayName: 'Alice A.' });
|
||||
cookie = `hb_session=${jwt.sign({ v: 1, uid: user.id, username: 'alice-git', iss: 'https://idp.example.test', sub: 's1' }, SECRET, { algorithm: 'HS256', expiresIn: 3600 })}`;
|
||||
request = supertest.agent(await createApp()).set('X-Forwarded-Proto', 'https');
|
||||
});
|
||||
afterAll(async ()=>{
|
||||
await cleanup?.();
|
||||
connectSpy?.mockRestore();
|
||||
await remote?.close();
|
||||
fs.rmSync(workdir, { recursive: true, force: true });
|
||||
process.env = envBackup;
|
||||
});
|
||||
|
||||
const api = (method, url)=>request[method](url).set(version).set('Cookie', cookie);
|
||||
|
||||
const loadBrew = async (editId)=>{
|
||||
const b = await storage.getStorage().brews.findByEditId(editId);
|
||||
return b;
|
||||
};
|
||||
// Wie der Editor: Patches gegen den zuletzt geladenen (entpackten) Text
|
||||
const save = async (editId, newText, query = '')=>{
|
||||
const lookup = await request.get(`/admin/lookup/${editId}`).set('Authorization', `Basic ${Buffer.from('admin:password3').toString('base64')}`);
|
||||
const loaded = lookup.body;
|
||||
const oldText = loaded.text.normalize('NFC');
|
||||
return api('put', `/api/update/${editId}${query}`).send({
|
||||
...loaded, text : newText, hash : await md5(oldText),
|
||||
patches : stringifyPatches(makePatches(encodeURI(oldText), encodeURI(newText)))
|
||||
});
|
||||
};
|
||||
|
||||
test('Verbindung anlegen, Brew in Git anlegen, speichern, Konflikt, Überschreiben, Pull, Teilen ohne Git', async ()=>{
|
||||
const { url: repoUrl, dir } = remote.createRepo('db.git');
|
||||
const conn = await api('post', '/api/git/connections').send({ label: 'Lokal', repoUrl, authUsername: remote.username, token: remote.token });
|
||||
expect(conn.status).toBe(201);
|
||||
expect(JSON.stringify(conn.body)).not.toContain(remote.token);
|
||||
|
||||
const created = await api('post', '/api/git/brews').send({ connectionId: conn.body.id, path: 'brews/db.md', brew: { title: 'DB Brew', text: 'Erste Fassung', renderer: 'V3' } });
|
||||
expect(created.status).toBe(200);
|
||||
const { editId, shareId } = created.body;
|
||||
if(process.env.GIT_TEST_LOG) console.log('CREATED', JSON.stringify(created.body), JSON.stringify(await storage.getStorage().brews.findByEditId(editId)));
|
||||
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Erste Fassung');
|
||||
const status = await api('get', `/api/git/brews/${editId}`);
|
||||
expect(status.body).toMatchObject({ linked: true, path: 'brews/db.md', branch: 'main', isConnectionOwner: true });
|
||||
|
||||
// Speichern → Commit
|
||||
const s1 = await save(editId, 'Zweite Fassung');
|
||||
expect(s1.status).toBe(200);
|
||||
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Zweite Fassung');
|
||||
expect(remote.log(dir, 'main')).toHaveLength(2);
|
||||
expect((await loadBrew(editId)).text).toContain('Zweite Fassung');
|
||||
expect((await api('get', `/api/git/brews/${editId}`)).body.lastCommitSha).toBe(remote.head(dir, 'main'));
|
||||
|
||||
// Teilen: Share-Routen brauchen keinen Git-Zugriff (Server hängt)
|
||||
remote.setHang(true);
|
||||
const shared = await request.get(`/source/${shareId}`);
|
||||
remote.setHang(false);
|
||||
expect(shared.status).toBe(200);
|
||||
expect(shared.text).toContain('Zweite Fassung');
|
||||
|
||||
// Fremder Commit → 409 G01
|
||||
remote.commitFile(dir, 'main', 'brews/db.md', '```metadata\ntitle: Extern\n```\n\nExterne Fassung\n');
|
||||
const conflict = await save(editId, 'Dritte Fassung');
|
||||
expect(conflict.status).toBe(409);
|
||||
expect(conflict.body).toMatchObject({ HBErrorCode: 'G01' });
|
||||
expect(conflict.body.remoteBlobSha).toMatch(/^[0-9a-f]{40}$/);
|
||||
expect((await loadBrew(editId)).text).toContain('Zweite Fassung'); // DB unverändert
|
||||
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Externe Fassung');
|
||||
|
||||
// Meine Version behalten → Commit auf dem neuen Stand
|
||||
const over = await save(editId, 'Dritte Fassung', `?gitOverwrite=${conflict.body.remoteBlobSha}`);
|
||||
expect(over.status).toBe(200);
|
||||
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Dritte Fassung');
|
||||
expect(remote.log(dir, 'main')).toHaveLength(4);
|
||||
|
||||
// Externer Commit, dann Pull → Snapshot folgt
|
||||
remote.commitFile(dir, 'main', 'brews/db.md', '```metadata\ntitle: Extern 2\n```\n\nVierte Fassung\n');
|
||||
const pulled = await api('post', `/api/git/brews/${editId}/pull`);
|
||||
expect(pulled.status).toBe(200);
|
||||
const after = await loadBrew(editId);
|
||||
expect(after.title).toBe('Extern 2');
|
||||
expect(after.text).toContain('Vierte Fassung');
|
||||
|
||||
// Löschen: Brew und Link weg, Datei bleibt (F9)
|
||||
const removed = await api('get', `/api/remove/${editId}`);
|
||||
expect(removed.status).toBe(204);
|
||||
expect(await loadBrew(editId)).toBeNull();
|
||||
expect(remote.readFile(dir, 'main', 'brews/db.md')).toContain('Vierte Fassung');
|
||||
expect(await storage.getStorage().brewGitLinks.findByBrewId(created.body.id)).toBeNull();
|
||||
});
|
||||
|
||||
test('Konten ohne uid (nicht angemeldet) bekommen 403 G07', async ()=>{
|
||||
const res = await request.get('/api/git/connections').set(version);
|
||||
expect([res.status, res.body.HBErrorCode]).toEqual([403, 'G07']);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
// Integration ohne Netz und ohne Datenbank (ADR 0003, "Tests"): echtes `git` gegen einen lokalen
|
||||
// `git http-backend` mit Basic-Auth, Storage im Speicher. Die DB-Varianten laufen in git-backend.db.test.js.
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
import express from 'express';
|
||||
import supertest from 'supertest';
|
||||
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 { createGitRouter } from '../../server/fork/git/routes.js';
|
||||
import { createTokenCrypto } from '../../server/fork/git/crypto.js';
|
||||
import { createGitClient } from '../../server/fork/git/gitClient.js';
|
||||
import packageJSON from '../../package.json' with { type: 'json' };
|
||||
import { startGitHttpServer } from './git-http-test-server.js';
|
||||
import { createMemoryStorage } from './git-memory-storage.js';
|
||||
|
||||
const silent = process.env.GIT_TEST_LOG ? console : { warn: ()=>{}, error: ()=>{}, log: ()=>{} };
|
||||
const version = { 'Homebrewery-Version': packageJSON.version };
|
||||
const asAccount = (a)=>({ 'x-account': JSON.stringify(a) });
|
||||
|
||||
const KEY = crypto.randomBytes(32).toString('base64');
|
||||
let remote; let storage; let svc; let request; let workdir; let alice; let bob; let cfg;
|
||||
const ALICE = ()=>({ username: 'alice', uid: alice.id });
|
||||
const NC = { username: 'carol' }; // naturalcrit-Konto ohne uid
|
||||
|
||||
const build = (overrides = {}, serviceOverrides = {})=>{
|
||||
cfg = { ...readGitConfig({ HB_GIT_TOKEN_KEY: KEY, HB_PUBLIC_URL: 'https://hb.example.test', HB_GIT_WORKDIR: workdir }),
|
||||
allowHttp : true, allowPrivate : true, openTimeoutMs : 1000, timeoutMs : 5000, ...overrides };
|
||||
svc = createGitService({ cfg, getStorage: ()=>storage, api, splitTextStyleAndMetadata, logger: silent, ...serviceOverrides });
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, res, next)=>{ if(req.headers['x-account']) req.account = JSON.parse(req.headers['x-account']); next(); });
|
||||
app.use(createGitRouter(svc, { logger: silent }));
|
||||
app.get('/edit/:id', (req, res)=>res.send('editor'));
|
||||
request = supertest(app);
|
||||
};
|
||||
|
||||
const newConn = async (extra = {})=>{
|
||||
const { url } = remote.createRepo(`r${Math.random().toString(36).slice(2)}.git`);
|
||||
const res = await request.post('/api/git/connections').set(version).set(asAccount(ALICE()))
|
||||
.send({ label: 'Test', repoUrl: url, authUsername: remote.username, token: remote.token, ...extra });
|
||||
expect(res.status).toBe(201);
|
||||
return { url, dir: path.join(remote.dirRoot ?? '', ''), conn: res.body };
|
||||
};
|
||||
|
||||
const repoDir = (url)=>{ const name = new URL(url).pathname.slice(1); return remote.dirOf(name); };
|
||||
|
||||
const leftovers = ()=>{
|
||||
const procs = fs.readdirSync('/proc').filter((p)=>/^\d+$/.test(p)).filter((p)=>{
|
||||
try { return fs.readlinkSync(`/proc/${p}/cwd`).startsWith(workdir); } catch { return false; }
|
||||
});
|
||||
return { procs, dirs: fs.existsSync(workdir) ? fs.readdirSync(workdir) : [] };
|
||||
};
|
||||
|
||||
beforeAll(async ()=>{
|
||||
remote = await startGitHttpServer();
|
||||
workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'hb-git-work-'));
|
||||
});
|
||||
afterAll(async ()=>{
|
||||
await remote.close();
|
||||
fs.rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
beforeEach(async ()=>{
|
||||
storage = createMemoryStorage();
|
||||
alice = await storage.users.create({ username: 'alice', displayName: 'Alice A.' });
|
||||
bob = await storage.users.create({ username: 'bob' });
|
||||
build();
|
||||
});
|
||||
|
||||
describe('Verbindungen', ()=>{
|
||||
test('Token wird verschlüsselt gespeichert und nie ausgeliefert oder geloggt', async ()=>{
|
||||
const logs = [];
|
||||
build({}, { logger: { warn: (...a)=>logs.push(a.join(' ')), error: (...a)=>logs.push(a.join(' ')) } });
|
||||
const { conn } = await newConn();
|
||||
expect(conn).toMatchObject({ hasToken: true, defaultBranch: 'main', brewDir: 'brews', assetsDir: 'assets' });
|
||||
expect(JSON.stringify(conn)).not.toContain(remote.token);
|
||||
expect(conn.tokenEnc).toBeUndefined();
|
||||
const stored = await storage.gitConnections.findById(conn.id);
|
||||
expect(stored.tokenEnc).toMatch(/^v1\./);
|
||||
expect(stored.tokenEnc).not.toContain(remote.token);
|
||||
|
||||
const list = await request.get('/api/git/connections').set(version).set(asAccount(ALICE()));
|
||||
expect(JSON.stringify(list.body)).not.toContain(remote.token);
|
||||
expect(list.body).toHaveLength(1);
|
||||
|
||||
// Fehlerfall mit falschem Token: weder Antwort noch Log enthalten ihn
|
||||
await request.patch(`/api/git/connections/${conn.id}`).set(version).set(asAccount(ALICE())).send({ token: 'falscher-token-xyz' });
|
||||
const test = await request.post(`/api/git/connections/${conn.id}/test`).set(version).set(asAccount(ALICE()));
|
||||
expect(test.status).toBe(502);
|
||||
expect(test.body.HBErrorCode).toBe('G02');
|
||||
expect(JSON.stringify(test.body)).not.toContain('falscher-token-xyz');
|
||||
expect(logs.join('\n')).not.toContain('falscher-token-xyz');
|
||||
expect(logs.join('\n')).not.toContain(remote.token);
|
||||
});
|
||||
|
||||
test('Test-Button, Branches und Dateiliste', async ()=>{
|
||||
const { url, conn } = await newConn();
|
||||
const dir = repoDir(url);
|
||||
remote.commitFile(dir, 'main', 'brews/eins.md', 'x');
|
||||
remote.commitFile(dir, 'dev', 'brews/zwei.md', 'y');
|
||||
const a = asAccount(ALICE());
|
||||
const t = await request.post(`/api/git/connections/${conn.id}/test`).set(version).set(a);
|
||||
expect(t.body).toMatchObject({ ok: true, branchCount: 2 });
|
||||
const b = await request.get(`/api/git/connections/${conn.id}/branches`).set(version).set(a);
|
||||
expect(b.body.branches).toEqual(['dev', 'main']);
|
||||
const f = await request.get(`/api/git/connections/${conn.id}/files`).query({ branch: 'dev', dir: 'brews' }).set(version).set(a);
|
||||
expect(f.body.files).toEqual(['brews/zwei.md']);
|
||||
const nope = await request.get(`/api/git/connections/${conn.id}/files`).query({ branch: 'gibtsnicht' }).set(version).set(a);
|
||||
expect(nope.body.HBErrorCode).toBe('G03');
|
||||
});
|
||||
|
||||
test('Verbindungen sind pro Benutzer: fremde Verbindung → 404', async ()=>{
|
||||
const { conn } = await newConn();
|
||||
const other = { username: 'bob', uid: bob.id };
|
||||
const res = await request.delete(`/api/git/connections/${conn.id}`).set(version).set(asAccount(other));
|
||||
expect(res.status).toBe(404);
|
||||
expect((await request.get('/api/git/connections').set(version).set(asAccount(other))).body).toEqual([]);
|
||||
expect((await request.delete(`/api/git/connections/${conn.id}`).set(version).set(asAccount(ALICE()))).status).toBe(204);
|
||||
});
|
||||
|
||||
test('ungültige Eingaben: URL mit Zugangsdaten, SSRF-Ziel, fehlender Token', async ()=>{
|
||||
build({ allowPrivate: false, allowHttp: false });
|
||||
const post = (body)=>request.post('/api/git/connections').set(version).set(asAccount(ALICE())).send(body);
|
||||
expect((await post({ label: 'x', repoUrl: 'https://u:p@git.example.test/a/b', token: 't' })).body.HBErrorCode).toBe('G08');
|
||||
expect((await post({ label: 'x', repoUrl: 'https://127.0.0.1/a/b', token: 't' })).body.HBErrorCode).toBe('G08');
|
||||
expect((await post({ label: 'x', repoUrl: 'https://169.254.169.254/latest', token: 't' })).status).toBe(400);
|
||||
expect((await post({ label: 'x', repoUrl: 'http://git.example.test/a/b', token: 't' })).status).toBe(400);
|
||||
build({ allowedHosts: ['git.example.test'] });
|
||||
expect((await post({ label: 'x', repoUrl: 'https://anderer.example.test/a/b', token: 't' })).status).toBe(400);
|
||||
expect((await post({ label: 'x', repoUrl: 'https://git.example.test/a/b' })).status).toBe(400);
|
||||
expect((await post({ label: '', repoUrl: 'https://git.example.test/a/b', token: 't' })).status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Zugriffsregeln', ()=>{
|
||||
test('ohne Schlüssel: 503; ohne OIDC-uid: 403 G07; Status/Pull brauchen nur Bearbeitungsrecht', async ()=>{
|
||||
build({ enabled: false, key: undefined });
|
||||
const off = await request.get('/api/git/connections').set(version).set(asAccount(ALICE()));
|
||||
expect(off.status).toBe(503);
|
||||
build();
|
||||
for (const [method, url] of [['get', '/api/git/connections'], ['post', '/api/git/connections'], ['post', '/api/git/brews'], ['post', '/api/git/brews/import'], ['post', '/api/git/brews/abc/link'], ['delete', '/api/git/brews/abc/link']]) {
|
||||
const res = await request[method](url).set(version).set(asAccount(NC)).send({});
|
||||
expect([res.status, res.body.HBErrorCode]).toEqual([403, 'G07']);
|
||||
}
|
||||
const anon = await request.get('/api/git/connections').set(version);
|
||||
expect([anon.status, anon.body.HBErrorCode]).toEqual([403, 'G07']);
|
||||
|
||||
// Status und Pull mit Bearbeitungsrecht (naturalcrit-Mitautor)
|
||||
const { conn } = await newConn();
|
||||
const brew = await storage.brews.create({ title: 'T', text: 'Hallo', authors: ['alice', 'carol'] });
|
||||
await request.post(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, path: 'brews/t.md' }).expect(200);
|
||||
const st = await request.get(`/api/git/brews/${brew.editId}`).set(version).set(asAccount(NC));
|
||||
expect(st.status).toBe(200);
|
||||
expect(st.body).toMatchObject({ linked: true, branch: 'main', path: 'brews/t.md', isConnectionOwner: false });
|
||||
expect((await request.post(`/api/git/brews/${brew.editId}/pull`).set(version).set(asAccount(NC))).status).toBe(200);
|
||||
// ohne Bearbeitungsrecht
|
||||
expect((await request.get(`/api/git/brews/${brew.editId}`).set(version).set(asAccount({ username: 'dave' }))).status).toBe(401);
|
||||
expect((await request.get(`/api/git/brews/${brew.editId}`).set(version)).status).toBe(401);
|
||||
// Lösen darf nur der Besitzer der Verbindung
|
||||
expect((await request.delete(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount({ username: 'bob', uid: bob.id }))).status).toBe(401);
|
||||
});
|
||||
|
||||
test('Client-Version wird geprüft', async ()=>{
|
||||
const res = await request.get('/api/git/connections').set(asAccount(ALICE()));
|
||||
expect(res.status).toBe(412);
|
||||
});
|
||||
|
||||
test('fremde Verbindung kann nicht zum Verknüpfen genutzt werden', async ()=>{
|
||||
const { conn } = await newConn();
|
||||
const brew = await storage.brews.create({ title: 'B', text: 'x', authors: ['bob'] });
|
||||
const res = await request.post(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount({ username: 'bob', uid: bob.id })).send({ connectionId: conn.id, path: 'a.md' });
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Brew anlegen, importieren, verknüpfen', ()=>{
|
||||
test('Root-Commit in leerem Repo, Autor = Benutzer, Committer = Homebrewery', async ()=>{
|
||||
const { url, conn } = await newConn();
|
||||
const res = await request.post('/api/git/brews').set(version).set(asAccount(ALICE()))
|
||||
.send({ connectionId: conn.id, brew: { title: 'Mein Brew', text: '# Hallo\n', renderer: 'V3' } });
|
||||
expect(res.status).toBe(200);
|
||||
const dir = repoDir(url);
|
||||
const file = remote.readFile(dir, 'main', 'brews/mein-brew.md');
|
||||
expect(file).toContain('```metadata');
|
||||
expect(file).toContain('# Hallo');
|
||||
expect(remote.log(dir, 'main')).toEqual(['Alice A.|Homebrewery|Create brews/mein-brew.md via Homebrewery']);
|
||||
const link = await storage.brewGitLinks.findByBrewId(res.body.id);
|
||||
expect(link).toMatchObject({ branch: 'main', path: 'brews/mein-brew.md', lastCommitSha: remote.head(dir, 'main'), lastError: null });
|
||||
expect(res.body.authors).toEqual(['alice']);
|
||||
// existierende Datei → G06
|
||||
const dup = await request.post('/api/git/brews').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, path: 'brews/mein-brew.md', brew: { title: 'x', text: 'y' } });
|
||||
expect([dup.status, dup.body.HBErrorCode]).toEqual([409, 'G06']);
|
||||
});
|
||||
|
||||
test('neuer Branch in nicht leerem Repo setzt auf default_branch auf', async ()=>{
|
||||
const { url, conn } = await newConn();
|
||||
const dir = repoDir(url);
|
||||
const base = remote.commitFile(dir, 'main', 'README.md', 'hi');
|
||||
const res = await request.post('/api/git/brews').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, branch: 'neu', brew: { title: 'Auf Branch', text: 'x' } });
|
||||
expect(res.status).toBe(200);
|
||||
expect(remote.log(dir, 'neu')).toHaveLength(2);
|
||||
expect(remote.readFile(dir, 'neu', 'README.md')).toBe('hi');
|
||||
expect(remote.head(dir, 'main')).toBe(base);
|
||||
});
|
||||
|
||||
test('Import liest eine vorhandene Datei, Doppel-Import → G06', async ()=>{
|
||||
const { url, conn } = await newConn();
|
||||
const dir = repoDir(url);
|
||||
remote.commitFile(dir, 'main', 'brews/alt.md', '```metadata\ntitle: Alt\ndescription: D\nrenderer: V3\n```\n\n# Text\n');
|
||||
const res = await request.post('/api/git/brews/import').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, branch: 'main', path: 'brews/alt.md' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toMatchObject({ title: 'Alt', description: 'D', renderer: 'V3', authors: ['alice'] });
|
||||
expect(res.body.text).toContain('# Text');
|
||||
const link = await storage.brewGitLinks.findByBrewId(res.body.id);
|
||||
expect(link.lastBlobSha).toMatch(/^[0-9a-f]{40}$/);
|
||||
const again = await request.post('/api/git/brews/import').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, branch: 'main', path: 'brews/alt.md' });
|
||||
expect(again.body.HBErrorCode).toBe('G06');
|
||||
const missing = await request.post('/api/git/brews/import').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, branch: 'main', path: 'brews/fehlt.md' });
|
||||
expect(missing.body.HBErrorCode).toBe('G03');
|
||||
});
|
||||
|
||||
test('Pfad-Validierung und Google-Brews', async ()=>{
|
||||
const { conn } = await newConn();
|
||||
for (const bad of ['../x.md', '/x.md', '.git/x.md', 'x.txt']) {
|
||||
const res = await request.post('/api/git/brews').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, path: bad, brew: { title: 't', text: 'x' } });
|
||||
expect([res.status, res.body.HBErrorCode]).toEqual([400, 'G08']);
|
||||
}
|
||||
const g = await storage.brews.create({ title: 'G', text: 'x', authors: ['alice'], googleId: '1abc' });
|
||||
const res = await request.post(`/api/git/brews/${g.editId}/link`).set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, path: 'g.md' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
test('Lösen der Verknüpfung lässt Brew und Datei bestehen', async ()=>{
|
||||
const { url, conn } = await newConn();
|
||||
const brew = await storage.brews.create({ title: 'T', text: 'Hallo', authors: ['alice'] });
|
||||
await request.post(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount(ALICE())).send({ connectionId: conn.id }).expect(200);
|
||||
expect(remote.readFile(repoDir(url), 'main', 'brews/t.md')).toBe('Hallo');
|
||||
await request.delete(`/api/git/brews/${brew.editId}/link`).set(version).set(asAccount(ALICE())).expect(204);
|
||||
expect((await request.get(`/api/git/brews/${brew.editId}`).set(version).set(asAccount(ALICE()))).body).toEqual({ linked: false });
|
||||
expect(await storage.brews.findByEditId(brew.editId)).not.toBeNull();
|
||||
expect(remote.readFile(repoDir(url), 'main', 'brews/t.md')).toBe('Hallo');
|
||||
});
|
||||
});
|
||||
|
||||
// Hilfsfunktion: verknüpften Brew anlegen und Speichern über den Hook simulieren
|
||||
const linked = async (text = 'Version 1')=>{
|
||||
const { url, conn } = await newConn();
|
||||
const created = await request.post('/api/git/brews').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, path: 'brews/b.md', brew: { title: 'B', text } });
|
||||
const dir = repoDir(url);
|
||||
const brew = await storage.brews.findByEditId(created.body.editId);
|
||||
const fakeRes = ()=>{ const r = { status(c) { r.code = c; return r; }, json(b) { r.body = b; return r; } }; return r; };
|
||||
const save = async (newText, query = {}, account = ALICE())=>{
|
||||
const res = fakeRes();
|
||||
const current = await storage.brews.findByEditId(brew.editId);
|
||||
const ctx = await svc.beforeBrewSave({ brew: { ...current, text: newText }, req: { query, account }, res });
|
||||
if(ctx) {
|
||||
const saved = await storage.brews.update({ ...current, text: newText, version: current.version + 1 });
|
||||
await svc.afterBrewSave(ctx, saved);
|
||||
}
|
||||
return { ctx, res };
|
||||
};
|
||||
return { url, dir, conn, brew, save };
|
||||
};
|
||||
|
||||
describe('Speichern (Hook beforeBrewSave/afterBrewSave)', ()=>{
|
||||
test('Save erzeugt einen Commit und aktualisiert den Link', async ()=>{
|
||||
const { dir, brew, save } = await linked();
|
||||
const { ctx } = await save('Version 2');
|
||||
expect(ctx.git.commit).toBe(remote.head(dir, 'main'));
|
||||
expect(remote.readFile(dir, 'main', 'brews/b.md')).toBe('Version 2');
|
||||
expect(remote.log(dir, 'main')[0]).toBe('Alice A.|Homebrewery|Update brews/b.md via Homebrewery');
|
||||
const link = await storage.brewGitLinks.findByBrewId(brew.id);
|
||||
expect(link).toMatchObject({ lastCommitSha: ctx.git.commit, lastBlobSha: ctx.git.blob, lastError: null });
|
||||
expect(svc.locks.keyCount).toBe(0);
|
||||
});
|
||||
|
||||
test('unveränderter Inhalt erzeugt keinen leeren Commit', async ()=>{
|
||||
const { dir, brew, save } = await linked('gleich');
|
||||
const before = remote.head(dir, 'main');
|
||||
await save((await storage.brews.findByEditId(brew.editId)).text);
|
||||
expect(remote.head(dir, 'main')).toBe(before);
|
||||
});
|
||||
|
||||
test('fremder Commit auf anderer Datei ist kein Konflikt', async ()=>{
|
||||
const { dir, save } = await linked();
|
||||
remote.commitFile(dir, 'main', 'andere.md', 'fremd');
|
||||
const { res, ctx } = await save('Version 2');
|
||||
expect(res.code).toBeUndefined();
|
||||
expect(ctx.git.commit).toBe(remote.head(dir, 'main'));
|
||||
expect(remote.readFile(dir, 'main', 'andere.md')).toBe('fremd'); // nichts überschrieben
|
||||
expect(remote.log(dir, 'main')).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('fremder Commit auf derselben Datei → 409 G01, weder Git noch DB ändern sich', async ()=>{
|
||||
const { dir, brew, save } = await linked();
|
||||
const foreign = remote.commitFile(dir, 'main', 'brews/b.md', 'Fremde Version');
|
||||
const linkBefore = await storage.brewGitLinks.findByBrewId(brew.id);
|
||||
const { ctx, res } = await save('Meine Version');
|
||||
expect(ctx).toBeNull();
|
||||
expect(res.code).toBe(409);
|
||||
expect(res.body).toMatchObject({ HBErrorCode: 'G01', remoteCommitSha: foreign });
|
||||
expect(res.body.remoteBlobSha).toMatch(/^[0-9a-f]{40}$/);
|
||||
expect(remote.head(dir, 'main')).toBe(foreign);
|
||||
expect((await storage.brews.findByEditId(brew.editId)).text).toContain('Version 1');
|
||||
expect(await storage.brewGitLinks.findByBrewId(brew.id)).toEqual(linkBefore);
|
||||
expect(svc.locks.keyCount).toBe(0); // Mutex trotz Fehler freigegeben
|
||||
});
|
||||
|
||||
test('gitOverwrite=<remoteBlob>: normaler Commit auf dem neuen Stand, fremde Historie bleibt', async ()=>{
|
||||
const { dir, save } = await linked();
|
||||
remote.commitFile(dir, 'main', 'brews/b.md', 'Fremde Version');
|
||||
const conflict = (await save('Meine Version')).res.body;
|
||||
const { ctx, res } = await save('Meine Version', { gitOverwrite: conflict.remoteBlobSha });
|
||||
expect(res.code).toBeUndefined();
|
||||
expect(remote.readFile(dir, 'main', 'brews/b.md')).toBe('Meine Version');
|
||||
const log = remote.log(dir, 'main');
|
||||
expect(log).toHaveLength(3);
|
||||
expect(log[1]).toBe('Dritter|Dritter|extern');
|
||||
expect(ctx.git.commit).toBe(remote.head(dir, 'main'));
|
||||
// falsche Overwrite-ID gilt nicht
|
||||
remote.commitFile(dir, 'main', 'brews/b.md', 'Noch fremder');
|
||||
expect((await save('Meine Version 2', { gitOverwrite: conflict.remoteBlobSha })).res.code).toBe(409);
|
||||
});
|
||||
|
||||
test('Push-Rennen: Non-Fast-Forward führt zu erneutem Versuch (max. 3), dann G05', async ()=>{
|
||||
const { dir, save } = await linked();
|
||||
const real = createGitClient(cfg);
|
||||
let raced = 0;
|
||||
build({}, { client: { ...real, fetchHead: async (...a)=>{ const h = await real.fetchHead(...a); if(raced < 1) { raced++; remote.commitFile(dir, 'main', `race${raced}.md`, 'x'); } return h; } } });
|
||||
const res1 = await save('Nach Rennen');
|
||||
expect(res1.res.code).toBeUndefined();
|
||||
expect(raced).toBe(1);
|
||||
expect(remote.readFile(dir, 'main', 'brews/b.md')).toBe('Nach Rennen');
|
||||
expect(remote.readFile(dir, 'main', 'race1.md')).toBe('x');
|
||||
|
||||
// dauerhaft verlorenes Rennen → 503 G05
|
||||
build({}, { client: { ...real, fetchHead: async (...a)=>{ const h = await real.fetchHead(...a); raced++; remote.commitFile(dir, 'main', `race${raced}.md`, 'x'); return h; } } });
|
||||
const res2 = await save('Nie');
|
||||
expect([res2.res.code, res2.res.body.HBErrorCode]).toEqual([503, 'G05']);
|
||||
expect(raced).toBe(4);
|
||||
});
|
||||
|
||||
test('falscher Token → 502 G02, DB unverändert', async ()=>{
|
||||
const { brew, conn, save } = await linked();
|
||||
await storage.gitConnections.update(conn.id, { tokenEnc: createTokenCrypto({ key: cfg.key }).encrypt('kaputt', conn.id) });
|
||||
const { res } = await save('X');
|
||||
expect([res.code, res.body.HBErrorCode]).toEqual([502, 'G02']);
|
||||
expect(JSON.stringify(res.body)).not.toContain(remote.token);
|
||||
expect((await storage.brews.findByEditId(brew.editId)).text).toContain('Version 1');
|
||||
});
|
||||
|
||||
test('saveToGoogle bei Git-Brew → 400', async ()=>{
|
||||
const { save } = await linked();
|
||||
const { res } = await save('X', { saveToGoogle: 'true' });
|
||||
expect([res.code, res.body.HBErrorCode]).toEqual([400, 'G08']);
|
||||
});
|
||||
|
||||
test('Mitautor ohne uid speichert mit dem Token des Verbindungsbesitzers', async ()=>{
|
||||
const { dir, brew, save } = await linked();
|
||||
await storage.brews.update({ ...(await storage.brews.findByEditId(brew.editId)), authors: ['alice', 'carol'] });
|
||||
const { res } = await save('Von Carol', {}, NC);
|
||||
expect(res.code).toBeUndefined();
|
||||
expect(remote.log(dir, 'main')[0]).toBe('carol|Homebrewery|Update brews/b.md via Homebrewery');
|
||||
});
|
||||
|
||||
test('gleichzeitige Saves desselben Brews werden serialisiert (kein falscher Konflikt)', async ()=>{
|
||||
const { dir, save } = await linked();
|
||||
const [a, b] = await Promise.all([save('Parallel A'), save('Parallel B')]);
|
||||
expect([a.res.code, b.res.code]).toEqual([undefined, undefined]);
|
||||
expect(remote.log(dir, 'main')).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('zu große Datei → 413 G09', async ()=>{
|
||||
build({ maxFileBytes: 100 });
|
||||
const { res } = await (async ()=>{
|
||||
const { conn } = await newConn();
|
||||
return { res: await request.post('/api/git/brews').set(version).set(asAccount(ALICE())).send({ connectionId: conn.id, brew: { title: 'Groß', text: 'x'.repeat(500) } }) };
|
||||
})();
|
||||
expect([res.status, res.body.HBErrorCode]).toEqual([413, 'G09']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Pull und Abgleich beim Öffnen', ()=>{
|
||||
test('Pull übernimmt den Remote-Stand in den Snapshot (Version + 1)', async ()=>{
|
||||
const { dir, brew } = await linked();
|
||||
remote.commitFile(dir, 'main', 'brews/b.md', '```metadata\ntitle: Neu von außen\n```\n\nRemote-Text\n');
|
||||
const res = await request.post(`/api/git/brews/${brew.editId}/pull`).set(version).set(asAccount(ALICE()));
|
||||
expect(res.status).toBe(200);
|
||||
const after = await storage.brews.findByEditId(brew.editId);
|
||||
expect(after).toMatchObject({ title: 'Neu von außen', version: brew.version + 1 });
|
||||
expect(after.text).toContain('Remote-Text');
|
||||
expect(res.body).toMatchObject({ linked: true, lastCommitSha: remote.head(dir, 'main'), lastError: null });
|
||||
});
|
||||
|
||||
test('Pull liest Brew unter dem Lock neu: Metadaten eines gleichzeitigen Saves bleiben erhalten', async ()=>{
|
||||
const { dir, brew } = await linked();
|
||||
remote.commitFile(dir, 'main', 'brews/b.md', 'Remote-Text\n');
|
||||
const release = await svc.locks.acquireKey(brew.id);
|
||||
const pending = request.post(`/api/git/brews/${brew.editId}/pull`).set(version).set(asAccount(ALICE())).then((r)=>r);
|
||||
await new Promise((r)=>setTimeout(r, 200)); // Pull hat den Brew gelesen und wartet auf den Lock
|
||||
const current = await storage.brews.findByEditId(brew.editId);
|
||||
await storage.brews.update({ ...current, tags: ['gleichzeitig'], version: current.version + 1 });
|
||||
release();
|
||||
const res = await pending;
|
||||
expect(res.status).toBe(200);
|
||||
const after = await storage.brews.findByEditId(brew.editId);
|
||||
expect(after.tags).toEqual(['gleichzeitig']);
|
||||
expect(after.version).toBe(current.version + 2);
|
||||
expect(after.text).toContain('Remote-Text');
|
||||
});
|
||||
|
||||
test('Öffnen holt externe Änderungen, ohne Änderung bleibt der Snapshot', async ()=>{
|
||||
const { dir, brew } = await linked();
|
||||
const a = asAccount(ALICE());
|
||||
await request.get(`/edit/${brew.editId}`).set(a).expect(200);
|
||||
expect((await storage.brews.findByEditId(brew.editId)).version).toBe(brew.version);
|
||||
remote.commitFile(dir, 'main', 'brews/b.md', 'Extern geändert');
|
||||
await request.get(`/edit/${brew.editId}`).set(a).expect(200);
|
||||
const after = await storage.brews.findByEditId(brew.editId);
|
||||
expect(after.text).toBe('Extern geändert');
|
||||
expect(after.version).toBe(brew.version + 1);
|
||||
});
|
||||
|
||||
test('hängender Server: Editor öffnet nach höchstens HB_GIT_OPEN_TIMEOUT_MS + 500 ms, last_error=G04, keine Reste', async ()=>{
|
||||
const { brew } = await linked();
|
||||
remote.setHang(true);
|
||||
const t0 = Date.now();
|
||||
const res = await request.get(`/edit/${brew.editId}`).set(asAccount(ALICE()));
|
||||
const took = Date.now() - t0;
|
||||
remote.setHang(false);
|
||||
expect(res.status).toBe(200);
|
||||
expect(took).toBeLessThan(cfg.openTimeoutMs + 500);
|
||||
const link = await storage.brewGitLinks.findByBrewId(brew.id);
|
||||
expect(link.lastError).toBe('G04');
|
||||
expect((await storage.brews.findByEditId(brew.editId)).text).toContain('Version 1');
|
||||
const left = leftovers();
|
||||
expect(left.procs).toEqual([]);
|
||||
expect(left.dirs).toEqual([]);
|
||||
expect(svc.locks.keyCount).toBe(0);
|
||||
// der Status zeigt den Fehler, ein späterer Abgleich löscht ihn
|
||||
expect((await request.get(`/api/git/brews/${brew.editId}`).set(version).set(asAccount(ALICE()))).body.lastError).toBe('G04');
|
||||
await request.get(`/edit/${brew.editId}`).set(asAccount(ALICE())).expect(200);
|
||||
expect((await storage.brewGitLinks.findByBrewId(brew.id)).lastError).toBeNull();
|
||||
});
|
||||
|
||||
test('Abgleich ohne Anmeldung oder Bearbeitungsrecht greift nicht auf Git zu', async ()=>{
|
||||
const { brew } = await linked();
|
||||
remote.requests.length = 0;
|
||||
await request.get(`/edit/${brew.editId}`).expect(200);
|
||||
await request.get(`/edit/${brew.editId}`).set(asAccount({ username: 'dave' })).expect(200);
|
||||
expect(remote.requests).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Aufräumen', ()=>{
|
||||
test('nach allen Operationen bleiben weder git-Prozesse noch temporäre Verzeichnisse', ()=>{
|
||||
const left = leftovers();
|
||||
expect(left.procs).toEqual([]);
|
||||
expect(left.dirs).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
// Lokales Git-Remote für Tests (ADR 0003, "Tests"): `git http-backend` hinter einem kleinen Node-HTTP-Server mit
|
||||
// Basic-Auth-Prüfung. Repos liegen als Bare-Repos mit uploadpack.allowFilter=true und http.receivepack=true.
|
||||
import http from 'http';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { execFileSync, spawn } from 'child_process';
|
||||
|
||||
const git = (args, opts = {})=>execFileSync('git', args, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], ...opts }).trim();
|
||||
|
||||
export const startGitHttpServer = async ({ username = 'tester', token = 'secret-token-123' } = {})=>{
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hb-git-remote-'));
|
||||
let hang = false;
|
||||
const requests = [];
|
||||
|
||||
const server = http.createServer((req, res)=>{
|
||||
requests.push(`${req.method} ${req.url}`);
|
||||
if(hang) return; // antwortet nie
|
||||
const auth = req.headers.authorization;
|
||||
const expected = `Basic ${Buffer.from(`${username}:${token}`).toString('base64')}`;
|
||||
if(auth !== expected) {
|
||||
res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="git"' });
|
||||
return res.end('unauthorized');
|
||||
}
|
||||
const url = new URL(req.url, 'http://x');
|
||||
const chunks = [];
|
||||
req.on('data', (c)=>chunks.push(c));
|
||||
req.on('end', ()=>{
|
||||
const body = Buffer.concat(chunks);
|
||||
const cgi = spawn('git', ['http-backend'], {
|
||||
env : {
|
||||
PATH : process.env.PATH,
|
||||
GIT_PROJECT_ROOT : root,
|
||||
GIT_HTTP_EXPORT_ALL : '1',
|
||||
REQUEST_METHOD : req.method,
|
||||
PATH_INFO : url.pathname,
|
||||
QUERY_STRING : url.search.slice(1),
|
||||
CONTENT_TYPE : req.headers['content-type'] || '',
|
||||
CONTENT_LENGTH : String(body.length),
|
||||
REMOTE_USER : username,
|
||||
REMOTE_ADDR : '127.0.0.1',
|
||||
HTTP_CONTENT_ENCODING : req.headers['content-encoding'] || '',
|
||||
HTTP_GIT_PROTOCOL : req.headers['git-protocol'] || ''
|
||||
}
|
||||
});
|
||||
cgi.stdin.on('error', ()=>{});
|
||||
cgi.stdin.end(body);
|
||||
const out = [];
|
||||
cgi.stdout.on('data', (c)=>out.push(c));
|
||||
cgi.on('close', ()=>{
|
||||
const buf = Buffer.concat(out);
|
||||
const sep = buf.indexOf('\r\n\r\n');
|
||||
if(sep < 0) { res.writeHead(500); return res.end(); }
|
||||
const headers = {};
|
||||
let status = 200;
|
||||
for (const line of buf.subarray(0, sep).toString().split('\r\n')) {
|
||||
const i = line.indexOf(':');
|
||||
if(i < 0) continue;
|
||||
const k = line.slice(0, i).trim();
|
||||
const v = line.slice(i + 1).trim();
|
||||
if(k.toLowerCase() === 'status') status = parseInt(v, 10); else headers[k] = v;
|
||||
}
|
||||
res.writeHead(status, headers);
|
||||
res.end(buf.subarray(sep + 4));
|
||||
});
|
||||
});
|
||||
});
|
||||
await new Promise((resolve)=>server.listen(0, '127.0.0.1', resolve));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
|
||||
return {
|
||||
base, username, token, requests, root,
|
||||
dirOf : (name)=>path.join(root, name),
|
||||
setHang : (v)=>{ hang = v; },
|
||||
// Legt ein leeres Bare-Repo an und liefert URL + Pfad
|
||||
createRepo : (name = 'r.git')=>{
|
||||
const dir = path.join(root, name);
|
||||
git(['init', '--bare', '-q', '-b', 'main', dir]);
|
||||
git(['-C', dir, 'config', 'uploadpack.allowFilter', 'true']);
|
||||
git(['-C', dir, 'config', 'uploadpack.allowAnySHA1InWant', 'true']);
|
||||
git(['-C', dir, 'config', 'http.receivepack', 'true']);
|
||||
return { url: `${base}/${name}`, dir };
|
||||
},
|
||||
// Commit direkt im Bare-Repo (simuliert Push eines Dritten). Liefert die Commit-ID.
|
||||
commitFile : (dir, branch, filePath, content, message = 'extern')=>{
|
||||
const env = { ...process.env, GIT_AUTHOR_NAME: 'Dritter', GIT_AUTHOR_EMAIL: 'd@example.test', GIT_COMMITTER_NAME: 'Dritter', GIT_COMMITTER_EMAIL: 'd@example.test', GIT_INDEX_FILE: path.join(dir, 'tmp-idx') };
|
||||
let parent;
|
||||
try { parent = git(['-C', dir, 'rev-parse', '--verify', `refs/heads/${branch}`]); } catch {}
|
||||
if(parent) git(['-C', dir, 'read-tree', parent], { env });
|
||||
const blob = git(['-C', dir, 'hash-object', '-w', '--stdin'], { input: content, env });
|
||||
git(['-C', dir, 'update-index', '--add', '--cacheinfo', `100644,${blob},${filePath}`], { env });
|
||||
const tree = git(['-C', dir, 'write-tree'], { env });
|
||||
const commit = git(['-C', dir, 'commit-tree', tree, ...(parent ? ['-p', parent] : []), '-m', message], { env });
|
||||
git(['-C', dir, 'update-ref', `refs/heads/${branch}`, commit]);
|
||||
fs.rmSync(env.GIT_INDEX_FILE, { force: true });
|
||||
return commit;
|
||||
},
|
||||
readFile : (dir, branch, filePath)=>git(['-C', dir, 'show', `refs/heads/${branch}:${filePath}`]),
|
||||
log : (dir, branch)=>git(['-C', dir, 'log', '--format=%an|%cn|%s', `refs/heads/${branch}`]).split('\n'),
|
||||
head : (dir, branch)=>git(['-C', dir, 'rev-parse', `refs/heads/${branch}`]),
|
||||
close : async ()=>{
|
||||
await new Promise((resolve)=>{ server.closeAllConnections?.(); server.close(resolve); });
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
// In-Memory-Storage mit dem Repository-Vertrag aus ADR 0002/0003 (nur für Tests ohne Datenbank).
|
||||
export const createMemoryStorage = ()=>{
|
||||
const users = new Map(); const brews = new Map(); const conns = new Map(); const links = new Map();
|
||||
const clone = (o)=>o ? structuredClone(o) : null;
|
||||
return {
|
||||
users : {
|
||||
async create(u) { const user = { id: randomUUID(), displayName: null, ...u }; users.set(user.id, user); return clone(user); },
|
||||
async findById(id) { return clone(users.get(id)); }
|
||||
},
|
||||
brews : {
|
||||
async create(b) { const brew = { ...b, id: randomUUID(), editId: b.editId ?? `e${randomUUID().slice(0, 11)}`, shareId: b.shareId ?? `s${randomUUID().slice(0, 11)}`, version: b.version ?? 1 }; brews.set(brew.id, brew); return clone(brew); },
|
||||
async findByEditId(editId) { return clone([...brews.values()].find((b)=>b.editId === editId)); },
|
||||
async update(b) { if(!brews.has(b.id)) return null; brews.set(b.id, { ...brews.get(b.id), ...b }); return clone(brews.get(b.id)); },
|
||||
async deleteById(id) { links.delete(id); return brews.delete(id); }
|
||||
},
|
||||
gitConnections : {
|
||||
async create(c) { const conn = { createdAt: new Date(), updatedAt: new Date(), lastVerifiedAt: null, authUsername: 'git', brewDir: 'brews', assetsDir: 'assets', ...c }; conns.set(conn.id, conn); return clone(conn); },
|
||||
async findById(id) { return clone(conns.get(id)); },
|
||||
async findByIdForOwner(id, uid) { const c = conns.get(id); return c && c.ownerUserId === uid ? clone(c) : null; },
|
||||
async listByOwner(uid) { return [...conns.values()].filter((c)=>c.ownerUserId === uid).map(clone); },
|
||||
async update(id, patch) { if(!conns.has(id)) return null; Object.assign(conns.get(id), patch); return clone(conns.get(id)); },
|
||||
async delete(id) { for (const [k, l] of links)if(l.connectionId === id) links.delete(k); return conns.delete(id); }
|
||||
},
|
||||
brewGitLinks : {
|
||||
async upsert({ brewId, ...rest }) {
|
||||
for (const [k, l] of links)if(k !== brewId && l.connectionId === rest.connectionId && l.branch === rest.branch && l.path === rest.path) throw new Error('unique');
|
||||
links.set(brewId, { lastCommitSha: null, lastBlobSha: null, lastSyncedAt: null, lastError: null, ...links.get(brewId), brewId, ...rest }); return clone(links.get(brewId));
|
||||
},
|
||||
async findByBrewId(id) { return clone(links.get(id)); },
|
||||
async findByLocation(cid, branch, path) { return clone([...links.values()].find((l)=>l.connectionId === cid && l.branch === branch && l.path === path)); },
|
||||
async update(id, patch) { if(!links.has(id)) return null; Object.assign(links.get(id), patch); return clone(links.get(id)); },
|
||||
async delete(id) { return links.delete(id); }
|
||||
}
|
||||
};
|
||||
};
|
||||
Reference in new issue
Block a user