diff --git a/.github/workflows/markt.yml b/.github/workflows/markt.yml new file mode 100644 index 0000000..b6d35df --- /dev/null +++ b/.github/workflows/markt.yml @@ -0,0 +1,257 @@ +name: markt + +# Bringt eine neue Lunch-Version ohne Handgriff in den Markt +# (aimighty/aimighty-market): Nach einem Release baut sie den Eintrag auf dem +# frischen main des Markts (scripts/markt-eintrag.py — legt ihn beim ersten +# Mal an), beweist ihn mit wrangler (scripts/markt-beweis.sh), öffnet im Markt +# einen PR und mergt ihn (Squash), prüft main und meldet den Deploy-Lauf. +# Muster: aimighty/rocket .github/workflows/markt.yml. +# +# Braucht MARKT_TOKEN (Organisations-Geheimnis in aimighty). Run workflow mit +# „probe“ (Vorgabe) baut und beweist, ohne etwas zu schreiben; ein PR, der +# Markt-Texte oder diese Maschinerie ändert, macht dieselbe Probe. + +on: + pull_request: + paths: [olares/markt/**, olares/OlaresManifest.yaml, scripts/markt-*, .github/workflows/markt.yml] + # Nach einem Release: release.yml startet diesen Lauf selbst, mit der + # Version, sobald Tag und Release stehen (wie Rocket und Relay). + # Nicht mehr „workflow_run“: Das startete nach jedem Lauf von release.yml, + # auch einem ohne Tag, und so ein leerer Lauf verdrängte bei Relay den + # echten aus der Warteschlange (26.10.39 kam nicht in den Markt). + workflow_dispatch: + inputs: + probe: + description: "Probe: Eintrag bauen und beweisen, nichts schreiben" + type: boolean + default: true + version: + description: "Lunch-Version ohne v (z. B. 26.11.2); leer = olares/Chart.yaml" + required: false + +# Einer zur Zeit für den echten Eintrag (er baut auf frischem main des +# Markts und pusht). Die Probe im PR schreibt nichts und läuft je Zweig — +# bis 26.10.2026 teilten sich alle Läufe eine Gruppe, und zwei offene PRs +# brachen sich gegenseitig ab; Gitea meldet „cancelled“ als rot (#53). +concurrency: + group: markt-${{ github.event_name == 'pull_request' && github.head_ref || 'eintrag' }} + cancel-in-progress: false + +jobs: + eintrag: + # Nur ein echtes Release: Ein Lauf von release.yml ohne neuen Tag (Merge + # ohne Versionssprung) endet in „Der Markt kennt … schon“. + if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' + runs-on: ubuntu-latest + env: + MARKT_TOKEN: ${{ secrets.MARKT_TOKEN }} + GITEA: https://git.aimighty.olares.de + UPSTREAM: aimighty/aimighty-market + # Kennung, unter der die Boxen den Markt eingetragen haben (Marc + # bestätigt, 6.10.2026). Groß- und Kleinschreibung zählen; meldet sich + # der Markt anders, übernimmt die Box kein Update. aimighty/rocket docs/MARKT.md + # „Kennung des Markts“. + MARKT_QUELLE: market.aimighty + PROBE: ${{ github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && inputs.probe) }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.workflow_run.head_sha || github.event.pull_request.head.sha || github.sha }} + + - name: Version + id: v + run: | + V="${{ inputs.version }}" + if [ -z "$V" ] && [ "${{ github.event_name }}" = "pull_request" ]; then + # Die neueste Notiz: die Version, die das nächste Release bringt. + V=$(ls olares/markt | sed -n 's/^\([0-9]*\.[0-9]*\.[0-9]*\)\.md$/\1/p' | sort -V | tail -1) + fi + [ -n "$V" ] || V=$(awk '/^version:/{print $2}' olares/Chart.yaml | tr -d '"') + echo "version=$V" >> "$GITHUB_OUTPUT" + if [ "$PROBE" = "true" ]; then + echo "### Probelauf: Lunch $V für den Markt bauen und beweisen, nichts schreiben" >> "$GITHUB_STEP_SUMMARY" + else + echo "### Lunch $V in den Markt" >> "$GITHUB_STEP_SUMMARY" + fi + + - name: Token vorhanden? + id: token + run: | + if [ "$PROBE" = "true" ]; then + echo "weiter=true" >> "$GITHUB_OUTPUT" + elif [ -z "$MARKT_TOKEN" ]; then + echo "Kein Geheimnis MARKT_TOKEN — der Eintrag geht von Hand (aimighty/rocket docs/MARKT.md)." >> "$GITHUB_STEP_SUMMARY" + echo "weiter=false" >> "$GITHUB_OUTPUT" + else + echo "weiter=true" >> "$GITHUB_OUTPUT" + fi + + # Der Release-Anhang ist das Chart, das in den Markt geht. Eine Probe + # für eine Version ohne Release packt stattdessen das Chart dieses + # Stands. Helm aus aimighty/ci-tools: get.helm.sh ist vom Runner nicht + # erreichbar. + - name: install helm 3.16.2 + if: steps.token.outputs.weiter == 'true' + run: | + for url in \ + "$GITEA/aimighty/ci-tools/releases/download/helm-3.16.2/helm-v3.16.2-linux-amd64.tar.gz" \ + "https://get.helm.sh/helm-v3.16.2-linux-amd64.tar.gz"; do + if curl -fsSL --retry 3 --retry-all-errors --max-time 180 -o /tmp/helm.tgz "$url" \ + && tar -tzf /tmp/helm.tgz >/dev/null 2>&1; then + break + fi + done + tar -C /tmp -xzf /tmp/helm.tgz + install -m 0755 /tmp/linux-amd64/helm /usr/local/bin/helm + + - name: Chart holen + if: steps.token.outputs.weiter == 'true' + env: + V: ${{ steps.v.outputs.version }} + run: | + AUTH=(); [ -n "$MARKT_TOKEN" ] && AUTH=(-H "Authorization: token $MARKT_TOKEN") + URL=$(curl -sS "${AUTH[@]}" "$GITEA/api/v1/repos/$GITHUB_REPOSITORY/releases/tags/v$V" \ + | python3 -c "import sys,json; d=json.load(sys.stdin); print(next((a['browser_download_url'] for a in d.get('assets') or [] if a['name']==sys.argv[1]), ''))" "lunch-$V.tgz" || true) + if [ -n "$URL" ] && curl -fsSL "${AUTH[@]}" -o "$RUNNER_TEMP/lunch-$V.tgz" "$URL"; then + echo "Chart aus dem Release v$V." + elif [ "$PROBE" = "true" ]; then + helm package olares -d "$RUNNER_TEMP" --version "$V" --app-version "$V" + echo "Kein Release v$V — Chart aus diesem Stand gepackt (nur Probe)." + else + echo "::error::Release v$V hat kein lunch-$V.tgz"; exit 1 + fi + echo "SHA=$(sha256sum "$RUNNER_TEMP/lunch-$V.tgz" | cut -d' ' -f1)" >> "$GITHUB_ENV" + + - name: Markt frisch holen, Eintrag bauen + if: steps.token.outputs.weiter == 'true' + id: bau + env: + V: ${{ steps.v.outputs.version }} + run: | + if [ -n "$MARKT_TOKEN" ]; then + git clone -q "https://aimighty-bot:${MARKT_TOKEN}@${GITEA#https://}/${UPSTREAM}.git" "$RUNNER_TEMP/markt" + else + git clone -q "$GITEA/${UPSTREAM}.git" "$RUNNER_TEMP/markt" + fi + cd "$RUNNER_TEMP/markt" + BASIS=$(git rev-parse HEAD) + echo "basis=$BASIS" >> "$GITHUB_OUTPUT" + # Was sich seit dem letzten Lunch-Eintrag geändert hat — steht im + # PR, damit sichtbar ist, wenn sich der Markt selbst bewegt hat. + LETZTER=$(git log --format=%H --grep='^lunch ' -1 || true) + { + echo "" + echo "Seit dem letzten Lunch-Eintrag auf main:" + echo '```' + if [ -n "$LETZTER" ]; then git log --format='%h %an %s' "$LETZTER..HEAD" -- functions/; git diff --stat "$LETZTER" HEAD -- functions/ ':!functions/_apps.ts'; fi + echo '```' + } > "$RUNNER_TEMP/seit.md" + set +e + TITEL=$(python3 "$GITHUB_WORKSPACE/scripts/markt-eintrag.py" --markt . \ + --chart "$RUNNER_TEMP/lunch-$V.tgz" --version "$V" \ + --repo "$GITHUB_WORKSPACE" --pr-text "$RUNNER_TEMP/pr.md" --quelle "$MARKT_QUELLE") + RC=$? + set -e + if [ $RC -eq 3 ]; then + echo "Der Markt kennt Lunch $V schon — nichts zu tun." | tee -a "$GITHUB_STEP_SUMMARY" + echo "noetig=false" >> "$GITHUB_OUTPUT"; exit 0 + fi + [ $RC -eq 0 ] || exit $RC + cat "$RUNNER_TEMP/seit.md" >> "$RUNNER_TEMP/pr.md" + echo "titel=$TITEL" >> "$GITHUB_OUTPUT" + echo "noetig=true" >> "$GITHUB_OUTPUT" + git diff --stat + + - uses: actions/setup-node@v4 + if: steps.bau.outputs.noetig == 'true' + with: + node-version: 22 + + - name: Mit wrangler beweisen + if: steps.bau.outputs.noetig == 'true' + env: + V: ${{ steps.v.outputs.version }} + run: bash scripts/markt-beweis.sh "$RUNNER_TEMP/markt" "$V" "$SHA" + + - name: Probe endet hier + if: steps.bau.outputs.noetig == 'true' && env.PROBE == 'true' + run: | + echo "Probe bestanden — so ginge der PR in den Markt:" + echo "" + cat "$RUNNER_TEMP/pr.md" + + - name: Zweig, PR, Merge (Gitea) + if: steps.bau.outputs.noetig == 'true' && env.PROBE != 'true' + env: + V: ${{ steps.v.outputs.version }} + TITEL: ${{ steps.bau.outputs.titel }} + BASIS: ${{ steps.bau.outputs.basis }} + run: | + cd "$RUNNER_TEMP/markt" + REMOTE="https://aimighty-bot:${MARKT_TOKEN}@${GITEA#https://}/${UPSTREAM}.git" + git config user.name "aimighty-bot" + git config user.email "aimighty-bot@aimighty.local" + git checkout -q -b "lunch-$V" + git add functions/_apps.ts functions/_lib.ts + # Ein Eintrag ändert beide Dateien. + case "$(git diff --cached --name-only | sort | tr '\n' ' ')" in + "functions/_apps.ts functions/_lib.ts ") ;; + *) echo "unerwartete Dateien"; git diff --cached --name-only; exit 1 ;; + esac + git commit -q -m "$TITEL" + git push -q -f "$REMOTE" "lunch-$V" + # main darf sich seit dem Bau nicht bewegt haben (MARKT.md, Regel 4): + # sonst stimmt der Zeitstempel womöglich nicht mehr. Dann neu starten. + JETZT=$(git ls-remote "$REMOTE" refs/heads/main | cut -f1) + [ "$JETZT" = "$BASIS" ] || { echo "main hat sich bewegt ($BASIS → $JETZT) — Workflow neu starten" | tee -a "$GITHUB_STEP_SUMMARY"; exit 1; } + API="$GITEA/api/v1/repos/$UPSTREAM" + HEAD_SHA=$(git rev-parse HEAD) + PRJSON=$(python3 -c 'import json,sys; print(json.dumps({"head":"lunch-"+sys.argv[1],"base":"main","title":sys.argv[2],"body":open(sys.argv[3]).read()}))' "$V" "$TITEL" "$RUNNER_TEMP/pr.md") + RESP=$(curl -sS -X POST -H "Authorization: token $MARKT_TOKEN" -H "Content-Type: application/json" "$API/pulls" -d "$PRJSON") + URL=$(printf '%s' "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('html_url',''))") + NUM=$(printf '%s' "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('number',''))") + [ -n "$URL" ] && [ -n "$NUM" ] || { echo "PR-Anlage fehlgeschlagen"; printf '%s\n' "$RESP" | head -c 300; exit 1; } + echo "PR: $URL" | tee -a "$GITHUB_STEP_SUMMARY" + MERGEJSON=$(python3 -c 'import json,sys; print(json.dumps({"Do":"squash","merge_title_field":sys.argv[1]+" (#"+sys.argv[2]+")","head_commit_id":sys.argv[3],"delete_branch_after_merge":True}))' "$TITEL" "$NUM" "$HEAD_SHA") + curl -fsS -X POST -H "Authorization: token $MARKT_TOKEN" -H "Content-Type: application/json" "$API/pulls/$NUM/merge" -d "$MERGEJSON" > /dev/null + echo "PR_NUM=$NUM" >> "$GITHUB_ENV" + echo "PR_URL=$URL" >> "$GITHUB_ENV" + + - name: Auf main prüfen, Deploy-Lauf melden + if: steps.bau.outputs.noetig == 'true' && env.PROBE != 'true' + env: + V: ${{ steps.v.outputs.version }} + run: | + API="$GITEA/api/v1/repos/$UPSTREAM" + PR=$(curl -sS -H "Authorization: token $MARKT_TOKEN" "$API/pulls/$PR_NUM") + printf '%s' "$PR" | python3 -c "import sys,json; sys.exit(0 if json.load(sys.stdin).get('merged') else 1)" || { echo "PR nicht gemergt"; exit 1; } + MERGE=$(printf '%s' "$PR" | python3 -c "import sys,json; print(json.load(sys.stdin).get('merge_commit_sha') or '')") + [ -n "$MERGE" ] || { echo "Merge-Commit nicht gefunden"; exit 1; } + rm -rf "$RUNNER_TEMP/pruef" + git clone -q --depth 1 "https://aimighty-bot:${MARKT_TOKEN}@${GITEA#https://}/${UPSTREAM}.git" "$RUNNER_TEMP/pruef" + # Der Heredoc ohne Einrückung an python (aimighty/insilo: auf einem + # anderen Runner kam er eingerückt an und brach). + sed 's/^[[:space:]]*//' <<'PY' | python3 - "$RUNNER_TEMP/pruef/functions/_lib.ts" "$V" "$SHA" + import base64, hashlib, re, sys + lib, v, sha = open(sys.argv[1]).read(), sys.argv[2], sys.argv[3] + keys = re.findall(r'"(lunch-[0-9.]+\.tgz)": "([A-Za-z0-9+/=]+)"', lib) + assert [k for k, _ in keys] == [f"lunch-{v}.tgz"], f"Lunch-Schlüssel auf main: {[k for k, _ in keys]}" + assert hashlib.sha256(base64.b64decode(keys[0][1])).hexdigest() == sha, "Chart auf main weicht ab" + print(f"main: lunch-{v}.tgz byte-gleich, keine alten Schlüssel") + PY + grep -qF "export const SOURCE_ID = \"$MARKT_QUELLE\";" "$RUNNER_TEMP/pruef/functions/_lib.ts" \ + || { echo "SOURCE_ID auf main ist nicht $MARKT_QUELLE"; exit 1; } + echo "main: SOURCE_ID $MARKT_QUELLE" | tee -a "$GITHUB_STEP_SUMMARY" + # Der Deploy im Markt wird gesucht, nicht abgewartet: Er braucht + # denselben, einzigen Runner und startet erst nach diesem Lauf. + RUN="" + for _ in $(seq 1 12); do + RUN=$(curl -sS -H "Authorization: token $MARKT_TOKEN" "$API/actions/runs?head_sha=$MERGE&limit=5" | python3 -c "import sys,json; d=json.load(sys.stdin).get('workflow_runs',[]); r=[x for x in d if 'deploy.yml' in (x.get('path') or '')]; print(r[0]['id'] if r else '')" || true) + [ -n "$RUN" ] && break; sleep 5 + done + if [ -n "$RUN" ]; then + echo "Deploy-Lauf im Markt: $GITEA/$UPSTREAM/actions/runs/$RUN (startet, sobald dieser Lauf den Runner freigibt)" | tee -a "$GITHUB_STEP_SUMMARY" + else + echo "Deploy-Lauf zum Merge $MERGE nicht gefunden — im Markt-Repo unter Actions nachsehen." | tee -a "$GITHUB_STEP_SUMMARY" + fi + echo "Lunch $V steht im Markt: $PR_URL" | tee -a "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 311cba0..50c4000 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -272,5 +272,12 @@ jobs: echo "Tag und Release v$VERSION angelegt" echo "### Tag und Release v$VERSION angelegt" >> "${GITHUB_STEP_SUMMARY:-/dev/null}" - # Der Markt-Eintrag (markt.yml) kommt mit der eigenen Anmeldung; erst - # dann geht Lunch in den Markt (docs/PROJEKTSTART.md). + # Nur ein echtes Release startet markt.yml, mit seiner Version. + - name: start markt for this version + env: + GITEA_TOKEN: ${{ secrets.MARKT_TOKEN }} + run: | + curl -fsS -X POST -H "Authorization: token $GITEA_TOKEN" -H "Content-Type: application/json" \ + "$GITEA_API/repos/$GITHUB_REPOSITORY/actions/workflows/markt.yml/dispatches" \ + -d "{\"ref\":\"main\",\"inputs\":{\"probe\":\"false\",\"version\":\"$VERSION\"}}" + echo "markt für $VERSION angestoßen" | tee -a "${GITHUB_STEP_SUMMARY:-/dev/null}" diff --git a/.login-sicherheit/befunde-2026-11-06.json b/.login-sicherheit/befunde-2026-11-06.json new file mode 100644 index 0000000..b851ef9 --- /dev/null +++ b/.login-sicherheit/befunde-2026-11-06.json @@ -0,0 +1,108 @@ +{ + "projekt": "lunch", + "lauf": "2026-11-06", + "auth_typ": "passkey", + "asvs_level": 2, + "gesamturteil": "solide", + "live_geprueft": true, + "abdeckung": { + "geprueft": 31, + "erfuellt": 26, + "verletzt": 0, + "nicht_anwendbar": 5 + }, + "befunde": [ + { + "id": "passkey-ohne-user-verification", + "titel": "Passkey ohne Prüfung der Person", + "schweregrad": "mittel", + "asvs": [ + "6.5.x" + ], + "datei": "lib/auth/webauthn.ts", + "angriff": "Ein Schlüssel ohne PIN genügt.", + "fix": "userVerification required, requireUserVerification true", + "belegt_durch": "live", + "status": "behoben" + }, + { + "id": "geraet-person-nicht-entfernbar", + "titel": "Verlorenes Gerät und Personen nicht entfernbar", + "schweregrad": "mittel", + "asvs": [ + "7.4.x", + "7.5.x" + ], + "datei": "app/(app)/mehr/page.tsx", + "angriff": "Verlorenes Handy bleibt 180 Tage angemeldet.", + "fix": "Passkey und Person entfernen, Sitzungen hängen am Passkey", + "belegt_durch": "live", + "status": "behoben" + }, + { + "id": "kein-rueckweg-letzter-passkey", + "titel": "Kein Rückweg bei Verlust des letzten Passkeys", + "schweregrad": "mittel", + "asvs": [ + "6.4.x" + ], + "datei": "lib/auth/codes.ts", + "angriff": "Haushalt verloren, wenn das einzige Gerät weg ist.", + "fix": "Wiederherstellungscode in /app/data", + "belegt_durch": "live", + "status": "behoben" + }, + { + "id": "bremse-xff-umgehbar", + "titel": "Bremse über X-Forwarded-For umgehbar", + "schweregrad": "niedrig", + "asvs": [ + "6.3.1" + ], + "datei": "lib/auth/request.ts", + "angriff": "Je Versuch neue vorgetäuschte Adresse.", + "fix": "gemeinsamer Topf je Bremse", + "belegt_durch": "live", + "status": "behoben" + }, + { + "id": "kein-anmeldeprotokoll", + "titel": "Anmeldungen werden nicht protokolliert", + "schweregrad": "niedrig", + "asvs": [ + "16.x" + ], + "datei": "lib/auth/", + "angriff": "Missbrauch bleibt unbemerkt.", + "fix": "Protokolltabelle mit Arbeitspaket 2", + "belegt_durch": "live", + "status": "offen" + }, + { + "id": "sitzung-ohne-hoechstdauer", + "titel": "Sitzung ohne absolute Höchstdauer", + "schweregrad": "info", + "asvs": [ + "7.3.2" + ], + "datei": "lib/auth/session.ts", + "angriff": "Gestohlener Keks bleibt gültig, solange benutzt.", + "fix": "feste Obergrenze erwägen", + "belegt_durch": "live", + "status": "offen" + }, + { + "id": "keine-csp-hsts", + "titel": "Keine CSP, HSTS ungeklärt", + "schweregrad": "niedrig", + "asvs": [ + "3.4.x" + ], + "datei": "next.config.ts", + "angriff": "Härtung gegen XSS und Downgrade fehlt.", + "fix": "CSP mit Nonces, HSTS auf der Box prüfen", + "belegt_durch": "live", + "status": "offen" + } + ] +} diff --git a/CLAUDE.md b/CLAUDE.md index d2ccb5b..9d1c60f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,8 +7,9 @@ > **Plattform:** Olares One (Kubernetes), Repo und CI auf Gitea — kein Supabase, > kein Vercel (E-0001). Eigene Gestaltung, nicht AImighty (E-0002). > Verteilung über den Markt, Repo öffentlich (E-0005). -> **Status:** 26.11.1 — Gerüst, Chart, CI und Release; Arbeitspaket 1 läuft -> (Anmeldung offen, `docs/PROJEKTSTART.md`). +> **Status:** 26.11.2 — Arbeitspaket 1 fertig: Gerüst, Chart, CI, Release, Markt, +> eigene Anmeldung mit Passkeys (E-0006), Entrance `public`. Als Nächstes +> Arbeitspaket 2 (`docs/PROJEKTSTART.md`). > **Letzte Aktualisierung:** 6. November 2026 Diese Datei ist das Gedächtnis jeder Sitzung. Entscheidungen stehen in @@ -88,6 +89,21 @@ Datenmodells (`households`, `dishes`, `rounds`, `slots`, …). --- +## Anmeldung (E-0001, E-0006) + +- Alles in `lib/auth/` und `app/api/auth/`. **`withAuth()`** (`app.auth = on`) + sucht über Haushalte hinweg und ist nur dort erlaubt; jede Fachabfrage läuft + über **`withHousehold(session.householdId, …)`**. `tests/rls.test.ts` hält fest, + welche Tabellen `app_auth()` in der Policy haben dürfen — eine neue gehört nicht dazu. +- Jede Seite unter `app/(app)/` ruft `requireSession()`; jede Route, die etwas + ändert, prüft Sitzung **und** `sameOrigin(request, instance.origin)`. +- Passkeys hängen an der Adresse, unter der eingerichtet wurde (`instance`). + Geheimnisse (Keks, Links, Codes) liegen nur als Hash in der Datenbank. +- Der Ablauf im Browser mit virtuellem Passkey ist die Probe für jede Änderung + hier (Einrichten, Einladen, Anmelden, Gerät, Entfernen, Rückweg); vor einer + größeren Änderung den Skill `login-sicherheit` erneut laufen lassen und den + Bericht unter `docs/sicherheit/` fortschreiben. + ## Plattform: Olares One Dieselben Grenzen wie bei Rocket (`aimighty/rocket`, `CLAUDE.md`) — jede teuer @@ -96,8 +112,9 @@ gelernt: 1. **Namensregel:** Chart-Ordner, `Chart.yaml.name`, `metadata.name`, `metadata.appid` alle exakt `lunch`. 2. **Anmeldung macht die App selbst** (E-0001), weil die Familie kein - Olares-Konto hat; Entrance `public` erst, **nachdem** die eigene Anmeldung - steht — nie umgekehrt, sonst steht die App offen. + Olares-Konto hat; der Entrance ist seit 26.11.2 `public` — erst kam die + eigene Anmeldung, dann die Öffnung. Nie zurück auf einen Olares-Kopf + (`X-Bfl-User`) vertrauen. 3. **Nur ClusterIP.** Kein NodePort, kein LoadBalancer, kein hostNetwork. 4. **Ein Entrance bringt einen Envoy-Sidecar**, der Aufrufe gegen Authelia prüft. Öffentliche Wege (Einladungslink, Magic Link) vorher auf der Box diff --git a/OlaresManifest.yaml b/OlaresManifest.yaml index 544273c..5d3716d 100644 --- a/OlaresManifest.yaml +++ b/OlaresManifest.yaml @@ -21,7 +21,7 @@ metadata: title: What's cooking? description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box. icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png - version: 26.11.1 + version: 26.11.2 categories: - Applications @@ -29,16 +29,18 @@ metadata: # Einer: die App selbst. Ein Entrance bringt dem Pod einen Envoy-Sidecar, der # jeden Aufruf gegen Authelia prüft. # -# `internal`, solange Lunch keine eigene Anmeldung hat: Dann kommt nur herein, -# wer an der Box angemeldet ist. Auf `public` geht er erst, **nachdem** die -# eigene Anmeldung steht (E-0001) — nie umgekehrt, sonst steht die App offen. +# `public` seit 26.11.2: Die Familie hat kein Olares-Konto, also meldet Lunch +# selbst an (Passkeys, lib/auth/, E-0001). Die Reihenfolge war die Sicherheit: +# erst die eigene Anmeldung (26.11.2), dann öffnen — nie umgekehrt. Ohne +# Haushalt verlangt die App den Einrichtungscode aus /app/data; ein Kopf wie +# X-Bfl-User gilt nirgends. scripts/check-chart.sh wacht. entrances: - name: lunch host: lunch port: 3000 title: What's cooking? icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png - authLevel: internal + authLevel: public invisible: false openMethod: window @@ -59,7 +61,7 @@ permission: appData: true spec: - versionName: '26.11.1' + versionName: '26.11.2' featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png promoteImage: diff --git a/app/(app)/layout.tsx b/app/(app)/layout.tsx new file mode 100644 index 0000000..cb2cb26 --- /dev/null +++ b/app/(app)/layout.tsx @@ -0,0 +1,17 @@ +import { AppNav } from "@/components/app-nav"; +import { requireSession } from "@/lib/auth/session"; + +// Alles hier drin verlangt eine Sitzung. Die Prüfung steht im Layout und +// zusätzlich in jeder Seite, die Daten liest (requireSession) — Layouts +// werden beim Navigieren nicht jedes Mal neu ausgeführt. +export const dynamic = "force-dynamic"; + +export default async function AppLayout({ children }: { children: React.ReactNode }) { + await requireSession(); + return ( + <> +
{children}
+ + + ); +} diff --git a/app/(app)/mehr/page.tsx b/app/(app)/mehr/page.tsx new file mode 100644 index 0000000..2c6dd6a --- /dev/null +++ b/app/(app)/mehr/page.tsx @@ -0,0 +1,85 @@ +import { getLocale, getTranslations } from "next-intl/server"; +import { AddDevice, InvitePerson } from "@/components/more/invite-panel"; +import { LanguageSelect, SignOutButton } from "@/components/more/account-actions"; +import { RemoveButton } from "@/components/more/remove-button"; +import { requireSession } from "@/lib/auth/session"; +import { withHousehold } from "@/lib/db"; +import { isLocale } from "@/lib/locale"; + +function Section({ title, children }: { title: string; children: React.ReactNode }) { + return ( +
+

{title}

+ {children} +
+ ); +} + +export default async function MorePage() { + const session = await requireSession(); + const t = await getTranslations("more"); + const locale = await getLocale(); + const { members, passkeys } = await withHousehold(session.householdId, async (client) => { + const members = (await client.query("select id, display_name, role from members order by created_at")).rows; + const passkeys = ( + await client.query("select id, label, created_at, last_used_at from passkeys where member_id = $1 order by created_at", [ + session.memberId, + ]) + ).rows; + return { members, passkeys }; + }); + const date = new Intl.DateTimeFormat(locale, { dateStyle: "medium" }); + + return ( +
+

{t("title")}

+ +
+

{t("members")}

+
    + {members.map((m) => ( +
  • + + {m.display_name} + {m.id === session.memberId ? ({t("you")}) : null} + + + {t(`roles.${m.role}`)} + {session.role === "owner" && m.role !== "owner" ? : null} + +
  • + ))} +
+
+ + {session.role === "owner" ? ( +
+ +
+ ) : null} + +
+
    + {passkeys.map((p) => ( +
  • + {p.label || "Passkey"} + + {date.format(p.last_used_at ?? p.created_at)} + {passkeys.length > 1 ? : null} + +
  • + ))} +
+ {passkeys.length > 1 ?

{t("removeHint")}

: null} +

{t("addDevice")}

+ +
+ +
+ +
+ + +
+ ); +} diff --git a/app/page.tsx b/app/(app)/page.tsx similarity index 70% rename from app/page.tsx rename to app/(app)/page.tsx index 890bc36..d1417f0 100644 --- a/app/page.tsx +++ b/app/(app)/page.tsx @@ -1,11 +1,13 @@ import { CookingPot } from "lucide-react"; import { getTranslations } from "next-intl/server"; +import { requireSession } from "@/lib/auth/session"; // „Heute“ — vorerst nur der leere Zustand. Er sagt, was als Nächstes kommt. export default async function TodayPage() { + await requireSession(); const t = await getTranslations("today"); return ( -
+

