cards/apps/api/tests/media.test.ts
Till JS c9eb0a6f80 Phase 9k: Media-Upload via MinIO-Container
Eigener cards-minio-Container im docker-compose (9100/9101 — Plattform
auf 9000/9001 bleibt isoliert). cardsadmin/cardsadmin als Dev-Default,
prod via env-Vars (CARDS_S3_*).

apps/api/src/services/storage.ts — schmaler StorageService um den
minio-Client. ensureBucket() ist idempotent (auto-create beim ersten
Upload). removeObjectsByPrefix() implementiert den DSGVO-Bucket-Sweep,
weil die S3-API kein Cascade kennt.

Neue Tabelle media_files in pgSchema('cards'):
  id, user_id, object_key, mime_type, original_filename, size_bytes,
  kind, created_at — kein FK auf cards (ein File kann mehreren Karten
  gehören). objectKey-Format <userId>/<ulid>.<ext> für Bucket-Prefix-
  Sweep beim DSGVO-Delete. Legacy mediaRefs bleibt als Slot.

Neuer Router /api/v1/media:
  POST /upload   — multipart, 25 MiB Default-Limit, image/audio/video
                   only (415 sonst), schreibt media_files-Row + speichert
                   in MinIO unter <userId>/<ulid>.<ext>
  GET  /:id      — streamt aus MinIO mit Cache-Control: private,
                   immutable. Cross-User → 404 (nicht 403, anti-enumeration).
  GET  /         — listet alle eigenen Files

DSGVO-Pfade (Service-Key + /me/delete) räumen jetzt auch media_files
+ MinIO-Bucket-Prefix mit ab. Storage-Sweep ist non-fatal — DB ist erst
konsistent gelöscht, dead bytes wären die schlimmstmögliche Folge.

Anki-Import: parse.ts sanitizeAnkiHtml akzeptiert wieder eine
Filename→URL-Map (war in Phase 8c gedroppt). import.ts lädt vor den
Karten alle referenzierten Media-Files via uploadMedia() in MinIO,
sammelt URLs, ersetzt Anki-Filenames durch /api/v1/media/<id>-Pfade
in `<img>` (Markdown) und `[sound:…]` (HTML <audio>). 4-fache Worker-
Concurrency.

apps/web/src/lib/markdown.ts: DOMPurify lässt jetzt <audio>/<video>/
<source> mit src/controls/preload-Attributen durch — sonst würden die
Audio-Tags aus dem Anki-Import gestrippt.

i18n-Strings (DE/EN) auf Media-Stage erweitert: stage_media,
done_media, what_works_media, dropzone_hint, preview_media.
import.what_skipped_media wird zur Bestätigung dass Media seit
Sprint 9k mit übernommen wird.

Manueller E2E-Smoke gegen lokale MinIO (cards-minio :9100):
- 1×1-PNG hochgeladen → 201 mit ID + URL
- /api/v1/media/<id> streamt 200 image/png 69 bytes (file-Identifikation
  bestätigt)
- Cross-User → 404, ohne X-User-Id → 401, text/plain → 415

53 API-Tests grün (+4 neue media-Auth-Gate-Tests), 7 Web-Tests,
51 Domain-Tests, type-check + svelte-check 0 errors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 18:42:56 +02:00

53 lines
1.6 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import { Hono } from 'hono';
import { mediaRouter } from '../src/routes/media.ts';
import type { CardsDb } from '../src/db/connection.ts';
/**
* Auth-Gate-Tests für die Media-Routen ohne echte DB. Wir prüfen, dass
* der authMiddleware-Pfad ehrt und Validation-Errors konsistent sind.
* Ein echter MinIO-Roundtrip bleibt dem manuellen E2E-Smoke vorbehalten,
* weil sql.js + JSZip + MinIO-SDK in Vitest zu viel Mock-Overhead wäre.
*/
function buildApp() {
const app = new Hono();
const stub = {} as CardsDb;
app.route('/api/v1/media', mediaRouter({ db: stub }));
return { app };
}
describe('mediaRouter — auth-gate', () => {
it('GET ohne X-User-Id ist 401', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/media');
expect(res.status).toBe(401);
});
it('GET /:id ohne X-User-Id ist 401', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/media/abc');
expect(res.status).toBe(401);
});
it('POST /upload ohne X-User-Id ist 401', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/media/upload', {
method: 'POST',
});
expect(res.status).toBe(401);
});
});
describe('mediaRouter — Input-Validation', () => {
it('POST /upload ohne multipart-Body ist 400', async () => {
const { app } = buildApp();
const res = await app.request('/api/v1/media/upload', {
method: 'POST',
headers: { 'X-User-Id': 'u-1' },
});
expect(res.status).toBe(400);
const body = (await res.json()) as { error: string };
expect(body.error).toBe('expected_multipart');
});
});