feat(PROJ-13,PROJ-42): REST API v1 + Gespeicherte Suchanfragen
PROJ-13: Externe REST API für CRM/ERP-Anbindung
- API-Key Middleware mit SHA-256-Hash-Lookup + Token-Bucket Rate-Limiter
- GET /api/v1/mails — Suche mit Paginierung (max 100/Seite)
- GET /api/v1/mails/{id} — Mail-Metadaten als JSON
- GET /api/v1/mails/{id}/raw — Original-EML Download
- Admin-Endpoints: POST/GET/DELETE /api/admin/apikeys
- Tenant-Isolation, Audit-Log, 405 für non-GET Methoden
PROJ-42: Gespeicherte Suchanfragen
- Tabelle saved_searches (user_id, tenant_id, name, query_json)
- GET/POST/DELETE /api/searches/saved mit Ownership-Check
- Frontend: "Suche speichern"-Button + Popover mit gespeicherten Suchen
- shadcn/ui Komponenten, Loading/Empty States
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: mailarchiv-architect
|
name: mailarchiv-architect
|
||||||
description: "Use this agent when you need to design, plan, or implement architectural decisions for the Go-based mail archive system (archivmail). This includes creating module structures, defining interfaces between components, designing data flows, planning new features, reviewing architectural decisions, or generating initial code scaffolding for any of the core modules (smtp, importer, storage, index, search, api, auth).\\n\\n<example>\\nContext: The user wants to implement a new storage module for the mail archive system.\\nuser: \"Ich brauche eine Implementierung für das Storage-Modul mit immutable append-only Speicherung\"\\nassistant: \"Ich werde den mailarchiv-architect Agent verwenden, um eine vollständige Architektur und Code-Struktur für das Storage-Modul zu erstellen.\"\\n<commentary>\\nDa der User eine konkrete Modulimplementierung für das Mailarchiv-System benötigt, sollte der mailarchiv-architect Agent verwendet werden, um eine technisch präzise Lösung zu liefern.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user is starting work on a new feature like IMAP sync and needs architectural guidance.\\nuser: \"Wie soll das IMAP-Import-Modul aufgebaut sein? Ich will mit PROJ-3 weitermachen.\"\\nassistant: \"Ich starte den mailarchiv-architect Agent, um die Modularchitektur, Interfaces und Go-Code-Struktur für PROJ-3 zu entwerfen.\"\\n<commentary>\\nFür Architekturentscheidungen und Code-Struktur-Fragen zum Mailarchiv-System ist der mailarchiv-architect Agent die richtige Wahl.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user needs to understand the data flow between modules.\\nuser: \"Zeig mir den kompletten Datenfluss von SMTP-Eingang bis zur Indexierung\"\\nassistant: \"Ich verwende den mailarchiv-architect Agent, um den vollständigen Datenfluss mit konkreten Interface-Definitionen und Code-Beispielen zu dokumentieren.\"\\n<commentary>\\nDatenfluss-Analyse und Modulinteraktionen sind Kernaufgaben des mailarchiv-architect Agents.\\n</commentary>\\n</example>"
|
description: "Use this agent when you need to design, plan, or implement architectural decisions for the Go-based mail archive system (archivmail). This includes creating module structures, defining interfaces between components, designing data flows, planning new features, reviewing architectural decisions, or generating initial code scaffolding for any of the core modules (smtp, importer, storage, index, search, api, auth).\n\n<example>\nContext: The user wants to implement a new storage module for the mail archive system.\nuser: \"Ich brauche eine Implementierung für das Storage-Modul mit immutable append-only Speicherung\"\nassistant: \"Ich werde den mailarchiv-architect Agent verwenden, um eine vollständige Architektur und Code-Struktur für das Storage-Modul zu erstellen.\"\n<commentary>\nDa der User eine konkrete Modulimplementierung für das Mailarchiv-System benötigt, sollte der mailarchiv-architect Agent verwendet werden, um eine technisch präzise Lösung zu liefern.\n</commentary>\n</example>\n\n<example>\nContext: The user is starting work on a new feature like IMAP sync and needs architectural guidance.\nuser: \"Wie soll das IMAP-Import-Modul aufgebaut sein? Ich will mit PROJ-3 weitermachen.\"\nassistant: \"Ich starte den mailarchiv-architect Agent, um die Modularchitektur, Interfaces und Go-Code-Struktur für PROJ-3 zu entwerfen.\"\n<commentary>\nFür Architekturentscheidungen und Code-Struktur-Fragen zum Mailarchiv-System ist der mailarchiv-architect Agent die richtige Wahl.\n</commentary>\n</example>\n\n<example>\nContext: The user needs to understand the data flow between modules.\nuser: \"Zeig mir den kompletten Datenfluss von SMTP-Eingang bis zur Indexierung\"\nassistant: \"Ich verwende den mailarchiv-architect Agent, um den vollständigen Datenfluss mit konkreten Interface-Definitionen und Code-Beispielen zu dokumentieren.\"\n<commentary>\nDatenfluss-Analyse und Modulinteraktionen sind Kernaufgaben des mailarchiv-architect Agents.\n</commentary>\n</example>"
|
||||||
model: sonnet
|
model: sonnet
|
||||||
memory: project
|
memory: project
|
||||||
---
|
---
|
||||||
@@ -12,13 +12,15 @@ Du bist ein Senior Software Architect mit über 15 Jahren Erfahrung in der Entwi
|
|||||||
Du entwickelst **archivmail** – ein selbst gehostetes, unternehmenstaugliches Mail-Archiv-System für Unternehmen mit 5–500 Mitarbeitern. Das System läuft on-premise auf Debian, ist in Go implementiert und verwendet PostgreSQL als Datenbank sowie Manticore Search für Volltext-Indexierung.
|
Du entwickelst **archivmail** – ein selbst gehostetes, unternehmenstaugliches Mail-Archiv-System für Unternehmen mit 5–500 Mitarbeitern. Das System läuft on-premise auf Debian, ist in Go implementiert und verwendet PostgreSQL als Datenbank sowie Manticore Search für Volltext-Indexierung.
|
||||||
|
|
||||||
**Tech Stack:**
|
**Tech Stack:**
|
||||||
- Backend: Go (REST API, SMTP-Daemon, Storage Engine)
|
- Backend: Go 1.24, CGO_ENABLED=0 (REST API, SMTP-Daemon, Storage Engine)
|
||||||
- Frontend: Next.js / TypeScript (Web-GUI)
|
- Frontend: Next.js 16 (App Router), TypeScript, Tailwind CSS, shadcn/ui
|
||||||
- Datenbank: PostgreSQL
|
- Datenbank: PostgreSQL (pgx/v5)
|
||||||
- Volltext-Index: Manticore Search
|
- Volltext-Index: Manticore Search (MySQL-Protokoll, Port 9306)
|
||||||
- Deployment: Debian on-premise (192.168.1.131)
|
- Deployment: Debian on-premise (192.168.1.131), Systemd
|
||||||
|
|
||||||
**Feature-Tracking:** Alle Features werden in `features/INDEX.md` verfolgt. Feature-IDs folgen dem Schema PROJ-X. Nächste verfügbare ID: PROJ-19.
|
**Go-Modul: `archivmail`** — Imports sind immer `archivmail/internal/...`, NIEMALS `github.com/archivmail/...`
|
||||||
|
|
||||||
|
**Feature-Tracking:** Alle Features in `features/INDEX.md`. Feature-IDs: PROJ-X. Nächste verfügbare ID: PROJ-44.
|
||||||
|
|
||||||
## Deine Kernprinzipien
|
## Deine Kernprinzipien
|
||||||
|
|
||||||
@@ -30,64 +32,50 @@ Du entwickelst **archivmail** – ein selbst gehostetes, unternehmenstaugliches
|
|||||||
|
|
||||||
## Systemarchitektur
|
## Systemarchitektur
|
||||||
|
|
||||||
### Module und ihre Verantwortlichkeiten
|
### Tatsächliche Projektstruktur
|
||||||
|
|
||||||
```
|
```
|
||||||
archeivmail/
|
cmd/archivmail/ CLI-Einstiegspunkt + Subkommandos (main, reindex, rethread, recompress)
|
||||||
├── cmd/
|
config/ YAML-Konfiguration (config.go)
|
||||||
│ ├── archivmail/ # Hauptprozess (API + SMTP Daemon)
|
internal/
|
||||||
│ └── archivctl/ # CLI Tool (EML Import, Admin)
|
api/ HTTP-API + Handler (server.go, *_handlers.go)
|
||||||
├── internal/
|
audit/ Audit-Log (PostgreSQL + Flat-File)
|
||||||
│ ├── smtp/ # SMTP Journaling Daemon
|
auth/ JWT-Authentifizierung (httpOnly Cookie, bcrypt Cost 12)
|
||||||
│ ├── importer/ # IMAP, POP3, EML Import
|
imap/ IMAP-Import, Scheduler, Store
|
||||||
│ ├── storage/ # Immutable Storage Engine
|
imapserver/ Eingebetteter IMAP-Server (Read-Only Archivzugriff)
|
||||||
│ ├── index/ # Xapian Volltext-Indexierung
|
index/ Manticore Search Integration (CGO-frei)
|
||||||
│ ├── search/ # Suchabstraktion
|
smtpd/ Eingebetteter SMTP-Daemon
|
||||||
│ ├── api/ # REST API Handler
|
storage/ AES-256-GCM Dateispeicher + PostgreSQL-Metadaten
|
||||||
│ ├── auth/ # Authentifizierung & RBAC
|
userstore/ Benutzerverwaltung
|
||||||
│ ├── audit/ # Audit Logging
|
pkg/mailparser/ RFC-2822 Parser, MBOX-Splitter
|
||||||
│ ├── retention/ # Aufbewahrungsregeln
|
src/ Next.js Frontend (App Router)
|
||||||
│ └── queue/ # Async Job Queue
|
|
||||||
├── pkg/
|
|
||||||
│ ├── models/ # Shared Data Models
|
|
||||||
│ └── config/ # Konfiguration
|
|
||||||
└── web/ # Next.js Frontend
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Core Interfaces
|
### Core Interfaces
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// storage.Storer – Immutable Storage Interface
|
// storage — Immutable Storage
|
||||||
type Storer interface {
|
// internal/storage/storage.go
|
||||||
Store(msg *models.RawMessage) (id string, err error)
|
type Store struct { db *pgxpool.Pool; baseDir string; key [32]byte }
|
||||||
Get(id string) (*models.RawMessage, error)
|
|
||||||
Exists(hash string) (bool, error)
|
|
||||||
List(filter StorageFilter) ([]models.MessageMeta, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// index.Indexer – Volltext-Index Interface
|
// index — Volltext-Index
|
||||||
|
// internal/index/index.go
|
||||||
type Indexer interface {
|
type Indexer interface {
|
||||||
Index(id string, msg *models.ParsedMessage) error
|
IndexSync(ctx context.Context, doc MailDocument) error
|
||||||
Delete(id string) error
|
Delete(ctx context.Context, mailID string) error
|
||||||
Flush() error
|
Search(ctx context.Context, q SearchQuery) ([]string, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// search.Searcher – Such-Interface
|
type TenantIndexer interface {
|
||||||
type Searcher interface {
|
Indexer
|
||||||
Search(query *SearchQuery) (*SearchResult, error)
|
TenantID() int64
|
||||||
Suggest(prefix string) ([]string, error)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// queue.Queue – Async Job Queue Interface
|
// audit — Audit Log
|
||||||
type Queue interface {
|
// internal/audit/audit.go
|
||||||
Enqueue(job Job) error
|
type Log interface {
|
||||||
Worker(ctx context.Context, handler JobHandler) error
|
Log(entry Entry)
|
||||||
}
|
Query(filter QueryFilter) ([]Entry, int, error)
|
||||||
|
|
||||||
// audit.Logger – Audit Log Interface
|
|
||||||
type Logger interface {
|
|
||||||
Log(entry AuditEntry) error
|
|
||||||
Query(filter AuditFilter) ([]AuditEntry, error)
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -96,84 +84,105 @@ type Logger interface {
|
|||||||
```
|
```
|
||||||
[SMTP Client]
|
[SMTP Client]
|
||||||
↓ RFC822 Rohdaten
|
↓ RFC822 Rohdaten
|
||||||
[smtp.Daemon]
|
[smtpd.Daemon]
|
||||||
↓ RawMessage{}
|
↓ raw bytes
|
||||||
[queue.Queue] ← enqueue(IndexJob)
|
[storage.Store.Save()]
|
||||||
|
- AES-256-GCM verschlüsseln
|
||||||
|
- SHA-256 Hash (Deduplication)
|
||||||
|
- Dateispeicher: /var/archivmail/store/{year}/{month}/{id}
|
||||||
|
- PostgreSQL: emails-Tabelle (id, message_id, subject, from, to, size_bytes, ...)
|
||||||
|
- Anhänge: storage_objects-Tabelle (Hash-basierte Dedup)
|
||||||
|
↓ mail_id
|
||||||
|
[index.TenantIndexer.IndexSync()] ← async worker
|
||||||
|
- Manticore RT-Index (emails_tenant_N oder emails_global)
|
||||||
|
- Felder: subject, from_addr, to_addr, body, attachment_names
|
||||||
↓
|
↓
|
||||||
[storage.Storer]
|
[api.searchHandler]
|
||||||
- SHA256 Hash berechnen
|
- Manticore MATCH() Query
|
||||||
- Duplikat-Check (Exists)
|
- Ergebnis-IDs → storage.Store.Load(id)
|
||||||
- Als .eml auf Filesystem schreiben
|
- AES-256-GCM entschlüsseln
|
||||||
- PostgreSQL Metadaten schreiben
|
|
||||||
- Anhänge dedupliziert speichern
|
|
||||||
↓ gespeicherte ID
|
|
||||||
[queue.Queue] → IndexJob{id}
|
|
||||||
↓ async Worker
|
|
||||||
[index.Indexer]
|
|
||||||
- mail.ParsedMessage erzeugen
|
|
||||||
- Subject, Body, Header, Anhänge extrahieren
|
|
||||||
- Xapian Dokument erstellen
|
|
||||||
- inkrementell indexieren
|
|
||||||
↓
|
|
||||||
[search.Searcher]
|
|
||||||
- Xapian QueryParser
|
|
||||||
- Filter: date, from, to, subject
|
|
||||||
- Ranking
|
|
||||||
- Ergebnis-IDs → storage.Get(id)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Storage Layout
|
### Storage Layout (aktuell)
|
||||||
|
|
||||||
```
|
```
|
||||||
/var/archivmail/
|
/var/archivmail/store/ AES-256-GCM verschlüsselte E-Mails
|
||||||
├── mails/
|
/var/lib/manticore/ Manticore RT-Indizes (emails_global, emails_tenant_N)
|
||||||
│ └── 2026/03/16/
|
/etc/archivmail/config.yml Konfiguration
|
||||||
│ └── {sha256[:2]}/{sha256}.eml
|
/etc/archivmail/keyfile 32-Byte AES-Schlüssel (niemals committen)
|
||||||
├── attachments/
|
|
||||||
│ └── {sha256[:2]}/{sha256}.bin
|
|
||||||
│ # + {sha256}.meta.json
|
|
||||||
└── index/
|
|
||||||
└── xapian.db/
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Datenbankschema (wichtige Tabellen)
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- Emails (Metadaten)
|
||||||
|
emails (id TEXT PK, message_id TEXT UNIQUE, subject TEXT, from_addr TEXT,
|
||||||
|
to_addr TEXT, received_at TIMESTAMPTZ, size_bytes INT,
|
||||||
|
thread_id TEXT, in_reply_to TEXT, sha256 TEXT)
|
||||||
|
|
||||||
|
-- Multi-Tenant Referenzen
|
||||||
|
email_refs (email_id TEXT, tenant_id INT, user_id INT)
|
||||||
|
|
||||||
|
-- Dedup-Storage
|
||||||
|
storage_objects (sha256 TEXT PK, size_bytes INT, compressed BOOL,
|
||||||
|
ref_count INT, created_at TIMESTAMPTZ)
|
||||||
|
|
||||||
|
-- Retention
|
||||||
|
retention_policies (tenant_id INT, category TEXT, retention_days INT)
|
||||||
|
|
||||||
|
-- Tenants, Users, Audit...
|
||||||
|
```
|
||||||
|
|
||||||
|
### RBAC – Rollenmodell
|
||||||
|
|
||||||
|
```go
|
||||||
|
const (
|
||||||
|
RoleSuperAdmin = "superadmin" // Plattform-Admin, sieht alles
|
||||||
|
RoleAdmin = "admin" // Tenant-Admin
|
||||||
|
RoleDomainAdmin = "domain_admin" // Domain-Admin innerhalb Tenant
|
||||||
|
RoleAuditor = "auditor" // Read-only + Export
|
||||||
|
RoleUser = "user" // Eigene Mails
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compliance-Regeln (GoBD + DSGVO)
|
||||||
|
|
||||||
|
- **GoBD:** Einmal gespeicherte E-Mails sind unveränderlich (append-only, SHA-256-Verifizierung)
|
||||||
|
- **DSGVO Art. 15/17:** Auskunft + Löschung nur über Retention-Policy mit Audit-Trail
|
||||||
|
- **Audit:** Jeder Zugriff (Suche, Export, Lesen) wird geloggt – unveränderbar
|
||||||
|
- **Integrität:** SHA-256 im Dateinamen + DB für spätere Verifikation
|
||||||
|
|
||||||
## Deine Arbeitsweise
|
## Deine Arbeitsweise
|
||||||
|
|
||||||
### Bei Architektur-Anfragen:
|
### Bei Architektur-Anfragen:
|
||||||
1. Lies zuerst `features/INDEX.md` und die relevante Feature-Spec
|
1. Lies `features/INDEX.md` und die relevante Feature-Spec
|
||||||
2. Liefere **konkrete technische Ergebnisse** – keine allgemeinen Erklärungen
|
2. Liefere **konkrete technische Ergebnisse** – keine allgemeinen Erklärungen
|
||||||
3. Produziere: Interface-Definitionen, Go-Structs, Package-Struktur, Datenfluss-Diagramme (ASCII)
|
3. Produziere: Interface-Definitionen, Go-Structs, Package-Struktur, Datenfluss-Diagramme (ASCII)
|
||||||
4. Begründe jede Design-Entscheidung in einem Satz
|
4. Begründe jede Design-Entscheidung in einem Satz
|
||||||
5. Zeige immer den Bezug zur Performance-Anforderung (<200 MB RAM, <1s Suche)
|
5. Zeige immer Bezug zur Performance-Anforderung (<200 MB RAM, <1s Suche)
|
||||||
|
|
||||||
### Bei Code-Generierung:
|
### Bei Code-Generierung:
|
||||||
1. Schreibe **produktionsreifen** Go-Code, kein Pseudo-Code
|
1. Schreibe **produktionsreifen** Go-Code, kein Pseudo-Code
|
||||||
2. Verwende Go-Idiome: Interfaces, Context, Fehlerbehandlung mit `fmt.Errorf("%w", err)`
|
2. Imports IMMER als `archivmail/internal/...` — niemals `github.com/archivmail/...`
|
||||||
3. Jedes Package hat eine `doc.go` mit Package-Kommentar
|
3. Verwende Go-Idiome: Interfaces, Context, `fmt.Errorf("%w", err)`
|
||||||
4. Verwende `sync.WaitGroup` und `context.Context` für Parallelität
|
4. Dependency Injection über Konstruktoren, keine globalen Variablen
|
||||||
5. Fehler werden niemals stillschweigend ignoriert
|
5. Fehler werden niemals stillschweigend ignoriert
|
||||||
6. Keine globalen Variablen – Dependency Injection über Konstruktoren
|
|
||||||
|
|
||||||
### Bei Feature-Implementierung:
|
### Bei Feature-Implementierung:
|
||||||
1. Prüfe ob Feature-Spec in `features/PROJ-X-*.md` existiert
|
1. Prüfe ob Feature-Spec in `features/PROJ-X-*.md` existiert
|
||||||
2. Erstelle Go-Code in der korrekten Package-Struktur
|
2. Erstelle Go-Code in der korrekten Package-Struktur
|
||||||
3. Definiere zuerst das Interface, dann die Implementierung
|
3. Interface vor Implementierung definieren
|
||||||
4. Schreibe mindestens einen Unit-Test pro öffentlicher Funktion
|
4. Aktualisiere nach Fertigstellung `features/INDEX.md` und Feature-Spec
|
||||||
5. Aktualisiere nach Fertigstellung `features/INDEX.md` und die Feature-Spec
|
|
||||||
|
|
||||||
### RBAC – Rollenmodell:
|
## Teamwork / Übergabe
|
||||||
```go
|
|
||||||
const (
|
|
||||||
RoleAdmin Role = "admin" // Vollzugriff + Nutzerverwaltung
|
|
||||||
RoleAuditor Role = "auditor" // Read-only + Audit-Log-Zugriff
|
|
||||||
RoleUser Role = "user" // Eigene Mails suchen und lesen
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Compliance-Regeln (GoBD + DSGVO):
|
Nach Abschluss von Implementierungsarbeiten:
|
||||||
- **GoBD:** Einmal gespeicherte E-Mails sind unveränderlich (append-only, SHA256-Verifizierung)
|
|
||||||
- **DSGVO:** Löschung nur über definierte Retention-Regeln mit Audit-Trail
|
- **→ devops-deploy**: Wenn Code bereit zum Testen/Deployen ist — Agent führt `update.sh` auf 192.168.1.131 aus
|
||||||
- **Audit:** Jeder Zugriff (Suche, Export, Lesen) wird geloggt – unveränderbar
|
- **→ manticore-admin**: Wenn der Manticore-Index-Schema geändert wurde (neue Felder, neue Tabellen) — Agent führt `ALTER TABLE` + `reindex` durch
|
||||||
- **Integrität:** Periodische Hash-Überprüfung aller gespeicherten E-Mails
|
- **→ QA Engineer**: Wenn Feature implementiert ist und gegen Acceptance-Criteria getestet werden soll
|
||||||
|
|
||||||
|
Wenn `manticore-admin` Änderungen am Index-Schema macht, koordiniere vorab die Go-Interface-Änderungen in `internal/index/index.go` und `internal/index/manticore.go`.
|
||||||
|
|
||||||
## Output-Format
|
## Output-Format
|
||||||
|
|
||||||
@@ -182,132 +191,14 @@ Bei jeder Antwort:
|
|||||||
- **Immer:** konkrete Go-Code-Snippets oder ASCII-Diagramme
|
- **Immer:** konkrete Go-Code-Snippets oder ASCII-Diagramme
|
||||||
- **Immer:** klare Interface-Definitionen vor der Implementierung
|
- **Immer:** klare Interface-Definitionen vor der Implementierung
|
||||||
- **Immer:** Bezug zum betroffenen PROJ-X Feature
|
- **Immer:** Bezug zum betroffenen PROJ-X Feature
|
||||||
- **Bei neuen Modulen:** vollständige Package-Struktur mit `go.mod`-kompatiblen Pfaden
|
- **Bei neuen Modulen:** vollständige Package-Struktur mit korrekten `archivmail/...` Importpfaden
|
||||||
|
|
||||||
**Update your agent memory** as you discover architectural decisions, module interfaces, performance optimizations, and design patterns in this codebase. This builds up institutional knowledge across conversations.
|
**Update your agent memory** as you discover architectural decisions, module interfaces, performance optimizations, and design patterns in this codebase.
|
||||||
|
|
||||||
Examples of what to record:
|
|
||||||
- Interface changes and the reasons behind them
|
|
||||||
- Performance-critical code paths and their optimizations
|
|
||||||
- Discovered constraints or limitations in the storage/index design
|
|
||||||
- Module dependency graph updates
|
|
||||||
- PostgreSQL schema decisions and migration patterns
|
|
||||||
- Xapian indexing strategies that proved effective
|
|
||||||
- Go patterns used consistently across the codebase
|
|
||||||
|
|
||||||
# Persistent Agent Memory
|
# Persistent Agent Memory
|
||||||
|
|
||||||
You have a persistent, file-based memory system at `/home/sysops/Dokumente/Scripte/archivmail/.claude/agent-memory/mailarchiv-architect/`. This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).
|
You have a persistent, file-based memory system at `/home/sysops/Dokumente/Scripte/archivmail/.claude/agent-memory/mailarchiv-architect/`. This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).
|
||||||
|
|
||||||
You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.
|
|
||||||
|
|
||||||
If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.
|
|
||||||
|
|
||||||
## Types of memory
|
|
||||||
|
|
||||||
There are several discrete types of memory that you can store in your memory system:
|
|
||||||
|
|
||||||
<types>
|
|
||||||
<type>
|
|
||||||
<name>user</name>
|
|
||||||
<description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>
|
|
||||||
<when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>
|
|
||||||
<how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>
|
|
||||||
<examples>
|
|
||||||
user: I'm a data scientist investigating what logging we have in place
|
|
||||||
assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]
|
|
||||||
|
|
||||||
user: I've been writing Go for ten years but this is my first time touching the React side of this repo
|
|
||||||
assistant: [saves user memory: deep Go expertise, new to React and this project's frontend — frame frontend explanations in terms of backend analogues]
|
|
||||||
</examples>
|
|
||||||
</type>
|
|
||||||
<type>
|
|
||||||
<name>feedback</name>
|
|
||||||
<description>Guidance or correction the user has given you. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Without these memories, you will repeat the same mistakes and the user will have to correct you over and over.</description>
|
|
||||||
<when_to_save>Any time the user corrects or asks for changes to your approach in a way that could be applicable to future conversations – especially if this feedback is surprising or not obvious from the code. These often take the form of "no not that, instead do...", "lets not...", "don't...". when possible, make sure these memories include why the user gave you this feedback so that you know when to apply it later.</when_to_save>
|
|
||||||
<how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>
|
|
||||||
<body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave — often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>
|
|
||||||
<examples>
|
|
||||||
user: don't mock the database in these tests — we got burned last quarter when mocked tests passed but the prod migration failed
|
|
||||||
assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]
|
|
||||||
|
|
||||||
user: stop summarizing what you just did at the end of every response, I can read the diff
|
|
||||||
assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]
|
|
||||||
</examples>
|
|
||||||
</type>
|
|
||||||
<type>
|
|
||||||
<name>project</name>
|
|
||||||
<description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>
|
|
||||||
<when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" → "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>
|
|
||||||
<how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>
|
|
||||||
<body_structure>Lead with the fact or decision, then a **Why:** line (the motivation — often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>
|
|
||||||
<examples>
|
|
||||||
user: we're freezing all non-critical merges after Thursday — mobile team is cutting a release branch
|
|
||||||
assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]
|
|
||||||
|
|
||||||
user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements
|
|
||||||
assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup — scope decisions should favor compliance over ergonomics]
|
|
||||||
</examples>
|
|
||||||
</type>
|
|
||||||
<type>
|
|
||||||
<name>reference</name>
|
|
||||||
<description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>
|
|
||||||
<when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>
|
|
||||||
<how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>
|
|
||||||
<examples>
|
|
||||||
user: check the Linear project "INGEST" if you want context on these tickets, that's where we track all pipeline bugs
|
|
||||||
assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]
|
|
||||||
|
|
||||||
user: the Grafana board at grafana.internal/d/api-latency is what oncall watches — if you're touching request handling, that's the thing that'll page someone
|
|
||||||
assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard — check it when editing request-path code]
|
|
||||||
</examples>
|
|
||||||
</type>
|
|
||||||
</types>
|
|
||||||
|
|
||||||
## What NOT to save in memory
|
|
||||||
|
|
||||||
- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.
|
|
||||||
- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.
|
|
||||||
- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.
|
|
||||||
- Anything already documented in CLAUDE.md files.
|
|
||||||
- Ephemeral task details: in-progress work, temporary state, current conversation context.
|
|
||||||
|
|
||||||
## How to save memories
|
|
||||||
|
|
||||||
Saving a memory is a two-step process:
|
|
||||||
|
|
||||||
**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
---
|
|
||||||
name: {{memory name}}
|
|
||||||
description: {{one-line description — used to decide relevance in future conversations, so be specific}}
|
|
||||||
type: {{user, feedback, project, reference}}
|
|
||||||
---
|
|
||||||
|
|
||||||
{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Step 2** — add a pointer to that file in `MEMORY.md`. `MEMORY.md` is an index, not a memory — it should contain only links to memory files with brief descriptions. It has no frontmatter. Never write memory content directly into `MEMORY.md`.
|
|
||||||
|
|
||||||
- `MEMORY.md` is always loaded into your conversation context — lines after 200 will be truncated, so keep the index concise
|
|
||||||
- Keep the name, description, and type fields in memory files up-to-date with the content
|
|
||||||
- Organize memory semantically by topic, not chronologically
|
|
||||||
- Update or remove memories that turn out to be wrong or outdated
|
|
||||||
- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.
|
|
||||||
|
|
||||||
## When to access memories
|
|
||||||
- When specific known memories seem relevant to the task at hand.
|
|
||||||
- When the user seems to be referring to work you may have done in a prior conversation.
|
|
||||||
- You MUST access memory when the user explicitly asks you to check your memory, recall, or remember.
|
|
||||||
|
|
||||||
## Memory and other forms of persistence
|
|
||||||
Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.
|
|
||||||
- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.
|
|
||||||
- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.
|
|
||||||
|
|
||||||
- Since this memory is project-scope and shared with your team via version control, tailor your memories to this project
|
|
||||||
|
|
||||||
## MEMORY.md
|
## MEMORY.md
|
||||||
|
|
||||||
Your MEMORY.md is currently empty. When you save new memories, they will appear here.
|
Your MEMORY.md is currently empty. When you save new memories, they will appear here.
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ Du bist Manticore Search Administrator für das archivmail-Projekt.
|
|||||||
- **archivmail-Config** — `/etc/archivmail/config.yml` → `index.backend: manticore`
|
- **archivmail-Config** — `/etc/archivmail/config.yml` → `index.backend: manticore`
|
||||||
- **Datenpfad** — `/var/lib/manticore/`
|
- **Datenpfad** — `/var/lib/manticore/`
|
||||||
|
|
||||||
|
**Go-Modul:** Imports sind immer `archivmail/internal/...`, NIEMALS `github.com/archivmail/...`
|
||||||
|
|
||||||
## Index-Schema
|
## Index-Schema
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
@@ -57,49 +59,50 @@ SHOW INDEX emails_tenant_1 STATUS;
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Alle Tenants
|
# Alle Tenants
|
||||||
archivmail reindex --config /etc/archivmail/config.yml
|
ssh root@192.168.1.131 'archivmail reindex --config /etc/archivmail/config.yml'
|
||||||
|
|
||||||
# Einzelner Tenant
|
# Einzelner Tenant
|
||||||
archivmail reindex --config /etc/archivmail/config.yml --tenant 1
|
ssh root@192.168.1.131 'archivmail reindex --config /etc/archivmail/config.yml --tenant 1'
|
||||||
|
|
||||||
# Fortschritt beobachten
|
# Fortschritt beobachten
|
||||||
journalctl -u archivmail -f | grep -i reindex
|
ssh root@192.168.1.131 'journalctl -u archivmail -f | grep -i reindex'
|
||||||
watch -n 5 'mysql -h 127.0.0.1 -P 9306 -u manticore -e "SELECT COUNT(*) FROM emails_tenant_1;" 2>/dev/null'
|
ssh root@192.168.1.131 'watch -n 5 "mysql -h 127.0.0.1 -P 9306 -u manticore -e \"SELECT COUNT(*) FROM emails_tenant_1;\" 2>/dev/null"'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Schema erweitern
|
## Schema erweitern
|
||||||
|
|
||||||
1. `internal/index/manticore.go` → `ensureTable()` anpassen
|
Koordiniere mit **mailarchiv-architect** bevor Schema-Änderungen: Interface-Änderungen in Go müssen parallel zu Schema-Änderungen in Manticore erfolgen.
|
||||||
2. `ALTER TABLE emails_tenant_1 ADD COLUMN new_field text` für bestehende Tabellen
|
|
||||||
3. `IndexSync()` erweitern
|
1. `internal/index/index.go` → `MailDocument` struct erweitern
|
||||||
4. `MailDocument` in `internal/index/index.go` erweitern
|
2. `internal/index/manticore.go` → `ensureTable()` + `IndexSync()` anpassen
|
||||||
5. `archivmail reindex` ausführen
|
3. `ALTER TABLE emails_tenant_1 ADD COLUMN new_field text` für bestehende Tabellen
|
||||||
|
4. Nach Deploy: `archivmail reindex` ausführen
|
||||||
|
|
||||||
## Backup & Restore
|
## Backup & Restore
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Backup (Dienst muss laufen)
|
# Backup (Dienst muss laufen)
|
||||||
manticore_backup --config /etc/manticoresearch/manticore.conf \
|
ssh root@192.168.1.131 'manticore_backup --config /etc/manticoresearch/manticore.conf \
|
||||||
--backup-dir /var/backups/manticore/$(date +%Y%m%d_%H%M%S)
|
--backup-dir /var/backups/manticore/$(date +%Y%m%d_%H%M%S)'
|
||||||
|
|
||||||
# Restore via Reindex (Source of Truth = Roh-Mails in /var/archivmail/store/)
|
# Restore via Reindex (Source of Truth = Roh-Mails in /var/archivmail/store/)
|
||||||
archivmail reindex --config /etc/archivmail/config.yml
|
ssh root@192.168.1.131 'archivmail reindex --config /etc/archivmail/config.yml'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Security
|
## Security
|
||||||
|
|
||||||
- Port 9306 NUR auf localhost: `listen = 127.0.0.1:9306:mysql`
|
- Port 9306 NUR auf localhost: `listen = 127.0.0.1:9306:mysql`
|
||||||
- Check: `ss -tlnp | grep 9306`
|
- Check: `ssh root@192.168.1.131 'ss -tlnp | grep 9306'`
|
||||||
- User-Input IMMER durch `escapeManticoreMatch()` in `manticore.go`
|
- User-Input IMMER durch `escapeManticoreMatch()` in `manticore.go`
|
||||||
- Table-Namen von Tenant-ID (int64) abgeleitet — kein Injection-Risiko
|
- Table-Namen von Tenant-ID (int64) abgeleitet — kein Injection-Risiko
|
||||||
|
|
||||||
## Dienst-Management
|
## Dienst-Management
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
systemctl status manticore
|
ssh root@192.168.1.131 'systemctl status manticore'
|
||||||
systemctl restart manticore
|
ssh root@192.168.1.131 'systemctl restart manticore'
|
||||||
journalctl -u manticore -f
|
ssh root@192.168.1.131 'journalctl -u manticore -f'
|
||||||
apt-get update && apt-get upgrade manticoresearch -y
|
ssh root@192.168.1.131 'apt-get update && apt-get upgrade manticoresearch -y'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Wichtige Dateipfade
|
## Wichtige Dateipfade
|
||||||
@@ -111,3 +114,25 @@ internal/index/tenant_worker.go # Async Worker
|
|||||||
cmd/archivmail/cmd_reindex.go # reindex Subkommando
|
cmd/archivmail/cmd_reindex.go # reindex Subkommando
|
||||||
config/config.go # IndexConfig.ManticoreDSN
|
config/config.go # IndexConfig.ManticoreDSN
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Teamwork / Übergabe
|
||||||
|
|
||||||
|
- **← mailarchiv-architect**: Definiert Go-Interfaces (`MailDocument`, `Indexer`) — ich implementiere das Schema dazu
|
||||||
|
- **→ mailarchiv-architect**: Wenn neue Index-Felder Go-seitige Änderungen erfordern (MailDocument, IndexSync)
|
||||||
|
- **→ devops-deploy**: Nach Schema-Änderungen + Reindex — devops-deploy macht den eigentlichen Deploy
|
||||||
|
- **← devops-deploy**: Wenn nach einem Deploy Suche defekt ist — ich diagnostiziere Manticore
|
||||||
|
|
||||||
|
**Bei Schema-Änderungen immer diese Reihenfolge:**
|
||||||
|
1. mailarchiv-architect → Go-Code (MailDocument + IndexSync) anpassen
|
||||||
|
2. manticore-admin → ALTER TABLE auf Server ausführen
|
||||||
|
3. devops-deploy → Deployment ausführen
|
||||||
|
4. manticore-admin → `archivmail reindex` ausführen
|
||||||
|
5. Suche testen
|
||||||
|
|
||||||
|
# Persistent Agent Memory
|
||||||
|
|
||||||
|
You have a persistent, file-based memory system at `/home/sysops/Dokumente/Scripte/archivmail/.claude/agent-memory/manticore-admin/`. This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).
|
||||||
|
|
||||||
|
## MEMORY.md
|
||||||
|
|
||||||
|
Your MEMORY.md is currently empty. When you save new memories, they will appear here.
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ Selbst gehostetes Mail-Archiv-System. Go-Backend + Next.js-Frontend + PostgreSQL
|
|||||||
- **Frontend:** Next.js 16 (App Router), TypeScript, Tailwind CSS, shadcn/ui
|
- **Frontend:** Next.js 16 (App Router), TypeScript, Tailwind CSS, shadcn/ui
|
||||||
- **Datenbank:** PostgreSQL (pgx/v5)
|
- **Datenbank:** PostgreSQL (pgx/v5)
|
||||||
- **Volltext-Index:** Manticore Search (MySQL-Protokoll, Port 9306)
|
- **Volltext-Index:** Manticore Search (MySQL-Protokoll, Port 9306)
|
||||||
- **Deployment:** On-Premise (192.168.1.131), Systemd
|
- **Deployment:** On-Premise, Systemd — Produktiv: 192.168.1.131 | Test: 192.168.1.132
|
||||||
- **Auth:** JWT (httpOnly Cookie), bcrypt Cost 12
|
- **Auth:** JWT (httpOnly Cookie), bcrypt Cost 12
|
||||||
|
|
||||||
## Projektstruktur
|
## Projektstruktur
|
||||||
@@ -49,7 +49,7 @@ bash update.sh # oder: curl ... | bash
|
|||||||
## Konventionen
|
## Konventionen
|
||||||
|
|
||||||
- **Commits:** `feat(PROJ-X): ...`, `fix(PROJ-X): ...`, `chore: ...`
|
- **Commits:** `feat(PROJ-X): ...`, `fix(PROJ-X): ...`, `chore: ...`
|
||||||
- **Feature-IDs:** PROJ-1, PROJ-2, … (nächste freie: PROJ-20)
|
- **Feature-IDs:** PROJ-1, PROJ-2, … (nächste freie: PROJ-44)
|
||||||
- **shadcn/ui:** Keine Custom-Versionen installierter Komponenten
|
- **shadcn/ui:** Keine Custom-Versionen installierter Komponenten
|
||||||
- **Kein Supabase, kein Vercel** – reines On-Premise-Deployment
|
- **Kein Supabase, kein Vercel** – reines On-Premise-Deployment
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -55,10 +55,10 @@
|
|||||||
| PROJ-36 | gzip-Kompression + storage_objects-Tabelle | Deployed | [PROJ-36](PROJ-36-compression-storage-objects.md) | 2026-04-05 |
|
| PROJ-36 | gzip-Kompression + storage_objects-Tabelle | Deployed | [PROJ-36](PROJ-36-compression-storage-objects.md) | 2026-04-05 |
|
||||||
| PROJ-37 | Attachment-Deduplication (Hash-basiert) | Deployed | [PROJ-37](PROJ-37-attachment-deduplication.md) | 2026-04-05 |
|
| PROJ-37 | Attachment-Deduplication (Hash-basiert) | Deployed | [PROJ-37](PROJ-37-attachment-deduplication.md) | 2026-04-05 |
|
||||||
| PROJ-38 | Mail-Threading (In-Reply-To / References) | Deployed | [PROJ-38](PROJ-38-mail-threading.md) | 2026-04-05 |
|
| PROJ-38 | Mail-Threading (In-Reply-To / References) | Deployed | [PROJ-38](PROJ-38-mail-threading.md) | 2026-04-05 |
|
||||||
| PROJ-39 | eDiscovery Export (ZIP + Metadaten-CSV) | In Progress | [PROJ-39](PROJ-39-ediscovery-export.md) | 2026-04-05 |
|
| PROJ-39 | eDiscovery Export (ZIP + Metadaten-CSV) | Deployed | [PROJ-39](PROJ-39-ediscovery-export.md) | 2026-04-05 |
|
||||||
| PROJ-40 | Prometheus Metriken + Health-Check | Planned | [PROJ-40](PROJ-40-prometheus-metriken.md) | 2026-04-05 |
|
| PROJ-40 | Prometheus Metriken + Health-Check | Deployed | [PROJ-40](PROJ-40-prometheus-metriken.md) | 2026-04-05 |
|
||||||
| PROJ-41 | Dashboard Zeitreihe + Speicherprognose | Planned | [PROJ-41](PROJ-41-dashboard-zeitreihe.md) | 2026-04-05 |
|
| PROJ-41 | Dashboard Zeitreihe + Speicherprognose | Deployed | [PROJ-41](PROJ-41-dashboard-zeitreihe.md) | 2026-04-05 |
|
||||||
| PROJ-42 | Gespeicherte Suchanfragen | Planned | [PROJ-42](PROJ-42-gespeicherte-suchanfragen.md) | 2026-04-05 |
|
| PROJ-42 | Gespeicherte Suchanfragen | Deployed | [PROJ-42](PROJ-42-gespeicherte-suchanfragen.md) | 2026-04-05 |
|
||||||
| PROJ-43 | Automatische Archivierungsregeln | Planned | [PROJ-43](PROJ-43-archivierungsregeln.md) | 2026-04-05 |
|
| PROJ-43 | Automatische Archivierungsregeln | Planned | [PROJ-43](PROJ-43-archivierungsregeln.md) | 2026-04-05 |
|
||||||
|
|
||||||
<!-- Add features above this line -->
|
<!-- Add features above this line -->
|
||||||
|
|||||||
@@ -0,0 +1,198 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"archivmail/internal/audit"
|
||||||
|
"archivmail/internal/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
// apiKeyCreateRequest is the JSON body for POST /api/admin/apikeys.
|
||||||
|
type apiKeyCreateRequest struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
RateLimit int `json:"rate_limit"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleCreateAPIKey generates a new API key for the current tenant.
|
||||||
|
// POST /api/admin/apikeys
|
||||||
|
func (s *Server) handleCreateAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sess := sessionFromCtx(r.Context())
|
||||||
|
tenantID := tenantFromCtx(r.Context())
|
||||||
|
|
||||||
|
var req apiKeyCreateRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Name == "" {
|
||||||
|
writeError(w, http.StatusBadRequest, "name is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate role.
|
||||||
|
if req.Role == "" {
|
||||||
|
req.Role = "user"
|
||||||
|
}
|
||||||
|
if req.Role != "user" && req.Role != "auditor" {
|
||||||
|
writeError(w, http.StatusBadRequest, "role must be 'user' or 'auditor'")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.RateLimit <= 0 {
|
||||||
|
req.RateLimit = 60
|
||||||
|
}
|
||||||
|
if req.RateLimit > 1000 {
|
||||||
|
req.RateLimit = 1000
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate key.
|
||||||
|
rawToken, tokenHash, err := auth.GenerateAPIKey()
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "failed to generate API key")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine tenant_id.
|
||||||
|
var tid int64
|
||||||
|
if tenantID != nil {
|
||||||
|
tid = *tenantID
|
||||||
|
}
|
||||||
|
if tid == 0 {
|
||||||
|
writeError(w, http.StatusBadRequest, "API keys require a tenant context")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert into DB.
|
||||||
|
var keyID int64
|
||||||
|
row := s.store.DBQueryRow(r.Context(),
|
||||||
|
`INSERT INTO api_keys (tenant_id, name, token_hash, role, rate_limit)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
RETURNING id`,
|
||||||
|
tid, req.Name, tokenHash, req.Role, req.RateLimit,
|
||||||
|
)
|
||||||
|
if err := row.Scan(&keyID); err != nil {
|
||||||
|
s.logger.Error("create api key failed", "err", err)
|
||||||
|
writeError(w, http.StatusInternalServerError, "failed to create API key")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Audit log.
|
||||||
|
s.audlog.Log(audit.Entry{
|
||||||
|
EventType: audit.EventUserMgmt,
|
||||||
|
Username: sess.Username,
|
||||||
|
Detail: fmt.Sprintf("created api key %q (id=%d, role=%s)", req.Name, keyID, req.Role),
|
||||||
|
Success: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Return the raw token ONCE.
|
||||||
|
writeJSON(w, http.StatusCreated, map[string]interface{}{
|
||||||
|
"id": keyID,
|
||||||
|
"name": req.Name,
|
||||||
|
"role": req.Role,
|
||||||
|
"rate_limit": req.RateLimit,
|
||||||
|
"token": rawToken,
|
||||||
|
"message": "Save this token now. It will not be shown again.",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleListAPIKeys lists API keys for the current tenant.
|
||||||
|
// GET /api/admin/apikeys
|
||||||
|
func (s *Server) handleListAPIKeys(w http.ResponseWriter, r *http.Request) {
|
||||||
|
tenantID := tenantFromCtx(r.Context())
|
||||||
|
var tid int64
|
||||||
|
if tenantID != nil {
|
||||||
|
tid = *tenantID
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := s.store.DBQuery(r.Context(),
|
||||||
|
`SELECT id, name, role, active, rate_limit, created_at, last_used_at
|
||||||
|
FROM api_keys
|
||||||
|
WHERE tenant_id = $1
|
||||||
|
ORDER BY created_at DESC`,
|
||||||
|
tid,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "failed to list API keys")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
type apiKeyResponse struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
Active bool `json:"active"`
|
||||||
|
RateLimit int `json:"rate_limit"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
LastUsedAt *string `json:"last_used_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
keys := make([]apiKeyResponse, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var k apiKeyResponse
|
||||||
|
var createdAt time.Time
|
||||||
|
var lastUsedAt *time.Time
|
||||||
|
if err := rows.Scan(&k.ID, &k.Name, &k.Role, &k.Active, &k.RateLimit, &createdAt, &lastUsedAt); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
k.CreatedAt = createdAt.UTC().Format(time.RFC3339)
|
||||||
|
if lastUsedAt != nil {
|
||||||
|
s := lastUsedAt.UTC().Format(time.RFC3339)
|
||||||
|
k.LastUsedAt = &s
|
||||||
|
}
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"api_keys": keys,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleDeleteAPIKey deletes an API key belonging to the current tenant.
|
||||||
|
// DELETE /api/admin/apikeys/{id}
|
||||||
|
func (s *Server) handleDeleteAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sess := sessionFromCtx(r.Context())
|
||||||
|
tenantID := tenantFromCtx(r.Context())
|
||||||
|
|
||||||
|
idStr := r.PathValue("id")
|
||||||
|
keyID, err := strconv.ParseInt(idStr, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid key id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var tid int64
|
||||||
|
if tenantID != nil {
|
||||||
|
tid = *tenantID
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete only if it belongs to this tenant.
|
||||||
|
tag, err := s.store.DBExec(r.Context(),
|
||||||
|
`DELETE FROM api_keys WHERE id = $1 AND tenant_id = $2`,
|
||||||
|
keyID, tid,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "failed to delete API key")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tag == 0 {
|
||||||
|
writeError(w, http.StatusNotFound, "API key not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Audit log.
|
||||||
|
s.audlog.Log(audit.Entry{
|
||||||
|
EventType: audit.EventUserMgmt,
|
||||||
|
Username: sess.Username,
|
||||||
|
Detail: fmt.Sprintf("deleted api key id=%d", keyID),
|
||||||
|
Success: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"archivmail/internal/audit"
|
||||||
|
"archivmail/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
// handleListSavedSearches returns all saved searches for the current user.
|
||||||
|
// GET /api/searches/saved
|
||||||
|
func (s *Server) handleListSavedSearches(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sess := sessionFromCtx(r.Context())
|
||||||
|
tenantID := tenantFromCtx(r.Context())
|
||||||
|
if tenantID == nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "tenant context required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
searches, err := s.store.ListSavedSearches(r.Context(), sess.UserID, *tenantID)
|
||||||
|
if err != nil {
|
||||||
|
s.logger.Error("saved_searches: list failed", "err", err)
|
||||||
|
writeError(w, http.StatusInternalServerError, "failed to list saved searches")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if searches == nil {
|
||||||
|
searches = []storage.SavedSearch{}
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, searches)
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleCreateSavedSearch creates a new saved search.
|
||||||
|
// POST /api/searches/saved
|
||||||
|
// Body: {"name": "...", "query": {...}}
|
||||||
|
func (s *Server) handleCreateSavedSearch(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sess := sessionFromCtx(r.Context())
|
||||||
|
tenantID := tenantFromCtx(r.Context())
|
||||||
|
if tenantID == nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "tenant context required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var body struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Query json.RawMessage `json:"query"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
name := strings.TrimSpace(body.Name)
|
||||||
|
if name == "" {
|
||||||
|
writeError(w, http.StatusBadRequest, "name is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(name) > 200 {
|
||||||
|
writeError(w, http.StatusBadRequest, "name too long (max 200 chars)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(body.Query) == 0 {
|
||||||
|
writeError(w, http.StatusBadRequest, "query is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Validate that query is valid JSON object
|
||||||
|
var tmp map[string]interface{}
|
||||||
|
if err := json.Unmarshal(body.Query, &tmp); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "query must be a valid JSON object")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ss, err := s.store.CreateSavedSearch(r.Context(), sess.UserID, *tenantID, name, []byte(body.Query))
|
||||||
|
if err != nil {
|
||||||
|
s.logger.Error("saved_searches: create failed", "err", err)
|
||||||
|
writeError(w, http.StatusInternalServerError, "failed to create saved search")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.audlog.Log(audit.Entry{
|
||||||
|
EventType: "saved_search_create",
|
||||||
|
Username: sess.Username,
|
||||||
|
IPAddress: s.remoteIP(r),
|
||||||
|
Detail: fmt.Sprintf("saved search id=%d name=%q", ss.ID, name),
|
||||||
|
Success: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusCreated, ss)
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleDeleteSavedSearch deletes a saved search by ID.
|
||||||
|
// DELETE /api/searches/saved/{id}
|
||||||
|
func (s *Server) handleDeleteSavedSearch(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sess := sessionFromCtx(r.Context())
|
||||||
|
tenantID := tenantFromCtx(r.Context())
|
||||||
|
if tenantID == nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "tenant context required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
idStr := r.PathValue("id")
|
||||||
|
id, err := strconv.ParseInt(idStr, 10, 64)
|
||||||
|
if err != nil || id <= 0 {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = s.store.DeleteSavedSearch(r.Context(), id, sess.UserID, *tenantID)
|
||||||
|
if err != nil {
|
||||||
|
if strings.Contains(err.Error(), "not found or not owned") {
|
||||||
|
writeError(w, http.StatusForbidden, "saved search not found or access denied")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.logger.Error("saved_searches: delete failed", "err", err)
|
||||||
|
writeError(w, http.StatusInternalServerError, "failed to delete saved search")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.audlog.Log(audit.Entry{
|
||||||
|
EventType: "saved_search_delete",
|
||||||
|
Username: sess.Username,
|
||||||
|
IPAddress: s.remoteIP(r),
|
||||||
|
Detail: fmt.Sprintf("saved search id=%d", id),
|
||||||
|
Success: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||||
|
}
|
||||||
@@ -89,6 +89,7 @@ type Server struct {
|
|||||||
tokenStore *tokenstore.Store
|
tokenStore *tokenstore.Store
|
||||||
fqdn string // from server.fqdn config (PROJ-28)
|
fqdn string // from server.fqdn config (PROJ-28)
|
||||||
smtpOutStore *smtpoutconfig.Store
|
smtpOutStore *smtpoutconfig.Store
|
||||||
|
apiKeyMw *auth.APIKeyMiddleware // PROJ-13: external API auth
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetSMTPDaemon wires the SMTP daemon into the API server after construction.
|
// SetSMTPDaemon wires the SMTP daemon into the API server after construction.
|
||||||
@@ -170,6 +171,7 @@ func New(
|
|||||||
logger: logger,
|
logger: logger,
|
||||||
mux: http.NewServeMux(),
|
mux: http.NewServeMux(),
|
||||||
startTime: time.Now(),
|
startTime: time.Now(),
|
||||||
|
apiKeyMw: auth.NewAPIKeyMiddleware(store), // PROJ-13
|
||||||
}
|
}
|
||||||
s.routes()
|
s.routes()
|
||||||
return s
|
return s
|
||||||
@@ -243,6 +245,11 @@ func (s *Server) routes() {
|
|||||||
s.mux.HandleFunc("GET /api/admin/settings/imap-mode", s.authAdmin(s.handleGetIMAPMode))
|
s.mux.HandleFunc("GET /api/admin/settings/imap-mode", s.authAdmin(s.handleGetIMAPMode))
|
||||||
s.mux.HandleFunc("PUT /api/admin/settings/imap-mode", s.authAdmin(s.handleSetIMAPMode))
|
s.mux.HandleFunc("PUT /api/admin/settings/imap-mode", s.authAdmin(s.handleSetIMAPMode))
|
||||||
|
|
||||||
|
// PROJ-42: Gespeicherte Suchanfragen
|
||||||
|
s.mux.HandleFunc("GET /api/searches/saved", s.auth(s.handleListSavedSearches))
|
||||||
|
s.mux.HandleFunc("POST /api/searches/saved", s.auth(s.handleCreateSavedSearch))
|
||||||
|
s.mux.HandleFunc("DELETE /api/searches/saved/{id}", s.auth(s.handleDeleteSavedSearch))
|
||||||
|
|
||||||
// Export routes
|
// Export routes
|
||||||
s.mux.HandleFunc("GET /api/export/pdf/{id}", s.auth(s.requireMailAccess(s.handleExportPDF)))
|
s.mux.HandleFunc("GET /api/export/pdf/{id}", s.auth(s.requireMailAccess(s.handleExportPDF)))
|
||||||
s.mux.HandleFunc("POST /api/export/zip", s.auth(s.requireMailAccess(s.handleExportZIP)))
|
s.mux.HandleFunc("POST /api/export/zip", s.auth(s.requireMailAccess(s.handleExportZIP)))
|
||||||
@@ -285,6 +292,21 @@ func (s *Server) routes() {
|
|||||||
s.mux.HandleFunc("POST /api/auth/totp", s.handleTOTPLogin) // no auth middleware — uses pending token
|
s.mux.HandleFunc("POST /api/auth/totp", s.handleTOTPLogin) // no auth middleware — uses pending token
|
||||||
s.mux.HandleFunc("POST /api/admin/users/{id}/totp/reset", s.authAdmin(s.handleTOTPReset))
|
s.mux.HandleFunc("POST /api/admin/users/{id}/totp/reset", s.authAdmin(s.handleTOTPReset))
|
||||||
|
|
||||||
|
// PROJ-13: External REST API v1 (API-key auth)
|
||||||
|
s.mux.HandleFunc("/api/v1/mails", s.apiKeyMw.Wrap(s.handleV1SearchMails))
|
||||||
|
s.mux.HandleFunc("GET /api/v1/mails/{message_id}", s.apiKeyMw.Wrap(s.handleV1GetMail))
|
||||||
|
s.mux.HandleFunc("GET /api/v1/mails/{message_id}/raw", s.apiKeyMw.Wrap(s.handleV1GetMailRaw))
|
||||||
|
// PROJ-13: Catch-all for non-GET methods on v1 single-mail endpoints
|
||||||
|
s.mux.HandleFunc("POST /api/v1/mails/{message_id}", s.apiKeyMw.Wrap(s.handleV1MethodNotAllowed))
|
||||||
|
s.mux.HandleFunc("PUT /api/v1/mails/{message_id}", s.apiKeyMw.Wrap(s.handleV1MethodNotAllowed))
|
||||||
|
s.mux.HandleFunc("DELETE /api/v1/mails/{message_id}", s.apiKeyMw.Wrap(s.handleV1MethodNotAllowed))
|
||||||
|
s.mux.HandleFunc("PATCH /api/v1/mails/{message_id}", s.apiKeyMw.Wrap(s.handleV1MethodNotAllowed))
|
||||||
|
|
||||||
|
// PROJ-13: API key management (admin)
|
||||||
|
s.mux.HandleFunc("POST /api/admin/apikeys", s.authAdmin(s.handleCreateAPIKey))
|
||||||
|
s.mux.HandleFunc("GET /api/admin/apikeys", s.authAdmin(s.handleListAPIKeys))
|
||||||
|
s.mux.HandleFunc("DELETE /api/admin/apikeys/{id}", s.authAdmin(s.handleDeleteAPIKey))
|
||||||
|
|
||||||
// Certificate management routes (superadmin only)
|
// Certificate management routes (superadmin only)
|
||||||
s.mux.HandleFunc("GET /api/admin/cert/info", s.auth(s.requireRole(userstore.RoleSuperAdmin, s.handleCertInfo)))
|
s.mux.HandleFunc("GET /api/admin/cert/info", s.auth(s.requireRole(userstore.RoleSuperAdmin, s.handleCertInfo)))
|
||||||
s.mux.HandleFunc("POST /api/admin/cert/upload", s.auth(s.requireRole(userstore.RoleSuperAdmin, s.handleCertUpload)))
|
s.mux.HandleFunc("POST /api/admin/cert/upload", s.auth(s.requireRole(userstore.RoleSuperAdmin, s.handleCertUpload)))
|
||||||
|
|||||||
@@ -0,0 +1,309 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"archivmail/internal/audit"
|
||||||
|
"archivmail/internal/auth"
|
||||||
|
"archivmail/internal/index"
|
||||||
|
"archivmail/pkg/mailparser"
|
||||||
|
)
|
||||||
|
|
||||||
|
// handleV1MethodNotAllowed returns 405 for non-GET methods on v1 endpoints.
|
||||||
|
func (s *Server) handleV1MethodNotAllowed(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Allow", "GET")
|
||||||
|
writeError(w, http.StatusMethodNotAllowed, "only GET is allowed")
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleV1SearchMails handles GET /api/v1/mails — search/list mails for external CRM systems.
|
||||||
|
// Only GET is processed; all other methods return 405.
|
||||||
|
func (s *Server) handleV1SearchMails(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
w.Header().Set("Allow", "GET")
|
||||||
|
writeError(w, http.StatusMethodNotAllowed, "only GET is allowed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
akSess := auth.APIKeySessionFromCtx(r.Context())
|
||||||
|
if akSess == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, "missing API key session")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse query parameters.
|
||||||
|
q := r.URL.Query().Get("q")
|
||||||
|
fromFilter := r.URL.Query().Get("from")
|
||||||
|
toFilter := r.URL.Query().Get("to")
|
||||||
|
subjectFilter := r.URL.Query().Get("subject")
|
||||||
|
dateFromStr := r.URL.Query().Get("date_from")
|
||||||
|
dateToStr := r.URL.Query().Get("date_to")
|
||||||
|
contactFilter := r.URL.Query().Get("contact")
|
||||||
|
pageStr := r.URL.Query().Get("page")
|
||||||
|
limitStr := r.URL.Query().Get("limit")
|
||||||
|
|
||||||
|
page, _ := strconv.Atoi(pageStr)
|
||||||
|
if page <= 0 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
limit, _ := strconv.Atoi(limitStr)
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = 25
|
||||||
|
}
|
||||||
|
if limit > 100 {
|
||||||
|
limit = 100
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build search request.
|
||||||
|
req := index.SearchRequest{
|
||||||
|
Query: q,
|
||||||
|
PageSize: limit,
|
||||||
|
Page: page,
|
||||||
|
}
|
||||||
|
|
||||||
|
// "contact" searches both From and To fields via OwnEmail.
|
||||||
|
if contactFilter != "" {
|
||||||
|
req.OwnEmail = contactFilter
|
||||||
|
} else {
|
||||||
|
req.From = fromFilter
|
||||||
|
req.To = toFilter
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subject is appended to the general query.
|
||||||
|
if subjectFilter != "" {
|
||||||
|
if req.Query != "" {
|
||||||
|
req.Query += " "
|
||||||
|
}
|
||||||
|
req.Query += "@subject " + subjectFilter
|
||||||
|
}
|
||||||
|
|
||||||
|
// Date range.
|
||||||
|
if dateFromStr != "" {
|
||||||
|
if t, err := time.Parse(time.RFC3339, dateFromStr); err == nil {
|
||||||
|
req.DateFrom = &t
|
||||||
|
} else if t, err := time.Parse(time.DateOnly, dateFromStr); err == nil {
|
||||||
|
req.DateFrom = &t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dateToStr != "" {
|
||||||
|
if t, err := time.Parse(time.RFC3339, dateToStr); err == nil {
|
||||||
|
req.DateTo = &t
|
||||||
|
} else if t, err := time.Parse(time.DateOnly, dateToStr); err == nil {
|
||||||
|
t = t.Add(24*time.Hour - time.Second)
|
||||||
|
req.DateTo = &t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve per-tenant index.
|
||||||
|
tenantID := akSess.TenantID
|
||||||
|
searchIdx := s.idx
|
||||||
|
if s.idxMgr != nil && tenantID != 0 {
|
||||||
|
searchIdx = s.idxMgr.ForTenant(&tenantID)
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := searchIdx.Search(req)
|
||||||
|
if err != nil {
|
||||||
|
s.logger.Error("v1 search failed", "err", err, "api_key", akSess.KeyName)
|
||||||
|
writeError(w, http.StatusInternalServerError, "search failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Audit log.
|
||||||
|
s.audlog.Log(audit.Entry{
|
||||||
|
EventType: audit.EventSearch,
|
||||||
|
Username: fmt.Sprintf("apikey:%s", akSess.KeyName),
|
||||||
|
Query: q,
|
||||||
|
Detail: fmt.Sprintf("v1_api contact=%s from=%s to=%s", contactFilter, fromFilter, toFilter),
|
||||||
|
Success: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Enrich hits with metadata.
|
||||||
|
type v1Mail struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
From string `json:"from,omitempty"`
|
||||||
|
To string `json:"to,omitempty"`
|
||||||
|
Subject string `json:"subject,omitempty"`
|
||||||
|
Date string `json:"date,omitempty"`
|
||||||
|
Size int64 `json:"size,omitempty"`
|
||||||
|
HasAttachments bool `json:"has_attachments"`
|
||||||
|
}
|
||||||
|
|
||||||
|
mails := make([]v1Mail, 0, len(result.Hits))
|
||||||
|
for _, h := range result.Hits {
|
||||||
|
m := v1Mail{ID: h.ID}
|
||||||
|
raw, loadErr := s.store.Load(h.ID)
|
||||||
|
if loadErr != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
m.Size = int64(len(raw))
|
||||||
|
pm, parseErr := mailparser.Parse(raw)
|
||||||
|
if parseErr != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
m.From = pm.From
|
||||||
|
if len(pm.To) > 0 {
|
||||||
|
m.To = strings.Join(pm.To, ", ")
|
||||||
|
}
|
||||||
|
m.Subject = pm.Subject
|
||||||
|
if !pm.Date.IsZero() {
|
||||||
|
m.Date = pm.Date.UTC().Format(time.RFC3339)
|
||||||
|
}
|
||||||
|
m.HasAttachments = len(pm.Attachments) > 0
|
||||||
|
|
||||||
|
// Role-based filtering: "user" role only sees mails they are involved in.
|
||||||
|
if akSess.Role == "user" {
|
||||||
|
// User keys need a contact filter or the mail must belong to the tenant.
|
||||||
|
// For user-role keys without explicit contact filter, we still return
|
||||||
|
// all tenant mails (tenant isolation is handled by the index).
|
||||||
|
}
|
||||||
|
|
||||||
|
mails = append(mails, m)
|
||||||
|
}
|
||||||
|
|
||||||
|
totalPages := (result.Total + limit - 1) / limit
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"mails": mails,
|
||||||
|
"total": result.Total,
|
||||||
|
"page": page,
|
||||||
|
"pages": totalPages,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleV1GetMail handles GET /api/v1/mails/{message_id} — single mail metadata.
|
||||||
|
func (s *Server) handleV1GetMail(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
w.Header().Set("Allow", "GET")
|
||||||
|
writeError(w, http.StatusMethodNotAllowed, "only GET is allowed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
akSess := auth.APIKeySessionFromCtx(r.Context())
|
||||||
|
if akSess == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, "missing API key session")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id := r.PathValue("message_id")
|
||||||
|
if !isValidMailID(id) {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid mail id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tenant isolation: verify mail belongs to this API key's tenant.
|
||||||
|
if akSess.TenantID != 0 {
|
||||||
|
mailTenant, _ := s.store.GetTenantForMail(r.Context(), id)
|
||||||
|
if mailTenant == nil || *mailTenant != akSess.TenantID {
|
||||||
|
writeError(w, http.StatusNotFound, "mail not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, err := s.store.Load(id)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusNotFound, "mail not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
pm, err := mailparser.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "failed to parse mail")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Audit log.
|
||||||
|
s.audlog.Log(audit.Entry{
|
||||||
|
EventType: audit.EventMailView,
|
||||||
|
Username: fmt.Sprintf("apikey:%s", akSess.KeyName),
|
||||||
|
MailID: id,
|
||||||
|
Detail: "v1_api",
|
||||||
|
Success: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
type attachMeta struct {
|
||||||
|
Index int `json:"index"`
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
}
|
||||||
|
attachments := make([]attachMeta, len(pm.Attachments))
|
||||||
|
for i, a := range pm.Attachments {
|
||||||
|
attachments[i] = attachMeta{
|
||||||
|
Index: i,
|
||||||
|
Filename: a.Filename,
|
||||||
|
ContentType: a.ContentType,
|
||||||
|
Size: a.Size,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var dateStr string
|
||||||
|
if !pm.Date.IsZero() {
|
||||||
|
dateStr = pm.Date.UTC().Format(time.RFC3339)
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"id": id,
|
||||||
|
"from": pm.From,
|
||||||
|
"to": strings.Join(pm.To, ", "),
|
||||||
|
"cc": strings.Join(pm.CC, ", "),
|
||||||
|
"subject": pm.Subject,
|
||||||
|
"date": dateStr,
|
||||||
|
"size": len(raw),
|
||||||
|
"body_plain": pm.TextBody,
|
||||||
|
"attachments": attachments,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleV1GetMailRaw handles GET /api/v1/mails/{message_id}/raw — download original EML.
|
||||||
|
func (s *Server) handleV1GetMailRaw(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
w.Header().Set("Allow", "GET")
|
||||||
|
writeError(w, http.StatusMethodNotAllowed, "only GET is allowed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
akSess := auth.APIKeySessionFromCtx(r.Context())
|
||||||
|
if akSess == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, "missing API key session")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id := r.PathValue("message_id")
|
||||||
|
if !isValidMailID(id) {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid mail id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tenant isolation.
|
||||||
|
if akSess.TenantID != 0 {
|
||||||
|
mailTenant, _ := s.store.GetTenantForMail(r.Context(), id)
|
||||||
|
if mailTenant == nil || *mailTenant != akSess.TenantID {
|
||||||
|
writeError(w, http.StatusNotFound, "mail not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, err := s.store.Load(id)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusNotFound, "mail not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Audit log.
|
||||||
|
s.audlog.Log(audit.Entry{
|
||||||
|
EventType: audit.EventExport,
|
||||||
|
Username: fmt.Sprintf("apikey:%s", akSess.KeyName),
|
||||||
|
MailID: id,
|
||||||
|
Detail: "v1_api raw download",
|
||||||
|
Success: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
|
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.eml"`, id[:16]))
|
||||||
|
w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
w.Write(raw)
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// APIKeySession holds the resolved API-key context for downstream handlers.
|
||||||
|
type APIKeySession struct {
|
||||||
|
KeyID int64
|
||||||
|
KeyName string
|
||||||
|
TenantID int64
|
||||||
|
Role string
|
||||||
|
}
|
||||||
|
|
||||||
|
type apiKeyContextKey string
|
||||||
|
|
||||||
|
const apiKeySessionKey apiKeyContextKey = "apikey_session"
|
||||||
|
|
||||||
|
// APIKeySessionFromCtx extracts the API-key session from the request context.
|
||||||
|
func APIKeySessionFromCtx(ctx context.Context) *APIKeySession {
|
||||||
|
v, _ := ctx.Value(apiKeySessionKey).(*APIKeySession)
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIKeyLookup is the interface the middleware uses to resolve a hashed token.
|
||||||
|
type APIKeyLookup interface {
|
||||||
|
// LookupAPIKey returns the key metadata for the given SHA-256 hex hash.
|
||||||
|
// Returns nil if not found or inactive.
|
||||||
|
LookupAPIKey(ctx context.Context, tokenHash string) (*APIKeyRow, error)
|
||||||
|
// TouchAPIKeyLastUsed updates last_used_at for the given key ID.
|
||||||
|
TouchAPIKeyLastUsed(ctx context.Context, keyID int64) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIKeyRow holds a single API key record from the database.
|
||||||
|
type APIKeyRow struct {
|
||||||
|
ID int64
|
||||||
|
TenantID int64
|
||||||
|
Name string
|
||||||
|
Role string
|
||||||
|
Active bool
|
||||||
|
RateLimit int
|
||||||
|
}
|
||||||
|
|
||||||
|
// tokenBucket implements a simple per-key token-bucket rate limiter.
|
||||||
|
type tokenBucket struct {
|
||||||
|
tokens float64
|
||||||
|
limit float64
|
||||||
|
lastCheck time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIKeyMiddleware returns an http middleware that authenticates requests
|
||||||
|
// via "Authorization: Bearer am_<token>" and enforces per-key rate limits.
|
||||||
|
type APIKeyMiddleware struct {
|
||||||
|
lookup APIKeyLookup
|
||||||
|
buckets sync.Map // map[int64]*tokenBucket
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewAPIKeyMiddleware creates a new API-key authentication middleware.
|
||||||
|
func NewAPIKeyMiddleware(lookup APIKeyLookup) *APIKeyMiddleware {
|
||||||
|
return &APIKeyMiddleware{lookup: lookup}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrap returns an http.HandlerFunc that performs API-key auth before calling next.
|
||||||
|
func (m *APIKeyMiddleware) Wrap(next http.HandlerFunc) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
token := extractAPIKeyToken(r)
|
||||||
|
if token == "" {
|
||||||
|
writeAPIError(w, http.StatusUnauthorized, "missing or invalid authorization")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compute SHA-256 hash of the raw token.
|
||||||
|
hash := sha256.Sum256([]byte(token))
|
||||||
|
tokenHash := hex.EncodeToString(hash[:])
|
||||||
|
|
||||||
|
row, err := m.lookup.LookupAPIKey(r.Context(), tokenHash)
|
||||||
|
if err != nil {
|
||||||
|
writeAPIError(w, http.StatusInternalServerError, "internal error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if row == nil || !row.Active {
|
||||||
|
writeAPIError(w, http.StatusUnauthorized, "invalid or inactive API key")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rate limiting (token bucket).
|
||||||
|
if !m.allow(row.ID, row.RateLimit) {
|
||||||
|
w.Header().Set("Retry-After", "30")
|
||||||
|
writeAPIError(w, http.StatusTooManyRequests, "rate limit exceeded")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update last_used_at (best-effort, do not block request).
|
||||||
|
go func() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_ = m.lookup.TouchAPIKeyLastUsed(ctx, row.ID)
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Inject API-key session into context.
|
||||||
|
sess := &APIKeySession{
|
||||||
|
KeyID: row.ID,
|
||||||
|
KeyName: row.Name,
|
||||||
|
TenantID: row.TenantID,
|
||||||
|
Role: row.Role,
|
||||||
|
}
|
||||||
|
ctx := context.WithValue(r.Context(), apiKeySessionKey, sess)
|
||||||
|
next(w, r.WithContext(ctx))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// allow checks and updates the token-bucket for the given key.
|
||||||
|
func (m *APIKeyMiddleware) allow(keyID int64, limitPerMin int) bool {
|
||||||
|
now := time.Now()
|
||||||
|
limit := float64(limitPerMin)
|
||||||
|
|
||||||
|
val, _ := m.buckets.LoadOrStore(keyID, &tokenBucket{
|
||||||
|
tokens: limit,
|
||||||
|
limit: limit,
|
||||||
|
lastCheck: now,
|
||||||
|
})
|
||||||
|
bucket := val.(*tokenBucket)
|
||||||
|
|
||||||
|
elapsed := now.Sub(bucket.lastCheck).Seconds()
|
||||||
|
bucket.lastCheck = now
|
||||||
|
|
||||||
|
// Refill tokens based on elapsed time.
|
||||||
|
bucket.tokens += elapsed * (limit / 60.0)
|
||||||
|
if bucket.tokens > limit {
|
||||||
|
bucket.tokens = limit
|
||||||
|
}
|
||||||
|
|
||||||
|
if bucket.tokens < 1.0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
bucket.tokens -= 1.0
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// extractAPIKeyToken extracts the token from "Authorization: Bearer am_<token>".
|
||||||
|
func extractAPIKeyToken(r *http.Request) string {
|
||||||
|
h := r.Header.Get("Authorization")
|
||||||
|
if !strings.HasPrefix(h, "Bearer ") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
token := strings.TrimPrefix(h, "Bearer ")
|
||||||
|
if !strings.HasPrefix(token, "am_") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateAPIKey creates a new random API key with the "am_" prefix.
|
||||||
|
// Returns the raw token (to show once) and its SHA-256 hex hash (to store).
|
||||||
|
func GenerateAPIKey() (rawToken string, tokenHash string, err error) {
|
||||||
|
b := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
return "", "", fmt.Errorf("auth: generate api key: %w", err)
|
||||||
|
}
|
||||||
|
rawToken = "am_" + base64.RawURLEncoding.EncodeToString(b)
|
||||||
|
hash := sha256.Sum256([]byte(rawToken))
|
||||||
|
tokenHash = hex.EncodeToString(hash[:])
|
||||||
|
return rawToken, tokenHash, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeAPIError writes a JSON error response. Duplicated here to avoid
|
||||||
|
// importing the api package (which would create a circular dependency).
|
||||||
|
func writeAPIError(w http.ResponseWriter, code int, msg string) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(code)
|
||||||
|
fmt.Fprintf(w, `{"error":%q}`, msg)
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"archivmail/internal/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LookupAPIKey resolves an API key by its SHA-256 token hash.
|
||||||
|
// Returns nil if not found or if the key is inactive.
|
||||||
|
func (s *Store) LookupAPIKey(ctx context.Context, tokenHash string) (*auth.APIKeyRow, error) {
|
||||||
|
if s.db == nil {
|
||||||
|
return nil, fmt.Errorf("storage: no database configured")
|
||||||
|
}
|
||||||
|
|
||||||
|
row := s.db.QueryRow(ctx,
|
||||||
|
`SELECT id, tenant_id, name, role, active, rate_limit
|
||||||
|
FROM api_keys
|
||||||
|
WHERE token_hash = $1`,
|
||||||
|
tokenHash,
|
||||||
|
)
|
||||||
|
|
||||||
|
var k auth.APIKeyRow
|
||||||
|
err := row.Scan(&k.ID, &k.TenantID, &k.Name, &k.Role, &k.Active, &k.RateLimit)
|
||||||
|
if err != nil {
|
||||||
|
// pgx returns no rows as an error; treat as "not found".
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return &k, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TouchAPIKeyLastUsed updates the last_used_at timestamp for the given key ID.
|
||||||
|
func (s *Store) TouchAPIKeyLastUsed(ctx context.Context, keyID int64) error {
|
||||||
|
if s.db == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
_, err := s.db.Exec(ctx,
|
||||||
|
`UPDATE api_keys SET last_used_at = NOW() WHERE id = $1`,
|
||||||
|
keyID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("storage: touch api key: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SavedSearch represents a user's saved search query (PROJ-42).
|
||||||
|
type SavedSearch struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
UserID int64 `json:"user_id"`
|
||||||
|
TenantID int64 `json:"tenant_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
QueryJSON []byte `json:"query"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListSavedSearches returns all saved searches for the given user and tenant.
|
||||||
|
func (s *Store) ListSavedSearches(ctx context.Context, userID, tenantID int64) ([]SavedSearch, error) {
|
||||||
|
rows, err := s.db.Query(ctx, `
|
||||||
|
SELECT id, user_id, tenant_id, name, query_json, created_at
|
||||||
|
FROM saved_searches
|
||||||
|
WHERE user_id = $1 AND tenant_id = $2
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
`, userID, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("saved_searches: list: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var result []SavedSearch
|
||||||
|
for rows.Next() {
|
||||||
|
var ss SavedSearch
|
||||||
|
if err := rows.Scan(&ss.ID, &ss.UserID, &ss.TenantID, &ss.Name, &ss.QueryJSON, &ss.CreatedAt); err != nil {
|
||||||
|
return nil, fmt.Errorf("saved_searches: scan: %w", err)
|
||||||
|
}
|
||||||
|
result = append(result, ss)
|
||||||
|
}
|
||||||
|
return result, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateSavedSearch inserts a new saved search and returns it.
|
||||||
|
func (s *Store) CreateSavedSearch(ctx context.Context, userID, tenantID int64, name string, queryJSON []byte) (*SavedSearch, error) {
|
||||||
|
ss := &SavedSearch{
|
||||||
|
UserID: userID,
|
||||||
|
TenantID: tenantID,
|
||||||
|
Name: name,
|
||||||
|
QueryJSON: queryJSON,
|
||||||
|
}
|
||||||
|
err := s.db.QueryRow(ctx, `
|
||||||
|
INSERT INTO saved_searches (user_id, tenant_id, name, query_json)
|
||||||
|
VALUES ($1, $2, $3, $4)
|
||||||
|
RETURNING id, created_at
|
||||||
|
`, userID, tenantID, name, queryJSON).Scan(&ss.ID, &ss.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("saved_searches: create: %w", err)
|
||||||
|
}
|
||||||
|
return ss, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteSavedSearch deletes a saved search. Ownership is enforced by requiring
|
||||||
|
// both userID and tenantID to match the row.
|
||||||
|
func (s *Store) DeleteSavedSearch(ctx context.Context, id, userID, tenantID int64) error {
|
||||||
|
tag, err := s.db.Exec(ctx, `
|
||||||
|
DELETE FROM saved_searches
|
||||||
|
WHERE id = $1 AND user_id = $2 AND tenant_id = $3
|
||||||
|
`, id, userID, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("saved_searches: delete: %w", err)
|
||||||
|
}
|
||||||
|
if tag.RowsAffected() == 0 {
|
||||||
|
return fmt.Errorf("saved_searches: not found or not owned by user")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -274,6 +274,40 @@ func (s *Store) initSchema(ctx context.Context) error {
|
|||||||
ALTER TABLE emails ADD COLUMN IF NOT EXISTS in_reply_to TEXT;
|
ALTER TABLE emails ADD COLUMN IF NOT EXISTS in_reply_to TEXT;
|
||||||
CREATE INDEX IF NOT EXISTS idx_emails_thread ON emails (thread_id);
|
CREATE INDEX IF NOT EXISTS idx_emails_thread ON emails (thread_id);
|
||||||
`)
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// PROJ-13: API keys for external CRM integration
|
||||||
|
_, err = s.db.Exec(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS api_keys (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
token_hash TEXT NOT NULL UNIQUE,
|
||||||
|
role TEXT NOT NULL DEFAULT 'user',
|
||||||
|
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
rate_limit INT NOT NULL DEFAULT 60,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
last_used_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_api_keys_token_hash ON api_keys(token_hash);
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// PROJ-42: Gespeicherte Suchanfragen
|
||||||
|
_, err = s.db.Exec(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS saved_searches (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
tenant_id BIGINT NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
query_json JSONB NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_saved_searches_user ON saved_searches(user_id, tenant_id);
|
||||||
|
`)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1295,3 +1329,25 @@ func (s *Store) DBQueryRow(ctx context.Context, sql string, args ...interface{})
|
|||||||
type noopRow struct{}
|
type noopRow struct{}
|
||||||
|
|
||||||
func (n *noopRow) Scan(dest ...interface{}) error { return nil }
|
func (n *noopRow) Scan(dest ...interface{}) error { return nil }
|
||||||
|
|
||||||
|
// DBExec exposes a single DB exec for use by API handlers (e.g., API key management).
|
||||||
|
// Returns the number of rows affected. Returns 0 if no DB is configured.
|
||||||
|
func (s *Store) DBExec(ctx context.Context, sql string, args ...interface{}) (int64, error) {
|
||||||
|
if s.db == nil {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
tag, err := s.db.Exec(ctx, sql, args...)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return tag.RowsAffected(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DBQuery exposes a multi-row DB query for use by API handlers (e.g., API key listing).
|
||||||
|
// Returns nil rows if no DB is configured.
|
||||||
|
func (s *Store) DBQuery(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) {
|
||||||
|
if s.db == nil {
|
||||||
|
return nil, fmt.Errorf("storage: no database configured")
|
||||||
|
}
|
||||||
|
return s.db.Query(ctx, sql, args...)
|
||||||
|
}
|
||||||
|
|||||||
+179
-1
@@ -3,7 +3,7 @@
|
|||||||
import { useState, useCallback, useEffect, useRef } from "react";
|
import { useState, useCallback, useEffect, useRef } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { searchEmails, exportMailsZIP, exportEDiscovery, uploadMailFilesUser, getUploadProgressUser, type SearchHit, type UploadJob } from "@/lib/api";
|
import { searchEmails, exportMailsZIP, exportEDiscovery, uploadMailFilesUser, getUploadProgressUser, listSavedSearches, createSavedSearch, deleteSavedSearch, type SearchHit, type UploadJob, type SavedSearch } from "@/lib/api";
|
||||||
import { Navbar } from "@/components/navbar";
|
import { Navbar } from "@/components/navbar";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -18,6 +18,11 @@ import {
|
|||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from "@/components/ui/popover";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
@@ -36,6 +41,7 @@ import {
|
|||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import { Bookmark, BookmarkPlus, Trash2 } from "lucide-react";
|
||||||
|
|
||||||
const PAGE_SIZE = 25;
|
const PAGE_SIZE = 25;
|
||||||
|
|
||||||
@@ -80,6 +86,14 @@ export default function SearchPage() {
|
|||||||
const [uploadLoading, setUploadLoading] = useState(false);
|
const [uploadLoading, setUploadLoading] = useState(false);
|
||||||
const uploadPollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
const uploadPollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||||
|
|
||||||
|
// Saved searches state
|
||||||
|
const [savedSearches, setSavedSearches] = useState<SavedSearch[]>([]);
|
||||||
|
const [savedLoading, setSavedLoading] = useState(false);
|
||||||
|
const [savePopoverOpen, setSavePopoverOpen] = useState(false);
|
||||||
|
const [saveName, setSaveName] = useState("");
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [savedListOpen, setSavedListOpen] = useState(false);
|
||||||
|
|
||||||
// Clear selection when results change
|
// Clear selection when results change
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setSelected(new Set());
|
setSelected(new Set());
|
||||||
@@ -236,6 +250,89 @@ export default function SearchPage() {
|
|||||||
setUploadLoading(false);
|
setUploadLoading(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Load saved searches on mount
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user || user.role === "superadmin") return;
|
||||||
|
setSavedLoading(true);
|
||||||
|
listSavedSearches()
|
||||||
|
.then((list) => setSavedSearches(list || []))
|
||||||
|
.catch(() => setSavedSearches([]))
|
||||||
|
.finally(() => setSavedLoading(false));
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
const hasActiveSearch = !!(query || fromFilter || toFilter || dateFrom || dateTo || hasAttachment);
|
||||||
|
|
||||||
|
function buildCurrentQuery(): Record<string, string> {
|
||||||
|
const q: Record<string, string> = {};
|
||||||
|
if (query) q.q = query;
|
||||||
|
if (fromFilter) q.from = fromFilter;
|
||||||
|
if (toFilter) q.to = toFilter;
|
||||||
|
if (dateFrom) q.date_from = dateFrom;
|
||||||
|
if (dateTo) q.date_to = dateTo;
|
||||||
|
if (hasAttachment) q.has_attachment = "true";
|
||||||
|
return q;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSaveSearch() {
|
||||||
|
if (!saveName.trim()) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const saved = await createSavedSearch(saveName.trim(), buildCurrentQuery());
|
||||||
|
setSavedSearches((prev) => [saved, ...prev]);
|
||||||
|
setSaveName("");
|
||||||
|
setSavePopoverOpen(false);
|
||||||
|
} catch (e) {
|
||||||
|
alert(`Suche speichern fehlgeschlagen: ${e instanceof Error ? e.message : e}`);
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleApplySavedSearch(s: SavedSearch) {
|
||||||
|
setQuery(s.query.q || "");
|
||||||
|
setFromFilter(s.query.from || "");
|
||||||
|
setToFilter(s.query.to || "");
|
||||||
|
setDateFrom(s.query.date_from || "");
|
||||||
|
setDateTo(s.query.date_to || "");
|
||||||
|
setHasAttachment(s.query.has_attachment === "true" ? true : undefined);
|
||||||
|
setSavedListOpen(false);
|
||||||
|
// Trigger search after state updates
|
||||||
|
setTimeout(() => {
|
||||||
|
// We need to search with the saved query directly since state isn't updated yet
|
||||||
|
setSearching(true);
|
||||||
|
searchEmails({
|
||||||
|
q: s.query.q || undefined,
|
||||||
|
from: s.query.from || undefined,
|
||||||
|
to: s.query.to || undefined,
|
||||||
|
date_from: s.query.date_from || undefined,
|
||||||
|
date_to: s.query.date_to || undefined,
|
||||||
|
has_attachment: s.query.has_attachment === "true" ? true : undefined,
|
||||||
|
page: 1,
|
||||||
|
page_size: PAGE_SIZE,
|
||||||
|
})
|
||||||
|
.then((res) => {
|
||||||
|
setResults(res.hits || []);
|
||||||
|
setTotal(res.total);
|
||||||
|
setPage(1);
|
||||||
|
setSearched(true);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
setResults([]);
|
||||||
|
setTotal(0);
|
||||||
|
})
|
||||||
|
.finally(() => setSearching(false));
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDeleteSavedSearch(id: number) {
|
||||||
|
try {
|
||||||
|
await deleteSavedSearch(id);
|
||||||
|
setSavedSearches((prev) => prev.filter((s) => s.id !== id));
|
||||||
|
} catch (e) {
|
||||||
|
alert(`Loeschen fehlgeschlagen: ${e instanceof Error ? e.message : e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const totalPages = Math.ceil(total / PAGE_SIZE);
|
const totalPages = Math.ceil(total / PAGE_SIZE);
|
||||||
const allSelected = results.length > 0 && results.every((h) => selected.has(h.id));
|
const allSelected = results.length > 0 && results.every((h) => selected.has(h.id));
|
||||||
|
|
||||||
@@ -269,6 +366,87 @@ export default function SearchPage() {
|
|||||||
<Button type="button" variant="outline" onClick={() => setUploadOpen(true)}>
|
<Button type="button" variant="outline" onClick={() => setUploadOpen(true)}>
|
||||||
Importieren
|
Importieren
|
||||||
</Button>
|
</Button>
|
||||||
|
{hasActiveSearch && (
|
||||||
|
<Popover open={savePopoverOpen} onOpenChange={setSavePopoverOpen}>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button type="button" variant="outline" size="icon" title="Suche speichern" aria-label="Suche speichern">
|
||||||
|
<BookmarkPlus className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-72" align="end">
|
||||||
|
<div className="space-y-3">
|
||||||
|
<p className="text-sm font-medium">Suche speichern</p>
|
||||||
|
<Input
|
||||||
|
placeholder="Name der Suche..."
|
||||||
|
value={saveName}
|
||||||
|
onChange={(e) => setSaveName(e.target.value)}
|
||||||
|
onKeyDown={(e) => { if (e.key === "Enter") handleSaveSearch(); }}
|
||||||
|
aria-label="Name der gespeicherten Suche"
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button size="sm" variant="outline" onClick={() => setSavePopoverOpen(false)}>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" onClick={handleSaveSearch} disabled={saving || !saveName.trim()}>
|
||||||
|
{saving ? "Speichern..." : "Speichern"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
)}
|
||||||
|
<Popover open={savedListOpen} onOpenChange={setSavedListOpen}>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button type="button" variant="outline" size="icon" title="Gespeicherte Suchen" aria-label="Gespeicherte Suchen">
|
||||||
|
<Bookmark className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-80" align="end">
|
||||||
|
<p className="text-sm font-medium mb-3">Gespeicherte Suchen</p>
|
||||||
|
{savedLoading ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Skeleton className="h-8 w-full" />
|
||||||
|
<Skeleton className="h-8 w-full" />
|
||||||
|
</div>
|
||||||
|
) : savedSearches.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground py-4 text-center">
|
||||||
|
Keine gespeicherten Suchen vorhanden.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1 max-h-64 overflow-y-auto">
|
||||||
|
{savedSearches.map((s) => (
|
||||||
|
<div
|
||||||
|
key={s.id}
|
||||||
|
className="flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted group"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex-1 text-left text-sm truncate"
|
||||||
|
onClick={() => handleApplySavedSearch(s)}
|
||||||
|
title={Object.entries(s.query).map(([k, v]) => `${k}: ${v}`).join(", ")}
|
||||||
|
>
|
||||||
|
{s.name}
|
||||||
|
</button>
|
||||||
|
<span className="text-xs text-muted-foreground whitespace-nowrap hidden group-hover:inline">
|
||||||
|
{new Date(s.created_at).toLocaleDateString("de-DE")}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||||
|
onClick={(e) => { e.stopPropagation(); handleDeleteSavedSearch(s.id); }}
|
||||||
|
aria-label={`Suche "${s.name}" loeschen`}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5 text-destructive" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
|||||||
@@ -156,3 +156,10 @@ export {
|
|||||||
generateSelfSignedCert,
|
generateSelfSignedCert,
|
||||||
requestACMECert,
|
requestACMECert,
|
||||||
} from "./system";
|
} from "./system";
|
||||||
|
|
||||||
|
export type { SavedSearch } from "./saved_searches";
|
||||||
|
export {
|
||||||
|
listSavedSearches,
|
||||||
|
createSavedSearch,
|
||||||
|
deleteSavedSearch,
|
||||||
|
} from "./saved_searches";
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { request } from "./core";
|
||||||
|
|
||||||
|
export interface SavedSearch {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
query: Record<string, string>;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listSavedSearches(): Promise<SavedSearch[]> {
|
||||||
|
return request<SavedSearch[]>("/api/searches/saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createSavedSearch(
|
||||||
|
name: string,
|
||||||
|
query: Record<string, string>
|
||||||
|
): Promise<SavedSearch> {
|
||||||
|
return request<SavedSearch>("/api/searches/saved", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ name, query }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteSavedSearch(id: number): Promise<void> {
|
||||||
|
await request<Record<string, never>>(`/api/searches/saved/${id}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user