A full rewrite of WaifuDB, with the aim of visualizing complex relationships.
  • TypeScript 93.1%
  • CSS 6.8%
Find a file
amayakase 48c99ab7c6 Add split counterpart family tie kind
Introduce a symmetric 'split' kind for beings that separated from a shared body or identity. It is stored once in ascending ID order with role 'parent' and modifier 'unspecified'.

- API: validate and normalize split facts; treat them like siblings in ancestry conflict checks; label direct paths 'split counterpart' and tag extended paths with a 'split' modifier.
- Graph: present split ties as Family connections with 'split counterpart' labels on both sides.
- DB: migration 17 extends the character_family.kind enum.
- Web: add a 'split counterpart' option to the add dialog (hides the family type selector), and render split ties as sibling-style links in the tree, lists and legend. Layout aligns split counterparts on the same generation.
- Tests and docs/family.md updated.
2026-10-19 00:55:27 +02:00
apps Add split counterpart family tie kind 2026-10-19 00:55:27 +02:00
docs Add split counterpart family tie kind 2026-10-19 00:55:27 +02:00
scripts Retire legacy work_connections table 2026-10-17 23:46:17 +02:00
state Retire legacy work_connections table 2026-10-17 23:46:17 +02:00
storage/assets Add image asset upload and attachment APIs 2026-10-17 15:24:48 +02:00
.gitignore Add franchise backfill and explicit franchise API 2026-10-17 23:01:19 +02:00
AGENTS.md Document frontend design guidance 2026-10-17 15:59:11 +02:00
LICENSE Initial commit 2026-10-14 15:40:19 +02:00
package-lock.json Add franchise relationship graph tab 2026-10-17 19:51:00 +02:00
package.json Retire legacy work_connections table 2026-10-17 23:46:17 +02:00
README.md Retire legacy work_connections table 2026-10-17 23:46:17 +02:00
tsconfig.base.json Scaffold React web app and Express API monorepo 2026-10-17 14:07:34 +02:00
tsconfig.scripts.json Add accounts, sessions, roles and DB migrations 2026-10-17 14:35:20 +02:00

WaifuDBNext

A full rewrite of WaifuDB, with the aim of visualizing complex relationships.

Design guidance

The current visual direction is documented in docs/design-guidance.md. Agents should follow the root AGENTS.md when extending the frontend.

Getting started

Requires Node.js 22.12+ and npm. From the repository root:

npm install
# Configure apps/api/.env using apps/api/.env.example before starting.
npm run dev

Open the frontend URL printed in the terminal to view the landing page. Stop both servers with Ctrl+C. Frontend changes use Vite hot reload; API changes restart the dev launcher.

Project layout

  • apps/web: React, Vite, TypeScript, and plain CSS.
  • apps/api: Express API and MariaDB connection pool.
  • scripts/dev.ts: starts both servers and connects Vite's /api proxy to the actual API port.

The API tries port 3001 and advances when occupied. Vite tries 5173 and advances when occupied. The servers bind the selected ports directly, avoiding a separate check-and-release step. Each dev instance has its own proxy target, so multiple checkouts can run together. Set API_PORT or WEB_PORT to change the starting ports; API_PORT=0 lets the OS choose the API port.

MariaDB

Copy apps/api/.env.example to apps/api/.env and fill in your existing database credentials. The .env file is ignored by Git. Use a dedicated MariaDB application user.

The API applies numbered migrations before listening. It initializes an empty database, or creates the configured database if missing and the database user has CREATE DATABASE permission. For restricted users, provision the database first and grant the schema permissions needed for migrations. Startup stops if database initialization fails. /api/health checks the API; /api/health/database checks MariaDB connectivity.

Migrations use a MariaDB advisory lock and stored checksums. They preserve existing accounts, passwords, roles, and sessions. Add a new migration for future schema changes; never edit an applied migration. The auth_ tables belong to this application; unrelated tables are left alone. An incompatible or newer schema fails startup instead of being reset. Automatic upgrades cover this application's versioned schema, not arbitrary databases from other applications.

Use the query<T>(sql, values) helper in apps/api/src/database.ts for database access. Always pass user-supplied values through placeholders, for example:

const rows = await query<{ id: number; name: string }[]>(
  'SELECT id, name FROM characters WHERE id = ?',
  [characterId],
);

