Phase 12 R2: Marketplace-Backend α + β — Authors + Deck-Init + Publish

Routes (additiv unter /api/v1/marketplace/*):
- POST/GET /authors/me — eigenes Author-Profil anlegen/updaten/lesen
- GET /authors/:slug — public Profile-Lookup (banned-reason gestrippt)
- POST /decks — Deck-Init (Slug-Validation + Pflicht-Author-Profil +
  CHECK auf paid + Pro-License)
- POST /decks/:slug/publish — Versions-Snapshot mit per-Karte
  cardContentHash aus @cards/domain, per-Version-Hash, AI-Mod-Stub-Log,
  atomarer latest_version_id-Bump in Drizzle-Transaction
- PATCH /decks/:slug — Metadaten-Update (Owner-Only)
- GET /decks/:slug — Public-Detail mit optional-auth-Middleware

Geport aus cards-decommission-base:services/cards-server/, mit
Greenfield-Anpassungen:
- Hashing über @cards/domain.cardContentHash (gemeinsame SoT
  zwischen privatem cards.cards und marketplace.deck_cards), per-
  Version-Hash als SHA-256 über sortierte Karten-Hashes mit Ord-Prefix
- AI-Moderation als R2-Stub (pass+rationale+model='stub'),
  echte mana-llm-Anbindung in späterer Welle
- Auth-Middleware-Shape an Greenfield (userId/tier/authMode in
  c.get(...) statt user-Object), optional-auth als Schwester für
  anonymen Public-Read
- Hono-typing: outer Marketplace-Decks-Router ist Partial<AuthVars>
  weil Public-GET kein JWT braucht; Auth-Subroute ist strict

Lese-Referenz:
- 3331 LOC altes cards-server-Code (routes, services, middleware,
  lib) unter docs/marketplace/archive/code/ archiviert. Read-only,
  nicht im Build-Path.

Verifikation:
- 16 neue Vitest-Tests (Slug + Version-Hash), 72 gesamt grün
- type-check 0 errors
- E2E-Smoke gegen lokale cards-api: Cardecky-Author + Deck
  r2-stoische-ethik mit 3 Karten v1.0.0 (basic + basic + cloze),
  per-Karten-Hashes geschrieben, ai_moderation_log-Row da, semver-409
  + paid-422-Errors verifiziert. Smoke-Daten danach aufgeräumt.

Verbleibend für R3+: Discovery (explore + search), Engagement (stars/
subscribe/fork), Smart-Merge mit FSRS-State-Erhalt; danach R4 PRs +
Card-Discussions, R5 Frontend-Routes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Till JS 2026-05-09 15:13:58 +02:00
parent 9a7068dd19
commit 7dbbf63523
40 changed files with 4004 additions and 1 deletions

View file

@ -0,0 +1,42 @@
/**
* AI-Moderation-First-Pass für Deck-Publishes.
*
* Verdict: `pass` | `flag` | `block`. Per Mission-Prinzip AI ist
* Moderator, nicht Gatekeeper" wird `block` nur für unmissverständliche
* Verstöße benutzt (CSAM, Doxxing); alles ambivalente fließt zur
* menschlichen Review als `flag`.
*
* **Aktueller Stand: Stub.** R2 implementiert nur den Pass-Through
* (`verdict='pass'`, `model='stub'`) plus den Audit-Log-Eintrag.
* Echte mana-llm-Integration kommt in einer späteren Welle (siehe
* cards-decommission-base:services/cards-server/src/lib/ai-moderation.ts
* für die alte Voll-Implementation als Lese-Referenz unter
* `docs/marketplace/archive/code/lib/ai-moderation.ts`).
*
* Fail-open im Original: bei mana-llm-Ausfall wurde `flag` gesetzt,
* damit ein menschlicher Reviewer es trotzdem sieht. Solange wir nur
* Cardecky-Decks publishen, ist der Stub `pass` ausreichend Cardecky
* ist eine kuratierte Identität.
*/
export interface ModerationVerdict {
verdict: 'pass' | 'flag' | 'block';
categories: string[];
rationale: string;
model: string;
}
export interface ModerationInput {
title: string;
description?: string;
cards: { fields: Record<string, string> }[];
}
export async function moderateDeckContent(_input: ModerationInput): Promise<ModerationVerdict> {
return {
verdict: 'pass',
categories: [],
rationale: 'R2-stub: AI-Mod nicht aktiv, alles passt durch.',
model: 'stub',
};
}

View file

@ -0,0 +1,64 @@
/**
* URL-safe Slug-Helpers für Marketplace-Author-Profile + Deck-URLs.
*
* `slugify` ist best-effort macht Anna Lang!" zu „anna-lang" als
* Vorschlag. `validateSlug` ist strikt und wird auf jeden Write
* enforced, damit der URL-Raum vorhersehbar bleibt.
*
* 1:1 ported aus
* `cards-decommission-base:services/cards-server/src/lib/slug.ts`.
*/
const MAX_SLUG_LEN = 60;
const MIN_SLUG_LEN = 3;
const SLUG_RE = /^[a-z0-9](?:[a-z0-9-]{1,58}[a-z0-9])?$/;
const RESERVED_SLUGS = new Set([
'admin',
'api',
'app',
'auth',
'docs',
'explore',
'feed',
'help',
'me',
'mana',
'marketplace',
'new',
'public',
'search',
'settings',
'support',
'system',
'u',
'd',
'v1',
'v2',
]);
export function slugify(input: string): string {
return input
.normalize('NFKD')
.replace(/[̀-ͯ]/g, '') // strip diacritics
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, MAX_SLUG_LEN);
}
export type SlugInvalidReason = 'too-short' | 'too-long' | 'invalid-chars' | 'reserved';
export interface SlugValidation {
ok: boolean;
reason?: SlugInvalidReason;
}
export function validateSlug(slug: string): SlugValidation {
if (slug.length < MIN_SLUG_LEN) return { ok: false, reason: 'too-short' };
if (slug.length > MAX_SLUG_LEN) return { ok: false, reason: 'too-long' };
if (!SLUG_RE.test(slug)) return { ok: false, reason: 'invalid-chars' };
if (RESERVED_SLUGS.has(slug)) return { ok: false, reason: 'reserved' };
return { ok: true };
}