{t("emptyTitle")}

{t("emptyText")}

diff --git a/app/anmelden/page.tsx b/app/anmelden/page.tsx new file mode 100644 index 0000000..b07b05e --- /dev/null +++ b/app/anmelden/page.tsx @@ -0,0 +1,18 @@ +import { redirect } from "next/navigation"; +import { getTranslations } from "next-intl/server"; +import { AuthShell } from "@/components/auth/auth-shell"; +import { LoginButton } from "@/components/auth/login-button"; +import { getSession, isSetUp } from "@/lib/auth/session"; + +export const dynamic = "force-dynamic"; + +export default async function SignInPage() { + if (!(await isSetUp())) redirect("/einrichten"); + if (await getSession()) redirect("/"); + const t = await getTranslations("auth.login"); + return ( + + + + ); +} diff --git a/app/api/auth/invite/options/route.ts b/app/api/auth/invite/options/route.ts new file mode 100644 index 0000000..0835cf4 --- /dev/null +++ b/app/api/auth/invite/options/route.ts @@ -0,0 +1,46 @@ +import { randomUUID } from "node:crypto"; +import { withAuth } from "@/lib/db"; +import { fail, json, readJson, sameOrigin } from "@/lib/auth/http"; +import { findInvitation } from "@/lib/auth/invitations"; +import { clientIp } from "@/lib/auth/request"; +import { inviteOptionsBody } from "@/lib/auth/schemas"; +import { tooManyAttempts } from "@/lib/auth/throttle"; +import { loadInstance, registrationOptions } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +// Einladung annehmen, Schritt 1: Passkey-Optionen für die neue Person oder +// das neue Gerät einer vorhandenen. +export async function POST(request: Request) { + const body = inviteOptionsBody.safeParse(await readJson(request)); + return withAuth(async (client) => { + const instance = await loadInstance(client); + if (!instance) return fail("notSetUp", 409); + if (!sameOrigin(request, instance.origin)) return fail("origin", 403); + if ( + (await tooManyAttempts(client, `invite:${clientIp(request)}`, 20, 15)) || + (await tooManyAttempts(client, "invite:*", 200, 15)) + ) { + return fail("tooMany", 429); + } + if (!body.success) return fail("invalid", 400); + const invitation = await findInvitation(client, body.data.token); + if (!invitation) return fail("invitation", 410); + + let memberId: string; + let name: string; + let exclude: { id: string; transports: string[] }[] = []; + if (invitation.memberId) { + memberId = invitation.memberId; + name = invitation.memberName ?? ""; + const { rows } = await client.query("select id, transports from passkeys where member_id = $1", [memberId]); + exclude = rows; + } else { + memberId = randomUUID(); + name = body.data.name ?? invitation.displayName ?? ""; + } + if (!name) return fail("invalid", 400); + const context = { invitationId: invitation.id, memberId, isNew: !invitation.memberId, name, householdId: invitation.householdId }; + return json(await registrationOptions(client, instance, { id: memberId, name }, "invite", context, exclude)); + }); +} diff --git a/app/api/auth/invite/verify/route.ts b/app/api/auth/invite/verify/route.ts new file mode 100644 index 0000000..cc119ae --- /dev/null +++ b/app/api/auth/invite/verify/route.ts @@ -0,0 +1,64 @@ +import type { RegistrationResponseJSON } from "@simplewebauthn/server"; +import { withAuth } from "@/lib/db"; +import { fail, isSecure, json, readJson, sameOrigin } from "@/lib/auth/http"; +import { challengeBody } from "@/lib/auth/schemas"; +import { startSession } from "@/lib/auth/session"; +import { deviceLabel, loadInstance, takeChallenge, verifyRegistration } from "@/lib/auth/webauthn"; +import { cookies } from "next/headers"; +import { LOCALE_COOKIE, resolveLocale } from "@/lib/locale"; + +export const dynamic = "force-dynamic"; + +type InviteContext = { invitationId: string; memberId: string; isNew: boolean; name: string; householdId: string }; + +// Einladung annehmen, Schritt 2: Passkey prüfen, die Einladung verbrauchen +// (genau einmal), Person anlegen, falls neu, Sitzung beginnen. +export async function POST(request: Request) { + const body = challengeBody.safeParse(await readJson(request)); + if (!body.success) return fail("invalid", 400); + return withAuth(async (client) => { + const instance = await loadInstance(client); + if (!instance) return fail("notSetUp", 409); + if (!sameOrigin(request, instance.origin)) return fail("origin", 403); + const taken = await takeChallenge(client, body.data.challengeId, "invite"); + if (!taken) return fail("expired", 400); + const ctx = taken.context; + + const passkey = await verifyRegistration(instance, taken.challenge, body.data.response as unknown as RegistrationResponseJSON).catch( + () => null, + ); + if (!passkey) return fail("passkey", 400); + + const used = await client.query( + "update invitations set used_at = now() where id = $1 and used_at is null and expires_at > now() returning id", + [ctx.invitationId], + ); + if (used.rowCount !== 1) return fail("invitation", 410); + + if (ctx.isNew) { + await client.query("insert into members (id, household_id, display_name, role, locale) values ($1, $2, $3, 'adult', $4)", [ + ctx.memberId, + ctx.householdId, + ctx.name, + resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value, request.headers.get("accept-language")), + ]); + } + await client.query( + `insert into passkeys (id, member_id, household_id, public_key, counter, transports, device_type, backed_up, label) + values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, + [ + passkey.id, + ctx.memberId, + ctx.householdId, + passkey.publicKey, + passkey.counter, + passkey.transports, + passkey.deviceType, + passkey.backedUp, + deviceLabel(request.headers.get("user-agent")), + ], + ); + await startSession(client, { id: ctx.memberId, householdId: ctx.householdId, passkeyId: passkey.id }, request, isSecure(instance.origin)); + return json({ ok: true }); + }); +} diff --git a/app/api/auth/login/options/route.ts b/app/api/auth/login/options/route.ts new file mode 100644 index 0000000..7c3eec8 --- /dev/null +++ b/app/api/auth/login/options/route.ts @@ -0,0 +1,24 @@ +import { withAuth } from "@/lib/db"; +import { fail, json, sameOrigin } from "@/lib/auth/http"; +import { clientIp } from "@/lib/auth/request"; +import { tooManyAttempts } from "@/lib/auth/throttle"; +import { authenticationOptions, loadInstance } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +// Anmelden mit Passkey, Schritt 1. Ohne Namen: Der Passkey auf dem Gerät +// weiß selbst, wem er gehört (discoverable credential). +export async function POST(request: Request) { + return withAuth(async (client) => { + const instance = await loadInstance(client); + if (!instance) return fail("notSetUp", 409); + if (!sameOrigin(request, instance.origin)) return fail("origin", 403); + if ( + (await tooManyAttempts(client, `login:${clientIp(request)}`, 30, 15)) || + (await tooManyAttempts(client, "login:*", 600, 15)) + ) { + return fail("tooMany", 429); + } + return json(await authenticationOptions(client, instance)); + }); +} diff --git a/app/api/auth/login/verify/route.ts b/app/api/auth/login/verify/route.ts new file mode 100644 index 0000000..73bc81c --- /dev/null +++ b/app/api/auth/login/verify/route.ts @@ -0,0 +1,41 @@ +import type { AuthenticationResponseJSON } from "@simplewebauthn/server"; +import { withAuth } from "@/lib/db"; +import { fail, isSecure, json, readJson, sameOrigin } from "@/lib/auth/http"; +import { challengeBody } from "@/lib/auth/schemas"; +import { startSession } from "@/lib/auth/session"; +import { loadInstance, takeChallenge, verifyAuthentication } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +// Anmelden mit Passkey, Schritt 2: Signatur prüfen, Zähler fortschreiben, +// Sitzung anlegen. Ein unbekannter Passkey und eine falsche Signatur geben +// dieselbe Antwort. +export async function POST(request: Request) { + const body = challengeBody.safeParse(await readJson(request)); + if (!body.success) return fail("invalid", 400); + return withAuth(async (client) => { + const instance = await loadInstance(client); + if (!instance) return fail("notSetUp", 409); + if (!sameOrigin(request, instance.origin)) return fail("origin", 403); + const taken = await takeChallenge(client, body.data.challengeId, "login"); + if (!taken) return fail("expired", 400); + + const { rows } = await client.query( + "select id, member_id, household_id, public_key, counter, transports from passkeys where id = $1", + [body.data.response.id], + ); + const row = rows[0]; + if (!row) return fail("passkey", 401); + const newCounter = await verifyAuthentication(instance, taken.challenge, body.data.response as unknown as AuthenticationResponseJSON, { + id: row.id, + publicKey: row.public_key, + counter: Number(row.counter), + transports: row.transports, + }).catch(() => null); + if (newCounter === null) return fail("passkey", 401); + + await client.query("update passkeys set counter = $2, last_used_at = now() where id = $1", [row.id, newCounter]); + await startSession(client, { id: row.member_id, householdId: row.household_id, passkeyId: row.id }, request, isSecure(instance.origin)); + return json({ ok: true }); + }); +} diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.ts new file mode 100644 index 0000000..5e32dad --- /dev/null +++ b/app/api/auth/logout/route.ts @@ -0,0 +1,8 @@ +import { endSession } from "@/lib/auth/session"; + +export const dynamic = "force-dynamic"; + +export async function POST() { + await endSession(); + return new Response(null, { status: 204 }); +} diff --git a/app/api/auth/recovery/options/route.ts b/app/api/auth/recovery/options/route.ts new file mode 100644 index 0000000..528ac82 --- /dev/null +++ b/app/api/auth/recovery/options/route.ts @@ -0,0 +1,44 @@ +import { z } from "zod"; +import { withAuth } from "@/lib/db"; +import { recoveryCodeMatches } from "@/lib/auth/codes"; +import { fail, json, readJson, sameOrigin } from "@/lib/auth/http"; +import { clientIp } from "@/lib/auth/request"; +import { tooManyAttempts } from "@/lib/auth/throttle"; +import { loadInstance, registrationOptions } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +// Rückweg, Schritt 1: Code prüfen, Passkey-Optionen für die Person, die den +// Haushalt eingerichtet hat. Sie kann danach unter „Mehr“ verlorene Geräte +// entfernen und andere neu einladen. +export async function POST(request: Request) { + const body = z.object({ code: z.string().min(1).max(64) }).safeParse(await readJson(request)); + return withAuth(async (client) => { + const instance = await loadInstance(client); + if (!instance) return fail("notSetUp", 409); + if (!sameOrigin(request, instance.origin)) return fail("origin", 403); + if ( + (await tooManyAttempts(client, `recovery-code:${clientIp(request)}`, 10, 15)) || + (await tooManyAttempts(client, "recovery-code:*", 100, 60)) + ) { + return fail("tooMany", 429); + } + if (!body.success) return fail("invalid", 400); + if (!(await recoveryCodeMatches(body.data.code))) return fail("code", 401); + + const { rows } = await client.query("select id, household_id, display_name from members where role = 'owner' order by created_at limit 1"); + const owner = rows[0]; + if (!owner) return fail("unknown", 500); + const existing = await client.query("select id, transports from passkeys where member_id = $1", [owner.id]); + return json( + await registrationOptions( + client, + instance, + { id: owner.id, name: owner.display_name }, + "recovery", + { memberId: owner.id, householdId: owner.household_id }, + existing.rows, + ), + ); + }); +} diff --git a/app/api/auth/recovery/request/route.ts b/app/api/auth/recovery/request/route.ts new file mode 100644 index 0000000..d01b3b7 --- /dev/null +++ b/app/api/auth/recovery/request/route.ts @@ -0,0 +1,28 @@ +import { withAuth } from "@/lib/db"; +import { writeRecoveryCode } from "@/lib/auth/codes"; +import { fail, sameOrigin } from "@/lib/auth/http"; +import { clientIp } from "@/lib/auth/request"; +import { tooManyAttempts } from "@/lib/auth/throttle"; +import { loadInstance } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +// Rückweg, Schritt 0: einen Code in die Dateien der Box legen. Verrät nichts +// und gibt niemandem Zugang, der nicht an die Box kommt. +export async function POST(request: Request) { + const allowed = await withAuth(async (client) => { + const instance = await loadInstance(client); + if (!instance) return fail("notSetUp", 409); + if (!sameOrigin(request, instance.origin)) return fail("origin", 403); + if ( + (await tooManyAttempts(client, `recovery:${clientIp(request)}`, 5, 60)) || + (await tooManyAttempts(client, "recovery:*", 20, 60)) + ) { + return fail("tooMany", 429); + } + return null; + }); + if (allowed) return allowed; + await writeRecoveryCode(); + return new Response(null, { status: 204 }); +} diff --git a/app/api/auth/recovery/verify/route.ts b/app/api/auth/recovery/verify/route.ts new file mode 100644 index 0000000..cc25a21 --- /dev/null +++ b/app/api/auth/recovery/verify/route.ts @@ -0,0 +1,49 @@ +import type { RegistrationResponseJSON } from "@simplewebauthn/server"; +import { withAuth } from "@/lib/db"; +import { removeRecoveryCode } from "@/lib/auth/codes"; +import { fail, isSecure, json, readJson, sameOrigin } from "@/lib/auth/http"; +import { challengeBody } from "@/lib/auth/schemas"; +import { startSession } from "@/lib/auth/session"; +import { deviceLabel, loadInstance, takeChallenge, verifyRegistration } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +type RecoveryContext = { memberId: string; householdId: string }; + +export async function POST(request: Request) { + const body = challengeBody.safeParse(await readJson(request)); + if (!body.success) return fail("invalid", 400); + const result = await withAuth(async (client) => { + const instance = await loadInstance(client); + if (!instance) return fail("notSetUp", 409); + if (!sameOrigin(request, instance.origin)) return fail("origin", 403); + const taken = await takeChallenge(client, body.data.challengeId, "recovery"); + if (!taken) return fail("expired", 400); + const passkey = await verifyRegistration(instance, taken.challenge, body.data.response as unknown as RegistrationResponseJSON).catch( + () => null, + ); + if (!passkey) return fail("passkey", 400); + const { memberId, householdId } = taken.context; + await client.query( + `insert into passkeys (id, member_id, household_id, public_key, counter, transports, device_type, backed_up, label) + values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, + [ + passkey.id, + memberId, + householdId, + passkey.publicKey, + passkey.counter, + passkey.transports, + passkey.deviceType, + passkey.backedUp, + deviceLabel(request.headers.get("user-agent")), + ], + ); + await startSession(client, { id: memberId, householdId, passkeyId: passkey.id }, request, isSecure(instance.origin)); + return null; + }); + if (result) return result; + // Einmal benutzt, dann weg. + await removeRecoveryCode(); + return json({ ok: true }); +} diff --git a/app/api/auth/setup/options/route.ts b/app/api/auth/setup/options/route.ts new file mode 100644 index 0000000..7bce87d --- /dev/null +++ b/app/api/auth/setup/options/route.ts @@ -0,0 +1,40 @@ +import { randomUUID } from "node:crypto"; +import { withAuth } from "@/lib/db"; +import { fail, json, readJson } from "@/lib/auth/http"; +import { browserOrigin, clientIp } from "@/lib/auth/request"; +import { setupOptionsBody } from "@/lib/auth/schemas"; +import { setupCodeMatches } from "@/lib/auth/codes"; +import { tooManyAttempts } from "@/lib/auth/throttle"; +import { loadInstance, registrationOptions } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +// Einrichtung, Schritt 1: Code prüfen, Passkey-Optionen für die erste Person. +export async function POST(request: Request) { + const body = setupOptionsBody.safeParse(await readJson(request)); + const origin = browserOrigin(request); + return withAuth(async (client) => { + if (await loadInstance(client)) return fail("alreadySetUp", 409); + if ( + (await tooManyAttempts(client, `setup:${clientIp(request)}`, 10, 15)) || + (await tooManyAttempts(client, "setup:*", 100, 60)) + ) { + return fail("tooMany", 429); + } + if (!body.success) return fail("invalid", 400); + if (!origin) return fail("origin", 400); + if (!(await setupCodeMatches(body.data.code))) return fail("code", 401); + + const memberId = randomUUID(); + const householdId = randomUUID(); + const instance = { origin: origin.origin, rpId: origin.hostname }; + const { challengeId, options } = await registrationOptions( + client, + instance, + { id: memberId, name: body.data.name }, + "setup", + { memberId, householdId, name: body.data.name, household: body.data.household, ...instance }, + ); + return json({ challengeId, options }); + }); +} diff --git a/app/api/auth/setup/verify/route.ts b/app/api/auth/setup/verify/route.ts new file mode 100644 index 0000000..2fc3d14 --- /dev/null +++ b/app/api/auth/setup/verify/route.ts @@ -0,0 +1,62 @@ +import type { RegistrationResponseJSON } from "@simplewebauthn/server"; +import { withAuth } from "@/lib/db"; +import { fail, isSecure, json, readJson } from "@/lib/auth/http"; +import { challengeBody } from "@/lib/auth/schemas"; +import { startSession } from "@/lib/auth/session"; +import { removeSetupCode } from "@/lib/auth/codes"; +import { deviceLabel, loadInstance, takeChallenge, verifyRegistration } from "@/lib/auth/webauthn"; +import { cookies } from "next/headers"; +import { resolveLocale, LOCALE_COOKIE } from "@/lib/locale"; + +export const dynamic = "force-dynamic"; + +type SetupContext = { memberId: string; householdId: string; name: string; household: string; origin: string; rpId: string }; + +// Einrichtung, Schritt 2: Passkey prüfen, dann Box, Haushalt, erste Person, +// Passkey und Sitzung in einer Transaktion anlegen. +export async function POST(request: Request) { + const body = challengeBody.safeParse(await readJson(request)); + if (!body.success) return fail("invalid", 400); + const result = await withAuth(async (client) => { + if (await loadInstance(client)) return fail("alreadySetUp", 409); + const taken = await takeChallenge(client, body.data.challengeId, "setup"); + if (!taken) return fail("expired", 400); + const ctx = taken.context; + const instance = { origin: ctx.origin, rpId: ctx.rpId }; + const passkey = await verifyRegistration(instance, taken.challenge, body.data.response as unknown as RegistrationResponseJSON).catch( + () => null, + ); + if (!passkey) return fail("passkey", 400); + + const locale = resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value, request.headers.get("accept-language")); + await client.query("select set_config('app.household_id', $1, true)", [ctx.householdId]); + await client.query("insert into instance (origin, rp_id) values ($1, $2)", [instance.origin, instance.rpId]); + await client.query("insert into households (id, name) values ($1, $2)", [ctx.householdId, ctx.household]); + await client.query("insert into members (id, household_id, display_name, role, locale) values ($1, $2, $3, 'owner', $4)", [ + ctx.memberId, + ctx.householdId, + ctx.name, + locale, + ]); + await client.query( + `insert into passkeys (id, member_id, household_id, public_key, counter, transports, device_type, backed_up, label) + values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, + [ + passkey.id, + ctx.memberId, + ctx.householdId, + passkey.publicKey, + passkey.counter, + passkey.transports, + passkey.deviceType, + passkey.backedUp, + deviceLabel(request.headers.get("user-agent")), + ], + ); + await startSession(client, { id: ctx.memberId, householdId: ctx.householdId, passkeyId: passkey.id }, request, isSecure(instance.origin)); + return null; + }); + if (result) return result; + await removeSetupCode(); + return json({ ok: true }); +} diff --git a/app/api/household/invitations/route.ts b/app/api/household/invitations/route.ts new file mode 100644 index 0000000..092b3b5 --- /dev/null +++ b/app/api/household/invitations/route.ts @@ -0,0 +1,42 @@ +import { withAuth, withHousehold } from "@/lib/db"; +import { fail, json, readJson, sameOrigin } from "@/lib/auth/http"; +import { createInvitationBody } from "@/lib/auth/schemas"; +import { getSession } from "@/lib/auth/session"; +import { hashToken, randomToken } from "@/lib/auth/tokens"; +import { loadInstance } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +// Einladungslink: eine neue Person (nur wer eingerichtet hat) oder ein +// weiteres eigenes Gerät (jede erwachsene Person). Der Link wird einmal +// gezeigt; gespeichert ist nur sein Hash. +const DAYS = { person: 7, device: 1 } as const; + +export async function POST(request: Request) { + const session = await getSession(); + if (!session) return fail("signedOut", 401); + const instance = await withAuth(loadInstance); + if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403); + const body = createInvitationBody.safeParse(await readJson(request)); + if (!body.success) return fail("invalid", 400); + if (body.data.kind === "person" && session.role !== "owner") return fail("forbidden", 403); + if (session.role === "child") return fail("forbidden", 403); + + const token = randomToken(); + const data = body.data; + await withHousehold(session.householdId, (client) => + client.query( + `insert into invitations (household_id, token_hash, member_id, display_name, created_by, expires_at) + values ($1, $2, $3, $4, $5, now() + make_interval(days => $6))`, + [ + session.householdId, + hashToken(token), + data.kind === "device" ? session.memberId : null, + data.kind === "person" ? data.name : null, + session.memberId, + DAYS[data.kind], + ], + ), + ); + return json({ url: `${instance.origin}/einladung/${token}`, days: DAYS[data.kind] }); +} diff --git a/app/api/household/members/remove/route.ts b/app/api/household/members/remove/route.ts new file mode 100644 index 0000000..702f5d4 --- /dev/null +++ b/app/api/household/members/remove/route.ts @@ -0,0 +1,23 @@ +import { z } from "zod"; +import { withAuth, withHousehold } from "@/lib/db"; +import { fail, readJson, sameOrigin } from "@/lib/auth/http"; +import { getSession } from "@/lib/auth/session"; +import { loadInstance } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +// Eine Person aus dem Haushalt nehmen — nur wer eingerichtet hat, nie sich +// selbst. Passkeys, Sitzungen und offene Einladungen gehen mit (on delete cascade). +export async function POST(request: Request) { + const session = await getSession(); + if (!session) return fail("signedOut", 401); + const instance = await withAuth(loadInstance); + if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403); + if (session.role !== "owner") return fail("forbidden", 403); + const body = z.object({ id: z.string().uuid() }).safeParse(await readJson(request)); + if (!body.success || body.data.id === session.memberId) return fail("invalid", 400); + return withHousehold(session.householdId, async (client) => { + const removed = await client.query("delete from members where id = $1 and role <> 'owner'", [body.data.id]); + return removed.rowCount === 1 ? new Response(null, { status: 204 }) : fail("invalid", 404); + }); +} diff --git a/app/api/me/locale/route.ts b/app/api/me/locale/route.ts new file mode 100644 index 0000000..2e226f8 --- /dev/null +++ b/app/api/me/locale/route.ts @@ -0,0 +1,25 @@ +import { cookies } from "next/headers"; +import { z } from "zod"; +import { withAuth, withHousehold } from "@/lib/db"; +import { fail, readJson, sameOrigin } from "@/lib/auth/http"; +import { getSession } from "@/lib/auth/session"; +import { loadInstance } from "@/lib/auth/webauthn"; +import { LOCALE_COOKIE, LOCALES } from "@/lib/locale"; + +export const dynamic = "force-dynamic"; + +// Die Sprache gehört der Person: gespeichert am Mitglied, damit sie auf +// jedem Gerät gilt, und als Keks für dieses Gerät. +export async function POST(request: Request) { + const session = await getSession(); + if (!session) return fail("signedOut", 401); + const instance = await withAuth(loadInstance); + if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403); + const body = z.object({ locale: z.enum(LOCALES) }).safeParse(await readJson(request)); + if (!body.success) return fail("invalid", 400); + await withHousehold(session.householdId, (client) => + client.query("update members set locale = $2 where id = $1", [session.memberId, body.data.locale]), + ); + (await cookies()).set(LOCALE_COOKIE, body.data.locale, { path: "/", sameSite: "lax", maxAge: 365 * 24 * 60 * 60 }); + return new Response(null, { status: 204 }); +} diff --git a/app/api/me/passkeys/remove/route.ts b/app/api/me/passkeys/remove/route.ts new file mode 100644 index 0000000..e65f5ce --- /dev/null +++ b/app/api/me/passkeys/remove/route.ts @@ -0,0 +1,25 @@ +import { z } from "zod"; +import { withAuth, withHousehold } from "@/lib/db"; +import { fail, readJson, sameOrigin } from "@/lib/auth/http"; +import { getSession } from "@/lib/auth/session"; +import { loadInstance } from "@/lib/auth/webauthn"; + +export const dynamic = "force-dynamic"; + +// Einen eigenen Passkey entfernen (Gerät verloren oder verkauft). Jede +// Sitzung, die mit ihm begann, endet mit ihm. Der letzte bleibt — sonst +// sperrt man sich selbst aus. +export async function POST(request: Request) { + const session = await getSession(); + if (!session) return fail("signedOut", 401); + const instance = await withAuth(loadInstance); + if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403); + const body = z.object({ id: z.string().min(1).max(1024) }).safeParse(await readJson(request)); + if (!body.success) return fail("invalid", 400); + return withHousehold(session.householdId, async (client) => { + const { rows } = await client.query("select count(*)::int as n from passkeys where member_id = $1", [session.memberId]); + if ((rows[0]?.n ?? 0) <= 1) return fail("lastPasskey", 409); + const removed = await client.query("delete from passkeys where id = $1 and member_id = $2", [body.data.id, session.memberId]); + return removed.rowCount === 1 ? new Response(null, { status: 204 }) : fail("invalid", 404); + }); +} diff --git a/app/einladung/[token]/page.tsx b/app/einladung/[token]/page.tsx new file mode 100644 index 0000000..b332691 --- /dev/null +++ b/app/einladung/[token]/page.tsx @@ -0,0 +1,25 @@ +import { getTranslations } from "next-intl/server"; +import { AuthShell } from "@/components/auth/auth-shell"; +import { InviteForm } from "@/components/auth/invite-form"; +import { findInvitation } from "@/lib/auth/invitations"; +import { withAuth } from "@/lib/db"; + +export const dynamic = "force-dynamic"; +// Der Link ist ein Geheimnis: nie als Referrer weitergeben. +export const metadata = { referrer: "no-referrer" as const }; + +export default async function InvitationPage({ params }: { params: Promise<{ token: string }> }) { + const { token } = await params; + const t = await getTranslations("auth.invite"); + const invitation = token.length <= 100 ? await withAuth((client) => findInvitation(client, token)) : null; + if (!invitation) return ; + const isDevice = Boolean(invitation.memberId); + return ( + + + + ); +} diff --git a/app/einrichten/page.tsx b/app/einrichten/page.tsx new file mode 100644 index 0000000..124a1ab --- /dev/null +++ b/app/einrichten/page.tsx @@ -0,0 +1,19 @@ +import { redirect } from "next/navigation"; +import { getTranslations } from "next-intl/server"; +import { AuthShell } from "@/components/auth/auth-shell"; +import { SetupForm } from "@/components/auth/setup-form"; +import { isSetUp } from "@/lib/auth/session"; +import { ensureSetupCode } from "@/lib/auth/codes"; + +export const dynamic = "force-dynamic"; + +export default async function SetupPage() { + if (await isSetUp()) redirect("/anmelden"); + await ensureSetupCode(); + const t = await getTranslations("auth.setup"); + return ( + + + + ); +} diff --git a/app/wiederherstellen/page.tsx b/app/wiederherstellen/page.tsx new file mode 100644 index 0000000..7c12cef --- /dev/null +++ b/app/wiederherstellen/page.tsx @@ -0,0 +1,17 @@ +import { redirect } from "next/navigation"; +import { getTranslations } from "next-intl/server"; +import { AuthShell } from "@/components/auth/auth-shell"; +import { RecoveryForm } from "@/components/auth/recovery-form"; +import { isSetUp } from "@/lib/auth/session"; + +export const dynamic = "force-dynamic"; + +export default async function RecoveryPage() { + if (!(await isSetUp())) redirect("/einrichten"); + const t = await getTranslations("auth.recovery"); + return ( + + + + ); +} diff --git a/components/app-nav.tsx b/components/app-nav.tsx new file mode 100644 index 0000000..36a5b41 --- /dev/null +++ b/components/app-nav.tsx @@ -0,0 +1,46 @@ +"use client"; + +import { Ellipsis, Sun } from "lucide-react"; +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { cn } from "@/lib/utils"; + +// Untere Leiste unter dem Daumen (Leitprinzip 8). Plan, Einkauf und Gerichte +// kommen mit ihren Arbeitspaketen dazu. +const ITEMS = [ + { href: "/", key: "today", icon: Sun }, + { href: "/mehr", key: "more", icon: Ellipsis }, +] as const; + +export function AppNav() { + const t = useTranslations("nav"); + const path = usePathname(); + return ( + + ); +} diff --git a/components/auth/auth-shell.tsx b/components/auth/auth-shell.tsx new file mode 100644 index 0000000..cf4ffdc --- /dev/null +++ b/components/auth/auth-shell.tsx @@ -0,0 +1,15 @@ +import Image from "next/image"; + +// Rahmen für Einrichten, Anmelden und Einladung: Symbol, Titel, Text, Inhalt. +export function AuthShell({ title, intro, children }: { title: string; intro?: string; children?: React.ReactNode }) { + return ( +
+
+ +