This is an example for a future table, not an included schema.

Franchise migration planning

Phases 1–2 add explicit franchises and character_franchises, then backfill and require works.franchise_id (schema versions 11–13). Existing accounts, credentials, roles and sessions are preserved. Phase 3 adds the franchise UI described in the roadmap. Startup blocks migration 13 when work or character assignments are unresolved, rather than silently guessing or serving incomplete franchise reads. Fresh empty databases initialize normally. Schema 15 retires the old work-link table after verification and archival; use the commands below to verify or retire an upgraded catalog with a fresh backup.

For a legacy catalog that still has work_connections, generate a durable JSON plan without running migrations or writing database rows. After retirement, use franchises:verify instead; historical plans and applied manifests remain available.

npm run franchises:report -- state/franchise-plan.json

The report uses one read-only consistent snapshot. It includes source work links, appearances, deterministic component keys, proposed names/artwork, work/character mappings, shared/unlinked characters, blockers and a source fingerprint. Existing output files are never overwritten. Exit code 0 means all characters are mapped; 2 means a report was saved with unresolved characters; 1 means the command failed. Treat reports as local catalog exports. A saved report is a point-in-time plan; regenerate and reconcile it before phase 2. Database IDs are null until backfill creates franchises; never treat component keys as allocated database IDs.

For characters with no appearances, pass an explicit mapping as the second argument:

npm run franchises:report -- state/franchise-plan-reviewed.json state/franchise-mapping.json

Example mapping (replace IDs/keys with values from your report):

{
  "newFranchises": [{ "key": "new:original", "name": "Original characters" }],
  "unlinkedCharacters": [
    { "characterId": 42, "franchiseKey": "component:1" },
    { "characterId": 43, "franchiseKey": "new:original" }
  ]
}

Each unlinked character needs one explicit destination. Invalid, duplicate or non-unlinked assignments fail validation. New keys must start with new: followed by 1–100 letters, digits, underscores or hyphens. Names do not merge franchises. Character memberships from appearances are deduplicated across each component. Franchise artwork reuses existing asset IDs and the existing cover/portrait formats; the report does not edit images.

Backfill and API cutover

Stop all application instances, background catalog writers and other users of the configured database/assets before running the backfill. Keep them stopped until it completes. Then generate/review a fresh plan and run:

npm run franchises:backfill -- state/franchise-plan-reviewed.json state/franchise-manifest.json

The command saves a database SQL backup and asset-directory copy under the ignored state/franchise-backups/, restores the SQL into a randomly named rehearsal database, rehearses data migration and the NOT NULL constraint, and removes that temporary database. It needs CREATE/DROP DATABASE privileges for rehearsal. It then prepares migrations 11–12, rejects stale/modified plans or unrecorded assignments, and commits franchise rows, memberships and the generated-ID manifest in one transaction. Exact legacy profiles, appearances, relationships, artwork references, assets and account/session rows are fingerprinted before/after the backfill. Migration 13 enforces required work membership only after reconciliation passes.

SQL backups contain private account/session data. Keep them local and protected. Restore into a new database with the matching pre-cutover code and asset copy; do not overwrite later catalog writes. Normal startup never resets a database.

If data commit succeeded but output export or final DDL was interrupted, rerun the same plan with a new output filename. The database manifest recovers the original generated IDs without inserting duplicates or reassigning later edits. A different plan cannot replace an applied migration. Output files are never overwritten.

Verification and legacy retirement

npm run franchises:verify -- state/franchise-verification.json

This read-only check validates historical component mappings, current membership, exact row/ID summaries and artwork references, then verifies every asset file's SHA-256 hash. Historical differences caused by later edits are reported separately; they do not cause old assignments to overwrite current memberships.

Stop all application instances and catalog/asset writers before retiring an upgraded catalog, and keep them stopped until the command finishes:

npm run franchises:retire -- state/franchise-retirement.json

The command backs up database and assets under ignored state/franchise-backups/, restores/rehearses on a temporary database, and verifies exact protected rows before and after migrations 14–15. Migration 14 adds the durable retirement audit; migration 15 archives the verified legacy edges and drops only work_connections. Nonempty unrecorded links or inconsistent historical/current mappings block cleanup. The original backfill manifest remains unchanged. Fresh initialization and interrupted DROP retries are supported; recovery fingerprints use the archive after retirement.

