fix: harden production flows and user messaging
This commit is contained in:
1 parent
52dce168dd
commit
86dfe8053d
43 files changed
+3520
-358
No files matched your search
@@ -0,0 +1,142 @@
|
||||
# AGB sowie Nutzungs- und Lizenzbedingungen – Arbeitsentwurf
|
||||
|
||||
> **Wichtiger Hinweis:** Dieser Text ist ein auf das derzeit beschriebene Geschäftsmodell zugeschnittener Arbeitsentwurf und keine Rechtsberatung. Vor Veröffentlichung sollte er von einer in Deutschland zugelassenen, auf Medien-, Urheber- und Vertragsrecht spezialisierten Rechtsanwältin oder einem entsprechenden Rechtsanwalt geprüft werden. Anbieterangaben, Zahlungsfrist, Leistungsumfang und Gerichtsstand müssen noch mit dem Impressum und der tatsächlichen Arbeitsweise abgeglichen werden.
|
||||
|
||||
## Vor der Implementierung ersetzen oder entscheiden
|
||||
|
||||
- `[VOLLSTÄNDIGER NAME/FIRMA]`, `[ANSCHRIFT]`, `[E-MAIL]` und gegebenenfalls `[UST-ID]` exakt aus dem Impressum übernehmen.
|
||||
- `[ORT DES GERICHTSSTANDS]` nur einsetzen, wenn Leon dort seinen allgemeinen Gerichtsstand hat; die Klausel gilt außerdem nur im gesetzlich zulässigen Umfang.
|
||||
- Prüfen, ob die Zahlungsfrist von 14 Tagen der tatsächlichen Rechnungspraxis entspricht.
|
||||
- Den Versionsstand sichtbar angeben und diese Version bei Portalregistrierung protokollieren.
|
||||
- Auf der Website vor Vertragsschluss deutlich auf die AGB verlinken und eine zumutbare Speichermöglichkeit anbieten.
|
||||
|
||||
---
|
||||
|
||||
# Allgemeine Geschäftsbedingungen sowie Nutzungs- und Lizenzbedingungen
|
||||
|
||||
**Stand: 11. August 2026**
|
||||
|
||||
## 1. Anbieter und Geltungsbereich
|
||||
|
||||
1. Anbieter der fotografischen Leistungen und Bildlizenzen ist `[VOLLSTÄNDIGER NAME/FIRMA]`, `[ANSCHRIFT]`, E-Mail: `[E-MAIL]` – nachfolgend „Fotograf“ genannt.
|
||||
2. Diese Bedingungen gelten für Verträge über Fotoaufträge, die Bereitstellung von Fotografien sowie die Einräumung von Nutzungsrechten, insbesondere über die Website und das Redaktionsportal des Fotografen.
|
||||
3. Das Angebot richtet sich ausschließlich an Unternehmer im Sinne des § 14 BGB, juristische Personen des öffentlichen Rechts und öffentlich-rechtliche Sondervermögen. Verträge mit Verbrauchern werden auf Grundlage dieser Bedingungen nicht geschlossen.
|
||||
4. Abweichende Bedingungen des Auftraggebers oder Lizenznehmers – nachfolgend gemeinsam „Kunde“ genannt – gelten nur, wenn der Fotograf ihrer Geltung ausdrücklich in Textform zugestimmt hat.
|
||||
5. Individuelle Vereinbarungen, Angebote und Lizenzangaben gehen diesen Bedingungen vor.
|
||||
|
||||
## 2. Vertragsschluss und Kommunikation
|
||||
|
||||
1. Darstellungen auf der Website und im Redaktionsportal sind noch kein verbindliches Angebot, sofern sie nicht ausdrücklich als solches bezeichnet sind.
|
||||
2. Ein Vertrag über einen Fotoauftrag kommt durch Annahme eines Angebots, eine Auftragsbestätigung in Textform oder durch Beginn der vereinbarten Leistung zustande.
|
||||
3. Beim Redaktionsportal gibt der Kunde mit der verbindlichen Auswahl eines Fotos, des Nutzungszwecks und der Downloadart eine Bestellung der angezeigten Lizenz ab. Der Vertrag kommt mit der Bereitstellung des Downloads zustande.
|
||||
4. Der Kunde muss Angaben zu Medium, Beitrag, Verwendungszweck, Umfang und gegebenenfalls Kampagne vollständig und wahrheitsgemäß machen. Unklare oder nachträglich geänderte Nutzungen sind vorab mit dem Fotografen abzustimmen.
|
||||
|
||||
## 3. Fotoaufträge
|
||||
|
||||
1. Inhalt, Termin, Ort, Umfang, Honorar und Lieferformat eines Fotoauftrags ergeben sich aus dem jeweiligen Angebot oder der Auftragsbestätigung.
|
||||
2. Die gestalterische und technische Umsetzung liegt im künstlerischen Ermessen des Fotografen, soweit keine konkreten Vorgaben in Textform vereinbart wurden. Ein Anspruch auf einen bestimmten Stil, einzelne Motive oder eine bestimmte Zahl gelungener Aufnahmen besteht nur, wenn dies ausdrücklich vereinbart wurde.
|
||||
3. Termine und Lieferfristen sind nur verbindlich, wenn sie ausdrücklich als verbindlich bestätigt wurden. Verzögerungen aufgrund höherer Gewalt oder anderer vom Fotografen nicht zu vertretender Umstände verlängern die Leistungsfrist angemessen.
|
||||
4. Sagt der Kunde einen bestätigten Termin ab oder verschiebt ihn, kann der Fotograf die bis dahin erbrachten Leistungen und nachweislich angefallenen, nicht mehr vermeidbaren Aufwendungen abrechnen. Weitergehende gesetzliche Ansprüche bleiben unberührt; ersparte Aufwendungen werden angerechnet.
|
||||
5. Rohdateien, unbearbeitete Aufnahmen und offene Bearbeitungsdateien gehören nicht zum Lieferumfang, sofern dies nicht ausdrücklich vereinbart wurde.
|
||||
|
||||
## 4. Redaktionsportal und Benutzerkonto
|
||||
|
||||
1. Der Zugang zum Redaktionsportal bedarf der Registrierung, E-Mail-Bestätigung und Freigabe durch den Fotografen. Ein Anspruch auf Freigabe oder dauerhafte Bereitstellung besteht nicht.
|
||||
2. Ein Redaktionskonto darf innerhalb der freigeschalteten Redaktion gemeinsam genutzt werden. Der Kunde stellt sicher, dass Zugangsdaten nur befugten Mitarbeitenden zugänglich sind, sicher verwahrt und bei Verdacht auf Missbrauch unverzüglich geändert werden.
|
||||
3. Sämtliche über das Redaktionskonto vorgenommenen lizenz- und abrechnungsrelevanten Handlungen werden der freigeschalteten Redaktion zugerechnet, soweit der Kunde keinen vom Fotografen zu vertretenden Missbrauch nachweist.
|
||||
4. Der Fotograf darf Zugänge bei Sicherheitsrisiken, Zahlungsverzug, vertragswidriger Nutzung oder Wegfall der Geschäftsbeziehung vorübergehend sperren. Bereits wirksam eingeräumte und bezahlte Nutzungsrechte bleiben hiervon unberührt.
|
||||
5. Das Portal wird mit angemessener Sorgfalt betrieben. Wartung, Sicherheitsmaßnahmen und Störungen bei technischen Dienstleistern können die Verfügbarkeit zeitweise einschränken. Eine ununterbrochene Verfügbarkeit wird nicht geschuldet.
|
||||
|
||||
## 5. Urheberrecht und Umfang der Bildlizenz
|
||||
|
||||
1. Sämtliche Fotografien bleiben urheber- beziehungsweise leistungsschutzrechtlich geschützt. Eigentum an Dateien oder Datenträgern und Nutzungsrechte sind voneinander zu unterscheiden.
|
||||
2. Soweit nichts anderes ausdrücklich vereinbart ist, erhält der Kunde ein einfaches, nicht ausschließliches und nicht übertragbares Nutzungsrecht ausschließlich für den bei Bestellung angegebenen Zweck. Inhaltlicher, zeitlicher, räumlicher und medialer Umfang richten sich nach dem Angebot, der Portalangabe und dem erkennbaren Vertragszweck.
|
||||
3. Eine Nutzung für einen neuen Beitrag, ein neues Projekt, eine neue Ausgabe, eine neue Kampagne oder einen sonstigen neuen Zweck ist eine neue lizenzpflichtige Nutzung. Sie muss im Portal als „neuer Zweck“ ausgewählt oder gesondert vereinbart werden.
|
||||
4. Ein erneuter Download für denselben bereits lizenzierten Zweck löst nur dann keine zusätzliche nutzungsabhängige Vergütung aus, wenn das Portal ihn ausdrücklich als kostenfreie Wiederholung bestätigt. Ein neuer Nutzungszweck bleibt auch bei identischer Datei gesondert vergütungspflichtig.
|
||||
5. Online- und Social-Media-Nutzungen, Werbung, Eigenwerbung, Presseverteilung, Syndikation, Archivdatenbanken, Print, Bewegtbild, Merchandising und sonstige Verwertungsarten sind nur umfasst, soweit sie vom vereinbarten Zweck oder Lizenzumfang erfasst sind.
|
||||
6. Ausschließliche Nutzungsrechte, Sperrfristen und Branchen- oder Gebietsexklusivität bedürfen einer ausdrücklichen Vereinbarung in Textform.
|
||||
|
||||
## 6. Unzulässige Nutzungen und Bearbeitungen
|
||||
|
||||
1. Ohne vorherige Zustimmung in Textform ist es insbesondere unzulässig,
|
||||
- Fotografien weiterzuverkaufen, unterzulizenzieren oder Dritten zur eigenständigen Nutzung zu überlassen,
|
||||
- Fotografien als Logo, Marke, Produktmotiv oder für Merchandising zu verwenden,
|
||||
- Fotografien in Bilddatenbanken, Stockplattformen, Datensätzen oder vergleichbaren Sammlungen bereitzustellen,
|
||||
- Fotografien zum Training, zur Feinabstimmung, Bewertung oder sonstigen Entwicklung generativer oder analytischer KI-Systeme zu verwenden,
|
||||
- den Aussagegehalt zu verfälschen, Personen oder Gegenstände sinnverändernd hinzuzufügen oder zu entfernen oder irreführende Montagen herzustellen.
|
||||
2. Zulässig sind technisch erforderliche Anpassungen wie maßvolle Ausschnitte, Skalierung sowie übliche Helligkeits- und Farbkorrekturen, soweit Aussage, Urheberpersönlichkeitsrecht und berechtigte Interessen abgebildeter Personen nicht beeinträchtigt werden.
|
||||
3. Bei redaktioneller Nutzung darf das Foto nicht in einen rechtswidrigen, herabwürdigenden, diskriminierenden oder irreführenden Zusammenhang gestellt werden.
|
||||
|
||||
## 7. Urhebervermerk und Metadaten
|
||||
|
||||
1. Soweit nicht ausdrücklich anders vereinbart oder im konkreten Medium branchenüblich ausgeschlossen, ist bei jeder Veröffentlichung gut lesbar und dem Bild zuordenbar der Urhebervermerk **„© Leon Tonhäuser“** anzubringen.
|
||||
2. Vorhandene Urheber-, Rechte- und Herkunftsangaben in Datei-Metadaten dürfen nicht entfernt oder verfälscht werden, soweit dies nicht technisch unvermeidbar ist.
|
||||
3. Der Kunde informiert den Fotografen auf Anfrage über Art und Umfang der erfolgten Nutzung und stellt nach Möglichkeit ein Belegexemplar oder einen Veröffentlichungslink bereit.
|
||||
|
||||
## 8. Rechte abgebildeter Personen und redaktioneller Kontext
|
||||
|
||||
1. Die Einräumung urheberrechtlicher Nutzungsrechte bedeutet nicht automatisch, dass jede denkbare Veröffentlichung persönlichkeits-, presse-, marken-, haus- oder datenschutzrechtlich zulässig ist.
|
||||
2. Der Fotograf informiert den Kunden über ihm bekannte, konkret vereinbarte Model-, Property- oder Veranstaltungsfreigaben und bekannte Nutzungsbeschränkungen. Eine weitergehende Freigabe gilt nur, wenn sie ausdrücklich bestätigt wurde.
|
||||
3. Der Kunde prüft eigenverantwortlich, ob die konkrete Nutzung, Bildunterschrift, Berichterstattung und Einbettung in ihrem jeweiligen Kontext zulässig ist. Das gilt insbesondere bei Werbung, sensiblen Themen, Montagen und Nutzungen außerhalb aktueller redaktioneller Berichterstattung.
|
||||
|
||||
## 9. Vergütung, Nutzungsnachweis und Rechnung
|
||||
|
||||
1. Es gelten die im Angebot, in der Preisliste oder im Redaktionsportal für die jeweilige Redaktion angezeigten beziehungsweise vereinbarten Preise. Alle Preise verstehen sich netto zuzüglich der gesetzlich geschuldeten Umsatzsteuer.
|
||||
2. Nutzungen können einzeln oder aufgrund einer individuell vereinbarten Monats- oder Quartalspauschale abgerechnet werden. Umfang, Preis und gegebenenfalls enthaltene Nutzungseinheiten einer Pauschale ergeben sich aus der Individualvereinbarung.
|
||||
3. Der im Portal oder per E-Mail bereitgestellte Nutzungsnachweis dokumentiert Downloads, Nutzungszwecke und Beträge. **Er ist keine Rechnung. Die Rechnung wird separat übermittelt.** Bei Widersprüchen hat die separate Rechnung Vorrang; offensichtliche Fehler im Nutzungsnachweis sind dem Fotografen unverzüglich mitzuteilen.
|
||||
4. Rechnungen sind innerhalb von 14 Kalendertagen ab Zugang ohne Abzug zahlbar, sofern auf der Rechnung keine andere Frist angegeben ist.
|
||||
5. Bei Zahlungsverzug gelten die gesetzlichen Vorschriften. Der Fotograf kann weitere Downloads bis zum Ausgleich fälliger Forderungen sperren.
|
||||
|
||||
## 10. Mitwirkung, Archivierung und Datensicherung
|
||||
|
||||
1. Der Kunde stellt benötigte Informationen, Freigaben, Ansprechpartner und Zutrittsberechtigungen rechtzeitig zur Verfügung. Mehraufwand und Verzögerungen aufgrund verspäteter oder unzutreffender Angaben können gesondert berechnet werden, soweit der Kunde sie zu vertreten hat.
|
||||
2. Der Kunde ist für die eigene, rechtmäßige Archivierung ausgelieferter Dateien verantwortlich. Der Fotograf schuldet keine zeitlich unbegrenzte Aufbewahrung oder erneute Bereitstellung.
|
||||
3. Beschreibungen, Dateinamen, Albumzuordnung und sonstige Metadaten dienen der Recherche. Sie ersetzen keine eigene redaktionelle Prüfung und werden nicht als vollständig oder fehlerfrei garantiert.
|
||||
|
||||
## 11. Mängel und Beanstandungen
|
||||
|
||||
1. Technisch fehlerhafte oder unvollständige Lieferungen sind nach Entdeckung nachvollziehbar zu melden. Der Fotograf erhält zunächst Gelegenheit zur Nacherfüllung, soweit diese möglich und zumutbar ist.
|
||||
2. Subjektive gestalterische Abweichungen begründen keinen Mangel, wenn sie sich innerhalb des vereinbarten Gestaltungsspielraums bewegen.
|
||||
3. Gesetzliche Untersuchungs- und Rügepflichten, insbesondere nach § 377 HGB, bleiben unberührt.
|
||||
|
||||
## 12. Haftung
|
||||
|
||||
1. Der Fotograf haftet unbeschränkt für Vorsatz und grobe Fahrlässigkeit, für Schäden aus der Verletzung von Leben, Körper oder Gesundheit, nach dem Produkthaftungsgesetz sowie im Umfang ausdrücklich übernommener Garantien.
|
||||
2. Bei leicht fahrlässiger Verletzung einer wesentlichen Vertragspflicht, deren Erfüllung die ordnungsgemäße Durchführung des Vertrags erst ermöglicht und auf deren Einhaltung der Kunde regelmäßig vertrauen darf, ist die Haftung auf den vertragstypischen, bei Vertragsschluss vorhersehbaren Schaden begrenzt.
|
||||
3. Im Übrigen ist die Haftung für leichte Fahrlässigkeit ausgeschlossen. Die vorstehenden Beschränkungen gelten entsprechend zugunsten der Beschäftigten und Erfüllungsgehilfen des Fotografen.
|
||||
4. Für vom Kunden bereitgestellte Inhalte, Weisungen, Bildunterschriften und Nutzungskontexte sowie für Nutzungen außerhalb der eingeräumten Lizenz ist der Kunde verantwortlich. Der Kunde stellt den Fotografen von berechtigten Ansprüchen Dritter frei, soweit diese auf einer vom Kunden zu vertretenden Pflichtverletzung beruhen; die angemessenen Kosten der Rechtsverteidigung sind umfasst. Der Fotograf informiert den Kunden unverzüglich und stimmt die Rechtsverteidigung angemessen mit ihm ab.
|
||||
|
||||
## 13. Vertragsdauer und Beendigung des Portalzugangs
|
||||
|
||||
1. Der Portalnutzungsvertrag läuft auf unbestimmte Zeit und kann von beiden Seiten mit einer Frist von 14 Tagen in Textform gekündigt werden, sofern keine individuelle Mindestlaufzeit vereinbart wurde.
|
||||
2. Das Recht zur außerordentlichen Kündigung aus wichtigem Grund bleibt unberührt. Ein wichtiger Grund liegt insbesondere bei schwerwiegender oder wiederholter vertragswidriger Bildnutzung, Manipulation von Abrechnungsdaten oder erheblichem Zahlungsverzug vor.
|
||||
3. Mit Vertragsende endet der Zugang zum Portal. Ordnungsgemäß erworbene und bezahlte Nutzungsrechte bleiben im vereinbarten Umfang bestehen; offene Zahlungs-, Auskunfts- und Unterlassungsansprüche bleiben unberührt.
|
||||
|
||||
## 14. Datenschutz
|
||||
|
||||
Informationen zur Verarbeitung personenbezogener Daten stehen in der gesonderten Datenschutzerklärung unter `[URL ZUR DATENSCHUTZERKLÄRUNG]`. Das Impressum ist unter `[URL ZUM IMPRESSUM]` erreichbar.
|
||||
|
||||
## 15. Schlussbestimmungen
|
||||
|
||||
1. Es gilt das Recht der Bundesrepublik Deutschland unter Ausschluss des UN-Kaufrechts.
|
||||
2. Ist der Kunde Kaufmann, juristische Person des öffentlichen Rechts oder öffentlich-rechtliches Sondervermögen, ist – soweit gesetzlich zulässig – ausschließlicher Gerichtsstand `[ORT DES GERICHTSSTANDS]`. Gesetzliche ausschließliche Gerichtsstände bleiben unberührt.
|
||||
3. Sollten einzelne Bestimmungen unwirksam sein oder werden, bleibt die Wirksamkeit der übrigen Bestimmungen unberührt. An die Stelle der unwirksamen Bestimmung treten die gesetzlichen Vorschriften.
|
||||
|
||||
---
|
||||
|
||||
## Hinweise für die KI im Website-Projekt
|
||||
|
||||
1. Den Text als eigene öffentliche Seite „AGB & Lizenzbedingungen“ ausgeben, nicht mit Impressum oder Datenschutz vermischen.
|
||||
2. Permanente URL empfehlen: `/agb` oder `/nutzungsbedingungen`.
|
||||
3. Im Footer sowie bei Kontakt-/Anfrageformularen verlinken. Im Redaktionsportal muss `LEGAL_TERMS_URL` auf genau diese öffentliche Seite zeigen.
|
||||
4. Bei einer verbindlichen Portalregistrierung eine nicht vorangekreuzte Checkbox mit Link und protokolliertem Versionsstand verwenden.
|
||||
5. Inhalt semantisch als `article` mit einer `h1` und fortlaufenden `h2`-Überschriften auszeichnen; druckfreundliche Darstellung vorsehen.
|
||||
6. Anbieterangaben und URLs aus dem bestehenden Impressum/Datenschutz übernehmen, nicht erraten.
|
||||
|
||||
## Verwendete amtliche Grundlagen
|
||||
|
||||
- §§ 305, 307 und 310 BGB: Einbeziehung und Inhaltskontrolle Allgemeiner Geschäftsbedingungen, auch im B2B-Bereich.
|
||||
- §§ 13, 15, 19a, 31 und 72 UrhG: Urheberbezeichnung, Verwertungsrechte, öffentliche Zugänglichmachung, Nutzungsrechte und Schutz von Lichtbildern.
|
||||
- §§ 22 und 23 KunstUrhG: Recht am eigenen Bild und gesetzliche Ausnahmen.
|
||||
- § 38 ZPO: Gerichtsstandsvereinbarungen insbesondere zwischen Kaufleuten.
|
||||
- § 5 DDG: gesonderte Anbieterkennzeichnung im Impressum.
|
||||
@@ -52,6 +52,7 @@ When placing Nginx or Traefik in front of the portal:
|
||||
```
|
||||
2. **Body Size Limits**: Unused (portal handles photo downloads only, not uploads).
|
||||
3. **Security Headers**: Managed by Next.js (`next.config.ts`), including restrictive CSP, frame denial (`DENY`), and strict Referrer-Policy.
|
||||
4. **Client-IP headers**: The portal accepts the proxy-appended final hop of `X-Forwarded-For` (the normal Zoraxy/Go reverse-proxy path) and alternatively `X-Real-IP` for abuse protection. Keep the application port unreachable from the public network so clients cannot bypass the trusted proxy. If a proxy sets `X-Real-IP`, it must overwrite rather than pass through a public client value.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
# Produktionshärtung und Nutzertexte – Implementierungsplan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Die bestätigten Sicherheits- und Abrechnungsfehler schließen und die gewünschten Passwort-/Nutzungsnachweis-Texte ergänzen.
|
||||
|
||||
**Architecture:** Bestehende Servicegrenzen bleiben erhalten. Autorisierung und Abrechnung werden an ihren serverseitigen Wahrheitsquellen korrigiert; UI und E-Mail konsumieren nur daraus abgeleitete, testbare Ergebnisse.
|
||||
|
||||
**Tech Stack:** Node.js 24, Next.js 16, React 19, TypeScript, Drizzle/PostgreSQL, Better Auth, Vitest.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Keine Clientdaten bestimmen Editorial-ID oder Preis.
|
||||
- Keine Historie wird gelöscht, um Abrechnungsfehler zu kaschieren.
|
||||
- Alle Geldbeträge bleiben Integer-Cents.
|
||||
- Alle Monatsgrenzen verwenden Europe/Berlin und halb offene UTC-Spannen.
|
||||
- Jede Produktionsänderung benötigt vorher einen fehlschlagenden Regressionstest.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Thumbnail-Autorisierung
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts`
|
||||
- Test: `src/app/api/assets/[assetId]/thumbnail/route.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `ImmichClient.listAlbumsForAsset`, `ImmichClient.getAlbum`.
|
||||
- Produces: generischer 404 oder autorisierte Thumbnail-Response.
|
||||
|
||||
- [ ] Test ergänzen: bekannte Fremd-Asset-ID trotz vorhandener Grants ergibt 404; Admin ohne passende Album-Cover-Bindung ergibt 404.
|
||||
- [ ] Fokussierten Test ausführen und erwartetes RED bestätigen.
|
||||
- [ ] Asset-Alben mit Grants schneiden und Admin-Cover-Bindung wiederherstellen.
|
||||
- [ ] Test erneut ausführen und GREEN bestätigen.
|
||||
|
||||
### Task 2: Flatrate-Wahrheit
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/admin/redaktionen/[id]/actions.ts`
|
||||
- Modify: `src/modules/usages/service.ts`
|
||||
- Modify: `src/modules/billing/reports.ts`
|
||||
- Test: `src/app/admin/redaktionen/[id]/actions.test.ts`
|
||||
- Test: `src/modules/usages/service.test.ts`
|
||||
- Test: `src/modules/billing/reports.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: validierte Flatrate-Konfiguration und konsistenter `flatrateCentsSnapshot`.
|
||||
|
||||
- [ ] RED: aktive Flatrate ohne positiven Preis wird abgelehnt.
|
||||
- [ ] RED: Berliner Monatsrand wird korrekt gezählt.
|
||||
- [ ] RED: gerenderter/persistierter Snapshot enthält denselben Pauschalbetrag wie `netTotalCents`.
|
||||
- [ ] Minimale Validierungs-, Perioden- und Snapshotkorrektur implementieren.
|
||||
- [ ] Fokussierte Tests GREEN ausführen.
|
||||
|
||||
### Task 3: ZIP-Abrechnung
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/api/lightbox/bulk-download/route.ts`
|
||||
- Create: `src/app/api/lightbox/bulk-download/route.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: Same-Origin-geschützten ZIP-Stream und terminale Downloadzustände.
|
||||
|
||||
- [ ] RED: Cross-Origin wird vor Seiteneffekten abgewiesen.
|
||||
- [ ] RED: Archivfehler nach Bytes markiert `interrupted`; Fehler vor Bytes voidet neue Nutzung; erfolgreicher Abschluss markiert erst nach Archivfinalisierung `completed`.
|
||||
- [ ] RED: Response enthält `private, no-store` und `nosniff`.
|
||||
- [ ] Handler-Abhängigkeiten isolieren und minimale Stream-/Settlement-Logik implementieren.
|
||||
- [ ] Fokussierte Tests GREEN ausführen.
|
||||
|
||||
### Task 4: Rate-Limit-Verdrahtung
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/modules/auth/auth.ts`
|
||||
- Modify: `src/app/(public)/registrieren/page.tsx`
|
||||
- Modify: `src/app/api/download-intents/intent-handler.ts`
|
||||
- Modify: `src/modules/albums/catalog.ts`
|
||||
- Modify: `src/app/api/lightbox/bulk-download/route.ts`
|
||||
- Test: zugehörige Auth-, Intent-, Catalog- und Bulk-Tests.
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: 429 plus `Retry-After`; persistente Portal-Limits und explizite Better-Auth-Regeln.
|
||||
|
||||
- [ ] RED-Tests pro produktivem Pfad ergänzen.
|
||||
- [ ] Stabile gehashte Schlüssel und 429-Response zentral implementieren.
|
||||
- [ ] Better-Auth-Regeln für Anmeldung und Reset konfigurieren.
|
||||
- [ ] Fokussierte Tests GREEN ausführen.
|
||||
|
||||
### Task 5: Nutzertexte
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/modules/auth/public-forms.tsx`
|
||||
- Modify: `src/modules/auth/public-forms.test.tsx`
|
||||
- Modify: `src/modules/email/service.ts`
|
||||
- Create/Modify: `src/modules/email/service.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: wahrheitsgemäße Passwort-Erfolgsmeldung mit Anmeldelink und eindeutig bezeichneten Nutzungsnachweis.
|
||||
|
||||
- [ ] RED: erfolgreicher Reset zeigt „Passwort wurde aktualisiert“ und Link `/anmelden`; API-Fehler zeigt keinen Erfolg.
|
||||
- [ ] RED: Billing-Mail enthält in Text und HTML „keine Rechnung“ sowie Hinweis auf separate Rechnung.
|
||||
- [ ] Minimale UI- und Mail-Content-Änderung implementieren.
|
||||
- [ ] Fokussierte Tests GREEN ausführen.
|
||||
|
||||
### Task 6: Quality Gates und Übergabe
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/modules/mail/mailer.test.ts`
|
||||
- Modify: `src/components/brand/logo.test.tsx`
|
||||
- Modify: `src/components/theme-toggle.tsx`
|
||||
- Modify: `eslint.config.mjs`
|
||||
- Delete: `drizzle/0007_album_auto_rules_and_archive.sql`
|
||||
- Create: `docs/legal/agb-und-lizenzbedingungen-entwurf.md`
|
||||
|
||||
- [ ] Veraltete Erwartungen an bewusst geändertes HTML/Logo aktualisieren.
|
||||
- [ ] Theme-Toggle lint-konform und hydration-sicher gestalten; `.worktrees/**` ignorieren.
|
||||
- [ ] Verwaiste, nicht journalisierte Doppel-Migration entfernen.
|
||||
- [ ] AGB-/Lizenzentwurf auf Basis offizieller deutscher Rechtsquellen erstellen.
|
||||
- [ ] Vollsuite, Typecheck, Lint, Drizzle-Check, Build und `git diff --check` ausführen.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Produktionshärtung und Nutzertexte – Design
|
||||
|
||||
## Ziel
|
||||
|
||||
Die nach dem Portal-Audit bestätigten Autorisierungs-, Abrechnungs- und Schutzlücken werden geschlossen. Zusätzlich erhalten Nutzer nach einem erfolgreichen Passwortwechsel eine eindeutige Anmeldung-Aufforderung, und der per E-Mail versandte PDF-Anhang wird unmissverständlich als Nutzungsnachweis statt als Rechnung bezeichnet.
|
||||
|
||||
## Freigegebener Umfang
|
||||
|
||||
Der Nutzer hat die im Audit vorgeschlagene Reihenfolge und die dort beschriebenen Korrekturen freigegeben. Änderungen bleiben auf folgende Bereiche begrenzt:
|
||||
|
||||
1. Thumbnail-Zugriff nur für Assets in aktuell freigegebenen Alben; Admin-Zugriff nur auf ein an ein Album gebundenes Cover.
|
||||
2. Flatrate nur mit positivem Preis; Berlin-sichere Monatsgrenzen; derselbe serverseitig ermittelte Pauschal-Snapshot in Summe, PDF und Datenbank.
|
||||
3. ZIP-Downloads mit Same-Origin-Prüfung, privaten No-Store-Headern, Abbruchpropagierung und wahrheitsgemäßen Terminalzuständen.
|
||||
4. Bestehende Rate-Limit-Policies werden an die produktiven Pfade angebunden. Auth-Endpunkte verwenden die Better-Auth-Regeln; registrierungs- und portalspezifische Pfade verwenden den vorhandenen PostgreSQL-Limiter.
|
||||
5. Passwort-Reset zeigt nur bei bestätigtem API-Erfolg einen Link zur Anmeldung; Fehler bleiben sichtbar.
|
||||
6. Abrechnungs-E-Mails heißen „Nutzungsnachweis“ und weisen in Text und HTML darauf hin, dass die Rechnung separat folgt.
|
||||
7. Veraltete Tests und die verwaiste Doppel-Migration werden bereinigt.
|
||||
|
||||
## Datenfluss und Sicherheitsgrenzen
|
||||
|
||||
### Thumbnails
|
||||
|
||||
Die Redaktion wird wie bisher aus der Session bestimmt. Danach werden die aktuellen Grant-IDs mit den durch Immich für das Asset gelieferten Album-IDs geschnitten. Eine leere Schnittmenge ergibt denselben generischen 404 wie ein unbekanntes Asset. Admins müssen `albumId` übergeben; nur `album.albumThumbnailAssetId === assetId` ist zulässig.
|
||||
|
||||
### Flatrate
|
||||
|
||||
Aktivierung ohne positiven Preis wird abgelehnt. `buildSnapshot` ist die einzige Quelle für den Pauschalbetrag. Der zurückgegebene Wert wird für PDF, Gesamtbetrag und persistierten Report wiederverwendet. Monatslimits verwenden `monthPeriod(..., "Europe/Berlin")` und eine halb offene UTC-Spanne.
|
||||
|
||||
### ZIP
|
||||
|
||||
Jeder Claim bleibt einem Asset zugeordnet. Ein vollständig erzeugtes und geschlossenenes Archiv setzt erfolgreich eingebrachte Events auf `completed`. Vor dem ersten Byte wird `failed_before_delivery` verwendet, nach Bytes `interrupted`. Abbruch oder Archivfehler terminalisiert alle bereits geclaimten, noch offenen Events; noch nicht begonnene Assets erzeugen keine Nutzung. Der Response ist `private, no-store` und `nosniff`.
|
||||
|
||||
### Rate-Limits
|
||||
|
||||
Authentifizierte Portalpfade verwenden stabile Schlüssel aus der serverseitigen Editorial-ID. Registrierung verwendet einen SHA-256-Schlüssel aus normalisierter E-Mail und einer vom Reverse Proxy gesetzten Clientadresse; Rohdaten werden nicht gespeichert. Eine Überschreitung liefert 429 und `Retry-After`. Better Auth erhält explizite Produktionsregeln für Anmeldung und Passwort-Reset.
|
||||
|
||||
## Fehlerbehandlung
|
||||
|
||||
- Autorisierungsfehler verraten weder Asset-Existenz noch Fremdzugriff.
|
||||
- Abrechnungsfehler löschen keine Historie.
|
||||
- Ein ungültiger oder verbrauchter Passwort-Reset-Link zeigt keine falsche Erfolgsmeldung.
|
||||
- E-Mail-Versandfehler ändern nicht den bereits atomar finalisierten Report.
|
||||
|
||||
## Tests
|
||||
|
||||
Jede Verhaltensänderung beginnt mit einem reproduzierenden RED-Test. Danach laufen fokussierte Tests, die vollständige deterministische Suite, Typecheck, Lint, Drizzle-Check und Produktionsbuild. Testcontainers-/E2E-Tests werden ausgeführt, sofern Docker verfügbar ist; andernfalls bleibt der externe Blocker dokumentiert.
|
||||
|
||||
## AGB-Übergabe
|
||||
|
||||
Der AGB-/Lizenzbedingungen-Entwurf wird getrennt von der Portalimplementierung erstellt. Er ist eine Arbeitsvorlage für die Hauptwebsite, enthält markierte Betreiber-/Vergütungsplatzhalter und muss vor Veröffentlichung anwaltlich geprüft werden.
|
||||
@@ -1,32 +0,0 @@
|
||||
-- 1. Create the album_auto_rules table
|
||||
CREATE TABLE IF NOT EXISTS "album_auto_rules" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"keyword" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"created_by_user_id" uuid
|
||||
);
|
||||
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE "album_auto_rules" ADD CONSTRAINT "album_auto_rules_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN null;
|
||||
END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE "album_auto_rules" ADD CONSTRAINT "album_auto_rules_created_by_user_id_users_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN null;
|
||||
END $$;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "album_auto_rules_editorial_account_id_keyword_idx" ON "album_auto_rules" ("editorial_account_id", lower("keyword"));
|
||||
|
||||
-- 2. Add archived_at and archived_by_user_id to editorial_accounts
|
||||
ALTER TABLE "editorial_accounts" ADD COLUMN "archived_at" timestamp with time zone;
|
||||
ALTER TABLE "editorial_accounts" ADD COLUMN "archived_by_user_id" uuid;
|
||||
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_archived_by_user_id_users_id_fk" FOREIGN KEY ("archived_by_user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN null;
|
||||
END $$;
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX "usages_created_at_idx" ON "usages" USING btree ("created_at");
|
||||
File diff suppressed because it is too large.
Load diff
@@ -64,6 +64,13 @@
|
||||
"when": 1786411419497,
|
||||
"tag": "0008_overjoyed_wrecking_crew",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "7",
|
||||
"when": 1786455754414,
|
||||
"tag": "0009_usage_created_at_index",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -1,5 +1,8 @@
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
|
||||
const eslintConfig = [...nextVitals];
|
||||
const eslintConfig = [
|
||||
{ ignores: [".next/**", ".worktrees/**"] },
|
||||
...nextVitals,
|
||||
];
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -1,5 +1,6 @@
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { env } from "@/config/env";
|
||||
import { registerEditorial } from "@/modules/auth/auth";
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
RegistrationForm,
|
||||
type RegistrationFormState,
|
||||
} from "@/modules/auth/public-forms";
|
||||
import { RateLimitExceededError } from "@/modules/security/rate-limit-guard";
|
||||
|
||||
export default function RegistrationPage() {
|
||||
return (
|
||||
@@ -62,8 +64,15 @@ async function registerAction(
|
||||
actsForBusiness: formData.has("actsForBusiness"),
|
||||
termsVersion: formData.has("termsAccepted") ? CURRENT_TERMS_VERSION : "",
|
||||
privacyAcknowledged: formData.has("privacyAcknowledged"),
|
||||
});
|
||||
}, await headers());
|
||||
} catch (error) {
|
||||
if (error instanceof RateLimitExceededError) {
|
||||
return {
|
||||
errors: {
|
||||
form: "Es wurden zu viele Registrierungsversuche gesendet. Bitte versuchen Sie es später erneut.",
|
||||
},
|
||||
};
|
||||
}
|
||||
if (error instanceof RegistrationValidationError) {
|
||||
return { errors: { [error.field]: error.message } };
|
||||
}
|
||||
|
||||
@@ -6,14 +6,21 @@ beforeEach(() => {
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
approveEditorial: vi.fn(),
|
||||
dbSet: vi.fn(),
|
||||
dbWhere: vi.fn(),
|
||||
headers: vi.fn(),
|
||||
requireAdmin: vi.fn(),
|
||||
revalidatePath: vi.fn(),
|
||||
}));
|
||||
|
||||
mocks.dbSet.mockReturnValue({ where: mocks.dbWhere });
|
||||
|
||||
vi.mock("next/headers", () => ({ headers: mocks.headers }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
|
||||
vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin }));
|
||||
vi.mock("@/db/client", () => ({
|
||||
db: { update: vi.fn(() => ({ set: mocks.dbSet })) },
|
||||
}));
|
||||
vi.mock("@/modules/editorials/service", () => ({
|
||||
editorialService: { approveEditorial: mocks.approveEditorial },
|
||||
EditorialServiceError: class EditorialServiceError extends Error {
|
||||
@@ -23,7 +30,7 @@ vi.mock("@/modules/editorials/service", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
import { approveEditorialAction } from "./actions";
|
||||
import { approveEditorialAction, updateFlatrateAction } from "./actions";
|
||||
|
||||
const initial = { ok: true, message: "" };
|
||||
|
||||
@@ -97,4 +104,34 @@ test("the approve action translates a service error into a German message", asyn
|
||||
ok: false,
|
||||
message: "Bitte weisen Sie zuerst mindestens ein Album zu.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("an active flatrate cannot be persisted without a positive price", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
const formData = new FormData();
|
||||
formData.set("flatrateActive", "on");
|
||||
|
||||
await expect(
|
||||
updateFlatrateAction("00000000-0000-4000-8000-000000000001", formData),
|
||||
).rejects.toThrow("INVALID_FLATRATE_PRICE");
|
||||
expect(mocks.dbSet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("an active flatrate persists a positive cents price and optional limit", async () => {
|
||||
mocks.headers.mockResolvedValue(new Headers());
|
||||
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||
mocks.dbWhere.mockResolvedValue(undefined);
|
||||
const formData = new FormData();
|
||||
formData.set("flatrateActive", "on");
|
||||
formData.set("flatratePriceEuros", "149,50");
|
||||
formData.set("flatrateAssetLimit", "20");
|
||||
|
||||
await updateFlatrateAction("00000000-0000-4000-8000-000000000001", formData);
|
||||
|
||||
expect(mocks.dbSet).toHaveBeenCalledWith({
|
||||
flatrateActive: true,
|
||||
flatratePriceCents: 14_950,
|
||||
flatrateAssetLimit: 20,
|
||||
});
|
||||
});
|
||||
@@ -98,6 +98,9 @@ export async function updateFlatrateAction(editorialId: string, formData: FormDa
|
||||
flatratePriceCents = price.cents;
|
||||
}
|
||||
}
|
||||
if (flatrateActive && flatratePriceCents === null) {
|
||||
throw new Error("INVALID_FLATRATE_PRICE");
|
||||
}
|
||||
|
||||
let flatrateAssetLimit: number | null = null;
|
||||
const rawLimit = formData.get("flatrateAssetLimit");
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createThumbnailHandler } from "./thumbnail-handler";
|
||||
vi.mock("sharp", () => {
|
||||
return {
|
||||
default: () => ({
|
||||
resize: vi.fn().mockReturnThis(),
|
||||
metadata: vi.fn().mockResolvedValue({ width: 100, height: 100 }),
|
||||
composite: vi.fn().mockReturnThis(),
|
||||
webp: vi.fn().mockReturnThis(),
|
||||
@@ -53,6 +54,13 @@ function createHandler(options?: {
|
||||
requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }),
|
||||
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
|
||||
immich: {
|
||||
listAlbumsForAsset: vi.fn().mockImplementation(async () => {
|
||||
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
|
||||
return (options?.assetAlbumIds ?? ["allowed"]).map((id) => ({
|
||||
...grantedAlbum,
|
||||
id,
|
||||
}));
|
||||
}),
|
||||
getAsset: vi.fn().mockImplementation(async () => {
|
||||
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
|
||||
return {
|
||||
@@ -97,6 +105,7 @@ test("streams a thumbnail when the requested asset belongs to any current grant"
|
||||
expect(response.headers.get("cache-control")).toBe("private, no-store");
|
||||
await expect(response.arrayBuffer()).resolves.toEqual(new Uint8Array([1, 2, 3]).buffer);
|
||||
expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("asset-1");
|
||||
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
|
||||
});
|
||||
|
||||
test("refuses a thumbnail immediately after its last grant is revoked", async () => {
|
||||
@@ -105,7 +114,7 @@ test("refuses a thumbnail immediately after its last grant is revoked", async ()
|
||||
const response = await call(handler);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(dependencies.immich.getAsset).not.toHaveBeenCalled();
|
||||
expect(dependencies.immich.listAlbumsForAsset).not.toHaveBeenCalled();
|
||||
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
|
||||
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -164,8 +173,8 @@ test("uses one asset-album membership lookup for a 60-photo gallery regardless o
|
||||
const response = await call(handler);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(dependencies.immich.getAsset).toHaveBeenCalledTimes(1);
|
||||
expect(dependencies.immich.getAsset).toHaveBeenCalledWith("asset-1");
|
||||
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
|
||||
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
|
||||
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
|
||||
|
||||
type ThumbnailImmich = {
|
||||
getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>;
|
||||
getAsset(assetId: string): Promise<{ albums: Array<{ id: string }> }>;
|
||||
listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
|
||||
getThumbnail(assetId: string): Promise<ImmichBinary>;
|
||||
};
|
||||
|
||||
@@ -37,7 +37,11 @@ export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencie
|
||||
const access = await authorizeRequest(dependencies, request.headers);
|
||||
const authorized =
|
||||
access.kind === "admin"
|
||||
? true
|
||||
? await isAdminAlbumCover(
|
||||
dependencies.immich,
|
||||
assetId,
|
||||
requestedUrl.searchParams.get("albumId"),
|
||||
)
|
||||
: await isGrantedEditorialAsset(dependencies, access.editorialId, assetId);
|
||||
if (!authorized) {
|
||||
return genericNotFound();
|
||||
@@ -74,21 +78,27 @@ async function authorizeRequest(
|
||||
async function isGrantedEditorialAsset(
|
||||
dependencies: ThumbnailHandlerDependencies,
|
||||
editorialId: string,
|
||||
assetId: string, // unused but kept for signature
|
||||
assetId: string,
|
||||
): Promise<boolean> {
|
||||
const grantedAlbumIds = await dependencies.getGrantedAlbumIds(editorialId);
|
||||
// If they have access to at least one album, we allow them to see the watermarked thumbnail.
|
||||
// UUIDs are unguessable (128-bit entropy), so an editorial user can only request thumbnails
|
||||
// for assets they already discovered through their granted albums.
|
||||
// We cannot reliably check asset.albums via getAsset because it is empty for older Immich assets.
|
||||
return grantedAlbumIds.length > 0;
|
||||
const grantedAlbumIds = new Set(await dependencies.getGrantedAlbumIds(editorialId));
|
||||
if (grantedAlbumIds.size === 0) return false;
|
||||
const assetAlbums = await dependencies.immich.listAlbumsForAsset(assetId);
|
||||
return assetAlbums.some((album) => grantedAlbumIds.has(album.id));
|
||||
}
|
||||
|
||||
|
||||
async function isAdminAlbumCover(
|
||||
immich: ThumbnailImmich,
|
||||
assetId: string,
|
||||
albumId: string | null,
|
||||
): Promise<boolean> {
|
||||
if (!albumId || !isSafeAssetId(albumId)) return false;
|
||||
const album = await immich.getAlbum(albumId);
|
||||
return album.albumThumbnailAssetId === assetId;
|
||||
}
|
||||
|
||||
function thumbnailResponse(thumbnail: ImmichBinary, assetId: string): Response {
|
||||
const responseHeaders = new Headers({
|
||||
"cache-control": "private, max-age=86400, stale-while-revalidate=604800",
|
||||
"cache-control": "private, no-store",
|
||||
"content-type": thumbnail.contentType,
|
||||
"x-content-type-options": "nosniff",
|
||||
"etag": `"${assetId}"`,
|
||||
@@ -100,7 +110,10 @@ function thumbnailResponse(thumbnail: ImmichBinary, assetId: string): Response {
|
||||
}
|
||||
|
||||
function genericNotFound(): Response {
|
||||
return new Response(null, { status: 404 });
|
||||
return new Response(null, {
|
||||
status: 404,
|
||||
headers: { "cache-control": "private, no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: string): Promise<Response> {
|
||||
@@ -158,7 +171,7 @@ async function watermarkedThumbnailResponse(thumbnail: ImmichBinary, assetId: st
|
||||
}
|
||||
|
||||
const responseHeaders = new Headers({
|
||||
"cache-control": "private, max-age=86400, stale-while-revalidate=604800",
|
||||
"cache-control": "private, no-store",
|
||||
"content-type": "image/webp",
|
||||
"content-length": String(watermarked.length),
|
||||
"x-content-type-options": "nosniff",
|
||||
|
||||
@@ -3,6 +3,12 @@ import { z } from "zod";
|
||||
import { createRepeatDownload } from "@/modules/downloads/service";
|
||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||
import { downloadIntentsPolicy, consumeRateLimit } from "@/modules/security/rate-limit";
|
||||
import {
|
||||
enforceRateLimit,
|
||||
RateLimitExceededError,
|
||||
type ConsumeRateLimit,
|
||||
} from "@/modules/security/rate-limit-guard";
|
||||
import { createNewUsage } from "@/modules/usages/service";
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
@@ -32,6 +38,7 @@ type IntentHandlerDependencies = {
|
||||
requireActiveEditorial: typeof requireActiveEditorial;
|
||||
createNewUsage: typeof createNewUsage;
|
||||
createRepeatDownload: typeof createRepeatDownload;
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
};
|
||||
|
||||
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
|
||||
@@ -39,6 +46,11 @@ export function createDownloadIntentHandler(dependencies: IntentHandlerDependenc
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||
await enforceRateLimit(
|
||||
dependencies.consumeRateLimit,
|
||||
`download-intent:${principal.editorialId}`,
|
||||
downloadIntentsPolicy,
|
||||
);
|
||||
const payload = intentPayload.safeParse(await readJson(request));
|
||||
if (!payload.success) return errorResponse(400, "INVALID_REQUEST");
|
||||
|
||||
@@ -85,6 +97,11 @@ async function readJson(request: Request): Promise<unknown> {
|
||||
}
|
||||
|
||||
function mappedError(error: unknown): Response {
|
||||
if (error instanceof RateLimitExceededError) {
|
||||
return errorResponse(429, "RATE_LIMITED", {
|
||||
"retry-after": String(error.retryAfterSeconds),
|
||||
});
|
||||
}
|
||||
if (error instanceof CrossOriginRequestError) {
|
||||
return errorResponse(403, "CROSS_ORIGIN_REQUEST");
|
||||
}
|
||||
@@ -115,10 +132,12 @@ function mappedError(error: unknown): Response {
|
||||
return errorResponse(500, "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function errorResponse(status: number, code: string): Response {
|
||||
function errorResponse(status: number, code: string, extraHeaders?: HeadersInit): Response {
|
||||
const headers = new Headers(extraHeaders);
|
||||
headers.set("cache-control", "private, no-store");
|
||||
return Response.json(
|
||||
{ code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
{ status, headers },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -126,4 +145,5 @@ export const authorizedDownloadIntentHandler = createDownloadIntentHandler({
|
||||
requireActiveEditorial,
|
||||
createNewUsage,
|
||||
createRepeatDownload,
|
||||
consumeRateLimit,
|
||||
});
|
||||
@@ -30,6 +30,7 @@ function dependencies() {
|
||||
status: "authorized",
|
||||
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||
}),
|
||||
consumeRateLimit: vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -138,3 +139,23 @@ test("passes one submitted idempotency key through unchanged", async () => {
|
||||
expect(deps.createNewUsage).toHaveBeenNthCalledWith(1, expect.objectContaining({ idempotencyKey }));
|
||||
expect(deps.createNewUsage).toHaveBeenNthCalledWith(2, expect.objectContaining({ idempotencyKey }));
|
||||
});
|
||||
|
||||
test("returns retry-after without creating an intent when the editorial limit is exhausted", async () => {
|
||||
const deps = dependencies();
|
||||
deps.consumeRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 23 });
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "new_usage",
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Titelgeschichte",
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(429);
|
||||
expect(response.headers.get("retry-after")).toBe("23");
|
||||
expect(deps.consumeRateLimit).toHaveBeenCalledWith(
|
||||
`download-intent:${editorialId}`,
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { PassThrough, type Readable as NodeReadable } from "node:stream";
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
const assetId = "22222222-2222-4222-8222-222222222222";
|
||||
const albumId = "33333333-3333-4333-8333-333333333333";
|
||||
const downloadId = "44444444-4444-4444-8444-444444444444";
|
||||
const secondAssetId = "66666666-6666-4666-8666-666666666666";
|
||||
|
||||
function fakeArchive(): BulkArchive {
|
||||
let destination: PassThrough | undefined;
|
||||
const pending: Promise<void>[] = [];
|
||||
return {
|
||||
pipe(target) {
|
||||
destination = target;
|
||||
},
|
||||
append(source: NodeReadable) {
|
||||
pending.push(
|
||||
new Promise((resolve, reject) => {
|
||||
source.on("data", (chunk) => destination?.write(chunk));
|
||||
source.once("end", resolve);
|
||||
source.once("error", reject);
|
||||
}),
|
||||
);
|
||||
},
|
||||
async finalize() {
|
||||
await Promise.all(pending);
|
||||
destination?.end();
|
||||
},
|
||||
abort() {
|
||||
destination?.destroy(new Error("aborted"));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function dependencies() {
|
||||
return {
|
||||
requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }),
|
||||
getGrantedAlbumIds: vi.fn().mockResolvedValue([albumId]),
|
||||
searchPhotos: vi.fn().mockResolvedValue({ items: [{ id: assetId }] }),
|
||||
getAsset: vi.fn().mockResolvedValue({ id: assetId, originalFileName: "foto.jpg" }),
|
||||
getOriginal: vi.fn().mockResolvedValue({
|
||||
body: new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
filename: "foto.jpg",
|
||||
contentType: "image/jpeg",
|
||||
contentLength: 3,
|
||||
}),
|
||||
listPriorUsages: vi.fn().mockResolvedValue([]),
|
||||
createNewUsage: vi.fn().mockResolvedValue({ id: downloadId }),
|
||||
createRepeatDownload: vi.fn(),
|
||||
repository: {
|
||||
claimAuthorized: vi.fn().mockResolvedValue({
|
||||
outcome: "claimed",
|
||||
download: {
|
||||
id: downloadId,
|
||||
usageId: "55555555-5555-4555-8555-555555555555",
|
||||
assetId,
|
||||
filename: "foto.jpg",
|
||||
intentKind: "new_usage",
|
||||
},
|
||||
}),
|
||||
failBeforeDelivery: vi.fn().mockResolvedValue(true),
|
||||
markCompleted: vi.fn().mockResolvedValue(true),
|
||||
markInterrupted: vi.fn().mockResolvedValue(true),
|
||||
},
|
||||
createArchive: vi.fn(fakeArchive),
|
||||
consumeRateLimit: vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 }),
|
||||
};
|
||||
}
|
||||
|
||||
function request(origin = "http://portal.test", assetIds = [assetId]) {
|
||||
return new Request("http://portal.test/api/lightbox/bulk-download", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", host: "portal.test", origin },
|
||||
body: JSON.stringify({ assetIds, purpose: "Titelgeschichte" }),
|
||||
});
|
||||
}
|
||||
|
||||
test("rejects cross-origin archive requests before authentication or accounting", async () => {
|
||||
const deps = dependencies();
|
||||
const response = await createBulkDownloadHandler(deps)(request("https://attacker.test"));
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(deps.requireActiveEditorial).not.toHaveBeenCalled();
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("streams a private archive and completes accounting after response consumption", async () => {
|
||||
const deps = dependencies();
|
||||
const incoming = request();
|
||||
const response = await createBulkDownloadHandler(deps)(incoming);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("cache-control")).toBe("private, no-store");
|
||||
expect(response.headers.get("x-content-type-options")).toBe("nosniff");
|
||||
expect(deps.repository.markCompleted).not.toHaveBeenCalled();
|
||||
|
||||
await response.arrayBuffer();
|
||||
|
||||
expect(deps.getOriginal).toHaveBeenCalledWith(assetId, incoming.signal);
|
||||
expect(deps.repository.markCompleted).toHaveBeenCalledWith(downloadId, 3);
|
||||
expect(deps.repository.failBeforeDelivery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rate-limits bulk creation before usages are opened", async () => {
|
||||
const deps = dependencies();
|
||||
deps.consumeRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 31 });
|
||||
|
||||
const response = await createBulkDownloadHandler(deps)(request());
|
||||
|
||||
expect(response.status).toBe(429);
|
||||
expect(response.headers.get("retry-after")).toBe("31");
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("settles an already claimed first item when preparation of a later item fails", async () => {
|
||||
const deps = dependencies();
|
||||
deps.searchPhotos.mockResolvedValue({ items: [{ id: assetId }, { id: secondAssetId }] });
|
||||
deps.getAsset.mockImplementation(async (id: string) => ({ id, originalFileName: `${id}.jpg` }));
|
||||
deps.createNewUsage
|
||||
.mockResolvedValueOnce({ id: downloadId })
|
||||
.mockRejectedValueOnce(new Error("accounting unavailable"));
|
||||
|
||||
const response = await createBulkDownloadHandler(deps)(
|
||||
request("http://portal.test", [assetId, secondAssetId]),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: true,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,343 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { basename } from "node:path";
|
||||
import { PassThrough, Readable, type Readable as NodeReadable } from "node:stream";
|
||||
|
||||
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import {
|
||||
createBulkDeliveryAccounting,
|
||||
streamBulkArchiveWithAccounting,
|
||||
} from "@/modules/downloads/bulk-accounting";
|
||||
import type { DownloadDeliveryRepository } from "@/modules/downloads/stream";
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||
import { downloadIntentsPolicy } from "@/modules/security/rate-limit";
|
||||
import {
|
||||
enforceRateLimit,
|
||||
RateLimitExceededError,
|
||||
type ConsumeRateLimit,
|
||||
} from "@/modules/security/rate-limit-guard";
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
export type BulkArchive = {
|
||||
pipe(destination: PassThrough): unknown;
|
||||
append(source: NodeReadable, options: { name: string }): unknown;
|
||||
finalize(): Promise<unknown> | unknown;
|
||||
abort(): unknown;
|
||||
};
|
||||
|
||||
type BulkDownloadHandlerDependencies = {
|
||||
requireActiveEditorial(headers: Headers): Promise<{ editorialId: string }>;
|
||||
getGrantedAlbumIds(editorialId: string): Promise<string[]>;
|
||||
searchPhotos(input: {
|
||||
albumIds: string[];
|
||||
type: "IMAGE";
|
||||
page: number;
|
||||
size: number;
|
||||
withExif: false;
|
||||
}): Promise<{ items: Array<{ id: string }> }>;
|
||||
getAsset(assetId: string): Promise<{ id: string; originalFileName: string }>;
|
||||
getOriginal(
|
||||
assetId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ body: ReadableStream<Uint8Array> }>;
|
||||
listPriorUsages(editorialId: string, assetId: string): Promise<Array<{ id: string }>>;
|
||||
createNewUsage(input: {
|
||||
editorialId: string;
|
||||
assetId: string;
|
||||
albumId: string;
|
||||
purpose: string;
|
||||
reference?: string;
|
||||
idempotencyKey: string;
|
||||
}): Promise<{ id: string }>;
|
||||
createRepeatDownload(input: {
|
||||
editorialId: string;
|
||||
usageId: string;
|
||||
idempotencyKey: string;
|
||||
}): Promise<{ id: string }>;
|
||||
repository: DownloadDeliveryRepository;
|
||||
createArchive(): BulkArchive;
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
};
|
||||
|
||||
type PreparedDownload = {
|
||||
assetId: string;
|
||||
downloadId: string;
|
||||
filename: string;
|
||||
};
|
||||
|
||||
export function createBulkDownloadHandler(dependencies: BulkDownloadHandlerDependencies) {
|
||||
return async function POST(request: Request): Promise<Response> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||
await enforceRateLimit(
|
||||
dependencies.consumeRateLimit,
|
||||
`bulk-download:${principal.editorialId}`,
|
||||
downloadIntentsPolicy,
|
||||
);
|
||||
const payload = await parsePayload(request);
|
||||
const grantedAlbumIds = await dependencies.getGrantedAlbumIds(principal.editorialId);
|
||||
const assetToGrantedAlbum = await grantedAssetMap(dependencies, grantedAlbumIds);
|
||||
const accounting = createBulkDeliveryAccounting(dependencies.repository);
|
||||
let downloads: PreparedDownload[];
|
||||
try {
|
||||
downloads = await prepareDownloads(
|
||||
dependencies,
|
||||
principal.editorialId,
|
||||
payload,
|
||||
assetToGrantedAlbum,
|
||||
async (item) => {
|
||||
const claim = await dependencies.repository.claimAuthorized(
|
||||
principal.editorialId,
|
||||
item.downloadId,
|
||||
);
|
||||
if (claim.outcome !== "claimed") {
|
||||
throw new Error("Fresh bulk-download intent could not be claimed");
|
||||
}
|
||||
accounting.track({
|
||||
downloadId: item.downloadId,
|
||||
intentKind: claim.download.intentKind,
|
||||
});
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
await accounting.failArchive().catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (downloads.length === 0) return plainError(404, "No valid assets found for download");
|
||||
|
||||
const passThrough = new PassThrough();
|
||||
const archive = dependencies.createArchive();
|
||||
archive.pipe(passThrough);
|
||||
const abortArchive = () => {
|
||||
try {
|
||||
archive.abort();
|
||||
} catch {
|
||||
// The archive may already be finalized.
|
||||
}
|
||||
passThrough.destroy(new Error("Archive request aborted"));
|
||||
};
|
||||
request.signal.addEventListener("abort", abortArchive, { once: true });
|
||||
passThrough.once("close", () => request.signal.removeEventListener("abort", abortArchive));
|
||||
|
||||
void produceArchive({
|
||||
archive,
|
||||
passThrough,
|
||||
downloads,
|
||||
requestSignal: request.signal,
|
||||
getOriginal: dependencies.getOriginal,
|
||||
accounting,
|
||||
});
|
||||
|
||||
const body = streamBulkArchiveWithAccounting(
|
||||
Readable.toWeb(passThrough) as ReadableStream<Uint8Array>,
|
||||
accounting,
|
||||
);
|
||||
const date = new Date().toISOString().slice(0, 10);
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
"cache-control": "private, no-store",
|
||||
"content-disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
|
||||
"content-type": "application/zip",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[bulk-download] failed:", error);
|
||||
return mappedBulkError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function produceArchive({
|
||||
archive,
|
||||
passThrough,
|
||||
downloads,
|
||||
requestSignal,
|
||||
getOriginal,
|
||||
accounting,
|
||||
}: {
|
||||
archive: BulkArchive;
|
||||
passThrough: PassThrough;
|
||||
downloads: PreparedDownload[];
|
||||
requestSignal: AbortSignal;
|
||||
getOriginal: BulkDownloadHandlerDependencies["getOriginal"];
|
||||
accounting: ReturnType<typeof createBulkDeliveryAccounting>;
|
||||
}) {
|
||||
try {
|
||||
for (const item of downloads) {
|
||||
if (requestSignal.aborted) throw new Error("Archive request aborted");
|
||||
const original = await getOriginal(item.assetId, requestSignal);
|
||||
const source = Readable.fromWeb(
|
||||
original.body as unknown as import("node:stream/web").ReadableStream<Uint8Array>,
|
||||
);
|
||||
source.on("data", (chunk: Buffer) => accounting.addBytes(item.downloadId, chunk.length));
|
||||
const ended = new Promise<void>((resolve, reject) => {
|
||||
source.once("end", resolve);
|
||||
source.once("error", reject);
|
||||
});
|
||||
archive.append(source, { name: safeArchiveFilename(item.filename) });
|
||||
await ended;
|
||||
accounting.markEntryReady(item.downloadId);
|
||||
}
|
||||
await archive.finalize();
|
||||
} catch (error) {
|
||||
await accounting.failArchive().catch(() => undefined);
|
||||
try {
|
||||
archive.abort();
|
||||
} catch {
|
||||
// Ignore cleanup errors; the accounting state is already terminal.
|
||||
}
|
||||
passThrough.destroy(error instanceof Error ? error : new Error("Archive failed"));
|
||||
}
|
||||
}
|
||||
|
||||
async function grantedAssetMap(
|
||||
dependencies: BulkDownloadHandlerDependencies,
|
||||
grantedAlbumIds: string[],
|
||||
) {
|
||||
const result = new Map<string, string>();
|
||||
const albums = await Promise.all(
|
||||
grantedAlbumIds.map(async (albumId) => {
|
||||
try {
|
||||
const page = await dependencies.searchPhotos({
|
||||
albumIds: [albumId],
|
||||
type: "IMAGE",
|
||||
page: 1,
|
||||
size: 1_000,
|
||||
withExif: false,
|
||||
});
|
||||
return { albumId, items: page.items };
|
||||
} catch {
|
||||
return { albumId, items: [] };
|
||||
}
|
||||
}),
|
||||
);
|
||||
for (const album of albums) {
|
||||
for (const asset of album.items) {
|
||||
if (!result.has(asset.id)) result.set(asset.id, album.albumId);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function prepareDownloads(
|
||||
dependencies: BulkDownloadHandlerDependencies,
|
||||
editorialId: string,
|
||||
payload: { assetIds: string[]; purpose: string },
|
||||
assetToGrantedAlbum: Map<string, string>,
|
||||
onPrepared: (item: PreparedDownload) => Promise<void>,
|
||||
) {
|
||||
const assets = await Promise.all(
|
||||
payload.assetIds.map(async (assetId) => {
|
||||
try {
|
||||
return await dependencies.getAsset(assetId);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
const downloads: PreparedDownload[] = [];
|
||||
for (const asset of assets) {
|
||||
if (!asset) continue;
|
||||
const albumId = assetToGrantedAlbum.get(asset.id);
|
||||
if (!albumId) continue;
|
||||
const prior = await dependencies.listPriorUsages(editorialId, asset.id);
|
||||
const intent = prior[0]
|
||||
? await dependencies.createRepeatDownload({
|
||||
editorialId,
|
||||
usageId: prior[0].id,
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
: await dependencies.createNewUsage({
|
||||
editorialId,
|
||||
assetId: asset.id,
|
||||
albumId,
|
||||
purpose: payload.purpose,
|
||||
reference: undefined,
|
||||
idempotencyKey: randomUUID(),
|
||||
});
|
||||
const prepared = {
|
||||
assetId: asset.id,
|
||||
downloadId: intent.id,
|
||||
filename: asset.originalFileName,
|
||||
};
|
||||
await onPrepared(prepared);
|
||||
downloads.push(prepared);
|
||||
}
|
||||
return downloads;
|
||||
}
|
||||
|
||||
async function parsePayload(request: Request) {
|
||||
const body = (await request.json()) as { assetIds?: unknown; purpose?: unknown };
|
||||
if (!Array.isArray(body.assetIds) || body.assetIds.length === 0 || body.assetIds.length > 100) {
|
||||
throw new BulkInputError();
|
||||
}
|
||||
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
if (body.assetIds.some((value) => typeof value !== "string" || !uuid.test(value))) {
|
||||
throw new BulkInputError();
|
||||
}
|
||||
if (typeof body.purpose !== "string" || body.purpose.trim().length === 0 || body.purpose.trim().length > 500) {
|
||||
throw new BulkInputError();
|
||||
}
|
||||
return { assetIds: body.assetIds as string[], purpose: body.purpose.trim() };
|
||||
}
|
||||
|
||||
class BulkInputError extends Error {}
|
||||
|
||||
function safeArchiveFilename(value: string) {
|
||||
const cleaned = basename(value)
|
||||
.replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_")
|
||||
.trim()
|
||||
.slice(0, 180);
|
||||
return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "foto";
|
||||
}
|
||||
|
||||
function plainError(status: number, message: string) {
|
||||
return new Response(message, {
|
||||
status,
|
||||
headers: { "cache-control": "private, no-store", "x-content-type-options": "nosniff" },
|
||||
});
|
||||
}
|
||||
|
||||
function mappedBulkError(error: unknown): Response {
|
||||
if (error instanceof RateLimitExceededError) {
|
||||
return jsonError(429, "RATE_LIMITED", {
|
||||
"retry-after": String(error.retryAfterSeconds),
|
||||
});
|
||||
}
|
||||
if (error instanceof CrossOriginRequestError) return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||
if (error instanceof BulkInputError) return jsonError(400, "INVALID_INPUT");
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
if (error instanceof UsageAccountingError) {
|
||||
const statusByCode: Record<UsageAccountingError["code"], number> = {
|
||||
INVALID_INPUT: 400,
|
||||
IDEMPOTENCY_CONFLICT: 409,
|
||||
ALBUM_NOT_GRANTED: 404,
|
||||
ASSET_NOT_FOUND: 404,
|
||||
ASSET_NOT_IN_ALBUM: 404,
|
||||
ASSET_NOT_IMAGE: 422,
|
||||
USAGE_NOT_FOUND: 404,
|
||||
IMMICH_UNAVAILABLE: 503,
|
||||
EDITORIAL_NOT_ACTIVE: 403,
|
||||
INVALID_PRICE: 409,
|
||||
};
|
||||
return jsonError(statusByCode[error.code] ?? 500, error.code);
|
||||
}
|
||||
return jsonError(500, "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function jsonError(status: number, code: string, extraHeaders?: HeadersInit) {
|
||||
const headers = new Headers(extraHeaders);
|
||||
headers.set("cache-control", "private, no-store");
|
||||
headers.set("x-content-type-options", "nosniff");
|
||||
return Response.json(
|
||||
{ code },
|
||||
{
|
||||
status,
|
||||
headers,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,231 +1,25 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { usageService } from "@/modules/usages/service";
|
||||
import { createRepeatDownload } from "@/modules/downloads/service";
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
|
||||
import { albumGrantService } from "@/modules/albums/grants";
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-explicit-any
|
||||
const archiver: any = require("archiver");
|
||||
import * as crypto from "crypto";
|
||||
import { Readable, PassThrough } from "stream";
|
||||
import { requireActiveEditorial } from "@/modules/auth/principal";
|
||||
import { createRepeatDownload } from "@/modules/downloads/service";
|
||||
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import { consumeRateLimit } from "@/modules/security/rate-limit";
|
||||
import { usageService } from "@/modules/usages/service";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const principal = await requireActiveEditorial(request.headers);
|
||||
const { assetIds, purpose } = await request.json();
|
||||
import { createBulkDownloadHandler, type BulkArchive } from "./bulk-handler";
|
||||
|
||||
if (!Array.isArray(assetIds) || assetIds.length === 0 || assetIds.length > 100) {
|
||||
return new Response("Invalid request: assetIds must be an array of 1 to 100 items", { status: 400 });
|
||||
}
|
||||
|
||||
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
for (const assetId of assetIds) {
|
||||
if (typeof assetId !== "string" || !uuidRegex.test(assetId)) {
|
||||
return new Response(`Invalid request: assetId ${assetId} is not a valid UUID format`, { status: 400 });
|
||||
}
|
||||
}
|
||||
const archiver = require("archiver") as { ZipArchive: new (options: unknown) => BulkArchive };
|
||||
|
||||
if (typeof purpose !== "string" || purpose.trim().length === 0 || purpose.trim().length > 500) {
|
||||
return new Response("Invalid request: purpose must be a non-empty string up to 500 characters", { status: 400 });
|
||||
}
|
||||
const trimmedPurpose = purpose.trim();
|
||||
|
||||
const grantedAlbumIds = await albumGrantService.getGrantedAlbumIds(principal.editorialId);
|
||||
|
||||
// Build a map of assetId -> a granted album that contains it. Immich's
|
||||
// GET /albums/:id no longer returns assets (metadata only), so fetch each
|
||||
// granted album's assets via /search/metadata instead.
|
||||
// ponytail: ceiling of 1000 assets per album; tail assets beyond that
|
||||
// won't map and are skipped from bulk download. Raise if needed.
|
||||
const assetToGrantedAlbum = new Map<string, string>();
|
||||
const albumAssets = await Promise.all(
|
||||
grantedAlbumIds.map(async (albumId) => {
|
||||
try {
|
||||
const page = await immichClient.searchPhotos({
|
||||
albumIds: [albumId],
|
||||
type: "IMAGE",
|
||||
page: 1,
|
||||
size: 1000,
|
||||
withExif: false,
|
||||
});
|
||||
return { albumId, items: page.items };
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch granted album assets", albumId, err);
|
||||
return { albumId, items: [] };
|
||||
}
|
||||
}),
|
||||
);
|
||||
for (const { albumId, items } of albumAssets) {
|
||||
for (const asset of items) {
|
||||
if (!assetToGrantedAlbum.has(asset.id)) {
|
||||
assetToGrantedAlbum.set(asset.id, albumId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const downloadsToProcess: { assetId: string, downloadId: string, filename: string, intentKind: "new_usage" | "repeat" }[] = [];
|
||||
|
||||
// 1. Fetch assets and validate in parallel
|
||||
const assetResults = await Promise.all(
|
||||
assetIds.map(async (assetId) => {
|
||||
try {
|
||||
const asset = await immichClient.getAsset(assetId);
|
||||
return { assetId, asset };
|
||||
} catch (err) {
|
||||
console.error("Asset fetch failed", assetId, err);
|
||||
return { assetId, asset: null };
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// 2. Process usages serially to avoid idempotency race conditions
|
||||
for (const { assetId, asset } of assetResults) {
|
||||
if (!asset) continue;
|
||||
|
||||
// Find the first album the editorial has access to
|
||||
const validAlbumId = assetToGrantedAlbum.get(assetId);
|
||||
if (!validAlbumId) continue; // Editorial does not have access
|
||||
|
||||
// Check for prior usages to avoid double charging
|
||||
const priorUsages = await usageService.listPriorUsages(principal.editorialId, assetId);
|
||||
const isRepeat = priorUsages.length > 0;
|
||||
|
||||
let downloadId: string;
|
||||
if (isRepeat) {
|
||||
// Create a repeat-download intent against the existing usage so the
|
||||
// delivery claim (claimAuthorized, which looks up download_events.id)
|
||||
// finds a valid intent. Reusing the usage id directly never matches.
|
||||
const repeatIntent = await createRepeatDownload({
|
||||
editorialId: principal.editorialId,
|
||||
usageId: priorUsages[0].id,
|
||||
idempotencyKey: crypto.randomUUID(),
|
||||
});
|
||||
downloadId = repeatIntent.id;
|
||||
} else {
|
||||
const idempotencyKey = crypto.randomUUID();
|
||||
|
||||
const newUsage = await usageService.createNewUsage({
|
||||
editorialId: principal.editorialId,
|
||||
assetId,
|
||||
albumId: validAlbumId,
|
||||
purpose: trimmedPurpose,
|
||||
reference: undefined,
|
||||
idempotencyKey,
|
||||
});
|
||||
downloadId = newUsage.id;
|
||||
}
|
||||
|
||||
downloadsToProcess.push({
|
||||
assetId,
|
||||
downloadId,
|
||||
filename: asset.originalFileName,
|
||||
intentKind: isRepeat ? "repeat" : "new_usage",
|
||||
});
|
||||
}
|
||||
|
||||
if (downloadsToProcess.length === 0) {
|
||||
return new Response("No valid assets found for download", { status: 404 });
|
||||
}
|
||||
|
||||
const passThrough = new PassThrough();
|
||||
// archiver v8 exports class constructors ({ ZipArchive, ... }), not a
|
||||
// callable. The old `archiver('zip', opts)` form throws TypeError at
|
||||
// runtime — which was masked until the membership fix populated the map
|
||||
// and this line was actually reached (before, the route 404'd early).
|
||||
const archive = new archiver.ZipArchive({ zlib: { level: 0 } });
|
||||
archive.pipe(passThrough);
|
||||
|
||||
// Start appending files asynchronously
|
||||
(async () => {
|
||||
try {
|
||||
for (const download of downloadsToProcess) {
|
||||
// Claim the download to verify it's authorized
|
||||
const claim = await downloadDeliveryRepository.claimAuthorized(principal.editorialId, download.downloadId);
|
||||
if (claim.outcome !== "claimed") continue;
|
||||
|
||||
try {
|
||||
const original = await immichClient.getOriginal(download.assetId);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const nodeStream = Readable.fromWeb(original.body as any);
|
||||
let transferredBytes = 0;
|
||||
|
||||
nodeStream.on('data', (chunk) => {
|
||||
transferredBytes += chunk.length;
|
||||
});
|
||||
|
||||
nodeStream.on('end', () => {
|
||||
downloadDeliveryRepository.markCompleted(download.downloadId, transferredBytes)
|
||||
.then(() => resolve())
|
||||
.catch(reject);
|
||||
});
|
||||
|
||||
nodeStream.on('error', (err) => reject(err));
|
||||
|
||||
archive.append(nodeStream, { name: download.filename });
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Failed to append original for asset", download.assetId, err);
|
||||
await downloadDeliveryRepository.failBeforeDelivery(download.downloadId, {
|
||||
voidNewUsage: download.intentKind === "new_usage"
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Archive stream failed", err);
|
||||
archive.abort();
|
||||
} finally {
|
||||
archive.finalize();
|
||||
}
|
||||
})();
|
||||
|
||||
const date = new Date().toISOString().split('T')[0];
|
||||
return new Response(Readable.toWeb(passThrough) as any, {
|
||||
headers: {
|
||||
"Content-Type": "application/zip",
|
||||
"Content-Disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
|
||||
},
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
// Surface the real cause. Without this, any UsageAccountingError from
|
||||
// createNewUsage/createRepeatDownload (e.g. IMMICH_UNAVAILABLE under load)
|
||||
// became an opaque 500 and the user only saw "Download fehlgeschlagen".
|
||||
console.error("[bulk-download] failed:", err);
|
||||
return mappedBulkError(err);
|
||||
}
|
||||
}
|
||||
|
||||
function mappedBulkError(error: unknown): Response {
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return Response.json(
|
||||
{ code: "FORBIDDEN" },
|
||||
{ status: error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
if (error instanceof UsageAccountingError) {
|
||||
const statusByCode: Record<UsageAccountingError["code"], number> = {
|
||||
INVALID_INPUT: 400,
|
||||
IDEMPOTENCY_CONFLICT: 409,
|
||||
ALBUM_NOT_GRANTED: 404,
|
||||
ASSET_NOT_FOUND: 404,
|
||||
ASSET_NOT_IN_ALBUM: 404,
|
||||
ASSET_NOT_IMAGE: 422,
|
||||
USAGE_NOT_FOUND: 404,
|
||||
IMMICH_UNAVAILABLE: 503,
|
||||
EDITORIAL_NOT_ACTIVE: 403,
|
||||
INVALID_PRICE: 409,
|
||||
};
|
||||
const status = statusByCode[error.code] ?? 500;
|
||||
return Response.json(
|
||||
{ code: error.code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
return Response.json(
|
||||
{ code: "REQUEST_FAILED" },
|
||||
{ status: 500, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
export const POST = createBulkDownloadHandler({
|
||||
requireActiveEditorial,
|
||||
getGrantedAlbumIds: (editorialId) => albumGrantService.getGrantedAlbumIds(editorialId),
|
||||
searchPhotos: (input) => immichClient.searchPhotos(input),
|
||||
getAsset: (assetId) => immichClient.getAsset(assetId),
|
||||
getOriginal: (assetId, signal) => immichClient.getOriginal(assetId, signal),
|
||||
listPriorUsages: (editorialId, assetId) => usageService.listPriorUsages(editorialId, assetId),
|
||||
createNewUsage: (input) => usageService.createNewUsage(input),
|
||||
createRepeatDownload,
|
||||
repository: downloadDeliveryRepository,
|
||||
createArchive: () => new archiver.ZipArchive({ zlib: { level: 0 } }),
|
||||
consumeRateLimit,
|
||||
});
|
||||
@@ -158,7 +158,10 @@ async function loadAlbumPage({
|
||||
const lightboxAssetIds = new Set(lightboxItems.map((i) => i.assetId));
|
||||
return { album, page: resultPage, currentPage, downloadOptions, lightboxAssetIds, unavailable: false as const };
|
||||
} catch (error) {
|
||||
if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") {
|
||||
if (
|
||||
error instanceof AlbumCatalogError &&
|
||||
(error.code === "IMMICH_UNAVAILABLE" || error.code === "RATE_LIMITED")
|
||||
) {
|
||||
return { album: null, page: null, currentPage: 1, downloadOptions: undefined, lightboxAssetIds: new Set<string>(), unavailable: true as const };
|
||||
}
|
||||
throw error;
|
||||
@@ -190,4 +193,4 @@ function ImmichUnavailable() {
|
||||
</PageHeader>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -23,11 +23,19 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
const jahr = singleValue(rawSearchParams.jahr);
|
||||
|
||||
if (query) {
|
||||
const results = await albumCatalog.searchVisiblePhotos(principal.editorialId, {
|
||||
description: query,
|
||||
page: 1,
|
||||
size: SEARCH_FETCH_SIZE,
|
||||
});
|
||||
let results;
|
||||
try {
|
||||
results = await albumCatalog.searchVisiblePhotos(principal.editorialId, {
|
||||
description: query,
|
||||
page: 1,
|
||||
size: SEARCH_FETCH_SIZE,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AlbumCatalogError && error.code === "RATE_LIMITED") {
|
||||
return <SearchRateLimited query={query} format={format} jahr={jahr} />;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const filtered = filterPhotos(results.items, { format, jahr });
|
||||
const { result: page, currentPage } = paginatePhotos(filtered, singleValue(rawSearchParams.page), PHOTO_PAGE_SIZE);
|
||||
@@ -86,6 +94,18 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi
|
||||
);
|
||||
}
|
||||
|
||||
function SearchRateLimited({ query, format, jahr }: { query: string; format?: string; jahr?: string }) {
|
||||
return (
|
||||
<div className="space-y-6 max-w-7xl" aria-labelledby="albums-title">
|
||||
<PageHeader kicker="Bildarchiv · Suche" title="Bitte kurz warten" titleId="albums-title" />
|
||||
<GlobalSearchForm query={query} format={format} jahr={jahr} />
|
||||
<p className="bg-muted p-4 rounded-md" role="status">
|
||||
Es wurden sehr viele Suchanfragen gestellt. Bitte versuchen Sie es in Kürze erneut.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function GlobalSearchForm({ query, format, jahr }: { query: string; format?: string; jahr?: string; }) {
|
||||
const currentYear = new Date().getFullYear();
|
||||
const years = Array.from({ length: 10 }, (_, i) => currentYear - i);
|
||||
|
||||
@@ -8,20 +8,18 @@ import { expect, test } from "vitest";
|
||||
import { PortalShell } from "@/components/layout/portal-shell";
|
||||
import { BrandLogo } from "./logo";
|
||||
|
||||
test("uses the supplied logo's true intrinsic dimensions and renders both light and dark variants", () => {
|
||||
test("lets CSS constrain both supplied logo variants without oversized intrinsic attributes", () => {
|
||||
render(<BrandLogo />);
|
||||
const logos = screen.getAllByAltText("Leon Tonhäuser Sportfotografie");
|
||||
|
||||
expect(logos).toHaveLength(2);
|
||||
|
||||
// Light mode logo
|
||||
expect(logos[0].getAttribute("width")).toBe("1000");
|
||||
expect(logos[0].getAttribute("height")).toBe("1000");
|
||||
expect(logos[0].getAttribute("width")).toBeNull();
|
||||
expect(logos[0].getAttribute("height")).toBeNull();
|
||||
expect(logos[0].className).toContain("brand-logo-light");
|
||||
|
||||
// Dark mode logo
|
||||
expect(logos[1].getAttribute("width")).toBe("1000");
|
||||
expect(logos[1].getAttribute("height")).toBe("1000");
|
||||
expect(logos[1].getAttribute("width")).toBeNull();
|
||||
expect(logos[1].getAttribute("height")).toBeNull();
|
||||
expect(logos[1].className).toContain("brand-logo-dark");
|
||||
});
|
||||
|
||||
|
||||
@@ -6,8 +6,7 @@ import { authClient } from "@/modules/auth/client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
// Renders into the portal masthead. Better Auth's signOut clears the session
|
||||
// cookie server-side; we then hard-navigate to the login page so no stale
|
||||
// session remains in the client router cache.
|
||||
// cookie server-side; a hard replacement clears any stale router cache.
|
||||
export function LogoutButton() {
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
@@ -16,7 +15,7 @@ export function LogoutButton() {
|
||||
try {
|
||||
await authClient.signOut();
|
||||
} finally {
|
||||
window.location.assign("/anmelden");
|
||||
window.location.replace("/anmelden");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,4 +30,4 @@ export function LogoutButton() {
|
||||
{pending ? "…" : "Abmelden"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,31 +1,22 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Moon, Sun } from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { theme, setTheme } = useTheme()
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
|
||||
// Avoid hydration mismatch
|
||||
React.useEffect(() => setMounted(true), [])
|
||||
if (!mounted) return <div className="w-9 h-9" /> // Placeholder to prevent layout shift
|
||||
const { resolvedTheme, setTheme } = useTheme()
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
|
||||
onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
|
||||
title="Design umschalten"
|
||||
>
|
||||
{theme === "light" ? (
|
||||
<Sun className="h-[1.2rem] w-[1.2rem] transition-all" />
|
||||
) : (
|
||||
<Moon className="h-[1.2rem] w-[1.2rem] transition-all" />
|
||||
)}
|
||||
<Sun className="h-[1.2rem] w-[1.2rem] transition-all dark:hidden" />
|
||||
<Moon className="hidden h-[1.2rem] w-[1.2rem] transition-all dark:block" />
|
||||
<span className="sr-only">Design umschalten</span>
|
||||
</Button>
|
||||
)
|
||||
|
||||
@@ -28,11 +28,13 @@ function createCatalog(options?: {
|
||||
return { items: [], total: 0, nextPage: null, previousPage: null };
|
||||
}),
|
||||
};
|
||||
const consumeRateLimit = vi.fn().mockResolvedValue({ allowed: true, retryAfterSeconds: 0 });
|
||||
|
||||
return {
|
||||
catalog: createAlbumCatalog({ grants, immich }),
|
||||
catalog: createAlbumCatalog({ grants, immich, consumeRateLimit }),
|
||||
grants,
|
||||
immich,
|
||||
consumeRateLimit,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -141,3 +143,14 @@ test("does not expose a caller-controlled asset type in the catalog contract", a
|
||||
|
||||
expect(immich.searchPhotos).toHaveBeenCalledWith(expect.objectContaining({ type: "IMAGE" }));
|
||||
});
|
||||
|
||||
test("rate-limits description searches per authenticated editorial", async () => {
|
||||
const { catalog, consumeRateLimit, immich } = createCatalog();
|
||||
consumeRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 19 });
|
||||
|
||||
await expect(
|
||||
catalog.searchVisiblePhotos("editorial-1", { description: "Tor", page: 1 }),
|
||||
).rejects.toMatchObject({ code: "RATE_LIMITED", retryAfterSeconds: 19 });
|
||||
expect(consumeRateLimit).toHaveBeenCalledWith("search:editorial-1", expect.any(Object));
|
||||
expect(immich.searchPhotos).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -3,6 +3,12 @@ import "server-only";
|
||||
import { albumGrantService } from "@/modules/albums/grants";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import type { ImmichAlbumSummary, ImmichClient, ImmichSearchPage } from "@/modules/immich/types";
|
||||
import { consumeRateLimit, searchPolicy } from "@/modules/security/rate-limit";
|
||||
import {
|
||||
enforceRateLimit,
|
||||
RateLimitExceededError,
|
||||
type ConsumeRateLimit,
|
||||
} from "@/modules/security/rate-limit-guard";
|
||||
|
||||
export const PHOTO_PAGE_SIZE = 60;
|
||||
export const MAX_PHOTO_PAGE = 1_000;
|
||||
@@ -20,17 +26,21 @@ export type SearchVisiblePhotosInput = {
|
||||
export type AlbumCatalogDependencies = {
|
||||
grants: Pick<typeof albumGrantService, "getGrantedAlbumIds">;
|
||||
immich: Pick<ImmichClient, "listAlbums" | "searchPhotos">;
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
};
|
||||
|
||||
export class AlbumCatalogError extends Error {
|
||||
readonly name = "AlbumCatalogError";
|
||||
|
||||
constructor(readonly code: "IMMICH_UNAVAILABLE") {
|
||||
constructor(
|
||||
readonly code: "IMMICH_UNAVAILABLE" | "RATE_LIMITED",
|
||||
readonly retryAfterSeconds?: number,
|
||||
) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
export function createAlbumCatalog({ grants, immich }: AlbumCatalogDependencies) {
|
||||
export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }: AlbumCatalogDependencies) {
|
||||
return {
|
||||
async getVisibleAlbums(editorialId: string): Promise<VisibleAlbum[]> {
|
||||
const [grantedAlbumIds, albums] = await Promise.all([
|
||||
@@ -45,12 +55,22 @@ export function createAlbumCatalog({ grants, immich }: AlbumCatalogDependencies)
|
||||
editorialId: string,
|
||||
input: SearchVisiblePhotosInput,
|
||||
): Promise<ImmichSearchPage> {
|
||||
const description = normalizeDescription(input.description);
|
||||
if (description) {
|
||||
try {
|
||||
await enforceRateLimit(consume, `search:${editorialId}`, searchPolicy);
|
||||
} catch (error) {
|
||||
if (error instanceof RateLimitExceededError) {
|
||||
throw new AlbumCatalogError("RATE_LIMITED", error.retryAfterSeconds);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const grantedAlbumIds = await currentGrantIds(grants, editorialId);
|
||||
if (grantedAlbumIds.length === 0) {
|
||||
return emptySearchPage();
|
||||
}
|
||||
|
||||
const description = normalizeDescription(input.description);
|
||||
const page = normalizePage(input.page);
|
||||
const size = input.size ?? PHOTO_PAGE_SIZE;
|
||||
|
||||
@@ -169,4 +189,5 @@ async function loadAlbums(
|
||||
export const albumCatalog = createAlbumCatalog({
|
||||
grants: albumGrantService,
|
||||
immich: immichClient,
|
||||
consumeRateLimit,
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { expect, test, vi } from "vitest";
|
||||
|
||||
import { POST } from "@/app/api/auth/[...all]/route";
|
||||
|
||||
import { createPortalAuth } from "./auth";
|
||||
import { createPortalAuth, createRegistrationIngress } from "./auth";
|
||||
import { CURRENT_TERMS_VERSION } from "./registration";
|
||||
|
||||
test("allows the trusted registration service ingress while rejecting public direct sign-up", async () => {
|
||||
@@ -59,3 +59,65 @@ test("allows the trusted registration service ingress while rejecting public dir
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
});
|
||||
|
||||
test("rate-limits registration by a hashed email and proxy identity before sign-up", async () => {
|
||||
const register = vi.fn();
|
||||
const consume = vi.fn().mockResolvedValue({ allowed: false, retryAfterSeconds: 120 });
|
||||
const ingress = createRegistrationIngress({ register, consumeRateLimit: consume });
|
||||
|
||||
await expect(
|
||||
ingress(
|
||||
{
|
||||
companyName: "Beispiel GmbH",
|
||||
contactName: "Max Beispiel",
|
||||
email: "Redaktion@Example.com",
|
||||
password: "sicheres-passwort-123",
|
||||
billingAddress: {
|
||||
addressLine1: "Presseweg 1",
|
||||
postalCode: "10115",
|
||||
city: "Berlin",
|
||||
countryCode: "DE",
|
||||
},
|
||||
actsForBusiness: true,
|
||||
termsVersion: CURRENT_TERMS_VERSION,
|
||||
privacyAcknowledged: true,
|
||||
},
|
||||
new Headers({ "x-real-ip": "203.0.113.8" }),
|
||||
),
|
||||
).rejects.toMatchObject({ name: "RateLimitExceededError", retryAfterSeconds: 120 });
|
||||
|
||||
expect(consume).toHaveBeenCalledWith(expect.stringMatching(/^registration:[a-f0-9]{64}$/), expect.any(Object));
|
||||
expect(register).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("keeps Better Auth login limits separate for clients forwarded by Zoraxy", async () => {
|
||||
const registrationRepository = {
|
||||
createEditorial: vi.fn(),
|
||||
markPendingApproval: vi.fn(),
|
||||
removeUnverifiedAuthIdentity: vi.fn(),
|
||||
recordRegistrationCompensationFailure: vi.fn(),
|
||||
recordVerificationInconsistency: vi.fn(),
|
||||
canCreateSession: vi.fn().mockResolvedValue(false),
|
||||
};
|
||||
const { auth } = createPortalAuth({
|
||||
database: memoryAdapter({ user: [], account: [], session: [], verification: [] }),
|
||||
mailerService: { sendPasswordReset: vi.fn(), sendVerification: vi.fn() },
|
||||
registrationRepository,
|
||||
});
|
||||
const signIn = (forwardedFor: string) =>
|
||||
auth.handler(
|
||||
new Request("http://localhost:3000/api/auth/sign-in/email", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
"x-forwarded-for": forwardedFor,
|
||||
},
|
||||
body: JSON.stringify({ email: "nobody@example.com", password: "invalid-password" }),
|
||||
}),
|
||||
);
|
||||
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) await signIn("203.0.113.10");
|
||||
const otherClient = await signIn("203.0.113.11");
|
||||
|
||||
expect(otherClient.status).not.toBe(429);
|
||||
});
|
||||
@@ -7,6 +7,12 @@ import { env } from "@/config/env";
|
||||
import { db } from "@/db/client";
|
||||
import { accounts, sessions, users, verifications } from "@/db/schema";
|
||||
import { mailer } from "@/modules/mail/mailer";
|
||||
import { consumeRateLimit, registrationPolicy } from "@/modules/security/rate-limit";
|
||||
import {
|
||||
enforceRateLimit,
|
||||
hashedRequestIdentity,
|
||||
type ConsumeRateLimit,
|
||||
} from "@/modules/security/rate-limit-guard";
|
||||
|
||||
import {
|
||||
createEditorialRegistrationRepository,
|
||||
@@ -14,6 +20,19 @@ import {
|
||||
type RegistrationInput,
|
||||
} from "./registration";
|
||||
|
||||
export const portalAuthRateLimitOptions = {
|
||||
enabled: true,
|
||||
storage: "memory",
|
||||
window: 60,
|
||||
max: 100,
|
||||
customRules: {
|
||||
"/sign-in/email": { window: 15 * 60, max: 5 },
|
||||
"/request-password-reset": { window: 60 * 60, max: 5 },
|
||||
"/reset-password": { window: 60 * 60, max: 5 },
|
||||
"/send-verification-email": { window: 60 * 60, max: 5 },
|
||||
},
|
||||
} satisfies NonNullable<BetterAuthOptions["rateLimit"]>;
|
||||
|
||||
export function createPortalAuth({
|
||||
database,
|
||||
mailerService,
|
||||
@@ -29,11 +48,16 @@ export function createPortalAuth({
|
||||
baseURL: env.BETTER_AUTH_URL,
|
||||
secret: env.BETTER_AUTH_SECRET,
|
||||
database,
|
||||
rateLimit: portalAuthRateLimitOptions,
|
||||
// All id columns are typed `uuid`; Better Auth's default id generator emits
|
||||
// a nanoid-style string that Postgres rejects with "invalid input syntax
|
||||
// for type uuid". Generate real UUIDs so inserts (signUp, sessions,
|
||||
// verifications) match the schema.
|
||||
advanced: { database: { generateId: () => crypto.randomUUID() } },
|
||||
advanced: {
|
||||
database: { generateId: () => crypto.randomUUID() },
|
||||
// The reverse proxy must overwrite this header; see docs/operations.md.
|
||||
ipAddress: { ipAddressHeaders: ["x-forwarded-for", "x-real-ip"] },
|
||||
},
|
||||
// `role` is a custom column on `users` (portalRole enum: ADMIN | EDITORIAL).
|
||||
// Better Auth's parseUserOutput filters the session user to declared fields
|
||||
// only, so without this the drizzle adapter selects `role` but it is then
|
||||
@@ -123,6 +147,24 @@ const portalAuth = createPortalAuth({
|
||||
export const auth = portalAuth.auth;
|
||||
export const registrationService = portalAuth.registrationService;
|
||||
|
||||
export function registerEditorial(input: RegistrationInput): Promise<{ status: "pending_email" }> {
|
||||
return registrationService.register(input);
|
||||
export function createRegistrationIngress({
|
||||
register,
|
||||
consumeRateLimit: consume,
|
||||
}: {
|
||||
register(input: RegistrationInput): Promise<{ status: "pending_email" }>;
|
||||
consumeRateLimit: ConsumeRateLimit;
|
||||
}) {
|
||||
return async function registrationIngress(input: RegistrationInput, headers = new Headers()) {
|
||||
await enforceRateLimit(
|
||||
consume,
|
||||
hashedRequestIdentity("registration", input.email, headers),
|
||||
registrationPolicy,
|
||||
);
|
||||
return register(input);
|
||||
};
|
||||
}
|
||||
|
||||
export const registerEditorial = createRegistrationIngress({
|
||||
register: (input) => registrationService.register(input),
|
||||
consumeRateLimit,
|
||||
});
|
||||
@@ -1,9 +1,16 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
|
||||
import { RegistrationForm } from "./public-forms";
|
||||
const { resetPassword } = vi.hoisted(() => ({ resetPassword: vi.fn() }));
|
||||
vi.mock("./client", () => ({
|
||||
authClient: { resetPassword },
|
||||
}));
|
||||
|
||||
import { PasswordResetForm, RegistrationForm } from "./public-forms";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
test("registration presents separate B2B, terms, and privacy acknowledgements", () => {
|
||||
render(
|
||||
@@ -40,3 +47,33 @@ test("registration presents separate B2B, terms, and privacy acknowledgements",
|
||||
);
|
||||
expect(document.querySelector('input[name="termsVersion"]')).toBeNull();
|
||||
});
|
||||
|
||||
test("confirms a successful password reset and links directly to login", async () => {
|
||||
resetPassword.mockResolvedValueOnce({ data: { status: true }, error: null });
|
||||
render(<PasswordResetForm token="valid-token" />);
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/neues passwort/i), {
|
||||
target: { value: "neues-passwort-123" },
|
||||
});
|
||||
fireEvent.submit(screen.getByRole("button", { name: /passwort aktualisieren/i }).closest("form")!);
|
||||
|
||||
expect(await screen.findByText(/passwort wurde erfolgreich aktualisiert/i)).toBeTruthy();
|
||||
expect(screen.getByRole("link", { name: /jetzt anmelden/i }).getAttribute("href")).toBe(
|
||||
"/anmelden",
|
||||
);
|
||||
});
|
||||
|
||||
test("does not claim success when the reset link is invalid", async () => {
|
||||
resetPassword.mockResolvedValueOnce({ data: null, error: { code: "INVALID_TOKEN" } });
|
||||
render(<PasswordResetForm token="invalid-token" />);
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/neues passwort/i), {
|
||||
target: { value: "neues-passwort-123" },
|
||||
});
|
||||
fireEvent.submit(screen.getByRole("button", { name: /passwort aktualisieren/i }).closest("form")!);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("alert").textContent).toMatch(/link.*ungültig|abgelaufen/i),
|
||||
);
|
||||
expect(screen.queryByText(/erfolgreich aktualisiert/i)).toBeNull();
|
||||
});
|
||||
@@ -228,27 +228,41 @@ export function PasswordResetRequestForm() {
|
||||
}
|
||||
|
||||
export function PasswordResetForm({ token }: { token?: string }) {
|
||||
const [message, setMessage] = useState<string>();
|
||||
const [success, setSuccess] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setPending(true);
|
||||
setError(undefined);
|
||||
const formData = new FormData(event.currentTarget);
|
||||
|
||||
try {
|
||||
await authClient.resetPassword({ newPassword: readText(formData, "password"), token });
|
||||
const result = await authClient.resetPassword({
|
||||
newPassword: readText(formData, "password"),
|
||||
token,
|
||||
});
|
||||
if (result.error) {
|
||||
setError("Der Link ist ungültig oder abgelaufen. Bitte fordern Sie einen neuen Link an.");
|
||||
return;
|
||||
}
|
||||
setSuccess(true);
|
||||
} catch {
|
||||
setError("Der Link ist ungültig oder abgelaufen. Bitte fordern Sie einen neuen Link an.");
|
||||
} finally {
|
||||
setMessage("Wenn der Link gültig war, wurde Ihr Passwort aktualisiert.");
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (message) {
|
||||
if (success) {
|
||||
return (
|
||||
<p className="form-note" role="status">
|
||||
{message}
|
||||
</p>
|
||||
<div className="form-note" role="status">
|
||||
<p>Ihr Passwort wurde erfolgreich aktualisiert. Sie können sich jetzt damit anmelden.</p>
|
||||
<a className="primary-action" href="/anmelden">
|
||||
Jetzt anmelden
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -258,6 +272,7 @@ export function PasswordResetForm({ token }: { token?: string }) {
|
||||
Neues Passwort
|
||||
<input autoComplete="new-password" minLength={8} name="password" required type="password" />
|
||||
</label>
|
||||
<FieldError message={error} />
|
||||
<button className="primary-action" disabled={pending} type="submit">
|
||||
{pending ? "Passwort wird aktualisiert …" : "Passwort aktualisieren"}
|
||||
</button>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { monthPeriod, quarterPeriod, type BillingPeriod } from "./period";
|
||||
import { berlinMonthPeriodAt, monthPeriod, quarterPeriod, type BillingPeriod } from "./period";
|
||||
|
||||
test("converts a Berlin month to an exclusive UTC range", () => {
|
||||
expect(monthPeriod(2026, 3)).toEqual({
|
||||
@@ -9,6 +9,13 @@ test("converts a Berlin month to an exclusive UTC range", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("selects the Berlin calendar month at a UTC month-edge instant", () => {
|
||||
expect(berlinMonthPeriodAt(new Date("2026-03-31T22:30:00.000Z"))).toEqual({
|
||||
fromUtc: new Date("2026-03-31T22:00:00.000Z"),
|
||||
toUtcExclusive: new Date("2026-04-30T22:00:00.000Z"),
|
||||
});
|
||||
});
|
||||
|
||||
test("converts a Berlin month in full summer (CEST) to an exclusive UTC range", () => {
|
||||
expect(monthPeriod(2026, 8)).toEqual({
|
||||
fromUtc: new Date("2026-07-31T22:00:00.000Z"),
|
||||
@@ -68,4 +75,4 @@ test("supports an explicit timezone override", () => {
|
||||
fromUtc: new Date("2026-03-01T05:00:00.000Z"),
|
||||
toUtcExclusive: new Date("2026-04-01T04:00:00.000Z"),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,13 @@ export function monthPeriod(year: number, month: number, zone = "Europe/Berlin")
|
||||
return toBillingPeriod(startPlain, endPlain, zone);
|
||||
}
|
||||
|
||||
export function berlinMonthPeriodAt(instant: Date): BillingPeriod {
|
||||
const zoned = Temporal.Instant.fromEpochMilliseconds(instant.getTime()).toZonedDateTimeISO(
|
||||
"Europe/Berlin",
|
||||
);
|
||||
return monthPeriod(zoned.year, zoned.month, "Europe/Berlin");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the half-open UTC range for the given calendar quarter in the
|
||||
* given IANA time zone (default `Europe/Berlin`).
|
||||
@@ -71,4 +78,4 @@ function toBillingPeriod(
|
||||
function addMonths(year: number, month: number, count: number): { year: number; month: number } {
|
||||
const total = year * 12 + (month - 1) + count;
|
||||
return { year: Math.floor(total / 12), month: (total % 12) + 1 };
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,7 @@ function selectedUsage(id: string, status: "open" | "reopened" = "open"): Select
|
||||
// In-memory mock repository
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function createMockRepo() {
|
||||
function createMockRepo(options?: { flatratePriceCents?: number | null }) {
|
||||
const usageStatuses = new Map<string, string>([
|
||||
["u1", "open"],
|
||||
["u2", "open"],
|
||||
@@ -71,7 +71,12 @@ function createMockRepo() {
|
||||
},
|
||||
|
||||
async getEditorialFlatrate() {
|
||||
return { flatrateActive: false, flatratePriceCents: null, flatrateAssetLimit: null };
|
||||
const flatratePriceCents = options?.flatratePriceCents ?? null;
|
||||
return {
|
||||
flatrateActive: flatratePriceCents !== null,
|
||||
flatratePriceCents,
|
||||
flatrateAssetLimit: null,
|
||||
};
|
||||
},
|
||||
|
||||
async getSelectedUsages(_editorialId, usageIds) {
|
||||
@@ -247,6 +252,30 @@ test("previewReport returns PDF bytes without persisting or billing", async () =
|
||||
await expect(repo.getUsageStatuses(validSelection.usageIds)).resolves.toEqual(["open", "open"]);
|
||||
});
|
||||
|
||||
test("uses the server-read flatrate snapshot consistently in PDF, total, and persistence", async () => {
|
||||
const { repo, reports } = createMockRepo({ flatratePriceCents: 12_500 });
|
||||
const finalizeInTransaction = vi.spyOn(repo, "finalizeInTransaction");
|
||||
const { service, render } = createService(repo);
|
||||
|
||||
const result = await service.finalizeReport(validSelection);
|
||||
|
||||
expect(render).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
flatrateCentsSnapshot: 12_500,
|
||||
netTotalCents: 18_500,
|
||||
}),
|
||||
);
|
||||
expect(finalizeInTransaction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
flatrateCentsSnapshot: 12_500,
|
||||
netTotalCents: 18_500,
|
||||
}),
|
||||
);
|
||||
await expect(repo.getReport(result.reportId)).resolves.toMatchObject({
|
||||
netTotalCents: 18_500,
|
||||
});
|
||||
});
|
||||
|
||||
test("finalizeReport rejects when a selected usage is already billed", async () => {
|
||||
const mock = createMockRepo();
|
||||
const { repo } = mock;
|
||||
@@ -273,4 +302,4 @@ test("cancelReport rejects a reason longer than 500 characters", async () => {
|
||||
await expect(
|
||||
service.cancelReport({ reportId: "r1", reason: "x".repeat(501), adminUserId: "a1" }),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -227,8 +227,13 @@ export function createReportService({
|
||||
* bytes. No database writes are performed — the preview is not persisted.
|
||||
*/
|
||||
async previewReport(input: PreviewReportInput): Promise<Buffer> {
|
||||
const { usages: selectedUsages, address, repeatDownloads, netTotalCents } =
|
||||
await buildSnapshot(repo, input);
|
||||
const {
|
||||
usages: selectedUsages,
|
||||
address,
|
||||
repeatDownloads,
|
||||
netTotalCents,
|
||||
flatrateCentsSnapshot,
|
||||
} = await buildSnapshot(repo, input);
|
||||
|
||||
// Preview uses report number 0 and a "VORSCHAU" invoice number — the
|
||||
// preview is not persisted, so these placeholder values never collide
|
||||
@@ -238,7 +243,7 @@ export function createReportService({
|
||||
selectedPositions: selectedUsages.map(toReportPosition),
|
||||
repeatDownloads,
|
||||
netTotalCents,
|
||||
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
|
||||
flatrateCentsSnapshot,
|
||||
reportNumber: 0,
|
||||
invoiceNumber: "VORSCHAU",
|
||||
period: input.period,
|
||||
@@ -264,8 +269,13 @@ export function createReportService({
|
||||
* If the render fails, nothing is written.
|
||||
*/
|
||||
async finalizeReport(input: FinalizeReportInput): Promise<FinalizeResult> {
|
||||
const { usages: selectedUsages, address, repeatDownloads, netTotalCents } =
|
||||
await buildSnapshot(repo, input);
|
||||
const {
|
||||
usages: selectedUsages,
|
||||
address,
|
||||
repeatDownloads,
|
||||
netTotalCents,
|
||||
flatrateCentsSnapshot,
|
||||
} = await buildSnapshot(repo, input);
|
||||
|
||||
const reportNumber = await repo.allocateReportNumber();
|
||||
const invoiceNumber = buildInvoiceNumber(reportNumber, input.period);
|
||||
@@ -277,7 +287,7 @@ export function createReportService({
|
||||
selectedPositions: selectedUsages.map(toReportPosition),
|
||||
repeatDownloads,
|
||||
netTotalCents,
|
||||
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
|
||||
flatrateCentsSnapshot,
|
||||
reportNumber,
|
||||
invoiceNumber,
|
||||
period: input.period,
|
||||
@@ -303,7 +313,7 @@ export function createReportService({
|
||||
address,
|
||||
repeatDownloads,
|
||||
netTotalCents,
|
||||
flatrateCentsSnapshot: input.flatrateCentsSnapshot,
|
||||
flatrateCentsSnapshot,
|
||||
pdfBytes: rendered.bytes,
|
||||
pdfSha256: rendered.sha256,
|
||||
documentId,
|
||||
@@ -759,4 +769,4 @@ export const reportService = createReportService({
|
||||
export const previewReport = reportService.previewReport;
|
||||
export const finalizeReport = reportService.finalizeReport;
|
||||
export const cancelReport = reportService.cancelReport;
|
||||
export const getReportPdf = reportService.getReportPdf;
|
||||
export const getReportPdf = reportService.getReportPdf;
|
||||
@@ -0,0 +1,110 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createBulkDeliveryAccounting,
|
||||
streamBulkArchiveWithAccounting,
|
||||
} from "./bulk-accounting";
|
||||
|
||||
function repository() {
|
||||
return {
|
||||
failBeforeDelivery: vi.fn().mockResolvedValue(true),
|
||||
markCompleted: vi.fn().mockResolvedValue(true),
|
||||
markInterrupted: vi.fn().mockResolvedValue(true),
|
||||
};
|
||||
}
|
||||
|
||||
test("defers completion until the complete archive response has finished", async () => {
|
||||
const repo = repository();
|
||||
const accounting = createBulkDeliveryAccounting(repo);
|
||||
accounting.track({ downloadId: "d1", intentKind: "new_usage" });
|
||||
accounting.addBytes("d1", 4);
|
||||
accounting.markEntryReady("d1");
|
||||
|
||||
expect(repo.markCompleted).not.toHaveBeenCalled();
|
||||
await accounting.completeArchive();
|
||||
|
||||
expect(repo.markCompleted).toHaveBeenCalledWith("d1", 4);
|
||||
expect(repo.markInterrupted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("voids a new usage when the archive fails before its first source byte", async () => {
|
||||
const repo = repository();
|
||||
const accounting = createBulkDeliveryAccounting(repo);
|
||||
accounting.track({ downloadId: "d1", intentKind: "new_usage" });
|
||||
|
||||
await accounting.failArchive();
|
||||
|
||||
expect(repo.failBeforeDelivery).toHaveBeenCalledWith("d1", { voidNewUsage: true });
|
||||
expect(repo.markCompleted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("records an interrupted attempt when an archive fails after source bytes", async () => {
|
||||
const repo = repository();
|
||||
const accounting = createBulkDeliveryAccounting(repo);
|
||||
accounting.track({ downloadId: "d1", intentKind: "repeat_download" });
|
||||
accounting.addBytes("d1", 7);
|
||||
|
||||
await accounting.failArchive();
|
||||
|
||||
expect(repo.markInterrupted).toHaveBeenCalledWith("d1", 7);
|
||||
expect(repo.failBeforeDelivery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("settles every tracked event at most once across competing terminal signals", async () => {
|
||||
const repo = repository();
|
||||
const accounting = createBulkDeliveryAccounting(repo);
|
||||
accounting.track({ downloadId: "d1", intentKind: "new_usage" });
|
||||
accounting.addBytes("d1", 3);
|
||||
accounting.markEntryReady("d1");
|
||||
|
||||
await Promise.all([accounting.completeArchive(), accounting.failArchive()]);
|
||||
|
||||
expect(
|
||||
repo.markCompleted.mock.calls.length +
|
||||
repo.markInterrupted.mock.calls.length +
|
||||
repo.failBeforeDelivery.mock.calls.length,
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
test("completes accounting only after the archive response is fully consumed", async () => {
|
||||
const completeArchive = vi.fn().mockResolvedValue(undefined);
|
||||
const failArchive = vi.fn().mockResolvedValue(undefined);
|
||||
const stream = streamBulkArchiveWithAccounting(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2]));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{ completeArchive, failArchive },
|
||||
);
|
||||
|
||||
expect(completeArchive).not.toHaveBeenCalled();
|
||||
await new Response(stream).arrayBuffer();
|
||||
|
||||
expect(completeArchive).toHaveBeenCalledOnce();
|
||||
expect(failArchive).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("interrupts accounting when the client cancels the archive response", async () => {
|
||||
const cancel = vi.fn().mockResolvedValue(undefined);
|
||||
const completeArchive = vi.fn().mockResolvedValue(undefined);
|
||||
const failArchive = vi.fn().mockResolvedValue(undefined);
|
||||
const stream = streamBulkArchiveWithAccounting(
|
||||
new ReadableStream({
|
||||
pull(controller) {
|
||||
controller.enqueue(new Uint8Array([1]));
|
||||
},
|
||||
cancel,
|
||||
}),
|
||||
{ completeArchive, failArchive },
|
||||
);
|
||||
const reader = stream.getReader();
|
||||
await reader.read();
|
||||
|
||||
await reader.cancel("client aborted");
|
||||
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
expect(failArchive).toHaveBeenCalledOnce();
|
||||
expect(completeArchive).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { DownloadDeliveryRepository } from "./stream";
|
||||
|
||||
type BulkAccountingRepository = Pick<
|
||||
DownloadDeliveryRepository,
|
||||
"failBeforeDelivery" | "markCompleted" | "markInterrupted"
|
||||
>;
|
||||
|
||||
type TrackedDownload = {
|
||||
downloadId: string;
|
||||
intentKind: "new_usage" | "repeat_download" | "legacy";
|
||||
transferredBytes: number;
|
||||
entryReady: boolean;
|
||||
};
|
||||
|
||||
export function createBulkDeliveryAccounting(repository: BulkAccountingRepository) {
|
||||
const tracked = new Map<string, TrackedDownload>();
|
||||
let terminal: Promise<void> | undefined;
|
||||
|
||||
function track(input: Pick<TrackedDownload, "downloadId" | "intentKind">) {
|
||||
if (tracked.has(input.downloadId)) {
|
||||
throw new Error(`Download ${input.downloadId} is already tracked`);
|
||||
}
|
||||
tracked.set(input.downloadId, { ...input, transferredBytes: 0, entryReady: false });
|
||||
}
|
||||
|
||||
function get(downloadId: string) {
|
||||
const item = tracked.get(downloadId);
|
||||
if (!item) throw new Error(`Download ${downloadId} is not tracked`);
|
||||
return item;
|
||||
}
|
||||
|
||||
function addBytes(downloadId: string, count: number) {
|
||||
if (!Number.isSafeInteger(count) || count < 0) {
|
||||
throw new Error("Transferred byte count must be a non-negative safe integer");
|
||||
}
|
||||
const item = get(downloadId);
|
||||
item.transferredBytes += count;
|
||||
if (!Number.isSafeInteger(item.transferredBytes)) {
|
||||
throw new Error("Transferred byte count exceeds the supported range");
|
||||
}
|
||||
}
|
||||
|
||||
function markEntryReady(downloadId: string) {
|
||||
get(downloadId).entryReady = true;
|
||||
}
|
||||
|
||||
function settle(outcome: "completed" | "failed") {
|
||||
terminal ??= Promise.all(
|
||||
[...tracked.values()].map(async (item) => {
|
||||
if (outcome === "completed" && item.entryReady) {
|
||||
await repository.markCompleted(item.downloadId, item.transferredBytes);
|
||||
return;
|
||||
}
|
||||
if (item.transferredBytes > 0) {
|
||||
await repository.markInterrupted(item.downloadId, item.transferredBytes);
|
||||
return;
|
||||
}
|
||||
await repository.failBeforeDelivery(item.downloadId, {
|
||||
voidNewUsage: item.intentKind === "new_usage",
|
||||
});
|
||||
}),
|
||||
).then(() => undefined);
|
||||
return terminal;
|
||||
}
|
||||
|
||||
return {
|
||||
track,
|
||||
addBytes,
|
||||
markEntryReady,
|
||||
completeArchive: () => settle("completed"),
|
||||
failArchive: () => settle("failed"),
|
||||
};
|
||||
}
|
||||
|
||||
type BulkArchiveAccounting = {
|
||||
completeArchive(): Promise<void>;
|
||||
failArchive(): Promise<void>;
|
||||
};
|
||||
|
||||
export function streamBulkArchiveWithAccounting(
|
||||
upstream: ReadableStream<Uint8Array>,
|
||||
accounting: BulkArchiveAccounting,
|
||||
): ReadableStream<Uint8Array> {
|
||||
const reader = upstream.getReader();
|
||||
let stopped = false;
|
||||
|
||||
return new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
if (stopped) return;
|
||||
try {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
stopped = true;
|
||||
await accounting.completeArchive();
|
||||
reader.releaseLock();
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
controller.enqueue(value);
|
||||
} catch (error) {
|
||||
if (!stopped) {
|
||||
stopped = true;
|
||||
await accounting.failArchive().catch(() => undefined);
|
||||
}
|
||||
try {
|
||||
reader.releaseLock();
|
||||
} catch {
|
||||
// A pending read can retain the lock while the stream is failing.
|
||||
}
|
||||
controller.error(error);
|
||||
}
|
||||
},
|
||||
async cancel(reason) {
|
||||
if (!stopped) {
|
||||
stopped = true;
|
||||
await Promise.allSettled([reader.cancel(reason), accounting.failArchive()]);
|
||||
}
|
||||
try {
|
||||
reader.releaseLock();
|
||||
} catch {
|
||||
// Cancellation may race an active read.
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { billingReportMessage } from "./billing-report-message";
|
||||
|
||||
test("labels the attachment as a usage record and explicitly distinguishes it from the invoice", () => {
|
||||
const message = billingReportMessage("Juli 2026");
|
||||
|
||||
expect(message.subject).toContain("Nutzungsnachweis");
|
||||
expect(message.text).toMatch(/keine Rechnung/i);
|
||||
expect(message.text).toMatch(/Rechnung.*separat/i);
|
||||
expect(message.htmlContent).toMatch(/keine Rechnung/i);
|
||||
expect(message.htmlContent).toMatch(/Rechnung.*separat/i);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
export function billingReportMessage(reportMonth: string) {
|
||||
return {
|
||||
subject: `Ihr Nutzungsnachweis für ${reportMonth}`,
|
||||
text: `Hallo,
|
||||
|
||||
anbei erhalten Sie den Nutzungsnachweis für ${reportMonth} als PDF-Dokument.
|
||||
|
||||
Wichtiger Hinweis: Dieses Dokument ist keine Rechnung. Die Rechnung erhalten Sie separat.
|
||||
|
||||
Viele Grüße,
|
||||
Ihr Redaktions-Team`,
|
||||
htmlContent: `Hallo,
|
||||
|
||||
anbei erhalten Sie den Nutzungsnachweis für ${reportMonth} als PDF-Dokument.
|
||||
|
||||
Wichtiger Hinweis: Dieses Dokument ist keine Rechnung. Die Rechnung erhalten Sie separat.
|
||||
|
||||
Viele Grüße,
|
||||
Ihr Redaktions-Team`,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import "server-only";
|
||||
import nodemailer from "nodemailer";
|
||||
import { env } from "@/config/env";
|
||||
import { billingReportMessage } from "./billing-report-message";
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: env.SMTP_HOST,
|
||||
@@ -74,14 +75,15 @@ function buildHtml(title: string, content: string, button?: { text: string, url:
|
||||
|
||||
export const emailService = {
|
||||
async sendBillingReport(toEmail: string, reportMonth: string, pdfBytes: Buffer, invoiceNumber: string) {
|
||||
const filename = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") + ".pdf";
|
||||
const filename = "Nutzungsnachweis-" + invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") + ".pdf";
|
||||
const message = billingReportMessage(reportMonth);
|
||||
|
||||
await transporter.sendMail({
|
||||
from: env.SMTP_FROM,
|
||||
to: toEmail,
|
||||
subject: `Ihre Abrechnung für ${reportMonth}`,
|
||||
text: `Hallo,\n\nanbei erhalten Sie Ihre Abrechnung für den Monat ${reportMonth} als PDF-Dokument.\n\nViele Grüße,\nIhr Redaktions-Team`,
|
||||
html: buildHtml("Ihre Abrechnung ist da", `Hallo,\n\nanbei erhalten Sie Ihre Abrechnung für den Monat **${reportMonth}** bequem als PDF-Dokument angehängt.\n\nViele Grüße,\nIhr Redaktions-Team`),
|
||||
subject: message.subject,
|
||||
text: message.text,
|
||||
html: buildHtml("Ihr Nutzungsnachweis", message.htmlContent),
|
||||
attachments: [
|
||||
{
|
||||
filename,
|
||||
|
||||
@@ -11,14 +11,15 @@ test("sends a verification link through the configured SMTP boundary", async ()
|
||||
verificationUrl: "https://portal.example.com/api/auth/verify-email?token=secret-token",
|
||||
});
|
||||
|
||||
expect(transport.sendMail).toHaveBeenCalledWith({
|
||||
expect(transport.sendMail).toHaveBeenCalledWith(expect.objectContaining({
|
||||
from: "portal@example.com",
|
||||
to: "editorial@example.com",
|
||||
subject: "Bitte bestätigen Sie Ihre E-Mail-Adresse",
|
||||
text: expect.stringContaining(
|
||||
"https://portal.example.com/api/auth/verify-email?token=secret-token",
|
||||
),
|
||||
});
|
||||
html: expect.stringContaining("Jetzt bestätigen"),
|
||||
}));
|
||||
});
|
||||
|
||||
test("sends an approval notice without leaking SMTP credentials", async () => {
|
||||
@@ -27,10 +28,11 @@ test("sends an approval notice without leaking SMTP credentials", async () => {
|
||||
|
||||
await mailer.sendApprovalNotice({ to: "editorial@example.com", editorialName: "Neue Redaktion" });
|
||||
|
||||
expect(transport.sendMail).toHaveBeenCalledWith({
|
||||
expect(transport.sendMail).toHaveBeenCalledWith(expect.objectContaining({
|
||||
from: "portal@example.com",
|
||||
to: "editorial@example.com",
|
||||
subject: "Ihr Zugang zum Redaktionsportal ist freigegeben",
|
||||
text: expect.stringContaining("Neue Redaktion"),
|
||||
});
|
||||
html: expect.stringContaining("Account freigegeben"),
|
||||
}));
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
enforceRateLimit,
|
||||
hashedRequestIdentity,
|
||||
RateLimitExceededError,
|
||||
} from "./rate-limit-guard";
|
||||
|
||||
test("uses a non-reversible bounded key for email and proxy identity", () => {
|
||||
const key = hashedRequestIdentity(
|
||||
"registration",
|
||||
" Redaktion@Example.com ",
|
||||
new Headers({ "x-real-ip": "203.0.113.4" }),
|
||||
);
|
||||
|
||||
expect(key).toMatch(/^registration:[a-f0-9]{64}$/);
|
||||
expect(key).not.toContain("redaktion@example.com");
|
||||
expect(key).not.toContain("203.0.113.4");
|
||||
});
|
||||
|
||||
test("uses the proxy-appended final X-Forwarded-For hop instead of a spoofed prefix", () => {
|
||||
const fromRealIp = hashedRequestIdentity(
|
||||
"registration",
|
||||
"redaktion@example.com",
|
||||
new Headers({ "x-real-ip": "203.0.113.4" }),
|
||||
);
|
||||
const fromZoraxy = hashedRequestIdentity(
|
||||
"registration",
|
||||
"redaktion@example.com",
|
||||
new Headers({ "x-forwarded-for": "198.51.100.99, 203.0.113.4" }),
|
||||
);
|
||||
|
||||
expect(fromZoraxy).toBe(fromRealIp);
|
||||
});
|
||||
|
||||
test("throws a typed error with the retry interval when a policy is exhausted", async () => {
|
||||
const consume = vi.fn().mockResolvedValue({ allowed: false, retryAfterSeconds: 47 });
|
||||
|
||||
await expect(
|
||||
enforceRateLimit(consume, "download:editorial", { maxAttempts: 1, windowSeconds: 60 }),
|
||||
).rejects.toEqual(new RateLimitExceededError(47));
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { isIP } from "node:net";
|
||||
|
||||
import type { RateLimitPolicy, RateLimitResult } from "./rate-limit";
|
||||
|
||||
export type ConsumeRateLimit = (
|
||||
key: string,
|
||||
policy: RateLimitPolicy,
|
||||
) => Promise<RateLimitResult>;
|
||||
|
||||
export class RateLimitExceededError extends Error {
|
||||
readonly name = "RateLimitExceededError";
|
||||
|
||||
constructor(readonly retryAfterSeconds: number) {
|
||||
super("Rate limit exceeded");
|
||||
}
|
||||
}
|
||||
|
||||
export async function enforceRateLimit(
|
||||
consume: ConsumeRateLimit,
|
||||
key: string,
|
||||
policy: RateLimitPolicy,
|
||||
) {
|
||||
const result = await consume(key, policy);
|
||||
if (!result.allowed) throw new RateLimitExceededError(result.retryAfterSeconds);
|
||||
}
|
||||
|
||||
export function hashedRequestIdentity(scope: string, identity: string, headers: Headers) {
|
||||
const normalizedIdentity = identity.trim().toLocaleLowerCase("en-US");
|
||||
const address = safeProxyAddress(headers) ?? "unknown";
|
||||
const digest = createHash("sha256")
|
||||
.update(`${scope}\0${normalizedIdentity}\0${address}`, "utf8")
|
||||
.digest("hex");
|
||||
return `${scope}:${digest}`;
|
||||
}
|
||||
|
||||
function safeProxyAddress(headers: Headers) {
|
||||
const realIp = headers.get("x-real-ip")?.trim();
|
||||
if (realIp && isIP(realIp)) return realIp;
|
||||
const forwarded = headers.get("x-forwarded-for")?.split(",").at(-1)?.trim();
|
||||
return forwarded && isIP(forwarded) ? forwarded : null;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
usages,
|
||||
} from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
import { berlinMonthPeriodAt } from "@/modules/billing/period";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import type { ImmichAlbumSummary } from "@/modules/immich/types";
|
||||
import { deliveredOriginalEventCondition } from "@/modules/downloads/eligibility";
|
||||
@@ -141,6 +142,7 @@ export function createUsageServiceRepository(
|
||||
status: editorialAccounts.status,
|
||||
currentPriceCents: editorialAccounts.currentPriceCents,
|
||||
flatrateActive: editorialAccounts.flatrateActive,
|
||||
flatratePriceCents: editorialAccounts.flatratePriceCents,
|
||||
flatrateAssetLimit: editorialAccounts.flatrateAssetLimit,
|
||||
})
|
||||
.from(editorialAccounts)
|
||||
@@ -174,13 +176,17 @@ export function createUsageServiceRepository(
|
||||
let priceCents = editorial.currentPriceCents!;
|
||||
|
||||
if (editorial.flatrateActive) {
|
||||
if (
|
||||
!Number.isSafeInteger(editorial.flatratePriceCents) ||
|
||||
(editorial.flatratePriceCents ?? 0) <= 0
|
||||
) {
|
||||
throw new UsageAccountingError("INVALID_PRICE");
|
||||
}
|
||||
if (editorial.flatrateAssetLimit === null) {
|
||||
priceCents = 0; // Unlimited flatrate
|
||||
} else {
|
||||
// Limited flatrate - check how many usages this month
|
||||
const now = new Date();
|
||||
const startOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
||||
const endOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0, 23, 59, 59, 999));
|
||||
const period = berlinMonthPeriodAt(new Date());
|
||||
|
||||
const [{ count }] = await transaction
|
||||
.select({ count: sql<number>`cast(count(*) as integer)` })
|
||||
@@ -188,8 +194,8 @@ export function createUsageServiceRepository(
|
||||
.where(
|
||||
and(
|
||||
eq(usages.editorialAccountId, input.editorialId),
|
||||
sql`${usages.createdAt} >= ${startOfMonth}`,
|
||||
sql`${usages.createdAt} <= ${endOfMonth}`,
|
||||
sql`${usages.createdAt} >= ${period.fromUtc}`,
|
||||
sql`${usages.createdAt} < ${period.toUtcExclusive}`,
|
||||
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
|
||||
// For flatrate, we only count usages that were originally free via the flatrate
|
||||
// so we compare against priceCents = 0. Wait, any usage counts towards the limit?
|
||||
|
||||
Reference in new issue
Block a user