View file

@ -0,0 +1,38 @@
/**
* Per-Version-Content-Hash. Pro Karte wird `cardContentHash` aus
* `@cards/domain` benutzt (gemeinsame Source-of-Truth zwischen privatem
* Lern-Stack und Marketplace) pro Version hashen wir die geordnete
* Liste von Karten-Hashes plus deren Ordinal-Position.
*
* Smart-Merge nutzt das: zwei Versionen mit identischen Karten in
* identischer Reihenfolge bekommen denselben Version-Hash; eine
* Reihenfolgen-Änderung allein ändert den Version-Hash, weil das aus
* Lern-Sicht ein anderer Verlauf ist.
*
* Original-cards-server hatte eine eigene `hashCard`/`hashVersionCards`-
* Implementation; der Greenfield-`cardContentHash` benutzt aber ein
* leicht anderes Canonical-Format (sortiertes Tupel-Array statt
* sortiertes Object). Wir vereinheitlichen auf das Greenfield-Format,
* weil ein Fork eines Marketplace-Decks die Karten-Hashes mit den
* privaten `cards.cards.content_hash` matchen können soll.
*/
import { cardContentHash } from '@cards/domain';
export interface OrderedCardForHash {
type: string;
fields: Record<string, string>;
ord: number;
}
export async function hashVersionCards(cards: OrderedCardForHash[]): Promise<string> {
const ordered = [...cards].sort((a, b) => a.ord - b.ord);
const cardHashes = await Promise.all(
ordered.map(async (c) => `${c.ord}:${await cardContentHash({ type: c.type, fields: c.fields })}`)
);
const data = new TextEncoder().encode(cardHashes.join('|'));
const buf = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(buf))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}