{title}

+ {intro ?

{intro}

: null} +
+ {children} +
+ ); +} diff --git a/components/auth/invite-form.tsx b/components/auth/invite-form.tsx new file mode 100644 index 0000000..d12efa5 --- /dev/null +++ b/components/auth/invite-form.tsx @@ -0,0 +1,48 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { ErrorNotice } from "@/components/ui/notice"; +import { register, type ErrorKey } from "./passkey"; + +export function InviteForm({ token, suggestedName, askName }: { token: string; suggestedName: string; askName: boolean }) { + const t = useTranslations("auth"); + const router = useRouter(); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + async function onSubmit(event: React.FormEvent) { + event.preventDefault(); + const form = new FormData(event.currentTarget); + setBusy(true); + setError(null); + const result = await register( + "/api/auth/invite/options", + askName ? { token, name: form.get("name") } : { token }, + "/api/auth/invite/verify", + ); + setBusy(false); + if (result) setError(result); + else router.replace("/"); + } + + return ( +
+ {askName ? ( +
+ + +
+ ) : null} + {error ? {t(`errors.${error}`)} : null} + +

{t("setup.passkeyHint")}

+
+ ); +} diff --git a/components/auth/login-button.tsx b/components/auth/login-button.tsx new file mode 100644 index 0000000..734477d --- /dev/null +++ b/components/auth/login-button.tsx @@ -0,0 +1,40 @@ +"use client"; + +import { KeyRound } from "lucide-react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { ErrorNotice } from "@/components/ui/notice"; +import { signIn, type ErrorKey } from "./passkey"; + +export function LoginButton() { + const t = useTranslations("auth"); + const router = useRouter(); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + async function onClick() { + setBusy(true); + setError(null); + const result = await signIn(); + setBusy(false); + if (result) setError(result); + else router.replace("/"); + } + + return ( +
+ {error ? {t(`errors.${error}`)} : null} + +