No normal catalog, picker or graph flow reads the retired links. Roll back by restoring SQL/assets into a separate database with matching code, preserving later writes for reconciliation. Never reset the working catalog or restore old account state over current accounts. Backup SQL contains private credentials/session data; keep it protected. Verification JSON contains row digests instead of those values.

Accounts

Register using a username (3–32 ASCII letters, numbers, or underscores) and a password (12–128 characters). Usernames are case-insensitive. No email is collected. Registration logs you in with the regular user role. Avatars are nullable; image upload and attachment APIs are available below.

Passwords use individually salted scrypt hashes (N=131072, r=8, p=1). Sessions use random 256-bit tokens in HttpOnly, SameSite=Lax cookies; only SHA-256 token hashes are stored in MariaDB. Sessions survive API restarts, expire after seven days, rotate on login, and are revoked on logout. Every permission check reads the current database role. Public requests cannot assign roles.

Assign roles locally after the account has been registered:

npm run accounts:role -- YourUsername admin
npm run accounts:role -- AnotherUsername mod
npm run accounts:role -- AnotherUsername user

The command refuses to demote the last admin. It preserves passwords and sessions. No default admin password or automatic first-registrant admin is created.

Endpoints: POST /api/auth/register, POST /api/auth/login, POST /api/auth/logout, and GET /api/auth/me. Role guard examples are GET /api/auth/admin (admin) and GET /api/auth/moderation (admin/mod). Authentication responses are not cached. Mutations require JSON, an allowed Origin, and X-WaifuDB-Request: 1; CORS is not enabled.

For production, set NODE_ENV=production, serve the frontend over HTTPS, and set APP_ORIGINS to its exact origin (comma-separated for multiple origins). Production cookies use the Secure flag and __Host- prefix. Keep /api on the frontend origin via your reverse proxy. Login/registration are limited to 20 attempts per IP per 15 minutes in each API process. The API intentionally does not trust forwarded IP headers; when deploying multiple instances or behind a proxy, configure edge rate limiting using the actual client IP as well.

Validation and builds

npm run typecheck
npm run build
npm test
npm start

Builds go to apps/web/dist and apps/api/dist. npm start starts the compiled API. For production, serve the web build with a web server and forward /api to the API's printed address. Vite's proxy is for development only. Configure a fixed deployment port through API_PORT and ensure your deployment routes to the port actually selected.

npm test runs password, image decoding and HTTP security tests. To include real MariaDB integration tests in PowerShell:

$env:RUN_DATABASE_TESTS='1'
npm test
Remove-Item Env:RUN_DATABASE_TESTS

These create and remove a randomly named waifudb_auth_test_* database using the configured connection credentials. The configured application database is never used for test fixtures. The database user needs CREATE/DROP DATABASE permissions for these tests.

Works API

Works represent individual seasons, adaptations, books or games. Public reads:

  • GET /api/works/types: { types: string[] }, matching the MyWaifuList series filter: TV, OVA, Movie, Special, ONA, Game, Hentai, Manga, Manhwa, Manhua, Webtoon, Novel. Visual novels use Game.
  • GET /api/works?search=...&type=TV&page=1&pageSize=25: { works, total, page, pageSize }. Searches all three names; page size is 1–100; stable title/ID order.
  • GET /api/works/:id: { work }.
  • GET /api/works/:id/franchise: { franchise, works } from explicit membership, ordered by release date (unknown dates last), title and ID.
  • GET /api/works/:id/relationship-graph: the explicit franchise's graph, including characters without appearances.
  • Work results include franchiseId. Filters franchiseId and excludeFranchiseId support destination-franchise selection. The retired unconnectedTo filter returns 400.

Admin/mod mutations require the existing session cookie, allowed Origin, JSON content type and X-WaifuDB-Request: 1:

  • POST /api/works: create; optional franchiseId selects an existing franchise. Omitted/null creates one named from englishName (original title fallback) in the same transaction. Returns 201, Location and { work }.
  • PUT /api/works/:id: replace all editable fields; returns { work }.
  • DELETE /api/works/:id: delete the work; retains its franchise when characters remain, otherwise cleans up an empty franchise. Returns 204.
  • Legacy GET/PUT/DELETE work-connection routes are removed and return 404. Work moves use the franchise endpoints below.

Example create/replace body:

{
  "title": "原題",
  "romajiName": "Romaji title",
  "englishName": "English title",
  "type": "TV",
  "releaseDate": "2026-10-17",
  "episodeCount": 12,
  "synopsis": "Description of the work."
}

title (original name, 1–500 characters) and type are required. Other fields are nullable and default to null when omitted on create/replace. Names are trimmed; translated names are limited to 500 characters, synopsis to 10,000. Dates must be real YYYY-MM-DD dates, years 1000–9999. Unknown release dates/counts use null. Episode counts must be integers 1–1,000,000, supported only for TV, OVA, Movie, Special, ONA and Hentai; other types require null. Unknown body fields are rejected. Invalid input returns 400, unauthenticated edits 401, unauthorized edits 403 and missing works 404.

Legacy work links are archived in the retirement audit; their live table is removed. Franchise reads and character pickers use explicit membership.

Franchises API

Public reads:

  • GET /api/franchises?search=...&page=1&pageSize=24: { franchises, total, page, pageSize }.
  • GET /api/franchises/:id: { franchise } with name, cover and portrait.
  • GET /api/franchises/:id/works: paginated { works, total, page, pageSize }.
  • GET /api/franchises/:id/characters: paginated characters, including members without appearances.
  • GET /api/franchises/:id/relationship-graph: identical to member-work graph responses, keyed by the real franchise ID. Outside relatives can still provide family inference evidence.

Admin/mod mutations use the existing JSON, Origin, request-header and session protections:

  • PUT /api/franchises/:id with { "name": "Name" }: edit the name.
  • PUT /api/franchises/:id/images/cover or /portrait with { "assetId": "uuid-or-null" } (JSON null clears): reuse the existing asset upload/crop formats.
  • PUT /api/franchises/:id/works/:workId with {}: move only that work into this franchise. Returns { franchiseId, deletedFranchiseId }. Preserve appearances, add their characters to the destination, and retain source memberships while other works remain. If its last work leaves, transfer all remaining characters, deduplicate memberships, and delete the source. Destination name/artwork win; assets and characters are preserved. Adding an existing member is a no-op.
  • DELETE /api/franchises/:id/works/:workId with {}: detach into a new franchise named after the work. A changed source returns 409.
  • PUT /api/franchises/:id/characters/:characterId with {}: add an existing character directly, without an appearance.

Work moves, creation, membership writes and cleanup use one transaction/connection, lock franchises in ID order and recheck work ownership. Deadlocks and changed reads retry the complete transaction; exhausted contention returns 409 without partial writes.

POST /api/characters now requires a franchiseId or workId alongside its profile. A work context also adds its appearance atomically; if both are given they must agree. GET /api/characters?franchiseId=... filters direct membership, and sameFranchiseAs uses shared direct franchises for family/social pickers. GET /api/characters/:id/franchises lists memberships separately from appearances. An outside appearance added through PUT /api/characters/:id/works/:workId requires { "addFranchiseMembership": true }; without it the API returns 409. Removing an appearance does not erase membership.

The frontend exposes these actions at /franchises and /franchises/:id. Franchise detail pages share the existing work artwork/layout patterns, with Works, Characters and Relationships tabs. Search, tabs and listing pages use browser history. Name editing stays in a dialog, and cover/portrait changes use the existing crop workflow.

Create work on a franchise starts with it selected; global work creation can select an existing franchise or create one from the English title (original title fallback). Add work selects an existing work and shows its source, destination and last-work cleanup effects before the separate Move work action. Work pages link to the franchise instead of offering work-to-work connections. Move to new franchise uses its own confirmation.

Franchise characters are listed independently of appearances, with Create character and Add existing character actions. Global character creation requires a franchise; creation from a work automatically adds its appearance. Character profiles link all franchise memberships separately from Appears In. The appearance picker defaults to the character's franchises; Other franchises requires an explicit checkbox to add the corresponding memberships. Changing scope clears selection; searches/pages preserve it. Related API filters inFranchisesOf, outsideFranchisesOf, excludeFranchiseId and notAppearingInWork run before pagination.

Graph layouts now use the waifudb:franchise-graph:v3:franchise: storage namespace, shared between the franchise page and its works, avoiding old inferred-ID collisions.

Series browser