{t("login.noPasskey")}

+ + {t("login.lost")} + +
+ ); +} diff --git a/components/auth/passkey.ts b/components/auth/passkey.ts new file mode 100644 index 0000000..3d36039 --- /dev/null +++ b/components/auth/passkey.ts @@ -0,0 +1,66 @@ +"use client"; + +import { + browserSupportsWebAuthn, + startAuthentication, + startRegistration, + WebAuthnError, +} from "@simplewebauthn/browser"; + +// Der Ablauf im Browser: Optionen holen, Passkey vom Gerät, Antwort prüfen +// lassen. Gibt den Schlüssel eines Fehlers zurück (messages: auth.errors) +// oder null, wenn es geklappt hat. + +export type ErrorKey = + | "code" | "tooMany" | "invalid" | "expired" | "passkey" | "cancelled" + | "unsupported" | "invitation" | "alreadySetUp" | "origin" | "forbidden" | "lastPasskey" | "unknown"; + +const KNOWN: readonly string[] = [ + "code", "tooMany", "invalid", "expired", "passkey", "invitation", "alreadySetUp", "origin", "forbidden", "lastPasskey", +]; + +async function post(url: string, body: unknown): Promise<{ ok: boolean; data: Record }> { + const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const data = (await res.json().catch(() => ({}))) as Record; + return { ok: res.ok, data }; +} + +function errorKey(data: Record): ErrorKey { + const e = data.error; + return typeof e === "string" && KNOWN.includes(e) ? (e as ErrorKey) : "unknown"; +} + +function fromBrowser(error: unknown): ErrorKey { + if (error instanceof WebAuthnError && error.code === "ERROR_CEREMONY_ABORTED") return "cancelled"; + if (error instanceof Error && error.name === "NotAllowedError") return "cancelled"; + if (error instanceof WebAuthnError && error.code === "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED") return "passkey"; + return "unknown"; +} + +export async function register(optionsUrl: string, body: unknown, verifyUrl: string): Promise { + if (!browserSupportsWebAuthn()) return "unsupported"; + const first = await post(optionsUrl, body); + if (!first.ok) return errorKey(first.data); + let response; + try { + response = await startRegistration({ optionsJSON: first.data.options as never }); + } catch (error) { + return fromBrowser(error); + } + const second = await post(verifyUrl, { challengeId: first.data.challengeId, response }); + return second.ok ? null : errorKey(second.data); +} + +export async function signIn(): Promise { + if (!browserSupportsWebAuthn()) return "unsupported"; + const first = await post("/api/auth/login/options", {}); + if (!first.ok) return errorKey(first.data); + let response; + try { + response = await startAuthentication({ optionsJSON: first.data.options as never }); + } catch (error) { + return fromBrowser(error); + } + const second = await post("/api/auth/login/verify", { challengeId: first.data.challengeId, response }); + return second.ok ? null : errorKey(second.data); +} diff --git a/components/auth/recovery-form.tsx b/components/auth/recovery-form.tsx new file mode 100644 index 0000000..78f27af --- /dev/null +++ b/components/auth/recovery-form.tsx @@ -0,0 +1,56 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { ErrorNotice } from "@/components/ui/notice"; +import { register, type ErrorKey } from "./passkey"; + +export function RecoveryForm() { + const t = useTranslations("auth"); + const router = useRouter(); + const [requested, setRequested] = useState(false); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + async function requestCode() { + setError(null); + const res = await fetch("/api/auth/recovery/request", { method: "POST" }); + if (res.ok) setRequested(true); + else setError(res.status === 429 ? "tooMany" : "unknown"); + } + + async function onSubmit(event: React.FormEvent) { + event.preventDefault(); + const code = new FormData(event.currentTarget).get("code"); + setBusy(true); + setError(null); + const result = await register("/api/auth/recovery/options", { code }, "/api/auth/recovery/verify"); + setBusy(false); + if (result) setError(result); + else router.replace("/mehr"); + } + + return ( +
+ + {requested ?

{t("recovery.requested")}

: null} +
+
+ + +
+ {error ? {t(`errors.${error}`)} : null} + +
+

{t("recovery.others")}

+
+ ); +} diff --git a/components/auth/setup-form.tsx b/components/auth/setup-form.tsx new file mode 100644 index 0000000..215df2f --- /dev/null +++ b/components/auth/setup-form.tsx @@ -0,0 +1,54 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { ErrorNotice } from "@/components/ui/notice"; +import { register, type ErrorKey } from "./passkey"; + +export function SetupForm() { + const t = useTranslations("auth"); + const router = useRouter(); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + async function onSubmit(event: React.FormEvent) { + event.preventDefault(); + const form = new FormData(event.currentTarget); + setBusy(true); + setError(null); + const result = await register( + "/api/auth/setup/options", + { code: form.get("code"), name: form.get("name"), household: form.get("household") }, + "/api/auth/setup/verify", + ); + setBusy(false); + if (result) setError(result); + else router.replace("/"); + } + + return ( +
+
+ + +
+
+ + +
+
+ + +
+ {error ? {t(`errors.${error}`)} : null} + +

{t("setup.passkeyHint")}

+
+ ); +} diff --git a/components/more/account-actions.tsx b/components/more/account-actions.tsx new file mode 100644 index 0000000..1e4ad86 --- /dev/null +++ b/components/more/account-actions.tsx @@ -0,0 +1,52 @@ +"use client"; + +import { LogOut } from "lucide-react"; +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { Button } from "@/components/ui/button"; +import { LOCALES, type Locale } from "@/lib/locale"; + +const NAMES: Record = { de: "Deutsch", en: "English", fr: "Français", es: "Español" }; + +export function LanguageSelect({ current }: { current: Locale }) { + const t = useTranslations("more"); + const router = useRouter(); + return ( + + ); +} + +export function SignOutButton() { + const t = useTranslations("more"); + const router = useRouter(); + return ( + + ); +} diff --git a/components/more/invite-panel.tsx b/components/more/invite-panel.tsx new file mode 100644 index 0000000..90d02ed --- /dev/null +++ b/components/more/invite-panel.tsx @@ -0,0 +1,110 @@ +"use client"; + +import { Check, Copy, Share2 } from "lucide-react"; +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { ErrorNotice } from "@/components/ui/notice"; + +type Created = { url: string; days: number }; + +async function create(body: object): Promise { + const res = await fetch("/api/household/invitations", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); + const data = await res.json().catch(() => ({})); + return res.ok ? (data as Created) : String(data.error ?? "unknown"); +} + +function LinkResult({ created }: { created: Created }) { + const t = useTranslations("more"); + const [copied, setCopied] = useState(false); + const canShare = typeof navigator !== "undefined" && "share" in navigator; + return ( +
+

{t("linkReady", { days: created.days })}

+ e.currentTarget.select()} aria-label="Link" /> +
+ + {canShare ? ( + + ) : null} +
+
+ ); +} + +export function InvitePerson() { + const t = useTranslations("more"); + const te = useTranslations("auth.errors"); + const [created, setCreated] = useState(null); + const [error, setError] = useState(null); + return ( +
{ + event.preventDefault(); + const name = new FormData(event.currentTarget).get("name"); + const result = await create({ kind: "person", name }); + if (typeof result === "string") setError(result); + else { + setError(null); + setCreated(result); + } + }} + > +
+ + +
+ {error ? {te.has(error) ? te(error) : te("unknown")} : null} + + {created ? : null} + + ); +} + +export function AddDevice() { + const t = useTranslations("more"); + const te = useTranslations("auth.errors"); + const [created, setCreated] = useState(null); + const [error, setError] = useState(null); + return ( +
+

{t("addDeviceText")}

+ {error ? {te.has(error) ? te(error) : te("unknown")} : null} + + {created ? : null} +
+ ); +} diff --git a/components/more/remove-button.tsx b/components/more/remove-button.tsx new file mode 100644 index 0000000..62bbd77 --- /dev/null +++ b/components/more/remove-button.tsx @@ -0,0 +1,43 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useTranslations } from "next-intl"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; + +// Entfernen mit zweitem Tipp statt Dialog: Der erste Tipp fragt im Knopf +// selbst nach, der zweite entfernt. +export function RemoveButton({ url, id }: { url: string; id: string }) { + const t = useTranslations("more"); + const te = useTranslations("auth.errors"); + const router = useRouter(); + const [armed, setArmed] = useState(false); + const [error, setError] = useState(null); + return ( + + + {error ? ( + + {error} + + ) : null} + + ); +} diff --git a/components/ui/input.tsx b/components/ui/input.tsx new file mode 100644 index 0000000..e470b21 --- /dev/null +++ b/components/ui/input.tsx @@ -0,0 +1,17 @@ +import * as React from "react"; +import { cn } from "@/lib/utils"; + +// shadcn/ui Input, 44 px hoch, Schrift 16 px (iOS zoomt sonst beim Tippen). +export const Input = React.forwardRef>( + ({ className, ...props }, ref) => ( + + ), +); +Input.displayName = "Input"; diff --git a/components/ui/label.tsx b/components/ui/label.tsx new file mode 100644 index 0000000..369d4e9 --- /dev/null +++ b/components/ui/label.tsx @@ -0,0 +1,6 @@ +import * as React from "react"; +import { cn } from "@/lib/utils"; + +export function Label({ className, ...props }: React.LabelHTMLAttributes) { + return