/series is the public Series navigation page. The responsive grid uses 24 works per page, with pagination above and below results, a left search/type panel, and All / # / A–Z title filters. Search, type, letter and page are stored in the URL, including browser Back/Forward navigation. Letter filtering is performed by the API before pagination: GET /api/works?letter=A (or URL-encoded # for titles starting with numbers, symbols or non-Latin characters). Empty type/search values mean no filter.

Logged-in admins and moderators can use Add work beside the letter picker to create works in a modal. Each grid card is a clickable A4 portrait with the English title (original title fallback) and media-type chip overlaid on a dark gradient. Works without artwork use a gradient placeholder.

Individual work pages are available at /series/:id, linked from catalog titles and franchise entries. They have a full-width cover, portrait and metadata/synopsis sidebar, admin/mod editing through the shared create/edit work dialog, and Characters / Franchise / Relationships tabs. ?tab=franchise preserves the selected tab in browser history and links to the dedicated franchise page. Character controls here manage this work's appearances; franchise membership and work moves are managed on the franchise page.

Image assets

Migration 4 adds assets and nullable foreign keys auth_users.avatar_asset_id, works.cover_asset_id, and works.portrait_asset_id. Existing accounts, legacy avatar URLs, works and sessions are preserved. Images live in storage/assets at the project root (ignored by Git). Set ASSET_DIRECTORY to an absolute directory to override it. Back up this directory alongside MariaDB; all API instances must share it when running multiple instances.

  • POST /api/assets: authenticated upload. Send the image file itself as the body, with Content-Type: image/jpeg, image/png, or image/webp, the session cookie, an allowed Origin, and X-WaifuDB-Request: 1. This uses raw binary, not multipart or JSON/base64. Returns 201 and { asset: { id, ownerId, mimeType, byteSize, width, height, sha256, createdAt, url } }.
  • GET /api/assets/:id: public asset metadata.
  • GET /api/assets/:id/file: public image bytes, with immutable caching.
  • PUT /api/auth/me/avatar: attach an owned upload to the current account (moderators/admins may reuse any asset). JSON body { "assetId": "uuid" }; use null to clear.
  • PUT /api/works/:id/images/cover and PUT /api/works/:id/images/portrait: moderator/admin attachment endpoints using the same JSON body. Return { assetId, url }.

Attachment mutations use the standard JSON security headers. Missing records/assets return 404, invalid IDs/bodies 400, missing login 401 and insufficient permissions 403. Account responses include avatarAssetId and avatarUrl; work responses include coverAssetId, portraitAssetId, coverUrl and portraitUrl. Ordinary work edits preserve images.

Uploads are limited to 10 MiB, 40 megapixels and 20 requests per minute per IP. The server fully decodes supported single-frame raster images, applies orientation, removes metadata, and stores a normalized WebP under a generated UUID. SVG and animated images are rejected; client filenames are never used as paths. Invalid images return 400, unsupported content types 415, oversized requests 413, and rate-limited uploads 429. A failed database insert removes the new file. Images are public: do not upload private content. Replacing or clearing an attachment retains the previous asset for reuse; automatic cleanup/deletion is not included yet.

On work pages, moderators/admins can click the cover or portrait itself to select a file. Hover, keyboard focus and touch controls expose the artwork action. The crop dialog supports dragging, zoom, keyboard-accessible position sliders, reset and cancel, and shows errors without discarding the crop. Save uploads the cropped image and attaches it to the work immediately. Covers use 4:1 (1600×400); portraits use A4's 210:297 ratio (840×1188). apps/web/src/images.ts defines shared image formats and crop geometry; EditableImage handles selection and upload with an entity-specific attachment callback, and ImageCropDialog edits and exports images independently. Future character portraits can reuse imageFormats.portrait.

Browser example (the browser supplies Origin):

const response = await fetch('/api/assets', {
  method: 'POST', credentials: 'same-origin',
  headers: { 'Content-Type': file.type, 'X-WaifuDB-Request': '1' },
  body: file,
});
if (!response.ok) throw new Error('Image upload failed');
const { asset } = await response.json();
// Then PUT { assetId: asset.id } to an attachment endpoint.

Franchise workflow

Franchise pages own the Works listing and its creation/move controls. The searchable picker excludes current members before pagination and names the source/destination before a separate confirmation moves one work. Characters have direct franchise memberships independently of work appearances. Work and character pages link to these explicit franchises; no transitive work-link traversal remains.